@visual-z/xeno 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +7 -3
  3. package/docs/app-server.md +32 -3
  4. package/docs/foundations.md +88 -0
  5. package/docs/install.md +23 -2
  6. package/docs/research/foundation-clients-2026-10-09.md +27 -0
  7. package/docs/research/foundation-editing-2026-10-09.md +56 -0
  8. package/docs/research/foundation-network-2026-10-09.md +37 -0
  9. package/docs/research/foundation-workflow-2026-10-09.md +37 -0
  10. package/package.json +10 -2
  11. package/src/apps/acp-server.ts +41 -0
  12. package/src/apps/agent-profiles.ts +19 -0
  13. package/src/apps/app-server.ts +4 -2
  14. package/src/apps/cli.ts +18 -2
  15. package/src/apps/commands.ts +20 -0
  16. package/src/apps/control-transport.ts +3 -2
  17. package/src/apps/model-catalog.ts +57 -31
  18. package/src/apps/question-ui.ts +27 -0
  19. package/src/apps/resources.ts +63 -25
  20. package/src/apps/review.ts +109 -0
  21. package/src/apps/session-hub.ts +84 -0
  22. package/src/apps/shell.ts +54 -0
  23. package/src/apps/startup.ts +157 -22
  24. package/src/apps/ui/app.ts +21 -22
  25. package/src/apps/ui/surface.ts +1 -0
  26. package/src/apps/update-check.ts +71 -0
  27. package/src/apps/workflow.ts +58 -0
  28. package/src/core/agent-profile.ts +130 -0
  29. package/src/core/control-protocol.ts +8 -1
  30. package/src/core/file-precondition.ts +6 -0
  31. package/src/core/lsp-framing.ts +34 -0
  32. package/src/core/mcp-config.ts +68 -0
  33. package/src/core/patch.ts +130 -0
  34. package/src/core/permissions.ts +143 -4
  35. package/src/core/question.ts +94 -0
  36. package/src/core/review.ts +68 -0
  37. package/src/core/update-check.ts +24 -5
  38. package/src/core/web-content.ts +80 -0
  39. package/src/core/workflow-mode.ts +34 -0
  40. package/src/runtime/acp-agent.ts +289 -0
  41. package/src/runtime/agent-profiles.ts +21 -0
  42. package/src/runtime/catalog.ts +2 -2
  43. package/src/runtime/control-client.ts +149 -0
  44. package/src/runtime/control-connection.ts +39 -4
  45. package/src/runtime/extensions.ts +20 -2
  46. package/src/runtime/formatter-tool.ts +38 -0
  47. package/src/runtime/formatter.ts +50 -0
  48. package/src/runtime/foundation.ts +78 -0
  49. package/src/runtime/integrations.ts +8 -2
  50. package/src/runtime/loop.ts +68 -10
  51. package/src/runtime/lsp-client.ts +201 -0
  52. package/src/runtime/mcp-client.ts +264 -0
  53. package/src/runtime/mcp-oauth.ts +168 -0
  54. package/src/runtime/mcp-schema.ts +51 -0
  55. package/src/runtime/oauth.ts +1 -1
  56. package/src/runtime/output-schema.ts +26 -0
  57. package/src/runtime/patch-tool.ts +38 -0
  58. package/src/runtime/permission-resources.ts +11 -0
  59. package/src/runtime/provider.ts +2 -0
  60. package/src/runtime/question-tool.ts +62 -0
  61. package/src/runtime/review-tool.ts +48 -0
  62. package/src/runtime/session-control.ts +60 -2
  63. package/src/runtime/session-hub.ts +85 -0
  64. package/src/runtime/tool-discovery.ts +4 -3
  65. package/src/runtime/tools.ts +37 -7
  66. package/src/runtime/update-check.ts +3 -2
  67. package/src/runtime/web-http.ts +56 -0
  68. package/src/runtime/web-tools.ts +88 -0
  69. package/src/runtime/workspace-lifecycle.ts +14 -1
  70. package/src/store/agent-profile-files.ts +13 -0
  71. package/src/store/context-files.ts +77 -1
  72. package/src/store/file-checkpoints.ts +5 -4
  73. package/src/store/foundation-config.ts +24 -0
  74. package/src/store/lsp-document.ts +30 -0
  75. package/src/store/mcp-credentials.ts +85 -0
  76. package/src/store/patch.ts +92 -0
  77. package/src/store/permission-paths.ts +34 -0
  78. package/src/store/review.ts +109 -0
  79. package/src/store/search.ts +48 -9
@@ -0,0 +1,289 @@
1
+ /** ACP is a transport over the existing session owner, never a second agent loop (Q24/D8). */
2
+ import { isAbsolute, resolve } from "node:path";
3
+ import { agent, PROTOCOL_VERSION, RequestError, type AgentApp, type AgentConnection, type AgentContext,
4
+ type ClientCapabilities, type ContentBlock, type ElicitationPropertySchema, type McpServer,
5
+ type SessionModeState, type SessionUpdate, type StopReason, type ToolCall, type RequestPermissionResponse } from "@agentclientprotocol/sdk";
6
+ import { CONTROL_SCHEMA } from "../core/control-protocol.ts";
7
+ import { parseMcpServers, type McpServers } from "../core/mcp-config.ts";
8
+ import type { LogEvent } from "../core/events.ts";
9
+ import type { QuestionRequest, QuestionReply } from "../core/question.ts";
10
+ import type { ExecutionOutcome } from "../core/outcome.ts";
11
+ import type { PendingApproval, SessionControl } from "./session-control.ts";
12
+ import type { ApprovalChoice } from "./tools.ts";
13
+ import type { SessionHub } from "./session-hub.ts";
14
+
15
+ function invalid(message: string): never { throw RequestError.invalidParams(undefined, message); }
16
+ function object(value: unknown): Record<string, unknown> | undefined {
17
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
18
+ }
19
+
20
+ /** Normalize explicit client configuration; annotations and tool output cannot configure processes. */
21
+ export function acpMcpServers(servers: readonly McpServer[]): McpServers {
22
+ const result: Record<string, unknown> = Object.create(null);
23
+ for (const server of servers) {
24
+ if (Object.hasOwn(result, server.name)) invalid("MCP server names must be unique");
25
+ if ("type" in server) {
26
+ if (server.type !== "http") invalid("This agent supports stdio and HTTP MCP servers only");
27
+ result[server.name] = { transport: "http", url: server.url, headers: pairs(server.headers) };
28
+ } else result[server.name] = { transport: "stdio", command: server.command, args: [...server.args], env: pairs(server.env) };
29
+ }
30
+ try { return parseMcpServers(result); } catch { return invalid("Invalid MCP server configuration"); }
31
+ }
32
+ function pairs(values: readonly { name: string; value: string }[]): Record<string, string> {
33
+ const result: Record<string, string> = Object.create(null);
34
+ for (const value of values) {
35
+ if (Object.hasOwn(result, value.name)) invalid("Duplicate MCP environment or header name");
36
+ result[value.name] = value.value;
37
+ }
38
+ return result;
39
+ }
40
+ function modes(control: SessionControl): SessionModeState | undefined {
41
+ return control.configureWorkflow ? { currentModeId: control.session.config.tools.workflowMode ?? "build", availableModes: [
42
+ { id: "build", name: "Build", description: "Implement and verify workspace changes." },
43
+ { id: "plan", name: "Plan", description: "Inspect and plan with read-only tools." },
44
+ ] } : undefined;
45
+ }
46
+ function promptText(blocks: readonly ContentBlock[]): string {
47
+ const parts = blocks.map(block => {
48
+ if (block.type === "text") return block.text;
49
+ // Baseline resource links remain references. Reading them goes through the normal tool admission.
50
+ if (block.type === "resource_link") return `Resource ${JSON.stringify(block.name)}: ${JSON.stringify(block.uri)}${block.description ? `\n${block.description}` : ""}`;
51
+ if (block.type === "resource" && "text" in block.resource) return `Resource ${JSON.stringify(block.resource.uri)}:\n${block.resource.text}`;
52
+ return invalid("This agent accepts text, resource links and embedded text; image/audio/binary prompts are unavailable");
53
+ });
54
+ const text = parts.join("\n\n");
55
+ if (!text.trim() || Buffer.byteLength(text) > CONTROL_SCHEMA.limits.frameBytes) invalid("Prompt must contain text within the ACP message limit");
56
+ return text;
57
+ }
58
+ function stopReason(outcome: ExecutionOutcome | undefined, cancelled: boolean): StopReason {
59
+ if (cancelled || outcome?.status === "cancelled") return "cancelled";
60
+ if (outcome?.reason === "model_refusal") return "refusal";
61
+ if (outcome?.reason === "output_limit") return "max_tokens";
62
+ if (outcome?.status === "completed") return "end_turn";
63
+ if (outcome?.status === "stopped") return "max_turn_requests";
64
+ throw RequestError.internalError(undefined, "The session failed or its termination is unknown; inspect the durable outcome");
65
+ }
66
+ function title(name: string, input: unknown): string {
67
+ const raw = object(input), detail = raw?.["cmd"] ?? raw?.["command"] ?? raw?.["path"];
68
+ return typeof detail === "string" ? `${name}: ${detail}` : name;
69
+ }
70
+ function kind(name: string): ToolCall["kind"] {
71
+ if (["read", "diff"].includes(name)) return "read";
72
+ if (["write", "edit", "apply_patch", "format"].includes(name)) return "edit";
73
+ if (["bash", "exec_command", "write_stdin"].includes(name)) return "execute";
74
+ if (["search", "glob", "grep"].includes(name)) return "search";
75
+ if (["webfetch", "websearch"].includes(name)) return "fetch";
76
+ return "other";
77
+ }
78
+ function content(text: string) { return [{ type: "content" as const, content: { type: "text" as const, text } }]; }
79
+
80
+ /** SDK cancellation is cooperative; a peer ignoring it cannot hold the tool owner indefinitely. */
81
+ async function cancellable<T>(request: Promise<T>, signal: AbortSignal): Promise<T | undefined> {
82
+ if (signal.aborted) { void request.catch(() => {}); return undefined; }
83
+ let cancel = () => {};
84
+ const aborted = new Promise<undefined>(done => { cancel = () => done(undefined); signal.addEventListener("abort", cancel, { once: true }); });
85
+ try { return await Promise.race([request, aborted]); } finally { signal.removeEventListener("abort", cancel); }
86
+ }
87
+
88
+ async function elicit(client: AgentContext, sessionId: string, toolCallId: string, request: QuestionRequest, signal: AbortSignal): Promise<QuestionReply | undefined> {
89
+ const properties: Record<string, ElicitationPropertySchema> = Object.create(null), required: string[] = [];
90
+ request.questions.forEach((question, index) => {
91
+ const key = `q${index}`, options = question.options.map(option => ({ const: option.id, title: option.label,
92
+ ...(option.description ? { description: option.description } : {}) }));
93
+ if (options.length) {
94
+ properties[key] = question.multiple ? { type: "array", title: question.header, description: question.question,
95
+ items: { anyOf: options }, minItems: question.custom ? 0 : 1, maxItems: options.length } :
96
+ { type: "string", title: question.header, description: question.question, oneOf: options };
97
+ if (!question.custom) required.push(key);
98
+ }
99
+ if (question.custom || !options.length) {
100
+ properties[`${key}_text`] = { type: "string", title: `${question.header}: your answer`, description: question.question, minLength: 1 };
101
+ if (!options.length) required.push(`${key}_text`);
102
+ }
103
+ });
104
+ const response = await cancellable(client.request("elicitation/create", { sessionId, toolCallId, mode: "form",
105
+ message: request.questions.map(question => question.question).join("\n"), requestedSchema: { type: "object", properties, required } },
106
+ { cancellationSignal: signal }), signal);
107
+ if (response?.action !== "accept") return undefined;
108
+ const answers = object(response["content"]);
109
+ if (!answers || Object.keys(answers).some(key => !Object.hasOwn(properties, key))) return undefined;
110
+ return { request_id: request.request_id, turn_id: request.turn_id, answers: request.questions.map((question, index) => {
111
+ const value = answers[`q${index}`], text = answers[`q${index}_text`];
112
+ return { id: question.id, choices: typeof value === "string" ? [value] : Array.isArray(value) && value.every(item => typeof item === "string") ? value : [],
113
+ ...(typeof text === "string" && text.trim() ? { text } : {}) };
114
+ }) };
115
+ }
116
+
117
+ interface Binding {
118
+ control: SessionControl;
119
+ abort: AbortController | null;
120
+ pending: Map<string, ToolCall>;
121
+ send(update: SessionUpdate): void;
122
+ replay(node: number, event: LogEvent): void;
123
+ drain(): Promise<void>;
124
+ close(): void;
125
+ }
126
+
127
+ /** One AgentApp serves one client connection. Each workspace has an explicit host-owned hub. */
128
+ export function createAcpAgent(hub: SessionHub): AgentApp {
129
+ const app = agent({ name: "xeno" }), bindings = new Map<string, Binding>();
130
+ let connection: AgentConnection | undefined, initialized = false, capabilities: ClientCapabilities = {};
131
+ let inFlight = 0;
132
+ const admit = async <T>(operation: () => Promise<T>): Promise<T> => {
133
+ // Assumed ingress cap: SDK schema validation bounds frames, not concurrent async handlers.
134
+ if (inFlight >= CONTROL_SCHEMA.limits.queuedRequests) throw RequestError.invalidRequest(undefined, "ACP request concurrency limit exceeded");
135
+ inFlight++; try { return await operation(); } finally { inFlight--; }
136
+ };
137
+ const requireInitialized = () => { if (!initialized || !connection || connection.signal.aborted) throw RequestError.invalidRequest(undefined, "initialize must complete before session requests"); };
138
+ const workspace = (params: { cwd: string; additionalDirectories?: string[]; mcpServers: McpServer[] }) => {
139
+ requireInitialized();
140
+ if (!isAbsolute(params.cwd) || resolve(params.cwd) !== resolve(hub.initial.session.config.tools.root))
141
+ invalid("cwd must match this agent process workspace; start one process per workspace");
142
+ if (params.additionalDirectories?.length) invalid("Additional workspace directories are unavailable");
143
+ return { cwd: params.cwd, acpMcpServers: acpMcpServers(params.mcpServers) };
144
+ };
145
+ const get = (id: string) => { requireInitialized(); const value = bindings.get(id); if (!value) throw RequestError.resourceNotFound(id); return value; };
146
+ const bind = (control: SessionControl): Binding => {
147
+ const existing = bindings.get(control.threadId); if (existing) return existing;
148
+ const peer = connection!;
149
+ let queuedBytes = 0, tail: Promise<void> = Promise.resolve(), deliveryError: unknown;
150
+ const pending = new Map<string, ToolCall>(), originalInputs = new Map<string, unknown>();
151
+ const send = (update: SessionUpdate) => {
152
+ const bytes = Buffer.byteLength(JSON.stringify(update)); queuedBytes += bytes;
153
+ if (bytes > CONTROL_SCHEMA.limits.frameBytes || queuedBytes > CONTROL_SCHEMA.limits.outputBytes) { peer.close(Error("ACP output queue exceeded its limit")); return; }
154
+ tail = tail.then(async () => { if (deliveryError) return; await peer.client.notify("session/update", { sessionId: control.threadId, update }); })
155
+ .catch(error => { deliveryError = error; peer.close(Error("ACP notification delivery failed")); })
156
+ .finally(() => { queuedBytes -= bytes; });
157
+ };
158
+ const record = (node: number, event: LogEvent, replay = false) => {
159
+ if (event.t === "user" && replay) send({ sessionUpdate: "user_message_chunk", content: { type: "text", text: event.text }, messageId: `${node}:${event.id}` });
160
+ if (event.t === "assistant" && replay) for (const block of event.blocks) if (block.type === "text")
161
+ send({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: block.text }, messageId: `${node}:${event.id}` });
162
+ if (event.t === "assistant") for (const block of event.blocks) if (block.type === "tool_use") originalInputs.set(`${node}:${block.call_id}`, block.input);
163
+ if (event.t === "tool_invocation") {
164
+ // Unchanged direct calls omit inline input; recover it from the original model request.
165
+ const key = `${node}:${event.call_id}`, input = event.input ?? originalInputs.get(key); originalInputs.delete(key);
166
+ const call: ToolCall = { toolCallId: `${node}:${event.id}`, name: event.name, title: title(event.name, input), kind: kind(event.name)!, status: "pending",
167
+ ...(input !== undefined ? { rawInput: input } : {}) };
168
+ pending.set(`${node}:${event.call_id}`, call); send({ sessionUpdate: "tool_call", ...call });
169
+ }
170
+ if (event.t === "tool_result") {
171
+ const key = `${node}:${event.call_id}`, call = pending.get(key);
172
+ if (!call) {
173
+ send({ sessionUpdate: "tool_call", toolCallId: `${node}:${event.id}`, title: "Recorded tool result", status: "pending" });
174
+ }
175
+ send({ sessionUpdate: "tool_call_update", toolCallId: call?.toolCallId ?? `${node}:${event.id}`,
176
+ status: event.ok && (!event.outcome || event.outcome.status === "completed") ? "completed" : "failed", content: content(event.content), rawOutput: event.data ?? event.content });
177
+ pending.delete(key);
178
+ }
179
+ };
180
+ const permission = async (approval: PendingApproval) => {
181
+ const abort = binding.abort; if (!abort || abort.signal.aborted || peer.signal.aborted) return;
182
+ const request = approval.request;
183
+ const matches = [...pending.values()].filter(call => call.name === request.tool &&
184
+ (!request.command || object(call.rawInput)?.["cmd"] === request.command || object(call.rawInput)?.["command"] === request.command));
185
+ const call = matches.length === 1 ? matches[0]! : undefined;
186
+ const toolCall = { toolCallId: call?.toolCallId ?? `permission:${approval.id}`, name: request.tool,
187
+ title: title(request.tool, request), status: "pending" as const,
188
+ rawInput: call?.rawInput ?? request, ...(request.paths ? { locations: request.paths.map(path => ({ path: resolve(control.session.config.tools.root, path) })) } : {}) };
189
+ if (!call) send({ sessionUpdate: "tool_call", ...toolCall });
190
+ let choice: ApprovalChoice = "deny";
191
+ try {
192
+ await binding.drain();
193
+ if (abort.signal.aborted || peer.signal.aborted) return;
194
+ const response = await cancellable(peer.client.request<RequestPermissionResponse>("session/request_permission", { sessionId: control.threadId, toolCall,
195
+ options: [{ optionId: "once", name: "Allow once", kind: "allow_once" }, { optionId: "deny", name: "Reject", kind: "reject_once" }] },
196
+ { cancellationSignal: abort.signal }), abort.signal);
197
+ if (response?.outcome.outcome === "selected" && response.outcome.optionId === "once") choice = "once";
198
+ } catch { /* A failed permission request denies the original invocation; never retry it. */ }
199
+ if (!abort.signal.aborted && control.activeTurnId === approval.turnId) {
200
+ try { control.respond(approval.turnId, approval.id, choice); } catch { /* another legitimate client/cancel already resolved it */ }
201
+ }
202
+ if (!call) send({ sessionUpdate: "tool_call_update", toolCallId: toolCall.toolCallId, status: choice === "once" ? "completed" : "failed" });
203
+ };
204
+ const previousAsk = control.session.config.tools.askSlot?.current;
205
+ const ask = (request: Parameters<SessionControl["ask"]>[0]) => control.ask(request);
206
+ const askSlot = control.session.config.tools.askSlot;
207
+ if (askSlot) askSlot.current = ask;
208
+ const slot = control.questionSlot, previousQuestion = slot.current;
209
+ const question = (request: QuestionRequest, signal: AbortSignal) => control.askQuestion(request, signal,
210
+ value => elicit(peer.client, control.threadId, pending.get(`${control.session.state.node}:${value.call_id}`)?.toolCallId ?? value.call_id, value, signal));
211
+ // Capability negotiation must precede installation; unsupported form questions fail explicitly.
212
+ if (capabilities.elicitation?.form != null) slot.current = question;
213
+ const unsubscribe = control.subscribe(notice => {
214
+ if (notice.method === "approval/request") void permission(notice.params["approval"] as PendingApproval);
215
+ if (notice.method === "item/completed") {
216
+ const item = notice.params["item"] as { id: string; node: number };
217
+ const event = control.session.state.events.find(value => value.id === item.id);
218
+ if (event) record(item.node, event);
219
+ }
220
+ });
221
+ const binding: Binding = { control, abort: null, pending, send, replay: (node, event) => record(node, event, true), drain: async () => { await tail; if (deliveryError) throw RequestError.internalError(undefined, "ACP notification delivery failed"); },
222
+ close: () => { binding.abort?.abort(); if (control.activeTurnId && binding.abort) control.interrupt(control.activeTurnId); unsubscribe();
223
+ if (askSlot?.current === ask) { if (previousAsk) askSlot.current = previousAsk; else delete askSlot.current; }
224
+ if (slot.current === question) { if (previousQuestion) slot.current = previousQuestion; else delete slot.current; }
225
+ } };
226
+ bindings.set(control.threadId, binding);
227
+ return binding;
228
+ };
229
+ app.onConnect(peer => {
230
+ if (connection && !connection.signal.aborted) throw Error("ACP AgentApp already has a client connection");
231
+ connection = peer; initialized = false; capabilities = {};
232
+ peer.signal.addEventListener("abort", () => { for (const binding of bindings.values()) binding.close(); bindings.clear(); }, { once: true });
233
+ });
234
+ app.onRequest("initialize", ({ params }) => {
235
+ if (initialized) throw RequestError.invalidRequest(undefined, "Connection is already initialized");
236
+ if (params.protocolVersion < 1) invalid("ACP protocol version 1 is required");
237
+ capabilities = params.clientCapabilities ?? {}; initialized = true;
238
+ return { protocolVersion: PROTOCOL_VERSION, agentInfo: { name: "xeno", version: "0.1.0" },
239
+ agentCapabilities: { loadSession: true, promptCapabilities: { embeddedContext: true }, mcpCapabilities: { http: true }, sessionCapabilities: { close: {} } } };
240
+ });
241
+ app.onRequest("session/new", ({ params, signal }) => admit(async () => {
242
+ const forwarded = workspace(params), control = await hub.open("new", forwarded);
243
+ if (signal.aborted || connection!.signal.aborted) { await hub.close(control.threadId); throw RequestError.requestCancelled(); }
244
+ bind(control); const state = modes(control);
245
+ return { sessionId: control.threadId, ...(state ? { modes: state } : {}) };
246
+ }));
247
+ app.onRequest("session/load", ({ params, signal }) => admit(async () => {
248
+ const forwarded = workspace(params), control = await hub.open("resume", { ...forwarded, session: params.sessionId });
249
+ if (signal.aborted || connection!.signal.aborted) throw RequestError.requestCancelled();
250
+ if (control.busy) throw RequestError.invalidRequest(undefined, "Cannot replay a session with an active turn");
251
+ const binding = bind(control);
252
+ // Replay durable original messages/results only. Loading never executes tools or sends provider requests.
253
+ for (const { node, event } of await control.items()) { binding.replay(node, event); await binding.drain(); }
254
+ await binding.drain(); const state = modes(control); return state ? { modes: state } : {};
255
+ }));
256
+ app.onRequest("session/prompt", ({ params, signal }) => admit(async () => {
257
+ const binding = get(params.sessionId), control = binding.control, input = promptText(params.prompt);
258
+ if (control.busy || binding.abort) throw RequestError.invalidRequest(undefined, "A prompt is already running for this session");
259
+ const abort = new AbortController(); binding.abort = abort; binding.pending.clear();
260
+ const signals = AbortSignal.any([signal, abort.signal, connection!.signal]);
261
+ let outcome: ExecutionOutcome | undefined;
262
+ try {
263
+ for await (const event of control.send(input, signals)) {
264
+ // Emit committed model text once. Provider retry/discard deltas cannot become durable conversation.
265
+ if (event.kind === "assistant_text" && event.text) { binding.send({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: event.text } }); await binding.drain(); }
266
+ if (event.kind === "done") outcome = event.outcome;
267
+ }
268
+ await binding.drain(); return { stopReason: stopReason(outcome, signals.aborted) };
269
+ } catch {
270
+ if (signals.aborted) return { stopReason: "cancelled" as const };
271
+ throw RequestError.internalError(undefined, "Session prompt failed; inspect its durable outcome before continuing");
272
+ } finally { binding.abort = null; binding.pending.clear(); }
273
+ }));
274
+ app.onNotification("session/cancel", ({ params }) => {
275
+ const binding = get(params.sessionId); binding.abort?.abort();
276
+ if (binding.abort && binding.control.activeTurnId) binding.control.interrupt(binding.control.activeTurnId);
277
+ });
278
+ app.onRequest("session/set_mode", ({ params }) => admit(async () => {
279
+ const binding = get(params.sessionId), control = binding.control;
280
+ if (params.modeId !== "plan" && params.modeId !== "build") invalid("Unknown session mode");
281
+ if (!control.configureWorkflow) throw RequestError.methodNotFound("session/set_mode");
282
+ if (control.busy) throw RequestError.invalidRequest(undefined, "Mode changes require an idle checkpoint");
283
+ await control.configureWorkflow(params.modeId); binding.send({ sessionUpdate: "current_mode_update", currentModeId: params.modeId }); await binding.drain(); return {};
284
+ }));
285
+ app.onRequest("session/close", ({ params }) => admit(async () => {
286
+ const binding = get(params.sessionId); binding.close(); bindings.delete(params.sessionId); await hub.close(binding.control.threadId); return {};
287
+ }));
288
+ return app;
289
+ }
@@ -0,0 +1,21 @@
1
+ /** R13: configuration loading is separate from applying a role to a live Session. */
2
+ import { join } from "node:path";
3
+ import { configDir } from "../store/config.ts";
4
+ import { readAgentProfileFile } from "../store/agent-profile-files.ts";
5
+ import { parseAgentProfiles, type AgentProfileLayer } from "../core/agent-profile.ts";
6
+
7
+ export async function loadAgentProfileLayers(options: { readonly workspace: string; readonly trustProject: boolean; readonly userDir?: string }):
8
+ Promise<{ readonly layers: readonly AgentProfileLayer[]; readonly diagnostics: readonly string[] }> {
9
+ const paths = [{ kind: "user" as const, path: join(options.userDir ?? configDir(), "agents.json") },
10
+ ...(options.trustProject ? [{ kind: "project" as const, path: join(options.workspace, ".xeno", "agents.json") }] : [])];
11
+ const layers: AgentProfileLayer[] = [], diagnostics: string[] = [];
12
+ for (const source of paths) {
13
+ const file = await readAgentProfileFile(source.path);
14
+ if (!file) continue;
15
+ if (file.diagnostic) { diagnostics.push(file.diagnostic); continue; }
16
+ const parsed = parseAgentProfiles(file.value);
17
+ diagnostics.push(...parsed.diagnostics.map(diagnostic => `${source.path}: ${diagnostic}`));
18
+ if (parsed.diagnostics.length === 0) layers.push({ source, profiles: parsed.profiles });
19
+ }
20
+ return { layers, diagnostics };
21
+ }
@@ -58,10 +58,10 @@ export function loadCatalog(opts: { userText: string | null; cacheText?: string
58
58
  // Refresh metadata without replacing already verified wire dialects for existing sessions.
59
59
  const next = { ...spec, api: known.api, reasoning: known.reasoning };
60
60
  delete next.driver; delete next.compat; delete next.nativeCompat; delete next.thinkingLevelMap;
61
- if (known.compat) next.compat = known.compat;
62
- if (known.thinkingLevelMap) next.thinkingLevelMap = known.thinkingLevelMap;
63
61
  if (known.driver) next.driver = known.driver;
64
62
  if (known.nativeCompat) next.nativeCompat = known.nativeCompat;
63
+ if (known.compat) next.compat = known.compat;
64
+ if (known.thinkingLevelMap) next.thinkingLevelMap = known.thinkingLevelMap;
65
65
  if (known.baseUrl !== undefined) next.baseUrl = known.baseUrl;
66
66
  copyProviderAccess(spec, next);
67
67
  return next;
@@ -0,0 +1,149 @@
1
+ /** Typed local control client; requests are never retried after a delivery error. */
2
+ import { CONTROL_SCHEMA, parseControlRequest } from "../core/control-protocol.ts";
3
+ import type { ContextLens, LensFocus } from "../core/control-view.ts";
4
+ import type { LogEvent } from "../core/events.ts";
5
+ import type { QuestionReply } from "../core/question.ts";
6
+ import type { SessionList } from "../store/sessions.ts";
7
+ import type { ControlNotice, ControlSnapshot } from "./session-control.ts";
8
+
9
+ export interface ControlApi {
10
+ "thread/read": { params: { threadId: string }; result: ControlSnapshot };
11
+ "thread/list": { params: Record<string, never>; result: SessionList & { live: string[] } };
12
+ "thread/new": { params: { name?: string }; result: ControlSnapshot };
13
+ "thread/resume": { params: { session: string }; result: ControlSnapshot };
14
+ "thread/fork": { params: { threadId: string; name?: string }; result: ControlSnapshot };
15
+ "thread/close": { params: { threadId: string }; result: { closed: boolean } };
16
+ "thread/mode": { params: { threadId: string; mode: "build" | "plan" }; result: ControlSnapshot };
17
+ "turn/start": { params: { threadId: string; input: string }; result: { turnId: string } };
18
+ "turn/steer": { params: { threadId: string; turnId: string; input: string }; result: { queued: boolean } };
19
+ "turn/interrupt": { params: { threadId: string; turnId: string }; result: { interruptRequested: boolean } };
20
+ "approval/respond": { params: { threadId: string; turnId: string; approvalId: string; choice: "once" | "command" | "tool" | "deny" }; result: { accepted: boolean } };
21
+ "question/respond": { params: { threadId: string; turnId: string; requestId: string; reply: string }; result: { accepted: boolean } };
22
+ "acceptance/accept": { params: { threadId: string; requestId: string; criterionId: string }; result: { accepted: boolean } };
23
+ "context/read": { params: { threadId: string; focus: LensFocus; offset?: number; limit?: number }; result: {
24
+ node: number; streamId: string; sequence: number; focus: LensFocus; total: number; entries: readonly unknown[]; nextOffset: number | null;
25
+ components: ContextLens["components"]; used: ContextLens["used"]; countKind: ContextLens["countKind"] } };
26
+ "item/list": { params: { threadId: string; after?: { node: number; event: string }; limit?: number }; result: {
27
+ items: { node: number; id: string; type: LogEvent["t"] }[]; nextCursor: { node: number; event: string } | null } };
28
+ "item/read": { params: { threadId: string; node: number; event: string }; result: { node: number; event: LogEvent } };
29
+ "thread/subscribe": { params: { threadId: string; after?: { streamId: string; sequence: number } }; result: { snapshot: ControlSnapshot; resyncRequired: boolean } };
30
+ }
31
+ function record(value: unknown): value is Record<string, unknown> { return !!value && typeof value === "object" && !Array.isArray(value); }
32
+ function identity(value: unknown): value is string { return typeof value === "string" && value.length > 0 && value.length <= 128; }
33
+ function count(value: unknown): value is number { return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; }
34
+ function snapshot(value: unknown): boolean {
35
+ return record(value) && value["version"] === CONTROL_SCHEMA.protocol && identity(value["threadId"]) && identity(value["streamId"]) && count(value["sequence"])
36
+ && count(value["node"]) && (value["activeTurnId"] === null || identity(value["activeTurnId"])) && (value["goal"] === null || record(value["goal"]))
37
+ && [null, "permission", "question", "auth"].includes(value["waiting"] as null) && Array.isArray(value["approvals"]) && Array.isArray(value["questions"]) && record(value["context"]);
38
+ }
39
+ function result(method: keyof ControlApi, value: unknown): boolean {
40
+ if (["thread/read", "thread/new", "thread/resume", "thread/fork", "thread/mode"].includes(method)) return snapshot(value);
41
+ if (!record(value)) return false;
42
+ switch (method) {
43
+ case "thread/list": return Array.isArray(value["sessions"]) && count(value["truncated"]) && Array.isArray(value["live"]) && value["live"].every(identity);
44
+ case "thread/close": return typeof value["closed"] === "boolean";
45
+ case "turn/start": return identity(value["turnId"]);
46
+ case "turn/steer": return typeof value["queued"] === "boolean";
47
+ case "turn/interrupt": return typeof value["interruptRequested"] === "boolean";
48
+ case "approval/respond": case "question/respond": case "acceptance/accept": return typeof value["accepted"] === "boolean";
49
+ case "thread/subscribe": return snapshot(value["snapshot"]) && typeof value["resyncRequired"] === "boolean";
50
+ case "context/read": return count(value["node"]) && identity(value["streamId"]) && count(value["sequence"]) && ["messages", "omitted", "history"].includes(String(value["focus"]))
51
+ && count(value["total"]) && Array.isArray(value["entries"]) && (value["nextOffset"] === null || count(value["nextOffset"])) && record(value["components"])
52
+ && typeof value["used"] === "number" && typeof value["countKind"] === "string";
53
+ case "item/list": return Array.isArray(value["items"]) && value["items"].every(item => record(item) && count(item["node"]) && identity(item["id"]) && typeof item["type"] === "string")
54
+ && (value["nextCursor"] === null || record(value["nextCursor"]) && count(value["nextCursor"]["node"]) && identity(value["nextCursor"]["event"]));
55
+ case "item/read": return count(value["node"]) && record(value["event"]) && identity(value["event"]["id"]) && typeof value["event"]["t"] === "string";
56
+ default: return false;
57
+ }
58
+ }
59
+ export class ControlClient {
60
+ private readonly write: (line: string) => void;
61
+ private readonly closeTransport: (() => void) | undefined;
62
+ private next = 1;
63
+ private buffer = "";
64
+ private closed = false;
65
+ private ready = false;
66
+ private initializing = false;
67
+ private readonly pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void; timer: ReturnType<typeof setTimeout> }>();
68
+ private readonly listeners = new Set<(notice: ControlNotice) => void>();
69
+ constructor(write: (line: string) => void, options: { close?: () => void } = {}) { this.write = write; this.closeTransport = options.close; }
70
+ onNotice(listener: (notice: ControlNotice) => void, threadId?: string): () => void {
71
+ const actual = threadId ? (notice: ControlNotice) => { if (notice.params.threadId === threadId) listener(notice); } : listener;
72
+ this.listeners.add(actual); return () => { this.listeners.delete(actual); };
73
+ }
74
+ async initialize(name: string, version: string): Promise<{ threadId: string; streamId: string }> {
75
+ if (this.ready || this.initializing) throw Error("control client already initialized or initializing");
76
+ this.initializing = true;
77
+ try {
78
+ const value = await this.raw("initialize", { clientInfo: { name, version } });
79
+ if (!record(value) || value["protocol"] !== CONTROL_SCHEMA.protocol || !identity(value["threadId"]) || !identity(value["streamId"])) {
80
+ this.close("unsupported or invalid control initialize result"); throw Error("unsupported or invalid control initialize result");
81
+ }
82
+ try { this.write(JSON.stringify({ method: "initialized", params: {} }) + "\n"); }
83
+ catch { this.close("control handshake delivery failed"); throw Error("control handshake delivery failed"); }
84
+ this.ready = true; return { threadId: value["threadId"], streamId: value["streamId"] };
85
+ } finally { this.initializing = false; }
86
+ }
87
+ request<M extends keyof ControlApi>(method: M, params: ControlApi[M]["params"]): Promise<ControlApi[M]["result"]> {
88
+ if (!this.ready) return Promise.reject(Error("initialize the control client before making requests"));
89
+ return this.raw(method, params).then(value => {
90
+ if (!result(method, value)) { this.close("invalid typed control result"); throw Error("invalid typed control result"); }
91
+ return value as ControlApi[M]["result"];
92
+ });
93
+ }
94
+ respondQuestion(threadId: string, turnId: string, requestId: string, reply: QuestionReply): Promise<{ accepted: boolean }> {
95
+ return this.request("question/respond", { threadId, turnId, requestId, reply: JSON.stringify(reply) });
96
+ }
97
+ raw(method: string, params: Record<string, unknown>, timeoutMs = 30_000): Promise<unknown> {
98
+ if (this.closed) return Promise.reject(Error("control client is closed"));
99
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 300_000) return Promise.reject(Error("control timeout must be 1..300000 ms"));
100
+ if (this.pending.size >= CONTROL_SCHEMA.limits.queuedRequests) return Promise.reject(Error("client request limit reached"));
101
+ const id = this.next++, line = JSON.stringify({ id, method, params }) + "\n";
102
+ try { parseControlRequest({ id, method, params }); } catch { return Promise.reject(Error("invalid control request parameters")); }
103
+ if (Buffer.byteLength(line) > CONTROL_SCHEMA.limits.frameBytes) return Promise.reject(Error("request exceeds frame limit"));
104
+ return new Promise((resolve, reject) => {
105
+ const timer = setTimeout(() => { this.pending.delete(id); reject(Error("request timed out; effect is unknown, inspect before retrying")); }, timeoutMs);
106
+ this.pending.set(id, { resolve, reject, timer });
107
+ try { this.write(line); } catch { clearTimeout(timer); this.pending.delete(id); reject(Error("control delivery failed; effects are unknown, inspect before retrying")); }
108
+ });
109
+ }
110
+ feed(text: string): void {
111
+ if (this.closed) return;
112
+ this.buffer += text;
113
+ for (;;) {
114
+ const at = this.buffer.indexOf("\n");
115
+ if (at < 0) { if (Buffer.byteLength(this.buffer) > CONTROL_SCHEMA.limits.frameBytes) this.close("oversized control frame"); return; }
116
+ const line = this.buffer.slice(0, at); this.buffer = this.buffer.slice(at + 1);
117
+ if (Buffer.byteLength(line) > CONTROL_SCHEMA.limits.frameBytes) { this.close("oversized control frame"); return; }
118
+ if (!line.trim()) continue;
119
+ let data: unknown;
120
+ try { data = JSON.parse(line); } catch { this.close("invalid control JSON"); return; }
121
+ if (!record(data)) { this.close("invalid control envelope"); return; }
122
+ if (Object.hasOwn(data, "id")) {
123
+ const id = data["id"], error = data["error"];
124
+ if (!(id === null || typeof id === "number" && Number.isSafeInteger(id) && id >= 1) || Object.keys(data).some(key => !["id", "result", "error"].includes(key))
125
+ || Object.hasOwn(data, "result") === Object.hasOwn(data, "error")
126
+ || Object.hasOwn(data, "error") && (!record(error) || !Number.isSafeInteger(error["code"]) || typeof error["message"] !== "string" || Object.keys(error).some(key => !["code", "message"].includes(key)))) {
127
+ this.close("invalid control response envelope"); return;
128
+ }
129
+ if (id === null) { this.close("control server rejected the connection frame"); return; }
130
+ const pending = this.pending.get(id); if (!pending) continue;
131
+ this.pending.delete(id); clearTimeout(pending.timer);
132
+ if (record(error)) pending.reject(Error(`Control request rejected (${String(error["code"])}): ${String(error["message"]).slice(0, 512)}`)); else pending.resolve(data["result"]);
133
+ } else {
134
+ const params = data["params"], method = data["method"];
135
+ if (Object.keys(data).some(key => !["method", "params"].includes(key)) || typeof method !== "string" || !CONTROL_SCHEMA.notifications.some(name => name === method)
136
+ || !record(params) || !identity(params["threadId"]) || !identity(params["streamId"]) || !count(params["sequence"]) || params["sequence"] === 0
137
+ || params["turnId"] !== undefined && !identity(params["turnId"])) { this.close("invalid control notification envelope"); return; }
138
+ for (const listener of this.listeners) try { listener(structuredClone(data) as ControlNotice); } catch { /* observers do not own transport */ }
139
+ }
140
+ }
141
+ }
142
+ close(reason = "control transport closed; unresolved effects are unknown"): void {
143
+ if (this.closed) return;
144
+ this.closed = true; this.ready = false; this.buffer = "";
145
+ for (const item of this.pending.values()) { clearTimeout(item.timer); item.reject(Error(reason)); }
146
+ this.pending.clear(); this.listeners.clear();
147
+ try { this.closeTransport?.(); } catch { /* transport failures cannot reopen this client or replay requests */ }
148
+ }
149
+ }
@@ -4,6 +4,7 @@ import { selectLens, type LensFocus } from "../core/control-view.ts";
4
4
  import { assertNever } from "../core/exhaustive.ts";
5
5
  import type { SessionControl } from "./session-control.ts";
6
6
  import type { ApprovalChoice } from "./tools.ts";
7
+ import type { SessionHub } from "./session-hub.ts";
7
8
 
8
9
  export type RpcOutput = { id: RpcId | null; result?: unknown; error?: { code: number; message: string } } | { method: string; params: unknown };
9
10
 
@@ -17,9 +18,13 @@ export class ControlConnection {
17
18
  private attached: SessionControl | undefined;
18
19
  private stop: (() => void) | undefined;
19
20
  private readonly denyOnClose: boolean;
21
+ private readonly hub: SessionHub | undefined;
22
+ private readonly subscriptions = new Map<SessionControl, () => void>();
23
+ private readonly questionClients = new Map<SessionControl, () => void>();
20
24
 
21
- constructor(control: () => SessionControl, write: (output: RpcOutput) => void, options: { denyOnClose?: boolean } = {}) {
25
+ constructor(control: () => SessionControl, write: (output: RpcOutput) => void, options: { denyOnClose?: boolean; hub?: SessionHub } = {}) {
22
26
  this.control = control; this.write = write; this.denyOnClose = options.denyOnClose ?? false;
27
+ this.hub = options.hub;
23
28
  }
24
29
  private attach(): SessionControl {
25
30
  const control = this.control();
@@ -36,23 +41,50 @@ export class ControlConnection {
36
41
  if (typeof value === "object" && value !== null && "id" in value &&
37
42
  (typeof value.id === "string" && value.id.length <= 128 || typeof value.id === "number" && Number.isSafeInteger(value.id))) id = value.id;
38
43
  const request = parseControlRequest(value), params = request.params;
39
- const control = this.attach();
44
+ let control = this.attach();
40
45
  if (request.method === "initialize") {
41
46
  if (this.initialized) throw new ControlProtocolError(-32000, "already initialized");
42
47
  this.initialized = true;
43
48
  this.write({ id, result: { protocol: CONTROL_SCHEMA.protocol, experimental: true, threadId: control.threadId, streamId: control.streamId,
44
- capabilities: { turns: true, steering: true, approvals: true, contextLens: true, snapshotResync: true, durableEventReplay: "item/list", adaptiveExecution: false } } });
49
+ capabilities: { turns: true, steering: true, approvals: true, questions: true, contextLens: true, snapshotResync: true, durableEventReplay: "item/list", adaptiveExecution: false } } });
45
50
  return;
46
51
  }
47
52
  if (!this.initialized) throw new ControlProtocolError(-32000, "not initialized");
48
53
  if (request.method === "initialized") { if (this.ready) throw new ControlProtocolError(-32000, "already ready"); this.ready = true; return; }
49
54
  if (!this.ready) throw new ControlProtocolError(-32000, "send initialized before using the session");
55
+ if (request.method === "thread/list") {
56
+ if (!this.hub) throw Error("multi-session methods require app-server");
57
+ this.write({ id, result: await this.hub.list() }); return;
58
+ }
59
+ if (request.method === "thread/new" || request.method === "thread/resume") {
60
+ if (!this.hub) throw Error("multi-session methods require app-server");
61
+ const opened = await this.hub.open(request.method === "thread/new" ? "new" : "resume", params);
62
+ this.write({ id, result: await opened.snapshot() }); return;
63
+ }
64
+ if (this.hub && typeof params["threadId"] === "string") control = this.hub.get(params["threadId"]);
50
65
  if (params["threadId"] !== control.threadId) throw new ControlProtocolError(-32000, "stale or unknown threadId; initialize a new connection after changing sessions");
51
66
  let result: unknown;
52
67
  switch (request.method) {
68
+ case "thread/fork": {
69
+ if (!this.hub) throw Error("multi-session methods require app-server");
70
+ result = await (await this.hub.open("fork", { ...params, session: control.session.config.logDir })).snapshot(); break;
71
+ }
72
+ case "thread/close": {
73
+ if (!this.hub) throw Error("multi-session methods require app-server");
74
+ await this.hub.close(control.threadId); this.subscriptions.get(control)?.(); this.subscriptions.delete(control);
75
+ this.questionClients.get(control)?.(); this.questionClients.delete(control);
76
+ result = { closed: true }; break;
77
+ }
78
+ case "thread/mode": {
79
+ if (!control.configureWorkflow) throw Error("workflow changes are unavailable for this session");
80
+ await control.configureWorkflow(params["mode"] as "build" | "plan"); result = await control.snapshot(); break;
81
+ }
53
82
  case "thread/read": result = await control.snapshot(); break;
54
83
  case "thread/subscribe": {
55
- this.subscribed = true;
84
+ if (!this.questionClients.has(control)) this.questionClients.set(control, control.attachQuestionClient());
85
+ if (this.hub) {
86
+ if (!this.subscriptions.has(control)) this.subscriptions.set(control, control.subscribe(notice => { if (!this.closed) this.write(notice); }));
87
+ } else this.subscribed = true;
56
88
  const snapshot = await control.snapshot();
57
89
  const after = params["after"] as { streamId: string; sequence: number } | undefined;
58
90
  result = { snapshot, resyncRequired: after !== undefined && (after.streamId !== snapshot.streamId || after.sequence !== snapshot.sequence) };
@@ -62,6 +94,7 @@ export class ControlConnection {
62
94
  case "turn/steer": control.steer(String(params["turnId"]), String(params["input"])); result = { queued: true }; break;
63
95
  case "turn/interrupt": control.interrupt(String(params["turnId"])); result = { interruptRequested: true }; break;
64
96
  case "approval/respond": control.respond(String(params["turnId"]), String(params["approvalId"]), params["choice"] as ApprovalChoice); result = { accepted: true }; break;
97
+ case "question/respond": control.respondQuestion(String(params["turnId"]), String(params["requestId"]), JSON.parse(String(params["reply"]))); result = { accepted: true }; break;
65
98
  case "acceptance/accept": await control.accept(String(params["requestId"]), String(params["criterionId"])); result = { accepted: true }; break;
66
99
  case "context/read": {
67
100
  const snapshot = await control.snapshot(false), all = selectLens(snapshot.context, params["focus"] as LensFocus);
@@ -96,6 +129,8 @@ export class ControlConnection {
96
129
  }
97
130
  close(): void {
98
131
  this.closed = true; this.stop?.();
132
+ for (const stop of this.subscriptions.values()) stop(); this.subscriptions.clear();
133
+ for (const stop of this.questionClients.values()) stop(); this.questionClients.clear();
99
134
  if (this.denyOnClose && this.attached) {
100
135
  this.attached.denyApprovals();
101
136
  if (this.attached.activeTurnId) this.attached.interrupt(this.attached.activeTurnId);