@0perator/operator 0.1.235 → 0.1.261

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 (68) hide show
  1. package/README.md +2 -1
  2. package/dashboard/server.mjs +1 -1
  3. package/dist/acp/agent.js +290 -62
  4. package/dist/acp/auth.js +44 -0
  5. package/dist/acp/prompt.js +41 -0
  6. package/dist/acp/run.js +40 -15
  7. package/dist/acp/tool-map.js +48 -0
  8. package/dist/auth/byo.js +15 -8
  9. package/dist/auth/client.js +12 -6
  10. package/dist/auth/commands.js +39 -4
  11. package/dist/auth/identity.js +136 -0
  12. package/dist/auth/store.js +7 -5
  13. package/dist/autonomy/board.js +3 -2
  14. package/dist/autonomy/cron.js +332 -0
  15. package/dist/autonomy/delegate.js +168 -0
  16. package/dist/autonomy/media-robot.js +2 -3
  17. package/dist/autonomy/routines.js +5 -4
  18. package/dist/autonomy/session-factory.js +6 -1
  19. package/dist/browser/cdp.js +266 -0
  20. package/dist/browser/session.js +286 -0
  21. package/dist/cli.js +75 -11
  22. package/dist/config/brand.js +3 -3
  23. package/dist/config/home.js +70 -0
  24. package/dist/config/managed.js +230 -0
  25. package/dist/config/persona.js +59 -9
  26. package/dist/config/scaffold.js +142 -0
  27. package/dist/config/settings.js +38 -4
  28. package/dist/config/skills-index.js +175 -0
  29. package/dist/consolidation/scheduler.js +3 -3
  30. package/dist/consolidation/sleep.js +3 -3
  31. package/dist/engine/agent.js +80 -13
  32. package/dist/engine/aurora.js +6 -0
  33. package/dist/engine/batch-scheduler.js +128 -0
  34. package/dist/engine/json-repair.js +105 -0
  35. package/dist/engine/messages.js +50 -3
  36. package/dist/engine/rolling-summary.js +7 -5
  37. package/dist/enterprise/cli.js +137 -0
  38. package/dist/flywheel/processor.js +30 -2
  39. package/dist/flywheel/secret-gate.js +123 -0
  40. package/dist/mcp/index.js +18 -24
  41. package/dist/memory/index.js +0 -0
  42. package/dist/memory/session-index.js +324 -0
  43. package/dist/memory/session-rewind.js +92 -0
  44. package/dist/memory/state-maintenance.js +441 -0
  45. package/dist/observability/index.js +3 -3
  46. package/dist/permissions/index.js +24 -12
  47. package/dist/router/models.js +27 -8
  48. package/dist/selfimprove/index.js +9 -7
  49. package/dist/session.js +16 -6
  50. package/dist/skills/catalogue.js +167 -0
  51. package/dist/telemetry/audit-verify.js +94 -0
  52. package/dist/telemetry/events.js +86 -6
  53. package/dist/telemetry/lifecycle.js +18 -0
  54. package/dist/tools/deferred.js +117 -0
  55. package/dist/tools/executor.js +19 -20
  56. package/dist/tools/memory.js +117 -0
  57. package/dist/tools/registry.js +152 -21
  58. package/dist/tools/sandbox.js +63 -17
  59. package/dist/tools/searxng.js +2 -2
  60. package/dist/tools/tool-output-spill.js +2 -2
  61. package/dist/ui/Transcript.js +14 -2
  62. package/dist/ui/useInputHistory.js +3 -3
  63. package/dist/vault/cli.js +48 -0
  64. package/dist/vault/store.js +157 -0
  65. package/dist/vault/tool.js +50 -0
  66. package/package.json +3 -5
  67. package/CHANGELOG.md +0 -2487
  68. package/dist/ui/BusTray.js +0 -70
package/README.md CHANGED
@@ -59,7 +59,8 @@ operator # 1M-only
59
59
  operator+ --resume # reload the last conversation
60
60
  ```
61
61
  Requires Aurora serving locally (Air `:8098` / 1M `:8097`). Dev: `npm install && npm run dev`.
62
- Env: `KODE_AIR`, `KODE_1M`, `KODE_SADDLE`, `KODE_TSI_ROUTER=1m`, `KODE_SYSTEM_PROMPT`, `KODE_SESSION_FILE`.
62
+ Env (the internal `KODE_` prefix is retained for compatibility): `KODE_AIR`, `KODE_1M`, `KODE_SADDLE`,
63
+ `KODE_TSI_ROUTER=1m`, `KODE_SYSTEM_PROMPT`, `KODE_SESSION_FILE`.
63
64
 
64
65
  ## Testing
65
66
 
@@ -48,7 +48,7 @@ const DENIALS_MAX = 500;
48
48
 
49
49
  const KINDS = new Set(["tool", "turn", "control", "service"]);
50
50
  const TIERS = new Set(["admin", "enterprise", "readonly"]);
51
- const SURFACES = new Set(["cli", "web", "mobile"]);
51
+ const SURFACES = new Set(["cli", "web", "mobile", "acp"]);
52
52
 
53
53
  function validateEvent(e) {
54
54
  if (!e || typeof e !== "object") return "not an object";
package/dist/acp/agent.js CHANGED
@@ -3,46 +3,175 @@
3
3
  // layer: an ACP `session/prompt` becomes `Session.send()`, and the session's streaming callbacks become ACP
4
4
  // `session/update` notifications. Nothing re-implements the agent loop — like the remote-control host, ACP
5
5
  // funnels into the one `runTurn` (via Session), so compaction, loop-guard, and the verify gate come for free.
6
+ //
7
+ // Enterprise posture (see _ai-docs/decisions/2026-10-07-acp-hardening.md):
8
+ // - tool approvals under gated/enterprise policy become `session/request_permission` (fail-closed);
9
+ // - each session is isolated: its own root (no process.chdir), rolling summary, shell, audit identity;
10
+ // - protocol errors carry proper JSON-RPC codes; a session can't be driven by two prompts at once;
11
+ // - sessions are torn down when the editor detaches (no orphaned shells / MCP servers).
6
12
  import { randomUUID } from "node:crypto";
7
- import { PROTOCOL_VERSION } from "@zed-industries/agent-client-protocol";
13
+ import { readFileSync, rmSync, statSync } from "node:fs";
14
+ import { isAbsolute } from "node:path";
15
+ import { PROTOCOL_VERSION, RequestError } from "@zed-industries/agent-client-protocol";
8
16
  import { createAutonomySession } from "../autonomy/session-factory.js";
9
17
  import { modelRegistry, visibleModels } from "../router/models.js";
10
18
  import { hasByoToken } from "../auth/byo.js";
19
+ import { operatorPath } from "../config/home.js";
20
+ import { redactSecrets } from "../engine/redact.js";
21
+ import { EventSink } from "../telemetry/events.js";
22
+ import { PermissionPolicy } from "../permissions/index.js";
23
+ import { signatureLine } from "../permissions/signature.js";
24
+ import { allowSandboxWriteRoot } from "../tools/sandbox.js";
11
25
  import { buildModelConfigOption, configOptionUpdate } from "./config-options.js";
26
+ import { ACP_AUTH_METHOD, ACP_AUTH_METHOD_ID, defaultAcpAuth } from "./auth.js";
27
+ import { promptToText } from "./prompt.js";
28
+ import { capResult, resultStatus, toolKind, toolLocations, toolTitle } from "./tool-map.js";
29
+ export const defaultSessionFactory = (settings, o) => createAutonomySession(settings, {
30
+ cwd: o.cwd,
31
+ extra: { sessionId: o.sessionId, approve: o.approve, eventSink: o.eventSink, eventActor: o.eventActor, rollingSummaryPath: o.rollingSummaryPath },
32
+ });
33
+ const ALLOW_ONCE = "allow_once";
34
+ const REJECT_ONCE = "reject_once";
35
+ const DEFAULT_MAX_SESSIONS = 32;
36
+ const DEFAULT_MAX_PROMPT_CHARS = 2_000_000;
37
+ const PERMISSION_OPTIONS = [
38
+ { optionId: ALLOW_ONCE, name: "Allow", kind: "allow_once" },
39
+ { optionId: REJECT_ONCE, name: "Reject", kind: "reject_once" },
40
+ ];
41
+ function agentVersion() {
42
+ try {
43
+ return JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
44
+ }
45
+ catch {
46
+ return "0.0.0";
47
+ }
48
+ }
49
+ function envInt(name, fallback) {
50
+ const n = Number(process.env[name]);
51
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback;
52
+ }
53
+ /** Correlates a tool call the engine announced (onToolStart, with its id) to the (name,args) pair the
54
+ * permission wrapper later asks approval for — ApproveFn carries no call id, and the editor wants the
55
+ * approval attached to the card it already shows, not a second phantom one. */
56
+ export class ToolCallIndex {
57
+ byKey = new Map();
58
+ static key(name, args) { return `${name}\u0000${JSON.stringify(args ?? {})}`; }
59
+ start(id, name, args) {
60
+ const k = ToolCallIndex.key(name, args);
61
+ const q = this.byKey.get(k);
62
+ if (q)
63
+ q.push(id);
64
+ else
65
+ this.byKey.set(k, [id]);
66
+ }
67
+ idFor(name, args) {
68
+ return this.byKey.get(ToolCallIndex.key(name, args))?.[0];
69
+ }
70
+ settle(id) {
71
+ for (const [k, q] of this.byKey) {
72
+ const i = q.indexOf(id);
73
+ if (i >= 0) {
74
+ q.splice(i, 1);
75
+ if (!q.length)
76
+ this.byKey.delete(k);
77
+ return;
78
+ }
79
+ }
80
+ }
81
+ clear() { this.byKey.clear(); }
82
+ }
12
83
  export class OperatorAcpAgent {
13
84
  conn;
14
85
  settings;
15
86
  sessionFactory;
16
87
  sessions = new Map();
17
- constructor(conn, settings,
18
- // Structural seam (same discipline as CompactionOpts.meter): tests build the agent without the
19
- // whole router/MCP/permissions stack; production passes nothing and gets createAutonomySession.
20
- sessionFactory = createAutonomySession) {
88
+ auth;
89
+ sink;
90
+ actorOverride;
91
+ maxSessions;
92
+ maxPromptChars;
93
+ subject;
94
+ inflight = 0;
95
+ constructor(conn, settings, sessionFactory = defaultSessionFactory, opts = {}) {
21
96
  this.conn = conn;
22
97
  this.settings = settings;
23
98
  this.sessionFactory = sessionFactory;
99
+ this.auth = opts.auth ?? defaultAcpAuth(settings, { requireSignIn: settings.managed?.auth?.requireSignIn });
100
+ this.sink = opts.sink ?? new EventSink();
101
+ this.actorOverride = opts.actor;
102
+ this.maxSessions = opts.maxSessions ?? envInt("KODE_ACP_MAX_SESSIONS", DEFAULT_MAX_SESSIONS);
103
+ this.maxPromptChars = opts.maxPromptChars ?? envInt("KODE_ACP_MAX_PROMPT_CHARS", DEFAULT_MAX_PROMPT_CHARS);
104
+ }
105
+ // Read live from `settings`, not frozen at construction: a sign-in through `authenticate` re-resolves the
106
+ // seat (tier, subject) on the shared settings object, and the audit trail must follow it.
107
+ get actor() {
108
+ return { tier: this.settings.permissions?.tier ?? "admin", surface: "acp", sub: this.subject ?? this.settings.seat?.sub, ...this.actorOverride };
24
109
  }
25
- async initialize(_params) {
26
- // We negotiate the version we build against and advertise a text-prompt agent. loadSession is not yet
27
- // supported (each `session/new` is a fresh context); embeddedContext lets the editor inline file refs.
110
+ get audits() { return new PermissionPolicy(this.settings.permissions ?? {}).audits; }
111
+ async initialize(params) {
112
+ // Spec: answer the client's version when we speak it, else our latest. We speak exactly PROTOCOL_VERSION.
113
+ void params;
114
+ // loadSession is not supported (each `session/new` is a fresh context); embeddedContext lets the editor
115
+ // inline file refs. The advertised auth method appears ONLY when this deployment needs a sign-in — a
116
+ // loopback/LAN engine keeps the empty list and zero ceremony.
28
117
  return {
29
118
  protocolVersion: PROTOCOL_VERSION,
30
119
  agentCapabilities: {
31
120
  loadSession: false,
32
121
  promptCapabilities: { image: false, audio: false, embeddedContext: true },
33
122
  },
34
- authMethods: [], // Operator's own auth (AuthGate) is orthogonal; the local ACP link needs none.
123
+ authMethods: this.auth.required() ? [{ ...ACP_AUTH_METHOD }] : [],
124
+ // Extra field: the SDK validates REQUESTS only. Zed shows this as the agent's name/version.
125
+ agentInfo: { name: "operator", title: "Operator", version: agentVersion() },
35
126
  };
36
127
  }
37
128
  async newSession(params) {
38
- // Same building blocks as headless (router, MCP tools, permissions, telemetry) — no TUI, no ask_user.
39
- const session = this.sessionFactory(this.settings);
40
- const sessionId = randomUUID();
41
- this.sessions.set(sessionId, { session, cwd: params.cwd || process.cwd() });
42
- // GW-40: the stabilized configOptions surface (Zed dropdown for new clients; the SDK-0.4.5
43
- // legacy set_model below for current ones). Extra field on the response — the SDK validates
44
- // REQUESTS only, so this passes through to the wire untouched.
45
- return { sessionId, configOptions: [this.modelOption(sessionId)] };
129
+ const cwd = params.cwd;
130
+ if (typeof cwd !== "string" || !isAbsolute(cwd)) {
131
+ throw RequestError.invalidParams({ field: "cwd", reason: "cwd must be an absolute path" });
132
+ }
133
+ let isDir = false;
134
+ try {
135
+ isDir = statSync(cwd).isDirectory();
136
+ }
137
+ catch { /* falls to the error below */ }
138
+ if (!isDir)
139
+ throw RequestError.invalidParams({ field: "cwd", reason: "cwd is not an existing directory" });
140
+ if (this.sessions.size >= this.maxSessions) {
141
+ throw RequestError.invalidRequest({ reason: `session limit reached (${this.maxSessions}); close an editor thread first` });
142
+ }
143
+ if (this.auth.required()) {
144
+ const st = await this.auth.check(false);
145
+ if (!st.ok)
146
+ throw RequestError.authRequired({ authMethods: [ACP_AUTH_METHOD], reason: "sign in with `operator auth login`, then retry" });
147
+ this.subject = st.subject ?? this.subject;
148
+ }
149
+ // Spawning a client-named command is a security-sensitive surface we have not wired; say so rather
150
+ // than silently dropping the editor's tool config.
151
+ if (params.mcpServers?.length) {
152
+ process.stderr.write(`[operator-acp] ignoring ${params.mcpServers.length} client-supplied MCP server(s): not supported yet\n`);
153
+ }
154
+ const sid = randomUUID();
155
+ const auditId = `acp-${sid.slice(0, 12)}`;
156
+ const summaryPath = operatorPath("session-memory", "acp", `${sid}.md`);
157
+ const live = { sid, auditId, cwd, summaryPath, busy: false, cancelled: false, calls: new ToolCallIndex(), pending: new Set(), releaseRoot: allowSandboxWriteRoot(cwd) };
158
+ try {
159
+ live.session = this.sessionFactory(this.settings, {
160
+ cwd, sessionId: auditId, rollingSummaryPath: summaryPath,
161
+ approve: this.approver(live),
162
+ eventSink: this.sink,
163
+ eventActor: this.actor,
164
+ });
165
+ }
166
+ catch (e) {
167
+ live.releaseRoot();
168
+ throw e;
169
+ }
170
+ this.sessions.set(sid, live);
171
+ this.audit(auditId, { event: "session_start", detail: `surface=acp tier=${this.actor.tier} mode=${this.settings.permissions?.mode ?? "bypass"} cwd=${cwd}` });
172
+ // GW-40: the stabilized configOptions surface (Zed dropdown for new clients; the SDK-0.4.5 legacy
173
+ // set_model below for current ones). Extra field on the response — the SDK validates REQUESTS only.
174
+ return { sessionId: sid, configOptions: [this.modelOption(sid)] };
46
175
  }
47
176
  /** The live model selector for a session — honest (MOA listed only if configured), current value
48
177
  * read from the Session itself so a /model-style switch elsewhere is reflected here too. */
@@ -55,12 +184,10 @@ export class OperatorAcpAgent {
55
184
  * session/set_config_option is translated onto this method by the run.ts shim; both client
56
185
  * generations end up here, one switch, one source of truth (Session.setModel + its MOA guard). */
57
186
  async setSessionModel(params) {
58
- const live = this.sessions.get(params.sessionId);
59
- if (!live)
60
- throw new Error(`ACP: unknown session ${params.sessionId}`);
187
+ const live = this.live(params.sessionId);
61
188
  const r = live.session.setModel(params.modelId);
62
189
  if (!r.ok)
63
- throw new Error(r.error ?? `unknown model ${params.modelId}`);
190
+ throw new RequestError(-32602, r.error ?? `unknown model ${params.modelId}`, { modelId: params.modelId });
64
191
  // Spec: the agent notifies with the COMPLETE config state after its own changes.
65
192
  void this.conn.sessionUpdate({
66
193
  sessionId: params.sessionId,
@@ -72,71 +199,172 @@ export class OperatorAcpAgent {
72
199
  currentConfigOptions(sessionId) {
73
200
  return { configOptions: [this.modelOption(sessionId)] };
74
201
  }
75
- // Required by the interface; the local editor link is unauthenticated (authMethods is empty above).
76
- async authenticate(_params) {
202
+ /** Local deployments advertise no auth method, so this is a no-op ack (as before). When sign-in IS
203
+ * required, it re-checks the stored credential online — the editor calls it after the user has run
204
+ * `operator auth login` in a terminal — and adopts the token for the already-running engine. */
205
+ async authenticate(params) {
206
+ if (!this.auth.required())
207
+ return {};
208
+ if (params.methodId !== ACP_AUTH_METHOD_ID) {
209
+ throw RequestError.invalidParams({ field: "methodId", reason: `unknown auth method ${params.methodId}` });
210
+ }
211
+ const st = await this.auth.check(true);
212
+ if (!st.ok)
213
+ throw RequestError.authRequired({ authMethods: [ACP_AUTH_METHOD], reason: "no valid credential — run `operator auth login`" });
214
+ this.subject = st.subject ?? this.subject;
77
215
  return {};
78
216
  }
79
217
  async prompt(params) {
218
+ const live = this.live(params.sessionId);
219
+ if (live.busy) {
220
+ throw RequestError.invalidRequest({ sessionId: params.sessionId, reason: "a prompt turn is already in flight for this session; send session/cancel first" });
221
+ }
222
+ const text = promptToText(params.prompt, live.cwd);
223
+ if (!text.trim())
224
+ throw RequestError.invalidParams({ field: "prompt", reason: "prompt has no usable text content" });
225
+ if (text.length > this.maxPromptChars) {
226
+ throw RequestError.invalidParams({ field: "prompt", reason: `prompt exceeds ${this.maxPromptChars} characters` });
227
+ }
228
+ live.busy = true;
229
+ live.cancelled = false;
230
+ this.inflight++;
231
+ const handlers = acpHandlers((update) => void this.conn.sessionUpdate({ sessionId: live.sid, update: update }).catch(() => { }), { calls: live.calls, cwd: live.cwd });
232
+ try {
233
+ const outcome = await live.session.send(text, handlers);
234
+ return { stopReason: live.cancelled ? "cancelled" : acpStopReason(outcome) };
235
+ }
236
+ catch (e) {
237
+ if (live.cancelled)
238
+ return { stopReason: "cancelled" };
239
+ const message = redactSecrets(e instanceof Error ? e.message : String(e));
240
+ process.stderr.write(`[operator-acp] turn failed (${live.auditId}): ${message}\n`);
241
+ throw RequestError.internalError({ message });
242
+ }
243
+ finally {
244
+ live.busy = false;
245
+ live.calls.clear();
246
+ this.inflight--;
247
+ }
248
+ }
249
+ async cancel(params) {
80
250
  const live = this.sessions.get(params.sessionId);
81
251
  if (!live)
82
- throw new Error(`ACP: unknown session ${params.sessionId}`);
83
- // Operator's tools default to process.cwd(); honor the editor's project root for this turn.
252
+ return;
253
+ live.cancelled = true;
254
+ this.settleApprovals(live, false); // spec: the client answers a pending permission request "cancelled"; don't depend on it
255
+ live.session.interrupt?.();
256
+ }
257
+ /** Editor detached (stdin closed) or the process is going down: stop every turn, deny every open
258
+ * approval, and tear each session down so no shell / MCP server / summary file outlives the link. */
259
+ dispose(reason = "client_closed") {
260
+ for (const live of [...this.sessions.values()])
261
+ this.endSession(live, reason);
262
+ }
263
+ /** Resolve once every cancelled turn has settled (or after `timeoutMs`) so their final frames reach the pipe. */
264
+ async drain(timeoutMs) {
265
+ const deadline = Date.now() + timeoutMs;
266
+ while (this.inflight > 0 && Date.now() < deadline)
267
+ await new Promise((r) => setTimeout(r, 20));
268
+ }
269
+ endSession(live, reason) {
270
+ this.sessions.delete(live.sid);
271
+ live.cancelled = true;
272
+ this.settleApprovals(live, false);
273
+ try {
274
+ live.session.interrupt?.();
275
+ }
276
+ catch { /* best-effort */ }
277
+ try {
278
+ live.session.shutdown?.();
279
+ }
280
+ catch { /* best-effort */ }
281
+ live.releaseRoot();
84
282
  try {
85
- if (live.cwd)
86
- process.chdir(live.cwd);
283
+ rmSync(live.summaryPath, { force: true });
87
284
  }
88
- catch { /* dir gone — keep current cwd */ }
89
- const sid = params.sessionId;
90
- const handlers = acpHandlers((update) => void this.conn.sessionUpdate({ sessionId: sid, update: update }).catch(() => { }));
91
- const outcome = await live.session.send(promptToText(params.prompt), handlers);
92
- return { stopReason: outcome.interrupted ? "cancelled" : "end_turn" };
285
+ catch { /* derived artifact; nothing to keep */ }
286
+ this.audit(live.auditId, { event: "session_end", detail: reason });
93
287
  }
94
- async cancel(params) {
95
- this.sessions.get(params.sessionId)?.session.interrupt();
288
+ settleApprovals(live, allow) {
289
+ for (const settle of [...live.pending])
290
+ settle(allow);
291
+ live.pending.clear();
292
+ }
293
+ live(sessionId) {
294
+ const live = this.sessions.get(sessionId);
295
+ if (!live)
296
+ throw RequestError.invalidParams({ field: "sessionId", sessionId, reason: "unknown session" });
297
+ return live;
298
+ }
299
+ audit(session, control) {
300
+ if (!this.audits)
301
+ return; // inert-by-default: an unenforced owner session writes nothing
302
+ this.sink.emit({ kind: "control", session, actor: this.actor, control });
303
+ }
304
+ /** The permission bridge: a "gated" mutating call (or any "ask") becomes `session/request_permission`.
305
+ * FAIL-CLOSED — anything other than an explicit "Allow" (cancel, reject, error, an option we never
306
+ * offered, a hung-up client) is a denial, and a cancel/teardown denies whatever is still open. */
307
+ approver(live) {
308
+ return (name, args) => new Promise((resolve) => {
309
+ if (live.cancelled)
310
+ return resolve(false);
311
+ const settle = (allow) => { live.pending.delete(settle); resolve(allow); };
312
+ live.pending.add(settle);
313
+ const line = signatureLine(name, args);
314
+ this.conn.requestPermission({
315
+ sessionId: live.sid,
316
+ toolCall: {
317
+ toolCallId: live.calls.idFor(name, args) ?? `perm-${randomUUID()}`,
318
+ title: `${line ? `[human sign-off: ${line}] ` : ""}${toolTitle(name, args)}`,
319
+ kind: toolKind(name),
320
+ status: "pending",
321
+ rawInput: args,
322
+ locations: toolLocations(args, live.cwd),
323
+ },
324
+ options: PERMISSION_OPTIONS,
325
+ }).then((r) => settle(r?.outcome?.outcome === "selected" && r.outcome.optionId === ALLOW_ONCE), () => settle(false));
326
+ });
96
327
  }
97
328
  }
329
+ /** ACP stop reason for a settled turn: a model that hit its output cap or a content filter says so instead
330
+ * of masquerading as a clean end_turn. */
331
+ export function acpStopReason(outcome) {
332
+ if (outcome.interrupted)
333
+ return "cancelled";
334
+ if (outcome.stopReason === "length")
335
+ return "max_tokens";
336
+ if (outcome.stopReason === "content_filter")
337
+ return "refusal";
338
+ return "end_turn";
339
+ }
98
340
  /** Map Operator's turn callbacks to ACP session/update payloads. `emit` sends one update. Exported so the
99
341
  * mapping can be unit-tested without a live connection or model. */
100
- export function acpHandlers(emit) {
342
+ export function acpHandlers(emit, ctx = {}) {
101
343
  return {
102
344
  onDelta: (chunk) => emit({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: chunk } }),
103
345
  onReasoning: (chunk) => emit({ sessionUpdate: "agent_thought_chunk", content: { type: "text", text: chunk } }),
104
346
  onToolStart: (calls) => {
105
347
  for (const c of calls) {
106
- emit({ sessionUpdate: "tool_call", toolCallId: c.id, title: toolTitle(c), status: "in_progress", rawInput: c.args });
348
+ ctx.calls?.start(c.id, c.name, c.args);
349
+ emit({
350
+ sessionUpdate: "tool_call",
351
+ toolCallId: c.id,
352
+ title: toolTitle(c.name, c.args),
353
+ kind: toolKind(c.name),
354
+ status: "in_progress",
355
+ rawInput: c.args,
356
+ locations: toolLocations(c.args, ctx.cwd),
357
+ });
107
358
  }
108
359
  },
109
360
  onToolResult: (id, result) => {
361
+ ctx.calls?.settle(id);
110
362
  emit({
111
363
  sessionUpdate: "tool_call_update",
112
364
  toolCallId: id,
113
- status: "completed",
114
- content: [{ type: "content", content: { type: "text", text: result } }],
365
+ status: resultStatus(result),
366
+ content: [{ type: "content", content: { type: "text", text: capResult(result) } }],
115
367
  });
116
368
  },
117
369
  };
118
370
  }
119
- /** Flatten ACP prompt content blocks to the plain text Operator's Session.send expects. Text blocks pass
120
- * through; a resource_link / embedded resource becomes an `@path` mention the agent can act on. */
121
- function promptToText(blocks) {
122
- return blocks
123
- .map((b) => {
124
- if (b.type === "text")
125
- return b.text;
126
- if (b.type === "resource_link")
127
- return `@${b.uri}`;
128
- if (b.type === "resource") {
129
- const r = b.resource;
130
- return r.text ?? (r.uri ? `@${r.uri}` : "");
131
- }
132
- return "";
133
- })
134
- .filter(Boolean)
135
- .join("\n");
136
- }
137
- /** A human-readable tool_call title for the editor's tool timeline: "file_edit: src/x.ts", "bash: npm test". */
138
- function toolTitle(c) {
139
- const a = (c.args ?? {});
140
- const hint = a.path ?? a.file_path ?? a.command ?? a.query ?? a.url ?? a.pattern;
141
- return hint ? `${c.name}: ${String(hint).slice(0, 80)}` : c.name;
142
- }
@@ -0,0 +1,44 @@
1
+ // ACP authentication seam. The ACP link itself is a local stdio pipe (the OS process boundary is the trust
2
+ // boundary), so a loopback/LAN engine needs no sign-in. What DOES need one is an engine fronted by the AXE
3
+ // gateway (…axe.onl): without the operator bearer every prompt would 401 mid-turn. Surfacing that at
4
+ // `session/new` as ACP's `auth_required` lets the editor tell the user up front, and `authenticate` lets a
5
+ // login done AFTER the agent process started (the usual order: editor spawns us, user signs in in a
6
+ // terminal) take effect without restarting the agent.
7
+ import { loadCredentials } from "../auth/store.js";
8
+ import { verifyToken } from "../auth/client.js";
9
+ import { resolveSeat } from "../auth/identity.js";
10
+ import { requiresOperatorToken, setOperatorToken } from "../engine/aurora.js";
11
+ import { applySeat, setActiveSeat } from "../config/settings.js";
12
+ export const ACP_AUTH_METHOD_ID = "operator-login";
13
+ export const ACP_AUTH_METHOD = {
14
+ id: ACP_AUTH_METHOD_ID,
15
+ name: "Sign in to Operator",
16
+ description: "Run `operator auth login` in a terminal (email code or browser), then retry.",
17
+ };
18
+ export function defaultAcpAuth(settings, opts = {}) {
19
+ return {
20
+ required: () => !!opts.requireSignIn || requiresOperatorToken(settings.endpoints?.aurora?.base),
21
+ async check(verify) {
22
+ const env = process.env.KODE_OPERATOR_TOKEN;
23
+ const creds = env ? { token: env, user: undefined } : await loadCredentials().catch(() => null);
24
+ if (!creds?.token)
25
+ return { ok: false };
26
+ // A managed sign-in requirement that resolved to a lockdown (expired / foreign-domain / rejected) is not "signed in".
27
+ if (!verify)
28
+ return opts.requireSignIn && settings.seat?.source === "lockdown" ? { ok: false } : { ok: true, subject: creds.user };
29
+ const account = await verifyToken(creds.token);
30
+ if (!account)
31
+ return { ok: false };
32
+ setOperatorToken(creds.token);
33
+ // The seat was resolved at process start, possibly as a signed-out lockdown. Re-resolve it now that
34
+ // there is an identity, on the SHARED settings object, so sessions created from here on get the tier
35
+ // this identity is entitled to (and the audit trail names it).
36
+ const { seat } = await resolveSeat(settings, { creds });
37
+ setActiveSeat(seat);
38
+ Object.assign(settings, applySeat(settings, seat));
39
+ if (opts.requireSignIn && seat.source === "lockdown")
40
+ return { ok: false };
41
+ return { ok: true, subject: account.external_id };
42
+ },
43
+ };
44
+ }
@@ -0,0 +1,41 @@
1
+ // ACP prompt content blocks -> the plain text Session.send expects. A resource_link / embedded resource
2
+ // becomes a labelled `@path` mention the agent can act on; file:// URIs are turned into paths (relative to
3
+ // the session root when inside it) because that is the form the file tools and the model both understand.
4
+ import { fileURLToPath } from "node:url";
5
+ import { isAbsolute, relative } from "node:path";
6
+ export function uriToMention(uri, cwd) {
7
+ if (!uri.startsWith("file://"))
8
+ return `@${uri}`;
9
+ let p;
10
+ try {
11
+ p = fileURLToPath(uri);
12
+ }
13
+ catch {
14
+ return `@${uri}`;
15
+ }
16
+ if (cwd) {
17
+ const rel = relative(cwd, p);
18
+ if (rel && !rel.startsWith("..") && !isAbsolute(rel))
19
+ return `@${rel}`;
20
+ }
21
+ return `@${p}`;
22
+ }
23
+ export function promptToText(blocks, cwd) {
24
+ return blocks
25
+ .map((b) => {
26
+ if (b.type === "text")
27
+ return b.text;
28
+ if (b.type === "resource_link")
29
+ return uriToMention(b.uri, cwd);
30
+ if (b.type === "resource") {
31
+ const r = b.resource;
32
+ const label = r.uri ? uriToMention(r.uri, cwd) : "";
33
+ if (typeof r.text === "string")
34
+ return label ? `${label}\n${r.text}` : r.text;
35
+ return label;
36
+ }
37
+ return "";
38
+ })
39
+ .filter(Boolean)
40
+ .join("\n");
41
+ }
package/dist/acp/run.js CHANGED
@@ -1,8 +1,9 @@
1
1
  // `operator acp` — run Operator as an ACP agent over stdio. An ACP client (Zed, or VS Code via a bridge)
2
2
  // spawns this process and speaks JSON-RPC on stdin/stdout. stdout is therefore the PROTOCOL channel and must
3
- // carry nothing else, so we route console.* to stderr up front (a stray log would corrupt the framing).
3
+ // carry nothing else: we take a private handle on the real stdout, then repoint process.stdout.write (and
4
+ // console.*) at stderr, so a stray write from any dependency can never corrupt the framing.
4
5
  import { AgentSideConnection, ndJsonStream } from "@zed-industries/agent-client-protocol";
5
- import { Readable, Writable } from "node:stream";
6
+ import { Readable } from "node:stream";
6
7
  import { OperatorAcpAgent } from "./agent.js";
7
8
  import { translateSetConfigOption } from "./config-options.js";
8
9
  // GW-40 protocol shim. The stabilized spec's `session/set_config_option` is NOT in our pinned SDK
@@ -49,8 +50,10 @@ export class SetConfigOptionShim {
49
50
  return line;
50
51
  try {
51
52
  const msg = JSON.parse(line);
52
- const sid = msg && typeof msg.id !== "undefined" && this.pending.get(msg.id);
53
- if (sid !== undefined) {
53
+ // Responses only. The agent also sends REQUESTS (session/request_permission) whose ids come from the
54
+ // agent's own counter and can collide with a client id still pending here — never rewrite those.
55
+ const sid = msg && !("method" in msg) && typeof msg.id !== "undefined" && this.pending.get(msg.id);
56
+ if (sid !== undefined && sid !== false) {
54
57
  this.pending.delete(msg.id);
55
58
  if (!msg.error && this.agent)
56
59
  msg.result = this.agent.currentConfigOptions(sid);
@@ -82,23 +85,45 @@ export function rewriteIn(line, pending) {
82
85
  return line;
83
86
  }
84
87
  }
88
+ /** Serve one ACP connection over the given streams until the client detaches, then tear every session down.
89
+ * Split from runAcp so the whole handshake -> prompt -> permission path is testable over in-memory streams. */
90
+ export async function serveAcp(settings, io, deps = {}) {
91
+ const shim = new SetConfigOptionShim();
92
+ const outT = shim.output();
93
+ void outT.readable.pipeTo(io.output).catch(() => { });
94
+ const stream = ndJsonStream(outT.writable, io.input.pipeThrough(shim.input()));
95
+ let agent = null;
96
+ new AgentSideConnection((conn) => (agent = shim.agent = new OperatorAcpAgent(conn, settings, deps.sessionFactory, deps.agentOpts)), stream);
97
+ await io.closed;
98
+ const a = agent;
99
+ a?.dispose("client_closed");
100
+ await a?.drain(deps.drainMs ?? 2000);
101
+ return 0;
102
+ }
85
103
  export async function runAcp(settings) {
86
- // Safety net: anything that reaches for stdout (an MCP server, a dependency) would break the JSON-RPC
87
- // stream. Send every console channel to stderr; the ACP connection owns stdout exclusively.
104
+ // Take the real stdout for the protocol BEFORE anything is redirected, then send every other writer to
105
+ // stderr: process.stdout.write itself (any dependency, MCP child glue, a stray console.log) and the
106
+ // console channels. The connection owns the real handle exclusively.
107
+ const realWrite = process.stdout.write.bind(process.stdout);
108
+ process.stdout.write = ((chunk, encOrCb, cb) => process.stderr.write(chunk, encOrCb, cb));
88
109
  for (const k of ["log", "info", "debug", "warn"]) {
89
110
  console[k] = (...args) => process.stderr.write(args.map(String).join(" ") + "\n");
90
111
  }
91
- const output = Writable.toWeb(process.stdout);
112
+ // A background promise that rejects (consolidation, a dying MCP child) must not kill an editor session.
113
+ const onRejection = (e) => process.stderr.write(`[operator-acp] unhandled rejection: ${e instanceof Error ? e.message : String(e)}\n`);
114
+ process.on("unhandledRejection", onRejection);
115
+ const output = new WritableStream({
116
+ write: (chunk) => new Promise((resolve, reject) => { realWrite(chunk, (err) => (err ? reject(err) : resolve())); }),
117
+ });
92
118
  const input = Readable.toWeb(process.stdin);
93
- const shim = new SetConfigOptionShim();
94
- const outT = shim.output();
95
- void outT.readable.pipeTo(output).catch(() => { });
96
- const stream = ndJsonStream(outT.writable, input.pipeThrough(shim.input()));
97
- // The connection lives until the client closes stdin (the editor detached / quit).
98
- new AgentSideConnection((conn) => (shim.agent = new OperatorAcpAgent(conn, settings)), stream);
99
- await new Promise((resolve) => {
119
+ const closed = new Promise((resolve) => {
100
120
  process.stdin.once("end", resolve);
101
121
  process.stdin.once("close", resolve);
102
122
  });
103
- return 0;
123
+ try {
124
+ return await serveAcp(settings, { input, output, closed });
125
+ }
126
+ finally {
127
+ process.off("unhandledRejection", onRejection);
128
+ }
104
129
  }