@0perator/operator 0.1.222 → 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 (110) hide show
  1. package/README.md +6 -5
  2. package/dashboard/server.mjs +1 -1
  3. package/dist/acp/agent.js +320 -53
  4. package/dist/acp/auth.js +44 -0
  5. package/dist/acp/config-options.js +34 -0
  6. package/dist/acp/prompt.js +41 -0
  7. package/dist/acp/run.js +116 -10
  8. package/dist/acp/tool-map.js +48 -0
  9. package/dist/auth/byo.js +125 -0
  10. package/dist/auth/client.js +12 -6
  11. package/dist/auth/commands.js +71 -3
  12. package/dist/auth/identity.js +136 -0
  13. package/dist/auth/store.js +7 -5
  14. package/dist/autonomy/board.js +3 -2
  15. package/dist/autonomy/cron.js +332 -0
  16. package/dist/autonomy/delegate.js +168 -0
  17. package/dist/autonomy/dream.js +1 -1
  18. package/dist/autonomy/index.js +16 -2
  19. package/dist/autonomy/media-robot.js +137 -0
  20. package/dist/autonomy/profile.js +77 -0
  21. package/dist/autonomy/routines.js +5 -4
  22. package/dist/autonomy/session-factory.js +19 -10
  23. package/dist/background/index.js +8 -1
  24. package/dist/browser/cdp.js +266 -0
  25. package/dist/browser/session.js +286 -0
  26. package/dist/cli.js +207 -106
  27. package/dist/compose/client.js +56 -0
  28. package/dist/config/brand.js +3 -3
  29. package/dist/config/home.js +70 -0
  30. package/dist/config/managed.js +230 -0
  31. package/dist/config/persona.js +243 -21
  32. package/dist/config/scaffold.js +142 -0
  33. package/dist/config/settings.js +87 -20
  34. package/dist/config/skills-index.js +175 -0
  35. package/dist/consolidation/scheduler.js +10 -7
  36. package/dist/consolidation/sleep.js +17 -3
  37. package/dist/engine/agent.js +231 -21
  38. package/dist/engine/aurora.js +79 -14
  39. package/dist/engine/batch-scheduler.js +128 -0
  40. package/dist/engine/compaction.js +129 -2
  41. package/dist/engine/computer-event.js +139 -0
  42. package/dist/engine/continuation.js +55 -0
  43. package/dist/engine/contract.js +3 -1
  44. package/dist/engine/grandmaster.js +13 -3
  45. package/dist/engine/json-repair.js +105 -0
  46. package/dist/engine/messages.js +52 -5
  47. package/dist/engine/redact.js +25 -0
  48. package/dist/engine/rolling-summary.js +28 -11
  49. package/dist/engine/router-adapter.js +2 -0
  50. package/dist/engine/unrestricted.js +51 -0
  51. package/dist/engine/verify-gate.js +6 -0
  52. package/dist/enterprise/cli.js +137 -0
  53. package/dist/flywheel/processor.js +30 -2
  54. package/dist/flywheel/secret-gate.js +123 -0
  55. package/dist/index.browser.js +4 -0
  56. package/dist/index.js +4 -0
  57. package/dist/mcp/index.js +18 -24
  58. package/dist/memory/index.js +0 -0
  59. package/dist/memory/session-index.js +324 -0
  60. package/dist/memory/session-rewind.js +92 -0
  61. package/dist/memory/state-maintenance.js +441 -0
  62. package/dist/observability/index.js +3 -3
  63. package/dist/permissions/audit.js +4 -1
  64. package/dist/permissions/index.js +24 -12
  65. package/dist/permissions/policy.js +4 -3
  66. package/dist/permissions/tier.js +31 -14
  67. package/dist/remote/host.js +9 -2
  68. package/dist/router/models.js +62 -2
  69. package/dist/selfimprove/index.js +9 -7
  70. package/dist/session.js +129 -42
  71. package/dist/skills/catalogue.js +167 -0
  72. package/dist/telemetry/audit-verify.js +94 -0
  73. package/dist/telemetry/events.js +92 -7
  74. package/dist/telemetry/lifecycle.js +18 -0
  75. package/dist/tools/computer.js +1 -1
  76. package/dist/tools/deferred.js +117 -0
  77. package/dist/tools/executor.js +27 -23
  78. package/dist/tools/memory.js +117 -0
  79. package/dist/tools/mutating.js +6 -0
  80. package/dist/tools/registry.js +1022 -46
  81. package/dist/tools/sandbox.js +63 -17
  82. package/dist/tools/searxng.js +2 -2
  83. package/dist/tools/shell-session.js +36 -1
  84. package/dist/tools/tool-output-spill.js +4 -4
  85. package/dist/ui/ActivitySpinner.js +17 -6
  86. package/dist/ui/App.js +36 -14
  87. package/dist/ui/ArtifactPicker.js +109 -0
  88. package/dist/ui/Composer.js +39 -8
  89. package/dist/ui/Markdown.js +5 -3
  90. package/dist/ui/MouseProvider.js +99 -19
  91. package/dist/ui/QuestionPrompt.js +24 -3
  92. package/dist/ui/ThinkingSpinner.js +9 -5
  93. package/dist/ui/ToolStep.js +17 -12
  94. package/dist/ui/Transcript.js +28 -9
  95. package/dist/ui/capabilities.js +0 -9
  96. package/dist/ui/listhit.js +23 -0
  97. package/dist/ui/mouse.js +22 -0
  98. package/dist/ui/osc.js +7 -4
  99. package/dist/ui/progressbar.js +46 -0
  100. package/dist/ui/shimmer.js +43 -0
  101. package/dist/ui/theme.js +2 -0
  102. package/dist/ui/tick.js +48 -0
  103. package/dist/ui/toolicons.js +69 -0
  104. package/dist/ui/useInputHistory.js +3 -3
  105. package/dist/util/slash.js +1 -0
  106. package/dist/vault/cli.js +48 -0
  107. package/dist/vault/store.js +157 -0
  108. package/dist/vault/tool.js +50 -0
  109. package/package.json +3 -5
  110. package/CHANGELOG.md +0 -1629
package/dist/acp/run.js CHANGED
@@ -1,23 +1,129 @@
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";
8
+ import { translateSetConfigOption } from "./config-options.js";
9
+ // GW-40 protocol shim. The stabilized spec's `session/set_config_option` is NOT in our pinned SDK
10
+ // (0.4.5) — its dispatcher is a closed switch that would answer method-not-found. Rather than
11
+ // upgrade a protocol dependency mid-flight, we translate on the wire: inbound
12
+ // set_config_option{configId:"model"} -> legacy set_model (both land in Agent.setSessionModel),
13
+ // outbound response -> the spec's complete-configOptions result. JSON-RPC ids are remembered only
14
+ // for in-flight requests (deleted on answer), so a client reusing ids stays correct.
15
+ export class SetConfigOptionShim {
16
+ pending = new Map(); // rpc id -> sessionId
17
+ agent = null;
18
+ input() {
19
+ let buf = "";
20
+ const pending = this.pending;
21
+ return new TransformStream({
22
+ transform(chunk, controller) {
23
+ buf += new TextDecoder().decode(chunk, { stream: true });
24
+ const parts = buf.split("\n");
25
+ buf = parts.pop() ?? "";
26
+ for (const line of parts)
27
+ controller.enqueue(new TextEncoder().encode(rewriteIn(line, pending) + "\n"));
28
+ },
29
+ flush(controller) { if (buf)
30
+ controller.enqueue(new TextEncoder().encode(rewriteIn(buf, pending) + "\n")); },
31
+ });
32
+ }
33
+ output() {
34
+ let buf = "";
35
+ const self = this;
36
+ return new TransformStream({
37
+ transform(chunk, controller) {
38
+ buf += new TextDecoder().decode(chunk, { stream: true });
39
+ const parts = buf.split("\n");
40
+ buf = parts.pop() ?? "";
41
+ for (const line of parts)
42
+ controller.enqueue(new TextEncoder().encode(self.rewriteOut(line) + "\n"));
43
+ },
44
+ flush(controller) { if (buf)
45
+ controller.enqueue(new TextEncoder().encode(self.rewriteOut(buf) + "\n")); },
46
+ });
47
+ }
48
+ rewriteOut(line) {
49
+ if (!line.trim())
50
+ return line;
51
+ try {
52
+ const msg = JSON.parse(line);
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) {
57
+ this.pending.delete(msg.id);
58
+ if (!msg.error && this.agent)
59
+ msg.result = this.agent.currentConfigOptions(sid);
60
+ }
61
+ return JSON.stringify(msg);
62
+ }
63
+ catch {
64
+ return line;
65
+ }
66
+ }
67
+ }
68
+ export function rewriteIn(line, pending) {
69
+ if (!line.trim())
70
+ return line;
71
+ try {
72
+ const msg = JSON.parse(line);
73
+ if (msg?.method === "session/set_config_option" && typeof msg.id !== "undefined") {
74
+ const t = translateSetConfigOption(msg.params);
75
+ if (t) {
76
+ pending.set(msg.id, t.sessionId);
77
+ msg.method = "session/set_model";
78
+ msg.params = { sessionId: t.sessionId, modelId: t.modelId };
79
+ return JSON.stringify(msg);
80
+ }
81
+ }
82
+ return line;
83
+ }
84
+ catch {
85
+ return line;
86
+ }
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
+ }
7
103
  export async function runAcp(settings) {
8
- // Safety net: anything that reaches for stdout (an MCP server, a dependency) would break the JSON-RPC
9
- // 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));
10
109
  for (const k of ["log", "info", "debug", "warn"]) {
11
110
  console[k] = (...args) => process.stderr.write(args.map(String).join(" ") + "\n");
12
111
  }
13
- 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
+ });
14
118
  const input = Readable.toWeb(process.stdin);
15
- const stream = ndJsonStream(output, input);
16
- // The connection lives until the client closes stdin (the editor detached / quit).
17
- new AgentSideConnection((conn) => new OperatorAcpAgent(conn, settings), stream);
18
- await new Promise((resolve) => {
119
+ const closed = new Promise((resolve) => {
19
120
  process.stdin.once("end", resolve);
20
121
  process.stdin.once("close", resolve);
21
122
  });
22
- return 0;
123
+ try {
124
+ return await serveAcp(settings, { input, output, closed });
125
+ }
126
+ finally {
127
+ process.off("unhandledRejection", onRejection);
128
+ }
23
129
  }
@@ -0,0 +1,48 @@
1
+ // Pure mapping from Operator tool calls/results to the ACP vocabulary an editor renders: a tool `kind` (icon +
2
+ // grouping), a human title, the file `locations` the editor can follow, and a completed/failed status. Kept
3
+ // separate from agent.ts so the mapping is unit-testable without a connection or a model.
4
+ import { homedir } from "node:os";
5
+ import { isAbsolute, resolve } from "node:path";
6
+ import { isErrorResult } from "../ui/format.js";
7
+ const KINDS = {
8
+ file_read: "read", read_files: "read", list_directory: "read", git_status: "read", session_read: "read",
9
+ skill_fetch: "read", skill_list: "read", task_list: "read", image_analyze: "read", video_analyze: "read",
10
+ grep_search: "search", search: "search", memory_search: "search", session_search: "search", web_search: "search",
11
+ file_write: "edit", file_edit: "edit", memory_store: "edit", skill_save: "edit", scratchpad: "edit", session_handoff: "edit",
12
+ bash: "execute", shell_exec: "execute", shell_background: "execute", bash_kill: "execute", bash_output: "execute",
13
+ git_command: "execute", checkpoint: "execute", cronjob: "execute",
14
+ web_fetch: "fetch", http_request: "fetch", browser: "fetch", browser_read: "fetch",
15
+ delegate_task: "think",
16
+ };
17
+ export function toolKind(name) {
18
+ return KINDS[name] ?? "other";
19
+ }
20
+ /** "file_edit: src/x.ts", "bash: npm test" — the tool-timeline row label. */
21
+ export function toolTitle(name, args) {
22
+ const a = args ?? {};
23
+ const hint = a.path ?? a.file_path ?? a.command ?? a.query ?? a.url ?? a.pattern;
24
+ return hint ? `${name}: ${String(hint).slice(0, 80)}` : name;
25
+ }
26
+ /** The files a call touches, absolute, so the editor can open/follow them. Only paths that are plainly named
27
+ * by the call's own args — never guessed from free text. */
28
+ export function toolLocations(args, cwd) {
29
+ const a = args ?? {};
30
+ const raw = [a.path, a.file_path, a.file, a.filename].find((v) => typeof v === "string" && v.length > 0);
31
+ if (!raw)
32
+ return [];
33
+ if (raw.startsWith("~/"))
34
+ return [{ path: resolve(homedir(), raw.slice(2)) }];
35
+ if (isAbsolute(raw))
36
+ return [{ path: raw }];
37
+ return cwd ? [{ path: resolve(cwd, raw) }] : [];
38
+ }
39
+ /** A tool result reads as failed when it is an engine error/loop-guard/interrupt sentinel, a permission/tier
40
+ * refusal, or a sandbox block — the editor should paint those red instead of "completed". */
41
+ export function resultStatus(result) {
42
+ return isErrorResult(result) || /^(permission denied|sandbox)/i.test(result.trim()) ? "failed" : "completed";
43
+ }
44
+ export const MAX_RESULT_CHARS = 50_000;
45
+ /** One tool result is one JSON-RPC line to the editor; an uncapped `cat` of a build log would stall the pipe. */
46
+ export function capResult(result, max = MAX_RESULT_CHARS) {
47
+ return result.length <= max ? result : `${result.slice(0, max)}\n… [truncated ${result.length - max} chars for the editor]`;
48
+ }
@@ -0,0 +1,125 @@
1
+ // BYO vendor-key store (SPEC/providers.md §3: API-key connector, "paste once; stored in the Keychain";
2
+ // §5's gateway-first rule stays for api.axe.onl-routed models — a BYO connector is exactly the rare
3
+ // "client itself calls a vendor directly" fast path the spec allows, and the vendor key NEVER touches
4
+ // the gateway). Distinct keychain SERVICE from the operator token ("axe-operator") so a vendor key can
5
+ // never be read/mistaken for the operator bearer by any client — the separation IS the leak guard.
6
+ // Env override per account: KODE_BYO_<ACCOUNT> (uppercase, non-alnum → "_") for CI/headless.
7
+ // KODE_NO_KEYCHAIN=1 forces the 0600 JSON file (same convention as auth/store.ts).
8
+ import { execFileSync, spawnSync } from "node:child_process";
9
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { platform } from "node:os";
11
+ import { dirname } from "node:path";
12
+ import { operatorPath } from "../config/home.js";
13
+ const SERVICE = "axe-operator-byo";
14
+ // Resolved per call, not at import: the file follows $KODE_HOME / $KODE_PROFILE, so a profile's vendor keys
15
+ // never land in (or get read from) another identity's file.
16
+ const byoFile = () => process.env.KODE_BYO_FILE ?? operatorPath("byo.json");
17
+ const NO_KEYCHAIN = process.env.KODE_NO_KEYCHAIN === "1";
18
+ function envName(account) {
19
+ return "KODE_BYO_" + account.toUpperCase().replace(/[^A-Z0-9]/g, "_");
20
+ }
21
+ function readFile_() {
22
+ try {
23
+ const j = JSON.parse(readFileSync(byoFile(), "utf8"));
24
+ return j && typeof j === "object" ? j : {};
25
+ }
26
+ catch {
27
+ return {};
28
+ }
29
+ }
30
+ function writeFile_(map) {
31
+ mkdirSync(dirname(byoFile()), { recursive: true, mode: 0o700 });
32
+ writeFileSync(byoFile(), JSON.stringify(map, null, 1), { mode: 0o600 });
33
+ try {
34
+ chmodSync(byoFile(), 0o600);
35
+ }
36
+ catch { /* best-effort: a pre-existing looser file is tightened */ }
37
+ }
38
+ /** Sync read: env override → OS keychain → 0600 file fallback. Used by setModel (sync path).
39
+ * Keychain/file lookups are memoized per account: buildCapabilities calls the registry liberally and
40
+ * every miss would spawn `security`. Env stays live (process.env is cheap, CI can flip it mid-run). */
41
+ const _cache = new Map();
42
+ export function getByoToken(account) {
43
+ const env = process.env[envName(account)];
44
+ if (env)
45
+ return env.trim() || undefined;
46
+ if (_cache.has(account))
47
+ return _cache.get(account);
48
+ let found;
49
+ if (!NO_KEYCHAIN) {
50
+ try {
51
+ if (platform() === "darwin") {
52
+ const out = execFileSync("security", ["find-generic-password", "-s", SERVICE, "-a", account, "-w"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
53
+ if (out.trim())
54
+ found = out.trim();
55
+ }
56
+ else if (platform() === "linux") {
57
+ const out = execFileSync("secret-tool", ["lookup", "service", SERVICE, "account", account], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
58
+ if (out.trim())
59
+ found = out.trim();
60
+ }
61
+ }
62
+ catch { /* not stored here → fall through */ }
63
+ }
64
+ if (!found)
65
+ found = readFile_()[account] || undefined;
66
+ _cache.set(account, found);
67
+ return found;
68
+ }
69
+ /** True when an account's key resolves — the connector "Connected" state for pickers/gates. */
70
+ export function hasByoToken(account) {
71
+ return !!getByoToken(account);
72
+ }
73
+ export function clearByoCache(account) {
74
+ if (account)
75
+ _cache.delete(account);
76
+ else
77
+ _cache.clear();
78
+ }
79
+ /** Delete from all three tiers (env is the caller's process, only noted). */
80
+ export function deleteByoToken(account) {
81
+ try {
82
+ if (!NO_KEYCHAIN && platform() === "darwin") {
83
+ spawnSync("security", ["delete-generic-password", "-s", SERVICE, "-a", account], { stdio: "ignore" });
84
+ }
85
+ else if (!NO_KEYCHAIN && platform() === "linux") {
86
+ spawnSync("secret-tool", ["clear", "service", SERVICE, "account", account], { stdio: "ignore" });
87
+ }
88
+ }
89
+ catch { /* file tier below still cleans */ }
90
+ const m = readFile_();
91
+ if (account in m) {
92
+ delete m[account];
93
+ writeFile_(m);
94
+ }
95
+ clearByoCache(account);
96
+ }
97
+ /** Accounts with a stored key (file + keychain best-effort; for `operator auth byo` listing). */
98
+ export function listByoAccounts() {
99
+ return Object.keys(readFile_()).filter((a) => !!readFile_()[a]);
100
+ }
101
+ /**
102
+ * Interactive paste-and-store on the real TTY. macOS: `security add-generic-password -w` with NO value
103
+ * arg prompts twice with HIDDEN input — the key never echoes, never lands in shell history, and never
104
+ * passes through this process's memory at all. Non-mac / KODE_NO_KEYCHAIN: pass the key via
105
+ * KODE_BYO_<ACCOUNT> (or a direct 0600 write to the byo file) — we deliberately do NOT prompt in clear
106
+ * text where we cannot guarantee echo-off. Returns ok; the value is never logged.
107
+ */
108
+ export function setByoTokenInteractive(account) {
109
+ if (!NO_KEYCHAIN && platform() === "darwin") {
110
+ const r = spawnSync("security", ["add-generic-password", "-U", "-s", SERVICE, "-a", account, "-w"], { stdio: "inherit" });
111
+ if (r.status !== 0)
112
+ return false;
113
+ clearByoCache(account); // a fresh paste must beat the memoized miss
114
+ return true;
115
+ }
116
+ const env = getByoToken(account); // honors KODE_BYO_<ACCOUNT> when present
117
+ if (!env) {
118
+ process.stderr.write(`no keychain here — set ${envName(account)} or write ${byoFile()} (0600)\n`);
119
+ return false;
120
+ }
121
+ const m = readFile_();
122
+ m[account] = env;
123
+ writeFile_(m);
124
+ return true;
125
+ }
@@ -71,8 +71,7 @@ export async function awaitApproval(dc, opts = {}) {
71
71
  return r; // approved | denied | expired
72
72
  }
73
73
  }
74
- /** Validate a token (PAT or device-minted) against the backend. Returns the Account or null. */
75
- export async function verifyToken(token, timeoutMs = 10_000) {
74
+ export async function verifyTokenDetailed(token, timeoutMs = 10_000) {
76
75
  const ctrl = new AbortController();
77
76
  const t = setTimeout(() => ctrl.abort(), timeoutMs);
78
77
  try {
@@ -80,18 +79,25 @@ export async function verifyToken(token, timeoutMs = 10_000) {
80
79
  headers: { authorization: `Bearer ${token}` },
81
80
  signal: ctrl.signal,
82
81
  });
82
+ if (res.status >= 500)
83
+ return { state: "unreachable" }; // a sick backend is not a verdict on the token
83
84
  if (res.status !== 200)
84
- return null;
85
- const json = await res.json().catch(() => ({}));
86
- return (json.account ?? null);
85
+ return { state: "rejected", status: res.status };
86
+ const json = (await res.json().catch(() => ({})));
87
+ return json.account ? { state: "ok", account: json.account, raw: json } : { state: "rejected", status: 200 };
87
88
  }
88
89
  catch {
89
- return null;
90
+ return { state: "unreachable" };
90
91
  }
91
92
  finally {
92
93
  clearTimeout(t);
93
94
  }
94
95
  }
96
+ /** Validate a token (PAT or device-minted) against the backend. Returns the Account or null. */
97
+ export async function verifyToken(token, timeoutMs = 10_000) {
98
+ const r = await verifyTokenDetailed(token, timeoutMs);
99
+ return r.state === "ok" ? r.account : null;
100
+ }
95
101
  export function authBase() {
96
102
  return AUTH_BASE;
97
103
  }
@@ -16,6 +16,19 @@ import { platform } from "node:os";
16
16
  import { createInterface } from "node:readline/promises";
17
17
  import { requestDeviceCode, awaitApproval, verifyToken, authBase, signupStart, signupVerify, } from "./client.js";
18
18
  import { saveCredentials, loadCredentials, clearCredentials } from "./store.js";
19
+ import { listByoAccounts, hasByoToken, deleteByoToken, setByoTokenInteractive } from "./byo.js";
20
+ import { auditControl } from "../telemetry/lifecycle.js";
21
+ // Credential-lifecycle audit (inert unless the seat is audited — see telemetry/lifecycle.ts). Module-level
22
+ // because every login path ends in the same few exits; runAuth sets it once from the CLI's settings.
23
+ let auditCfg;
24
+ const audit = (event, detail, sub) => auditControl(auditCfg, event, detail, sub);
25
+ /** Read a secret from a stream (piped stdin) — keeps a token off argv, shell history and the process list. */
26
+ export async function readSecretFromStream(stream) {
27
+ let buf = "";
28
+ for await (const chunk of stream)
29
+ buf += chunk.toString();
30
+ return buf.trim();
31
+ }
19
32
  /** One-line prompt on the real TTY. Runs before Ink mounts, so plain readline is safe. */
20
33
  async function ask(question) {
21
34
  const rl = createInterface({ input: process.stdin, output: process.stdout });
@@ -59,6 +72,7 @@ async function loginEmail(emailArg) {
59
72
  console.error("✗ too many codes requested for that address — wait a few minutes, then try again");
60
73
  else
61
74
  console.error(`✗ couldn't start sign-in via ${authBase()} (${started.error})`);
75
+ await audit("auth_failed", `method=email stage=start reason=${started.error}`);
62
76
  return 1;
63
77
  }
64
78
  console.log(`\n ✓ Sent a 6-digit code to ${email} (valid 10 minutes).`);
@@ -74,12 +88,14 @@ async function loginEmail(emailArg) {
74
88
  if (v.ok) {
75
89
  await saveCredentials({ token: v.token, user: v.account.external_id, host: authBase(), issuedAt: Date.now() });
76
90
  console.log(`\n ✓ signed in as ${v.account.email ?? v.account.external_id}\n`);
91
+ await audit("auth_login", `method=email host=${authBase()}`, v.account.external_id);
77
92
  return 0;
78
93
  }
79
94
  if (v.error === "invalid_code") {
80
95
  console.error(attempt < 5 ? " ✗ wrong code — try again" : " ✗ wrong code");
81
96
  continue;
82
97
  }
98
+ await audit("auth_failed", `method=email stage=verify reason=${v.error}`);
83
99
  if (v.error === "no_pending_code") {
84
100
  console.error("✗ that code expired — run `operator auth login` again for a fresh one");
85
101
  return 1;
@@ -91,6 +107,7 @@ async function loginEmail(emailArg) {
91
107
  console.error(`✗ sign-in failed (${v.error})`);
92
108
  return 1;
93
109
  }
110
+ await audit("auth_failed", "method=email stage=verify reason=too_many_wrong_codes");
94
111
  console.error("✗ too many wrong tries — run `operator auth login` again for a fresh code");
95
112
  return 1;
96
113
  }
@@ -99,10 +116,12 @@ async function loginToken(token) {
99
116
  const account = await verifyToken(token);
100
117
  if (!account) {
101
118
  console.error("✗ that token was rejected by " + authBase());
119
+ await audit("auth_failed", "method=token reason=rejected");
102
120
  return 1;
103
121
  }
104
122
  await saveCredentials({ token, user: account.external_id, host: authBase(), issuedAt: Date.now() });
105
123
  console.log(`✓ signed in as ${account.email ?? account.external_id} (personal access token)`);
124
+ await audit("auth_login", `method=token host=${authBase()}`, account.external_id);
106
125
  return 0;
107
126
  }
108
127
  // --- RFC 8628 device grant (browser) ------------------------------------------------
@@ -130,10 +149,12 @@ async function loginDevice() {
130
149
  process.stdout.write("\n");
131
150
  if (r.state !== "approved") {
132
151
  console.error(`✗ sign-in ${r.state === "expired" ? "timed out" : r.state}`);
152
+ await audit("auth_failed", `method=browser reason=${r.state}`);
133
153
  return 1;
134
154
  }
135
155
  await saveCredentials({ token: r.token, user: r.account.external_id, host: authBase(), issuedAt: Date.now() });
136
156
  console.log(`✓ signed in as ${r.account.email ?? r.account.external_id}`);
157
+ await audit("auth_login", `method=browser host=${authBase()}`, r.account.external_id);
137
158
  return 0;
138
159
  }
139
160
  finally {
@@ -149,8 +170,10 @@ async function loginDefault() {
149
170
  return loginDevice();
150
171
  }
151
172
  async function logout() {
173
+ const who = (await loadCredentials().catch(() => null))?.user;
152
174
  await clearCredentials();
153
175
  console.log("✓ signed out");
176
+ await audit("auth_logout", "credentials cleared", who);
154
177
  return 0;
155
178
  }
156
179
  async function status() {
@@ -171,14 +194,58 @@ function flagValue(rest, flag) {
171
194
  const i = rest.indexOf(flag);
172
195
  return i >= 0 ? rest[i + 1] : undefined;
173
196
  }
197
+ /** `operator auth byo [account] [--list|--rm]` — BYO vendor-key connectors (SPEC/providers.md §2/§3):
198
+ * hidden paste into the OS keychain under the SEPARATE `axe-operator-byo` service (an operator token
199
+ * and a vendor key can never be confused), then /model's connectors light up. QwenCloud Token Plan
200
+ * example: `operator auth byo qwen` → paste the `sk-sp-…` key from home.qwencloud.com. */
201
+ async function byo(rest) {
202
+ const account = rest.find((a) => !a.startsWith("--"));
203
+ if (rest.includes("--list")) {
204
+ const accts = listByoAccounts();
205
+ for (const a of new Set([...accts, "qwen"]))
206
+ if (hasByoToken(a))
207
+ console.log(`connected: ${a}`);
208
+ if (!accts.length)
209
+ console.log('(no BYO keys stored yet — e.g. "operator auth byo qwen")');
210
+ return 0;
211
+ }
212
+ if (!account) {
213
+ console.error("usage: operator auth byo <account> | byo --list | byo <account> --rm");
214
+ return 1;
215
+ }
216
+ if (rest.includes("--rm")) {
217
+ deleteByoToken(account);
218
+ console.log(`✓ removed the ${account} key`);
219
+ await audit("credential_removed", `byo account=${account}`);
220
+ return 0;
221
+ }
222
+ if (setByoTokenInteractive(account)) {
223
+ console.log(`✓ ${account} key stored — /model now offers its connectors`);
224
+ await audit("credential_stored", `byo account=${account}`);
225
+ return 0;
226
+ }
227
+ console.error(`✗ could not store the ${account} key`);
228
+ return 1;
229
+ }
174
230
  /** Dispatch `operator auth <sub> [args]`. Returns a process exit code. */
175
- export async function runAuth(argv) {
231
+ export async function runAuth(argv, settings, stdin = process.stdin) {
232
+ auditCfg = settings;
176
233
  const [sub, ...rest] = argv;
177
234
  switch (sub) {
178
235
  case "login": {
236
+ if (rest.includes("--token-stdin")) {
237
+ const piped = await readSecretFromStream(stdin);
238
+ if (!piped) {
239
+ console.error("✗ --token-stdin: nothing on stdin (pipe the token in, e.g. `pass show operator | operator auth login --token-stdin`)");
240
+ return 1;
241
+ }
242
+ return loginToken(piped);
243
+ }
179
244
  const token = flagValue(rest, "--token");
180
- if (token)
245
+ if (token) {
246
+ console.error("note: a token on the command line is visible in the process list and shell history — prefer `--token-stdin` (or supply the operator token through the environment in CI).");
181
247
  return loginToken(token);
248
+ }
182
249
  const email = flagValue(rest, "--email");
183
250
  if (email)
184
251
  return loginEmail(email);
@@ -189,8 +256,9 @@ export async function runAuth(argv) {
189
256
  case "logout": return logout();
190
257
  case "status":
191
258
  case "whoami": return status();
259
+ case "byo": return byo(rest);
192
260
  default:
193
- console.log("usage: operator auth <login [--email <addr> | --browser | --token <pat>] | logout | status>");
261
+ console.log("usage: operator auth <login [--email <addr> | --browser | --token-stdin | --token <pat>] | logout | status | byo [account] [--list | --rm]>");
194
262
  return sub ? 1 : 0;
195
263
  }
196
264
  }
@@ -0,0 +1,136 @@
1
+ // Seat resolution — who is this process acting as, and what is the widest tier that identity may hold?
2
+ // Engine-side SSO/RBAC readiness. The engine does not run an IdP; it consumes what AuthGate already verifies
3
+ // (`GET /operator/verify`) and, when the org has deployed a managed auth policy (config/managed.ts), turns the
4
+ // verified claims into a tier CEILING:
5
+ //
6
+ // effective tier = narrowest of ( configured tier, claim tier, scope tier, role-map tier )
7
+ //
8
+ // Claims are OPTIONAL on the wire — the engine accepts, never requires, `account.tier`, `account.roles[]`,
9
+ // `account.groups[]` and an OAuth-style space-delimited `scope` (`operator:readonly|enterprise|admin`), so
10
+ // AuthGate can adopt them without a lockstep release. Identity can only NARROW a seat, never widen it: a
11
+ // token that says "admin" on a box whose policy says "enterprise" is an enterprise seat.
12
+ //
13
+ // With NO managed auth policy this is a no-op: no network, no behavior change for the local owner.
14
+ import { createHash } from "node:crypto";
15
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
16
+ import { dirname } from "node:path";
17
+ import { operatorPath } from "../config/home.js";
18
+ import { verifyTokenDetailed } from "./client.js";
19
+ const RANK = { readonly: 0, enterprise: 1, admin: 2 };
20
+ const isTier = (v) => v === "admin" || v === "enterprise" || v === "readonly";
21
+ export const narrowest = (tiers) => tiers.reduce((a, b) => (RANK[a] <= RANK[b] ? a : b));
22
+ export const widest = (tiers) => tiers.reduce((a, b) => (RANK[a] >= RANK[b] ? a : b));
23
+ const strList = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : typeof v === "string" ? v.split(/[\s,]+/).filter(Boolean) : []);
24
+ /** Tolerant parse of AuthGate's verify response: claims may sit on `account` or at the top level. */
25
+ export function claimsFromVerify(account, raw = {}) {
26
+ const pick = (k) => account[k] ?? raw[k];
27
+ return {
28
+ sub: account.external_id,
29
+ email: typeof account.email === "string" ? account.email : undefined,
30
+ tier: isTier(pick("tier")) ? pick("tier") : undefined,
31
+ roles: [...strList(pick("roles")), ...strList(pick("role"))],
32
+ groups: strList(pick("groups")),
33
+ scopes: strList(pick("scope")),
34
+ };
35
+ }
36
+ /** Claims -> a tier ceiling (or undefined = the claims say nothing about tiers). Every source that is present
37
+ * constrains; the NARROWEST wins, so a readonly-scoped PAT on an admin-role account is a readonly seat. */
38
+ export function tierFromClaims(c, policy) {
39
+ const found = [];
40
+ const why = [];
41
+ if (c.tier) {
42
+ found.push(c.tier);
43
+ why.push(`claim tier=${c.tier}`);
44
+ }
45
+ const scopeTiers = c.scopes.map((s) => /^operator:(admin|enterprise|readonly)$/.exec(s)?.[1]).filter(isTier);
46
+ if (scopeTiers.length) {
47
+ const t = widest(scopeTiers);
48
+ found.push(t);
49
+ why.push(`scope=${t}`);
50
+ }
51
+ if (policy?.roleTiers) {
52
+ const matched = [...c.roles, ...c.groups].map((n) => policy.roleTiers[n]).filter(isTier);
53
+ const t = matched.length ? widest(matched) : (policy.defaultTier ?? "readonly");
54
+ found.push(t);
55
+ why.push(matched.length ? `role-map=${t}` : `no role matched -> default ${t}`);
56
+ }
57
+ return found.length ? { tier: narrowest(found), reason: why.join(", ") } : { reason: "no tier-relevant claims" };
58
+ }
59
+ const fingerprint = (token) => createHash("sha256").update(token).digest("hex").slice(0, 16);
60
+ function readCache(path) {
61
+ try {
62
+ return JSON.parse(readFileSync(path, "utf8"));
63
+ }
64
+ catch {
65
+ return null;
66
+ }
67
+ }
68
+ function writeCache(path, c) {
69
+ try {
70
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
71
+ writeFileSync(path, JSON.stringify(c), { mode: 0o600 });
72
+ chmodSync(path, 0o600);
73
+ }
74
+ catch { /* the cache only buys offline grace; failing to write it must not fail startup */ }
75
+ }
76
+ /** Resolve the seat for this process. Never throws; with no managed auth policy it never touches the network. */
77
+ export async function resolveSeat(settings, deps) {
78
+ const configured = settings.seat?.configured ?? settings.permissions.tier ?? "admin";
79
+ const policy = settings.managed?.auth;
80
+ const creds = deps.creds;
81
+ const now = deps.now?.() ?? Date.now();
82
+ const local = (reasons) => ({ seat: { tier: configured, configured, source: "local-owner", sub: creds?.user, reasons }, events: [] });
83
+ if (!policy)
84
+ return local(["no managed auth policy"]);
85
+ const lock = (why) => ({
86
+ seat: { tier: "readonly", configured, source: "lockdown", sub: creds?.user, reasons: [why] },
87
+ events: [{ event: "tier_resolved", detail: `tier=readonly source=lockdown reason=${why}` }],
88
+ });
89
+ const unsigned = (why, dropToken = false) => ({ ...(policy.requireSignIn ? lock(why) : local([why])), ...(dropToken ? { dropToken } : {}) });
90
+ const token = creds?.token;
91
+ if (token && policy.maxTokenAgeHours) {
92
+ // Fail CLOSED on unknown age. issuedAt lives in the user-writable credentials.json, so a seat could just
93
+ // delete the field to dodge the org's session-lifetime cap (the token stays AuthGate-valid, so live verify
94
+ // still passes). A missing / non-number issuedAt is treated as expired, not skipped.
95
+ const issuedAt = typeof creds?.issuedAt === "number" ? creds.issuedAt : undefined;
96
+ if (issuedAt === undefined || now - issuedAt > policy.maxTokenAgeHours * 3_600_000) {
97
+ return unsigned(`sign-in older than ${policy.maxTokenAgeHours}h (or age unverifiable) — sign in again`, true);
98
+ }
99
+ }
100
+ if (!token)
101
+ return unsigned("not signed in");
102
+ const cachePath = deps.cachePath ?? operatorPath("identity.json");
103
+ const verified = await (deps.verify ?? verifyTokenDetailed)(token, 4000);
104
+ let claims;
105
+ let via = "identity";
106
+ if (verified.state === "ok") {
107
+ claims = claimsFromVerify(verified.account, verified.raw);
108
+ writeCache(cachePath, { sub: claims.sub, email: claims.email, claims, tokenFp: fingerprint(token), verifiedAt: now });
109
+ }
110
+ else if (verified.state === "rejected") {
111
+ return unsigned("token rejected by AuthGate", true);
112
+ }
113
+ else {
114
+ // SECURITY (2026-10-07 review): identity.json is a user-owned 0600 file and AuthGate does not yet sign its
115
+ // claims (task #17), so the cache's only integrity gate — tokenFp = sha256(token)[:16] — is computable by
116
+ // the seat. A readonly seat could forge `roles:["admin"]` / an allowed email, block the gateway, and have
117
+ // `resolveSeat` restore the forged (elevated) tier + pass the email-domain lock. So an UNVERIFIABLE cache
118
+ // must grant nothing the no-cache path wouldn't: fall back to `unsigned` (lockdown under requireSignIn;
119
+ // local owner otherwise — same as a cold offline start). Offline grace is intentionally disabled until
120
+ // AuthGate signs claims; then verify the signature HERE and restore full-tier grace. Elevation from an
121
+ // unauthenticated local file is the exact escalation this closes.
122
+ return unsigned("AuthGate unreachable; cached identity is unsigned and cannot be trusted — re-verify when back online");
123
+ }
124
+ if (policy.allowedEmailDomains?.length) {
125
+ const domain = claims.email?.split("@")[1]?.toLowerCase();
126
+ if (!domain || !policy.allowedEmailDomains.includes(domain))
127
+ return lock(`account domain ${domain ?? "(none)"} is not allowed by managed policy`);
128
+ }
129
+ const t = tierFromClaims(claims, policy);
130
+ const tier = t.tier ? narrowest([configured, t.tier]) : configured;
131
+ const reasons = [via, t.reason];
132
+ return {
133
+ seat: { tier, configured, source: "identity", sub: claims.sub, email: claims.email, reasons },
134
+ events: [{ event: "tier_resolved", detail: `tier=${tier} source=${via} sub=${claims.sub} ${t.reason}` }],
135
+ };
136
+ }