@0perator/operator 0.1.235 → 0.1.262

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 +104 -17
  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
@@ -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
+ }
package/dist/auth/byo.js CHANGED
@@ -6,18 +6,21 @@
6
6
  // Env override per account: KODE_BYO_<ACCOUNT> (uppercase, non-alnum → "_") for CI/headless.
7
7
  // KODE_NO_KEYCHAIN=1 forces the 0600 JSON file (same convention as auth/store.ts).
8
8
  import { execFileSync, spawnSync } from "node:child_process";
9
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
- import { homedir, platform } from "node:os";
11
- import { dirname, join } from "node:path";
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";
12
13
  const SERVICE = "axe-operator-byo";
13
- const FILE = process.env.KODE_BYO_FILE ?? join(homedir(), ".axe", "operator", "byo.json");
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");
14
17
  const NO_KEYCHAIN = process.env.KODE_NO_KEYCHAIN === "1";
15
18
  function envName(account) {
16
19
  return "KODE_BYO_" + account.toUpperCase().replace(/[^A-Z0-9]/g, "_");
17
20
  }
18
21
  function readFile_() {
19
22
  try {
20
- const j = JSON.parse(readFileSync(FILE, "utf8"));
23
+ const j = JSON.parse(readFileSync(byoFile(), "utf8"));
21
24
  return j && typeof j === "object" ? j : {};
22
25
  }
23
26
  catch {
@@ -25,8 +28,12 @@ function readFile_() {
25
28
  }
26
29
  }
27
30
  function writeFile_(map) {
28
- mkdirSync(dirname(FILE), { recursive: true, mode: 0o700 });
29
- writeFileSync(FILE, JSON.stringify(map, null, 1), { mode: 0o600 });
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 */ }
30
37
  }
31
38
  /** Sync read: env override → OS keychain → 0600 file fallback. Used by setModel (sync path).
32
39
  * Keychain/file lookups are memoized per account: buildCapabilities calls the registry liberally and
@@ -108,7 +115,7 @@ export function setByoTokenInteractive(account) {
108
115
  }
109
116
  const env = getByoToken(account); // honors KODE_BYO_<ACCOUNT> when present
110
117
  if (!env) {
111
- process.stderr.write(`no keychain here — set ${envName(account)} or write ${FILE} (0600)\n`);
118
+ process.stderr.write(`no keychain here — set ${envName(account)} or write ${byoFile()} (0600)\n`);
112
119
  return false;
113
120
  }
114
121
  const m = readFile_();
@@ -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
  }
@@ -17,6 +17,18 @@ 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
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
+ }
20
32
  /** One-line prompt on the real TTY. Runs before Ink mounts, so plain readline is safe. */
21
33
  async function ask(question) {
22
34
  const rl = createInterface({ input: process.stdin, output: process.stdout });
@@ -60,6 +72,7 @@ async function loginEmail(emailArg) {
60
72
  console.error("✗ too many codes requested for that address — wait a few minutes, then try again");
61
73
  else
62
74
  console.error(`✗ couldn't start sign-in via ${authBase()} (${started.error})`);
75
+ await audit("auth_failed", `method=email stage=start reason=${started.error}`);
63
76
  return 1;
64
77
  }
65
78
  console.log(`\n ✓ Sent a 6-digit code to ${email} (valid 10 minutes).`);
@@ -75,12 +88,14 @@ async function loginEmail(emailArg) {
75
88
  if (v.ok) {
76
89
  await saveCredentials({ token: v.token, user: v.account.external_id, host: authBase(), issuedAt: Date.now() });
77
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);
78
92
  return 0;
79
93
  }
80
94
  if (v.error === "invalid_code") {
81
95
  console.error(attempt < 5 ? " ✗ wrong code — try again" : " ✗ wrong code");
82
96
  continue;
83
97
  }
98
+ await audit("auth_failed", `method=email stage=verify reason=${v.error}`);
84
99
  if (v.error === "no_pending_code") {
85
100
  console.error("✗ that code expired — run `operator auth login` again for a fresh one");
86
101
  return 1;
@@ -92,6 +107,7 @@ async function loginEmail(emailArg) {
92
107
  console.error(`✗ sign-in failed (${v.error})`);
93
108
  return 1;
94
109
  }
110
+ await audit("auth_failed", "method=email stage=verify reason=too_many_wrong_codes");
95
111
  console.error("✗ too many wrong tries — run `operator auth login` again for a fresh code");
96
112
  return 1;
97
113
  }
@@ -100,10 +116,12 @@ async function loginToken(token) {
100
116
  const account = await verifyToken(token);
101
117
  if (!account) {
102
118
  console.error("✗ that token was rejected by " + authBase());
119
+ await audit("auth_failed", "method=token reason=rejected");
103
120
  return 1;
104
121
  }
105
122
  await saveCredentials({ token, user: account.external_id, host: authBase(), issuedAt: Date.now() });
106
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);
107
125
  return 0;
108
126
  }
109
127
  // --- RFC 8628 device grant (browser) ------------------------------------------------
@@ -131,10 +149,12 @@ async function loginDevice() {
131
149
  process.stdout.write("\n");
132
150
  if (r.state !== "approved") {
133
151
  console.error(`✗ sign-in ${r.state === "expired" ? "timed out" : r.state}`);
152
+ await audit("auth_failed", `method=browser reason=${r.state}`);
134
153
  return 1;
135
154
  }
136
155
  await saveCredentials({ token: r.token, user: r.account.external_id, host: authBase(), issuedAt: Date.now() });
137
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);
138
158
  return 0;
139
159
  }
140
160
  finally {
@@ -150,8 +170,10 @@ async function loginDefault() {
150
170
  return loginDevice();
151
171
  }
152
172
  async function logout() {
173
+ const who = (await loadCredentials().catch(() => null))?.user;
153
174
  await clearCredentials();
154
175
  console.log("✓ signed out");
176
+ await audit("auth_logout", "credentials cleared", who);
155
177
  return 0;
156
178
  }
157
179
  async function status() {
@@ -176,7 +198,7 @@ function flagValue(rest, flag) {
176
198
  * hidden paste into the OS keychain under the SEPARATE `axe-operator-byo` service (an operator token
177
199
  * and a vendor key can never be confused), then /model's connectors light up. QwenCloud Token Plan
178
200
  * example: `operator auth byo qwen` → paste the `sk-sp-…` key from home.qwencloud.com. */
179
- function byo(rest) {
201
+ async function byo(rest) {
180
202
  const account = rest.find((a) => !a.startsWith("--"));
181
203
  if (rest.includes("--list")) {
182
204
  const accts = listByoAccounts();
@@ -194,23 +216,36 @@ function byo(rest) {
194
216
  if (rest.includes("--rm")) {
195
217
  deleteByoToken(account);
196
218
  console.log(`✓ removed the ${account} key`);
219
+ await audit("credential_removed", `byo account=${account}`);
197
220
  return 0;
198
221
  }
199
222
  if (setByoTokenInteractive(account)) {
200
223
  console.log(`✓ ${account} key stored — /model now offers its connectors`);
224
+ await audit("credential_stored", `byo account=${account}`);
201
225
  return 0;
202
226
  }
203
227
  console.error(`✗ could not store the ${account} key`);
204
228
  return 1;
205
229
  }
206
230
  /** Dispatch `operator auth <sub> [args]`. Returns a process exit code. */
207
- export async function runAuth(argv) {
231
+ export async function runAuth(argv, settings, stdin = process.stdin) {
232
+ auditCfg = settings;
208
233
  const [sub, ...rest] = argv;
209
234
  switch (sub) {
210
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
+ }
211
244
  const token = flagValue(rest, "--token");
212
- 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).");
213
247
  return loginToken(token);
248
+ }
214
249
  const email = flagValue(rest, "--email");
215
250
  if (email)
216
251
  return loginEmail(email);
@@ -223,7 +258,7 @@ export async function runAuth(argv) {
223
258
  case "whoami": return status();
224
259
  case "byo": return byo(rest);
225
260
  default:
226
- console.log("usage: operator auth <login [--email <addr> | --browser | --token <pat>] | logout | status | byo [account] [--list | --rm]>");
261
+ console.log("usage: operator auth <login [--email <addr> | --browser | --token-stdin | --token <pat>] | logout | status | byo [account] [--list | --rm]>");
227
262
  return sub ? 1 : 0;
228
263
  }
229
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
+ }
@@ -4,12 +4,13 @@
4
4
  // `operator auth status` needs no network call. Both operator (this) and the Python `kode` read the
5
5
  // SAME service + file, so a token minted by either client authenticates both.
6
6
  import { execFile } from "node:child_process";
7
- import { readFile, writeFile, mkdir, rm } from "node:fs/promises";
8
- import { homedir, platform } from "node:os";
9
- import { join, dirname } from "node:path";
7
+ import { readFile, writeFile, mkdir, rm, chmod } from "node:fs/promises";
8
+ import { platform } from "node:os";
9
+ import { dirname } from "node:path";
10
+ import { operatorPath } from "../config/home.js";
10
11
  const SERVICE = "axe-operator"; // keychain service — shared contract with the Python client
11
12
  const ACCOUNT = "default";
12
- const FILE = process.env.KODE_CREDENTIALS ?? join(homedir(), ".axe", "operator", "credentials.json");
13
+ const FILE = process.env.KODE_CREDENTIALS ?? operatorPath("credentials.json");
13
14
  function run(cmd, args, input) {
14
15
  return new Promise((resolve, reject) => {
15
16
  const child = execFile(cmd, args, (err, stdout) => (err ? reject(err) : resolve(stdout.toString())));
@@ -78,11 +79,12 @@ async function readMeta() {
78
79
  }
79
80
  /** Persist credentials: token to the keychain (or, if unavailable, the 0600 file), metadata always to file. */
80
81
  export async function saveCredentials(creds) {
81
- await mkdir(dirname(FILE), { recursive: true });
82
+ await mkdir(dirname(FILE), { recursive: true, mode: 0o700 });
82
83
  const inKeychain = await keychainSet(creds.token);
83
84
  // File holds metadata always; it holds the token too ONLY when the keychain couldn't (fallback).
84
85
  const onDisk = { user: creds.user, host: creds.host, issuedAt: creds.issuedAt, ...(inKeychain ? {} : { token: creds.token }) };
85
86
  await writeFile(FILE, JSON.stringify(onDisk, null, 2), { mode: 0o600 });
87
+ await chmod(FILE, 0o600).catch(() => { });
86
88
  }
87
89
  /** Load credentials, or null if not signed in. Prefers the keychain token; falls back to the file's. */
88
90
  export async function loadCredentials() {
@@ -5,13 +5,14 @@
5
5
  // next re-read — the "continue on newly-added tasks" requirement, race-safe by construction.
6
6
  import { appendFileSync, readFileSync, mkdirSync } from "node:fs";
7
7
  import { homedir } from "node:os";
8
- import { join, dirname } from "node:path";
8
+ import { dirname } from "node:path";
9
+ import { operatorPath } from "../config/home.js";
9
10
  /** Default board path — one JSONL under ~/.axe/operator, overridable via settings.autonomy.boardFile. */
10
11
  export function boardPath(settings) {
11
12
  const p = settings?.autonomy?.boardFile;
12
13
  if (p)
13
14
  return p.replace(/^~(?=\/|$)/, homedir());
14
- return join(homedir(), ".axe", "operator", "board.jsonl");
15
+ return operatorPath("board.jsonl");
15
16
  }
16
17
  function appendEvent(file, event) {
17
18
  mkdirSync(dirname(file), { recursive: true });