graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
acp: T3 Code client profile (#1603)
justrachde027c1f95cc
diff --git a/docs/acp-compatibility.md b/docs/acp-compatibility.mdindex e1ddcf2d..7c38ef10 100644--- a/docs/acp-compatibility.md+++ b/docs/acp-compatibility.md@@ -41,6 +41,7 @@ optional feature or draft extension is enabled.| Resent prompts | `session/prompt` may carry a client message id as `messageId` or `_meta["graff/messageId"]`. Resending a prompt this process already finished for that session answers with the first turn's `stopReason` instead of starting another turn; a failed turn is not recorded, so its resend runs. The last 32 ids are kept in memory. `graff serve` and remote control take the same id as `message_id` on the request body and replay the first request's events. | `src/resend.zig`, `scripts/test-serve-resume.py` || Saved views | A completed `tool_call_update` whose result saved a `render_html` page or an MCP Apps result also carries `_meta["graff/view"]` = `{kind: "html" \| "mcp_app", id, path}`. `id` is the 32-hex snapshot name under `.graff/views` or `.graff/mcp-apps`; resolve by id and treat `path` as informational. The `[Rendered view](…)` / `[MCP app](…)` text link stays in the content. Replayed on `session/load`. | `scripts/test-acp-view-meta.py`, `src/acp_view_meta.zig` || Compaction | When the root agent compacts (automatically, `/compact`, or server-side), graff sends `compaction_update` `{compactionId, status}`: `in_progress`, then one of `completed` (a local summary rides `summary` as a text block), `failed` (with `error`) or `cancelled`. A provider that compacted in-stream gets one `completed`. ACP v1 marks this unstable, so it is sent only to clients that advertise `clientCapabilities.session.compaction`; ACP v2 clients always get it. | `src/acp_compaction.zig`, `scripts/test-acp-compaction.py` |+| Client profiles | A client whose `clientInfo.name` starts with `t3-code` gets the T3 Code profile: a slash command is the first prompt block, the session `cwd` is never swapped for an auto-isolated tree, a `model`-category config option lists reachable models (`<provider>/<model>`), and `/model` and `/yolo` are not advertised. | `src/acp_t3_tests.zig`, ADR 0278 || Transport | ACP uses JSON-RPC over stdio. HTTP/2 checks exercise the model request transport behind ACP; they do not redefine ACP as an HTTP/2 protocol. | `scripts/test-acp-http2.py`, `scripts/test-acp-http2-retry.py` |## ACP v2 preview (`GRAFF_ACP_V2=1`)diff --git a/docs/adr/0278-t3-code-acp-profile.md b/docs/adr/0278-t3-code-acp-profile.mdnew file mode 100644index 00000000..23378177--- /dev/null+++ b/docs/adr/0278-t3-code-acp-profile.md@@ -0,0 +1,45 @@+# 0278. T3 Code gets its own ACP profile++Status: accepted 2026-10-10++## Context++T3 Code runs any ACP Registry agent through one generic driver and gives each+thread its own agent process. Run against graff over ACP v1, four things broke:++- T3 appends a context block after every prompt, so a slash command arrived+ as `/models` plus T3's context and graff refused it as an unknown command.+- A second thread in the same checkout auto-isolated into+ `.graff/worktrees/session-*`, and because the session `cwd` named the+ owning checkout, `acp_workspace.adopt` kept that tree. Edits never reached+ the folder T3 diffs and checkpoints.+- T3's model picker reads a `model`-category config option; graff only offers+ its model list through the `graff/models` vendor method, so T3 showed one+ "Default" model.+- graff's `/model` duplicated T3's own, and `/yolo` bypassed T3's approval+ modes.++Harness and other clients rely on the opposite behavior for the worktree rule+and read models through `graff/models`.++## Decision++`initialize.clientInfo.name` starting with `t3-code` switches on a profile+(`acp_t3.zig`); no other client sees it.++- A slash command is the prompt's first text block alone; multi-line command+ output goes out as a text block so tables keep their columns.+- The client's `cwd` is entered as named, never kept as an auto-isolated tree.+- `session/new` and `session/load` add a `model` option (`acp_model_option.zig`):+ the reachable models in `graff/models` order, current first, at most 48.+ Choosing one runs `/model <provider> <model>`.+- The advertised commands omit `model` and `yolo`.++## Consequences++graff behaves like a native T3 provider without T3 shipping graff-specific+code, which its contribution guide rules out for registry agents. The+profile keys on a client name, so a T3 rename silently turns it off;+`acp_t3_tests.zig` pins the behavior for the names T3 sends today. Revisit+any rule that later becomes right for every client (the first-block slash+rule is the likeliest) by moving it out of the profile.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 6867ae7a..7e41ff9d 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -289,6 +289,7 @@ record only when you need the evidence or the edge cases.| [0260](0260-clef-compaction-replaces-client-summary.md) | `GRAFF_CLEF_COMPACT=1` routes client-summary compactions through the gateway's server-side `POST /v1/compact` (Clef decision-model pruning, text verbatim); OpenAI-family server paths are untouched and any failure falls back to the summary. || [0261](0261-client-summary-stays-the-compactor.md) | The client summary stays the compactor: `GRAFF_CLEF_COMPACT` defaults off (Clef rarely pruned and mostly fell back to the summary in measurement); first-party Responses routes use only the provider's own compaction. Supersedes 0260's default. || [0270](0270-a-closed-stdio-mcp-server-restarts-on-its-next-call.md) | A stdio MCP server whose connection closes goes back to dormant with its launch config and restarts on its next call; the failed call is never replayed, and after two restarts in a session its tools are withdrawn as before. |+| [0278](0278-t3-code-acp-profile.md) | An ACP client named `t3-code…` gets a profile: slash commands are the first prompt block, the client's `cwd` is never swapped for an auto-isolated tree, a `model` config option lists reachable models, and `/model` and `/yolo` are not advertised. || [0280](0280-mcp-servers-report-state-and-reconnect.md) | Every configured MCP server has one status row (`graff mcp status --json`, `/mcp`); `graff mcp reconnect` / `/mcp reconnect` run a real handshake and refresh its catalog; `graff mcp enable|disable` live in `~/.codegraff/mcp-state.json`; the catalog cache keys on cwd + env, and server `env` overlays graff's own. || [0281](0281-anthropic-console-sign-in-reads-the-sdk-profile.md) | Anthropic Console sign-in: graff reads the `user_oauth` profile Anthropic's CLI writes (`ant auth login`), in the SDK's precedence (API key wins), sends it as Bearer, and refreshes through `ant auth print-credentials`; `graff login anthropic` runs `ant auth login`. No claude.ai subscription login. |diff --git a/src/acp.zig b/src/acp.zigindex 0a4af038..ac06323f 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -123,13 +123,7 @@ fn liveModels(ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Requeconst keys = live.keys;const root = live.root;// Hydrate deferred local metadata without network refresh or MCP startup.- root.ensureStoredKeys(keys);- if (root.model_catalog) |*cached|- cached.ensureCached(root.io, root.gpa, root.arena, root.home, keys.get("codex") orelse "", keys.codex_account);- if (!live.local_catalog_loaded) {- if (root.home.len > 0) @import("router_catalog.zig").loadCachedAll(root.io, root.arena, root.home);- live.local_catalog_loaded = true;- }+ @import("acp_model_option.zig").hydrate(live);const er = @import("effort_route.zig");if (@import("gateway_picker_catalog.zig").requested(req.params)) @import("gateway_picker_catalog.zig").refresh(root.gpa, root.io, root.arena, keys.*);const catalog = pricing.models();diff --git a/src/acp_engine.zig b/src/acp_engine.zigindex f14a16f7..770bcb8d 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -82,6 +82,9 @@ pub const Dispatch = struct {extra: ?ExtraFn = null,config: ?ConfigFn = null,set_config: ?SetConfigFn = null,+ /// The `model` option; only T3 Code's profile offers it (acp_model_option.zig).+ model_config: ?ConfigFn = null,+ set_model: ?SetConfigFn = null,mcp_servers: ?McpServersFn = null,error_message: ?*const fn (ctx: *anyopaque, err: anyerror) []const u8 = null,cancel_info: ?*const fn (ctx: *anyopaque) ?Cancellation = null,@@ -118,26 +121,16 @@ fn supportsBackgroundSubagents(params: ?std.json.Value) bool {}pub fn configOptions(d: *Dispatch, arena: Allocator) ![]const ConfigOption {- const config = d.config orelse return &.{};- const option = try config(d.ctx, arena) orelse return &.{};- const items = try arena.alloc(ConfigOption, 1);- items[0] = option;- return items;-}--fn sameConfig(before: []const ConfigOption, after: []const ConfigOption) bool {- if (before.len != after.len) return false;- for (before, after) |a, b| {- if (!std.mem.eql(u8, a.currentValue, b.currentValue) or a.options.len != b.options.len) return false;- for (a.options, b.options) |av, bv| if (!std.mem.eql(u8, av.value, bv.value)) return false;- }- return true;+ var items: std.ArrayList(ConfigOption) = .empty;+ if (d.model_config) |model| if (try model(d.ctx, arena)) |option| try items.append(arena, option);+ if (d.config) |config| if (try config(d.ctx, arena)) |option| try items.append(arena, option);+ return items.items;}pub fn emitConfigChange(d: *Dispatch, arena: Allocator, w: *Io.Writer, sid: []const u8, before: []const ConfigOption) !void {if (d.config == null) return;const after = try configOptions(d, arena);- if (sameConfig(before, after)) return;+ if (@import("acp_model_option.zig").same(before, after)) return;try proto.writeNotification(w, "session/update", .{ .sessionId = sid, .update = .{.sessionUpdate = "config_option_update",.configOptions = after,@@ -202,14 +195,15 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)const config_before = configOptions(d, arena) catch |err| return turnError(d, w, req, err);const workspace_before = acp_workspace.snapshot(d.workspace, arena);// Before slash handling: an agent's room line must not run as a command.- const text = try @import("acp_room.zig").frame(arena, req.params, try flattenPrompt(arena, if (obj) |o| o.get("prompt") else null));+ const flat = try flattenPrompt(arena, if (obj) |o| o.get("prompt") else null);+ const text = try @import("acp_room.zig").frame(arena, req.params, flat);if (d.slash) |slash| {- const reply = slash(d.ctx, arena, text) catch |err| {+ const reply = slash(d.ctx, arena, @import("acp_t3.zig").slashText(if (obj) |o| o.get("prompt") else null, flat, text)) catch |err| {emitConfigChange(d, arena, w, sid, config_before) catch |config_err| return turnError(d, w, req, config_err);return turnError(d, w, req, err);};if (reply) |plain| {- if (plain.len > 0) try writeSessionUpdate(w, sid, plain);+ if (plain.len > 0) try writeSessionUpdate(w, sid, try @import("acp_t3.zig").slashReply(arena, plain));emitConfigChange(d, arena, w, sid, config_before) catch |config_err| return turnError(d, w, req, config_err);try acp_workspace.emitChange(d.workspace, arena, w, sid, workspace_before);try emitMeter(d, w, sid);@@ -293,6 +287,7 @@ pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const uconst req = parseRequest(arena, line) orelse return;if (std.mem.eql(u8, req.method, "initialize")) {v2.negotiate(req.params, d.seed);+ @import("acp_t3.zig").note(req.params);@import("acp_elicit.zig").configure(req.params);@import("acp_compaction.zig").noteInitialize(req.params);// The draft child-session RFD is a v1 shape; v2 gets tool-call progress.@@ -322,7 +317,7 @@ pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const utry respond(w, req, .{ .sessionId = d.session_id.?, ._meta = acp_workspace.meta(env, arena) })elsetry respond(w, req, .{ .sessionId = d.session_id.? });- try proto.writeAvailableCommands(w, d.session_id.?, proto.slashCommands());+ try proto.writeAvailableCommands(w, d.session_id.?, try @import("acp_t3.zig").commands(arena, proto.slashCommands()));return;}if ((d.load_session != null and (std.mem.eql(u8, req.method, "session/prompt") or std.mem.eql(u8, req.method, "session/cancel") or std.mem.eql(u8, req.method, "session/close"))) or@@ -352,9 +347,8 @@ pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const uif (params != .object) return respondError(w, req, -32602, "Invalid configuration option");const id = util.strFieldObj(params.object, "configId") orelse return respondError(w, req, -32602, "Invalid configuration option");const value = util.strFieldObj(params.object, "value") orelse return respondError(w, req, -32602, "Invalid configuration value");- if (!std.mem.eql(u8, id, "thought_level"))- return respondError(w, req, -32602, "Invalid configuration value");- const accepted = d.set_config.?(d.ctx, value) catch |err| return respondError(w, req, err_internal, @errorName(err));+ const setter = if (std.mem.eql(u8, id, "thought_level")) d.set_config.? else if (std.mem.eql(u8, id, "model")) d.set_model orelse return respondError(w, req, -32602, "Invalid configuration value") else return respondError(w, req, -32602, "Invalid configuration value");+ const accepted = setter(d.ctx, value) catch |err| return respondError(w, req, err_internal, @errorName(err));if (!accepted) return respondError(w, req, -32602, "Invalid configuration value");const options = configOptions(d, arena) catch |err| return respondError(w, req, err_internal, @errorName(err));return respond(w, req, .{ .configOptions = options });diff --git a/src/acp_model_option.zig b/src/acp_model_option.zignew file mode 100644index 00000000..0e675ac8--- /dev/null+++ b/src/acp_model_option.zig@@ -0,0 +1,115 @@+//! The `model` config option for T3 Code's model picker (acp_t3.zig): the+//! models this install can reach, in the `graff/models` election order.+//! Values are `<provider>/<model>`; choosing one runs `/model <provider> <model>`.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const engine = @import("acp_engine.zig");+const pricing = @import("pricing.zig");+const billing = @import("billing.zig");+const models_rank = @import("models_rank");+const LiveTurn = @import("acp_live_turn.zig").LiveTurn;++/// Whether two option lists offer and select the same values.+pub fn same(before: []const engine.ConfigOption, after: []const engine.ConfigOption) bool {+ if (before.len != after.len) return false;+ for (before, after) |a, b| {+ if (!std.mem.eql(u8, a.currentValue, b.currentValue) or a.options.len != b.options.len) return false;+ for (a.options, b.options) |av, bv| if (!std.mem.eql(u8, av.value, bv.value)) return false;+ }+ return true;+}++/// T3 shows at most 64 choices per option.+const max_choices = 48;++/// Local catalog state only: stored keys, cached provider lists. No network.+pub fn hydrate(live: *LiveTurn) void {+ const root = live.root;+ root.ensureStoredKeys(live.keys);+ if (root.model_catalog) |*cached|+ cached.ensureCached(root.io, root.gpa, root.arena, root.home, live.keys.get("codex") orelse "", live.keys.codex_account);+ if (!live.local_catalog_loaded) {+ if (root.home.len > 0) @import("router_catalog.zig").loadCachedAll(root.io, root.arena, root.home);+ live.local_catalog_loaded = true;+ }+}++pub const Choice = struct { provider: []const u8, model: []const u8 };++/// Reachable models, best first, with the current one always present.+pub fn choices(arena: Allocator, catalog: []const pricing.ModelInfo, keys: anytype, current: Choice) ![]const Choice {+ const ranked = try arena.alloc(models_rank.Scored, catalog.len);+ for (catalog, 0..) |m, i| ranked[i] = .{+ .idx = i,+ .score = models_rank.electionRank(keys.get(m.provider) != null, billing.costFor(m.provider, keys.source(m.provider))),+ };+ std.mem.sort(models_rank.Scored, ranked, {}, models_rank.scoredLess);+ var out: std.ArrayList(Choice) = .empty;+ try out.append(arena, current);+ for (ranked) |r| {+ if (out.items.len == max_choices) break;+ const m = catalog[r.idx];+ if (keys.get(m.provider) == null) continue;+ if (std.mem.eql(u8, m.provider, current.provider) and std.mem.eql(u8, m.name, current.model)) continue;+ try out.append(arena, .{ .provider = m.provider, .model = m.name });+ }+ return out.items;+}++pub fn option(ctx: *anyopaque, arena: Allocator) anyerror!?engine.ConfigOption {+ if (!@import("acp_t3.zig").active()) return null;+ const live: *LiveTurn = @ptrCast(@alignCast(ctx));+ hydrate(live);+ const root = live.root;+ const list = try choices(arena, pricing.models(), live.keys, .{ .provider = root.provider.id, .model = root.provider.model });+ const values = try arena.alloc(engine.ConfigValue, list.len);+ for (list, values) |c, *v| v.* = .{+ .value = try std.fmt.allocPrint(arena, "{s}/{s}", .{ c.provider, c.model }),+ .name = try std.fmt.allocPrint(arena, "{s} · {s}", .{ c.model, c.provider }),+ };+ return .{ .id = "model", .name = "Model", .category = "model", .currentValue = values[0].value, .options = values };+}++pub fn set(ctx: *anyopaque, value: []const u8) anyerror!bool {+ if (!@import("acp_t3.zig").active()) return false;+ const live: *LiveTurn = @ptrCast(@alignCast(ctx));+ const root = live.root;+ const cut = std.mem.indexOfScalar(u8, value, '/') orelse return false;+ const provider = value[0..cut];+ const model = value[cut + 1 ..];+ if (provider.len == 0 or model.len == 0 or std.mem.indexOfAny(u8, value, " \t\r\n") != null) return false;+ if (std.mem.eql(u8, provider, root.provider.id) and std.mem.eql(u8, model, root.provider.model)) return true;+ // The switched provider keeps slices of this line: allocate where the agent lives.+ const arena = root.arena;+ var sink: Io.Writer.Allocating = .init(root.gpa);+ defer sink.deinit();+ const line = try std.fmt.allocPrint(arena, "/model {s} {s}", .{ provider, model });+ try @import("main.zig").handleCommand(root, live.keys, arena, line, &sink.writer);+ return std.mem.eql(u8, root.provider.id, provider) and std.mem.eql(u8, root.provider.model, model);+}++test "model choices: reachable models only, current first, capped" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const Keys = struct {+ fn get(_: @This(), provider: []const u8) ?[]const u8 {+ return if (std.mem.eql(u8, provider, "codex") or std.mem.eql(u8, provider, "codegraff")) "k" else null;+ }+ fn source(_: @This(), _: []const u8) @import("provider.zig").Keys.CredentialSource {+ return .login;+ }+ };+ const catalog = [_]pricing.ModelInfo{+ .{ .provider = "anthropic", .name = "opus", .context = 1 },+ .{ .provider = "codex", .name = "gpt-a", .context = 1 },+ .{ .provider = "codegraff", .name = "kimi", .context = 1 },+ .{ .provider = "codex", .name = "gpt-b", .context = 1 },+ };+ const list = try choices(a, &catalog, Keys{}, .{ .provider = "codex", .model = "gpt-b" });+ try std.testing.expectEqual(@as(usize, 3), list.len);+ try std.testing.expectEqualStrings("gpt-b", list[0].model);+ for (list) |c| try std.testing.expect(!std.mem.eql(u8, c.provider, "anthropic"));+}diff --git a/src/acp_session_load.zig b/src/acp_session_load.zigindex ef2f214b..00006602 100644--- a/src/acp_session_load.zig+++ b/src/acp_session_load.zig@@ -21,6 +21,8 @@ pub fn configure(d: *engine.Dispatch, live: *LiveTurn) void {d.load_session = load;d.config = @import("acp_config.zig").option;d.set_config = @import("acp_config.zig").set;+ d.model_config = @import("acp_model_option.zig").option;+ d.set_model = @import("acp_model_option.zig").set;d.durable_session_id = if (session.validSessionName(live.root.session_name)) live.root.session_name else null;d.durable_name = durableName;live.dispatch = d;@@ -111,7 +113,7 @@ pub fn load(ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Requestif (!v2.on() or replayFromStart(params)) try replayHistory(arena, live.root, w, live.session_id);const options = engine.configOptions(d, arena) catch |err| return proto.writeError(w, req.id, engine.err_internal, @errorName(err));try proto.writeResult(w, req.id, .{ .configOptions = options, ._meta = acp_workspace.meta(env, arena) });- try proto.writeAvailableCommands(w, live.session_id, proto.slashCommands());+ try proto.writeAvailableCommands(w, live.session_id, try @import("acp_t3.zig").commands(arena, proto.slashCommands()));}/// #1557: the save parsed and its fields are present, so a failure here isdiff --git a/src/acp_t3.zig b/src/acp_t3.zignew file mode 100644index 00000000..48dcdbe1--- /dev/null+++ b/src/acp_t3.zig@@ -0,0 +1,127 @@+//! ACP client profile for T3 Code (`clientInfo.name` "t3-code…"). T3 owns+//! the session folder, worktrees, model choice and approval mode, and it+//! appends its own context block to every prompt. These hooks fit graff's v1+//! session to that; every other client keeps the default behavior.++const std = @import("std");+const Allocator = std.mem.Allocator;+const Value = std.json.Value;+const util = @import("util.zig");+const proto = @import("acp_protocol.zig");++var on: bool = false;++/// Read once per `initialize`; T3's probes use suffixed names ("t3-code-provider-test").+pub fn note(params: ?Value) void {+ on = isT3(params);+}++pub fn active() bool {+ return on;+}++fn isT3(params: ?Value) bool {+ const p = params orelse return false;+ if (p != .object) return false;+ const info = p.object.get("clientInfo") orelse return false;+ if (info != .object) return false;+ const name = util.strFieldObj(info.object, "name") orelse return false;+ return std.mem.startsWith(u8, name, "t3-code");+}++/// T3 sends a slash command as the first text block and appends a context+/// block after it; the command is that first block alone. Anything else+/// (including room-framed text) passes through unchanged.+pub fn slashText(prompt: ?Value, flattened: []const u8, framed: []const u8) []const u8 {+ if (!on or !std.mem.eql(u8, flattened, framed)) return framed;+ const blocks = prompt orelse return framed;+ if (blocks != .array or blocks.array.items.len < 2) return framed;+ const first = blocks.array.items[0];+ if (first != .object or !std.mem.eql(u8, util.strFieldObj(first.object, "type") orelse "", "text")) return framed;+ const text = util.strFieldObj(first.object, "text") orelse return framed;+ return if (std.mem.startsWith(u8, std.mem.trimStart(u8, text, " \t\r\n"), "/")) text else framed;+}++/// T3 renders replies as Markdown, which folds a command's table into one+/// paragraph; multi-line command output goes out as a text block.+pub fn slashReply(arena: Allocator, plain: []const u8) ![]const u8 {+ if (!on or std.mem.indexOfScalar(u8, std.mem.trim(u8, plain, "\n"), '\n') == null) return plain;+ return std.fmt.allocPrint(arena, "```text\n{s}\n```", .{std.mem.trimEnd(u8, plain, "\n")});+}++/// T3 diffs and checkpoints the folder it names; graff's auto-isolated tree+/// would hide every edit from it.+pub fn keepsIsolatedTree() bool {+ return !on;+}++/// T3 has its own `/model` (driven by the model config option) and its own+/// approval modes, which `/yolo` would silently bypass.+const hidden = [_][]const u8{ "model", "yolo" };++pub fn commands(arena: Allocator, all: []const proto.AvailableCommand) ![]const proto.AvailableCommand {+ if (!on) return all;+ var out: std.ArrayList(proto.AvailableCommand) = .empty;+ outer: for (all) |c| {+ for (hidden) |h| if (std.mem.eql(u8, c.name, h)) continue :outer;+ try out.append(arena, c);+ }+ return out.items;+}++test "profile turns on only for T3 Code's client names" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ defer on = false;+ for ([_][]const u8{ "{\"clientInfo\":{\"name\":\"t3-code\"}}", "{\"clientInfo\":{\"name\":\"t3-code-provider-test\"}}" }) |json| {+ note(try std.json.parseFromSliceLeaky(Value, a, json, .{}));+ try std.testing.expect(active());+ }+ for ([_][]const u8{ "{\"clientInfo\":{\"name\":\"zed\"}}", "{}", "{\"clientInfo\":\"t3-code\"}" }) |json| {+ note(try std.json.parseFromSliceLeaky(Value, a, json, .{}));+ try std.testing.expect(!active());+ }+ note(null);+ try std.testing.expect(!active());+}++test "T3 slash command is the first block; context, prose and room text pass through" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ defer on = false;+ const prompt = try std.json.parseFromSliceLeaky(Value, a, "[{\"type\":\"text\",\"text\":\"/models\"},{\"type\":\"text\",\"text\":\"<runtime_info>x</runtime_info>\"}]", .{});+ const flat = "/models\n\n<runtime_info>x</runtime_info>";+ try std.testing.expectEqualStrings(flat, slashText(prompt, flat, flat)); // other clients+ on = true;+ try std.testing.expectEqualStrings("/models", slashText(prompt, flat, flat));+ try std.testing.expectEqualStrings("[room] /models", slashText(prompt, flat, "[room] /models"));+ const prose = try std.json.parseFromSliceLeaky(Value, a, "[{\"type\":\"text\",\"text\":\"fix it\"},{\"type\":\"text\",\"text\":\"ctx\"}]", .{});+ try std.testing.expectEqualStrings("fix it\n\nctx", slashText(prose, "fix it\n\nctx", "fix it\n\nctx"));+}++test "T3 fences multi-line command output; one-liners and other clients unchanged" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ defer on = false;+ try std.testing.expectEqualStrings("a\nb\n", try slashReply(a, "a\nb\n"));+ on = true;+ try std.testing.expectEqualStrings("```text\na\nb\n```", try slashReply(a, "a\nb\n"));+ try std.testing.expectEqualStrings("effort: high\n", try slashReply(a, "effort: high\n"));+}++test "T3 hides its own duplicates from the command list and drops isolated trees" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ defer on = false;+ const all = proto.slashCommands();+ try std.testing.expect(keepsIsolatedTree());+ try std.testing.expectEqual(all.len, (try commands(arena_state.allocator(), all)).len);+ on = true;+ try std.testing.expect(!keepsIsolatedTree());+ const shown = try commands(arena_state.allocator(), all);+ try std.testing.expectEqual(all.len - hidden.len, shown.len);+ for (shown) |c| for (hidden) |h| try std.testing.expect(!std.mem.eql(u8, c.name, h));+}diff --git a/src/acp_t3_tests.zig b/src/acp_t3_tests.zignew file mode 100644index 00000000..d7b5a1d0--- /dev/null+++ b/src/acp_t3_tests.zig@@ -0,0 +1,86 @@+//! T3 Code profile through the engine.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const engine = @import("acp_engine.zig");+const t3 = @import("acp_t3.zig");++test {+ _ = @import("acp_model_option.zig");+ _ = t3;+}++const Fixture = struct {+ slashed: []const u8 = "",+ picked: []const u8 = "codex/gpt-a",+ fn turn(_: *anyopaque, _: Allocator, _: []const u8) anyerror![]const u8 {+ return "done";+ }+ fn slash(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror!?[]const u8 {+ const self: *@This() = @ptrCast(@alignCast(ctx));+ self.slashed = try arena.dupe(u8, text);+ return if (std.mem.eql(u8, text, "/models")) "models table" else null;+ }+ fn effort(_: *anyopaque, _: Allocator) anyerror!?engine.ConfigOption {+ return .{ .currentValue = "medium", .options = &.{.{ .value = "medium", .name = "Medium" }} };+ }+ fn setEffort(_: *anyopaque, _: []const u8) anyerror!bool {+ return true;+ }+ fn model(ctx: *anyopaque, _: Allocator) anyerror!?engine.ConfigOption {+ if (!t3.active()) return null;+ const self: *@This() = @ptrCast(@alignCast(ctx));+ return .{ .id = "model", .name = "Model", .category = "model", .currentValue = self.picked, .options = &.{ .{ .value = "codex/gpt-a", .name = "gpt-a" }, .{ .value = "codex/gpt-b", .name = "gpt-b" } } };+ }+ fn setModel(ctx: *anyopaque, value: []const u8) anyerror!bool {+ if (!t3.active()) return false;+ const self: *@This() = @ptrCast(@alignCast(ctx));+ self.picked = value;+ return true;+ }+};++fn run(d: *engine.Dispatch, a: Allocator, buf: []u8, line: []const u8) ![]const u8 {+ var w: Io.Writer = .fixed(buf);+ try engine.handleLine(d, a, &w, line);+ return w.buffered();+}++test "T3 Code profile: first-block slash, model option, trimmed commands; others unchanged" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ defer t3.note(null);+ var buf: [65536]u8 = undefined;+ const prompt = "{\"id\":3,\"method\":\"session/prompt\",\"params\":{\"sessionId\":\"acp-1-1\",\"prompt\":[{\"type\":\"text\",\"text\":\"/models\"},{\"type\":\"text\",\"text\":\"<runtime_info>ctx</runtime_info>\"}]}}";+ const pick = "{\"id\":4,\"method\":\"session/set_config_option\",\"params\":{\"sessionId\":\"acp-1-1\",\"configId\":\"model\",\"value\":\"codex/gpt-b\"}}";++ // Another client: whole prompt reaches the slash handler, no model option.+ var plain: Fixture = .{};+ var d: engine.Dispatch = .{ .turn = Fixture.turn, .ctx = &plain, .seed = 1, .slash = Fixture.slash, .config = Fixture.effort, .set_config = Fixture.setEffort, .model_config = Fixture.model, .set_model = Fixture.setModel };+ _ = try run(&d, a, &buf, "{\"id\":1,\"method\":\"initialize\",\"params\":{\"clientInfo\":{\"name\":\"zed\"}}}");+ var out = try run(&d, a, &buf, "{\"id\":2,\"method\":\"session/new\"}");+ try std.testing.expect(std.mem.indexOf(u8, out, "\"category\":\"model\"") == null);+ try std.testing.expect(std.mem.indexOf(u8, out, "\"name\":\"model\"") != null);+ _ = try run(&d, a, &buf, prompt);+ try std.testing.expect(std.mem.indexOf(u8, plain.slashed, "<runtime_info>") != null);+ out = try run(&d, a, &buf, pick);+ try std.testing.expect(std.mem.indexOf(u8, out, "\"code\":-32602") != null);++ // T3 Code: the command alone, the model picker, and no duplicate /model.+ var tee: Fixture = .{};+ d = .{ .turn = Fixture.turn, .ctx = &tee, .seed = 1, .slash = Fixture.slash, .config = Fixture.effort, .set_config = Fixture.setEffort, .model_config = Fixture.model, .set_model = Fixture.setModel };+ _ = try run(&d, a, &buf, "{\"id\":1,\"method\":\"initialize\",\"params\":{\"clientInfo\":{\"name\":\"t3-code\"}}}");+ out = try run(&d, a, &buf, "{\"id\":2,\"method\":\"session/new\"}");+ try std.testing.expect(std.mem.indexOf(u8, out, "\"category\":\"model\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "\"category\":\"thought_level\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "\"name\":\"model\"") == null);+ try std.testing.expect(std.mem.indexOf(u8, out, "\"name\":\"yolo\"") == null);+ out = try run(&d, a, &buf, prompt);+ try std.testing.expectEqualStrings("/models", tee.slashed);+ try std.testing.expect(std.mem.indexOf(u8, out, "models table") != null);+ out = try run(&d, a, &buf, pick);+ try std.testing.expectEqualStrings("codex/gpt-b", tee.picked);+ try std.testing.expect(std.mem.indexOf(u8, out, "\"currentValue\":\"codex/gpt-b\"") != null);+}diff --git a/src/acp_workspace.zig b/src/acp_workspace.zigindex 01771c9f..fff6f8b4 100644--- a/src/acp_workspace.zig+++ b/src/acp_workspace.zig@@ -113,7 +113,7 @@ pub fn adopt(env: Env, arena: Allocator, params: ?Value) AdoptError!void {dir.close(env.io);const active = workspace_switch.currentAbs(env.io, arena);if (workspace_switch.samePath(env.io, want, active)) return;- if (info(env, arena)) |tree| if (workspace_switch.samePath(env.io, want, tree.root)) return;+ if (@import("acp_t3.zig").keepsIsolatedTree()) if (info(env, arena)) |tree| if (workspace_switch.samePath(env.io, want, tree.root)) return;_ = workspace_switch.enterPath(env.gpa, env.io, arena, want) catch |err|return if (err == error.OutOfMemory) error.OutOfMemory else error.ChdirFailed;}diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 9b742058..cf3714f4 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -358,6 +358,7 @@ test {_ = @import("experiment_pool.zig");_ = @import("commands_experiment.zig");_ = @import("acp_engine.zig");+ _ = @import("acp_t3_tests.zig"); // T3 Code profile_ = @import("acp_config.zig");_ = @import("session_start_plugins_test.zig");_ = @import("acp_mcp_servers.zig");