@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/cli.js CHANGED
@@ -8,7 +8,6 @@ import { useCallback, useEffect, useRef, useState } from "react";
8
8
  import { render, Box, Text, useApp } from "ink";
9
9
  import { App } from "./ui/index.js";
10
10
  import { mastheadLines } from "./ui/Masthead.js";
11
- import { hyperlinkHint } from "./ui/capabilities.js";
12
11
  import { shouldPromptPlanExit, resolvePlanExit, PLAN_EXIT_OPTIONS } from "./ui/planExit.js";
13
12
  import { RemoteHost } from "./remote/host.js";
14
13
  import { pollBus, pollSent, selfAgent } from "./bus/inbox.js";
@@ -19,15 +18,23 @@ import { cacheBustNotice } from "./engine/aurora.js";
19
18
  import { seedCalibration } from "./engine/calibration-seed.js";
20
19
  import { AuroraRouter } from "./router/router.js";
21
20
  import { BackgroundAgents } from "./background/index.js";
22
- import { loadSettings, saveSettings, compactionThreshold, compactionCeilingTokens, rcAutostart } from "./config/settings.js";
23
- import { loadProjectContext, loadMemories, appendMemory, loadHandoff } from "./config/persona.js";
24
- import { renderHarnessContext } from "./config/operator-harness.js";
21
+ import { loadSettings, saveSettings, compactionThreshold, compactionCeilingTokens, rcAutostart, applySeat, setActiveSeat } from "./config/settings.js";
22
+ import { resolveSeat } from "./auth/identity.js";
23
+ import { PermissionPolicy } from "./permissions/index.js";
24
+ import { caps } from "./ui/capabilities.js";
25
+ import { composeSystemPrompt, appendMemory } from "./config/persona.js";
26
+ import { applyToolsBinPath, operatorPath } from "./config/home.js";
27
+ import { ensureOperatorHome } from "./config/scaffold.js";
28
+ import { modelCtxFor, LEAN_HARNESS_CTX } from "./router/models.js";
25
29
  import { disposeShellSession, getAgentTasks } from "./tools/registry.js";
26
- import { EventSink } from "./telemetry/events.js";
30
+ import { disposeBrowserNow } from "./browser/session.js";
31
+ import { EventSink, defaultEventsFile } from "./telemetry/events.js";
27
32
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
28
33
  import { expandFileMentions } from "./util/mentions.js";
29
34
  import { throttle } from "./util/throttle.js";
30
35
  import { isSlashCommand } from "./util/slash.js";
36
+ import * as compose from "./compose/client.js";
37
+ import { execFile } from "node:child_process";
31
38
  import { join, dirname } from "node:path";
32
39
  import { homedir, hostname } from "node:os";
33
40
  import { createHash } from "node:crypto";
@@ -45,8 +52,27 @@ const VERSION = (() => {
45
52
  })();
46
53
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
47
54
  const settings = loadSettings();
55
+ // Enterprise first-run: make the operator home's contract explicit BEFORE any module writes into it (0700
56
+ // root, ignore-everything .gitignore, README, settings.example.json, home.json). Idempotent, never throws.
57
+ const HOME_SCAFFOLD = ensureOperatorHome({ version: VERSION });
48
58
  // Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
49
59
  process.env.KODE_SANDBOX = settings.sandbox.mode;
60
+ // operator-home-v2 phase 5: the managed owner-CLI toolkit is a SINGLE PATH addition
61
+ // ($KODE_HOME/tools/bin, materialized by operator-home/tools/toolkit-verify.sh). Projected once at
62
+ // startup so every child inherits it — persistent bash, exec-file tools, in-process cron sessions.
63
+ applyToolsBinPath();
64
+ // HV3-05a: state hygiene at session start — self-paced by its own heartbeat (skips when a run is
65
+ // <20h old), fire-and-forget so it never blocks boot; a repair (quarantine+reindex) is invisible
66
+ // unless it fails. Dynamic import keeps state-maintenance off the neutral bundle graph entirely.
67
+ void import("./memory/state-maintenance.js").then(async (m) => {
68
+ const last = await m.stateMaintenanceStatus();
69
+ if (last && Date.now() - last.ranAtMs < 20 * 3600_000)
70
+ return;
71
+ const r = await m.maintainState();
72
+ if (!r.ok && r.unresolved.length) {
73
+ process.stderr.write(`state maintenance: ${r.unresolved.length} unresolved issue(s) — see state/maintenance.json\n`);
74
+ }
75
+ }).catch(() => undefined);
50
76
  // web_search reads KODE_AUTOPILOT_URL / KODE_SEARXNG_URL from the env at exec; project them from the
51
77
  // settings layer so a settings.json backend works without the user exporting anything. applyEnv already
52
78
  // folded any real env var into settings.search (env wins), so this never clobbers an explicit export.
@@ -92,13 +118,28 @@ if (settings.services?.stopOnExit?.searxng === false)
92
118
  // it once at boot from the keychain (or KODE_OPERATOR_TOKEN) and hand it to the engine; a local :8097
93
119
  // never receives it (aurora.ts only sends to a non-loopback base), so this is safe on JL1 and costs
94
120
  // nothing there. This is what lets a thin client (a 4 GB MacBook) run Operator against JL1's Aurora.
121
+ let bootCreds = null;
95
122
  try {
96
123
  const { loadCredentials } = await import("./auth/store.js");
97
124
  const { setOperatorToken } = await import("./engine/aurora.js");
98
125
  const creds = await loadCredentials().catch(() => null);
126
+ bootCreds = process.env.KODE_OPERATOR_TOKEN ? { token: process.env.KODE_OPERATOR_TOKEN } : creds;
99
127
  setOperatorToken(process.env.KODE_OPERATOR_TOKEN || creds?.token || undefined);
100
128
  }
101
129
  catch { /* auth is optional — a local engine needs none */ }
130
+ // Seat resolution (enterprise SSO/RBAC readiness): with a managed auth policy deployed, the verified identity
131
+ // decides the widest tier this process may hold (it can only NARROW, never widen). With no managed policy this
132
+ // is a no-op and touches no network. `operator auth …` / --version / --help skip it (they must work signed-out).
133
+ const SKIP_SEAT = process.argv[2] === "auth" || process.argv[2] === "audit" || process.argv.includes("--version") || process.argv.includes("-V") || process.argv.includes("--help");
134
+ const SEAT = SKIP_SEAT
135
+ ? { seat: { tier: settings.permissions.tier ?? "admin", source: "local-owner", reasons: ["seat resolution skipped for this command"] }, events: [], dropToken: false }
136
+ : await resolveSeat(settings, { creds: bootCreds });
137
+ setActiveSeat(SEAT.seat);
138
+ Object.assign(settings, applySeat(settings, SEAT.seat));
139
+ if (SEAT.dropToken) {
140
+ const { setOperatorToken } = await import("./engine/aurora.js");
141
+ setOperatorToken(undefined);
142
+ }
102
143
  // Computer control (opt-in, macOS embodiment). When enabled: register the control tools into the shared
103
144
  // registry and compute permission rules. The FOREGROUND forces each computer_* tool to "ask" so every
104
145
  // action prompts the owner via the approve() bridge in <Root>; BACKGROUND sub-agents get them DENIED —
@@ -148,11 +189,11 @@ const fgPermissions = { ...settings.permissions, rules: { ...settings.permission
148
189
  // grepped back into the model's own context (self-poisoning → runaway ctx growth), committed by
149
190
  // accident, or listed as project litter. One file per cwd (keyed by a short hash) so --resume stays
150
191
  // scoped to the directory you launched in.
151
- const SESSION_DIR = join(homedir(), ".axe", "operator", "sessions");
192
+ const SESSION_DIR = operatorPath("sessions");
152
193
  const SESSION_FILE = process.env.KODE_SESSION_FILE ??
153
194
  join(SESSION_DIR, `${createHash("sha1").update(process.cwd()).digest("hex").slice(0, 16)}.json`);
154
195
  try {
155
- mkdirSync(SESSION_DIR, { recursive: true });
196
+ mkdirSync(SESSION_DIR, { recursive: true, mode: 0o700 });
156
197
  }
157
198
  catch { /* best-effort; the write is guarded too */ }
158
199
  const RESUME = process.argv.includes("--resume") || process.argv.includes("-r") || process.env.KODE_RESUME === "1";
@@ -166,15 +207,27 @@ const SESSION_ID = createHash("sha1").update(`${process.cwd()}:${Date.now()}`).d
166
207
  // session_handoff tools; the handoff is auto-loaded into the system prompt below so the next session in
167
208
  // this directory resumes from it. Kept under ~/.axe/operator, never in the workspace.
168
209
  const WORKSPACE_HASH = createHash("sha1").update(process.cwd()).digest("hex").slice(0, 16);
169
- process.env.KODE_SCRATCH_FILE = join(homedir(), ".axe", "operator", "scratch", `${SESSION_ID}.md`);
170
- process.env.KODE_HANDOFF_FILE = join(homedir(), ".axe", "operator", "handoff", `${WORKSPACE_HASH}.md`);
210
+ process.env.KODE_SCRATCH_FILE = operatorPath("scratch", `${SESSION_ID}.md`);
211
+ process.env.KODE_HANDOFF_FILE = operatorPath("handoff", `${WORKSPACE_HASH}.md`);
171
212
  try {
172
213
  mkdirSync(dirname(process.env.KODE_SCRATCH_FILE), { recursive: true });
173
214
  mkdirSync(dirname(process.env.KODE_HANDOFF_FILE), { recursive: true });
174
215
  }
175
216
  catch { /* best-effort; the tools guard too */ }
176
- const EVENT_ACTOR = { tier: settings.permissions.tier ?? "admin", surface: "cli" };
217
+ const EVENT_ACTOR = { tier: settings.permissions.tier ?? "admin", surface: process.argv[2] === "acp" ? "acp" : "cli", sub: settings.seat?.sub };
177
218
  const eventSink = new EventSink();
219
+ // Startup audit — only for a seat that is audited at all (a narrowed tier / audit / gated mode); the inert owner
220
+ // writes nothing. Names the managed policy in force (by content id), the resolved seat and why.
221
+ if (new PermissionPolicy(settings.permissions).audits) {
222
+ const m = settings.managed;
223
+ if (m?.status === "invalid")
224
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "policy_invalid", detail: `${m.path}: ${m.errors.join("; ")}`.slice(0, 400) } });
225
+ else if (m?.status === "ok")
226
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "policy_loaded", detail: `${m.path} id=${m.id}` } });
227
+ for (const ev of SEAT.events)
228
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: ev });
229
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "session_start", detail: `entry=${process.argv[2] ?? "tui"} version=${VERSION} tier=${EVENT_ACTOR.tier} mode=${settings.permissions.mode} sandbox=${settings.sandbox.mode} policy=${m?.id ?? "none"} seat=${settings.seat?.source ?? "local-owner"} home=${HOME_SCAFFOLD.firstRun ? "created" : "existing"}` } });
230
+ }
178
231
  const emitTelemetry = settings.telemetry.enabled !== false;
179
232
  // Build the endpoint router. ONE model now: Aurora at its native 1M context on :8097 — both `operator`
180
233
  // and `operator+` serve the same single tier (the air/1m/saddle roster collapsed once Aurora ran true
@@ -215,90 +268,30 @@ function formatAgentDetail(a) {
215
268
  parts.push("— errored");
216
269
  return parts.join(" ");
217
270
  }
218
- // Project context + session handoff loaders live in config/persona.ts, shared with the headless
219
- // autonomy runners (autonomy/session-factory.ts) so an unattended `operator run/loop` picks up the
220
- // same AGENTS.md/CLAUDE.md + handoff the TUI does. See that module for the details.
221
- // Embodiment guidance, appended only when computer control is on. It steers Aurora to READ the screen
222
- // with chauffeur's textual accessibility tree instead of hand-rolling osascript — the exact loop that
223
- // failed on Slack (AppleScript can't read Electron UIs). chauffeur is reachable either via the scoped
224
- // embodiment hub or the full fleet MCP.
271
+ // The system prompt is assembled by config/persona.ts composeSystemPrompt — the SAME call the headless
272
+ // autonomy runners (autonomy/session-factory.ts) make — so the TUI and an unattended `operator run/loop`
273
+ // share one persona (Direct/unrestricted, media, verify-by-running) + project context + handoff.
274
+ // chauffeur (textual on-screen UI reads) is reachable via the scoped embodiment hub or the full fleet MCP —
275
+ // the gate for the embodiment guide composeSystemPrompt appends when computer control is on.
225
276
  const chauffeurReady = !!chauffeurServer || settings.mcp;
226
- const EMBODIMENT_GUIDE = settings.computer.enabled
227
- ? `\n## Controlling this computer\nComputer control is ON (every action asks the owner first). Drive apps with ` +
228
- `computer_app_open / computer_app_activate, computer_type, computer_key, computer_click, computer_screenshot.` +
229
- (chauffeurReady
230
- ? ` To SEE the screen use the chauffeur tools — NEVER shell_exec/osascript/System Events to read or drive ` +
231
- `a GUI (AppleScript cannot read Electron apps like Slack/VS Code/Discord and just errors). For ANY ` +
232
- `request about what is on screen, or to click/read/drive an app, you MUST call the chauffeur tools — ` +
233
- `never answer from memory and never say you cannot see the screen. First call: chauffeur:list_windows. ` +
234
- `Correct usage, follow it exactly:\n` +
235
- `- Do NOT pass a "session" argument to any chauffeur tool. Omit it — the implicit session is used ` +
236
- `automatically. (Inventing a session label causes "session has ended" errors.)\n` +
237
- `- At the START of any on-screen task, call chauffeur:set_agent_cursor_enabled {enabled: true} so the ` +
238
- `owner can watch the agent's cursor move — do this before the first click/type/drag.\n` +
239
- `- To read a window: call chauffeur:list_windows, take a window_id + pid FROM THAT RESULT, then ` +
240
- `immediately chauffeur:get_window_state {pid, window_id} → a TEXT accessibility tree (roles, labels, ` +
241
- `values, clickable elements + coordinates). window_ids go stale, so always list_windows again right ` +
242
- `before get_window_state; never reuse an old id.\n` +
243
- `- To act: chauffeur:click / chauffeur:type_text / chauffeur:press_key, addressing elements by the info ` +
244
- `from the latest get_window_state.\n` +
245
- `- If ANY chauffeur tool returns "session has ended", call chauffeur:start_session ONCE (no arguments), ` +
246
- `then retry the read — do not loop the failing call.\n` +
247
- `Work END-TO-END from the owner's one instruction: read → decide → act by chaining these tools yourself, ` +
248
- `then report the result. Reads run without a prompt; only actions ask. Use ask_user only for a genuine ` +
249
- `owner decision — never to walk through a task you can just do.`
250
- : ` NOTE: reliably READING on-screen UI (especially Electron apps like Slack) needs the chauffeur driver, ` +
251
- `which is not installed here; computer_screenshot only saves a PNG you cannot read back yet. Do not ` +
252
- `hand-write osascript to scrape a GUI — it will error on Electron apps.`)
253
- : "";
254
- const SYSTEM_PROMPT = (settings.systemPrompt ??
255
- `You are Operator, AXE's terminal coding agent — built by AXE, running on AXE's own model. Refer to ` +
256
- `yourself as Operator and to the platform as AXE; never call yourself or the platform Claude, ` +
257
- `Anthropic, or any other vendor. When you encounter files or directories on disk named "claude", ` +
258
- `".claude", "anthropic", etc., describe them neutrally (by their literal path, or as "AI tooling ` +
259
- `files") — do not attribute them to a vendor. Use your tools to inspect and edit the ` +
260
- `workspace; prefer doing over explaining. Answer concisely.\n## This machine\nWorking dir: ${process.cwd()}` +
261
- `\nContext window: 307,200 tokens (300K) — you run on AXE's model served locally with a real 300K-token ` +
262
- `context. You can hold large files and long histories; do not claim a different limit.` +
263
- `\n## Parallel tool calls\nWhen the next few steps are INDEPENDENT of each other — reading several ` +
264
- `files, running several greps/checks, inspecting multiple unrelated things — issue them as multiple ` +
265
- `tool calls in a SINGLE message so they run in parallel, instead of one call, waiting, then the next. ` +
266
- `Only serialize when one call's output feeds the next call's input (e.g. read a file, then edit it), ` +
267
- `or when a call mutates something the next call depends on seeing. Batching independent reads is ` +
268
- `almost always faster and is the default you should reach for; do not artificially serialize work ` +
269
- `that has no real dependency.` +
270
- `\n## Sub-agents\nFor independent, parallelizable subtasks (search a large tree, draft a file, a long ` +
271
- `build) call spawn_agent with a fully self-contained instruction — it runs on another session ` +
272
- `in parallel and posts its result back here; keep working meanwhile. The user watches each sub-agent's ` +
273
- `live tokens + time in the background panel. Don't delegate trivial work you can do inline, and don't ` +
274
- `spawn many at once — they all share this one model.` +
275
- `\n## Finding things\nTo search file CONTENTS (a symbol, a string, a config key), use the search tool ` +
276
- `(ripgrep — fast, parallel, .gitignore-aware) scoped to a directory: search {"pattern":"…","path":"src"}, ` +
277
- `and set files_with_matches to just locate the files before reading them. NEVER run ` +
278
- `\`find ~/ -maxdepth N | grep | grep\` over the whole home directory — it is slow, hits the command ` +
279
- `timeout, and can wedge the shell. Narrow FIRST: check the 2-3 most likely directories before any broad ` +
280
- `sweep, and batch independent searches in ONE message so they run in parallel.\nWhen asked to find a ` +
281
- `project or file by NAME that is NOT in the working directory: (1) run ls ~ to see the REAL top-level ` +
282
- `folders (projects live in non-obvious ones — e.g. ~/Axwell, ~/.axe/repos, ~/Desktop — not just ` +
283
- `~/Projects); (2) then a BOUNDED find scoped to a SPECIFIC directory with a generous timeout — ` +
284
- `shell_exec {"command":"find ~/.axe/repos -maxdepth 3 -iname \\"*name*\\" 2>/dev/null | head -80",` +
285
- `"timeout_ms":60000} — never an unbounded find over all of ~ or /. Widen the pattern if a repo may be ` +
286
- `named differently. Only report not-found after this real search, and say exactly where you looked.` +
287
- `\n## Scratchpad & handoff\nUse the scratchpad tool for private working notes, plans, and intermediate ` +
288
- `results — think there, not in the workspace or your reply. Before you finish a substantial task, or ` +
289
- `when you're running low on context, call session_handoff to record what you did, the state, and the ` +
290
- `next steps: your next session in this directory loads it automatically, so write it for your future self.`) +
291
- loadProjectContext() + loadMemories() + renderHarnessContext() + loadHandoff() + EMBODIMENT_GUIDE;
277
+ // Small-context models (e.g. a self-hosted 8K Venice) can't hold Operator's full memory + handoff — sized
278
+ // for Aurora's 300K, it fills the window and the model recites it instead of answering. Below
279
+ // LEAN_HARNESS_CTX, drop the heavy memory/handoff, KEEPING the base persona (incl. the Direct/unrestricted
280
+ // section) so the model stays uncensored.
281
+ const LEAN_HARNESS = modelCtxFor(settings.activeModel, settings.models) < LEAN_HARNESS_CTX;
282
+ // TODO(R1b): built once at startup — a mid-session /model does not rebuild it (ctxTokens + lean follow the startup model).
283
+ const SYSTEM_PROMPT = composeSystemPrompt({ settings, cwd: process.cwd(), ctxTokens: modelCtxFor(settings.activeModel, settings.models), lean: LEAN_HARNESS, interactive: true, chauffeurReady });
292
284
  const HELP = [
293
285
  "commands:",
294
286
  " /help this list",
295
- " /model [id] pick a model: operator-1m · operator-128k · moa (mixture-of-agents)",
287
+ " /model [id] pick a model: operator-1m · operator-128k · qwen connectors (auth byo qwen) · moa",
296
288
  " /endpoints show the Operator endpoint + live health",
297
289
  " /services ensure/inspect the service lever (Operator+autopilot+searxng); /services stop",
298
290
  " /audit [n] recent tool + control-plane events from the audit trail (default 15)",
299
291
  " /monitor live event stream — tool decisions, turns, control events (/monitor off)",
300
292
  " /stats session dashboard: turns · tools · tokens · throughput trend · context fill",
301
293
  " /dashboard launch the live swarm console (watches every Operator session)",
294
+ " /artifacts browse + attach your Compose (compose.casa) artifacts: search · attach · copy url · delete",
302
295
  " /plan plan mode: read-only research + propose a plan (/plan again to execute)",
303
296
  " /mode [plan|manual|auto] set operating mode (plan · manual · autonomous); also Shift+Tab to cycle",
304
297
  " /think extended reasoning: Operator thinks before answering (/think again = off)",
@@ -306,7 +299,7 @@ const HELP = [
306
299
  " /compact force-compact the conversation now",
307
300
  " /remember <note> store a note to recall in future sessions",
308
301
  " /memory [query] show remembered notes (all, or matching query)",
309
- " /mcp count of fleet MCP tools this session (KODE_TSI_MCP=1)",
302
+ " /mcp [on|off] fleet MCP tools: status, or switch the layer on/off (saved)",
310
303
  " /login <email> · /logout · /whoami sign in by 6-digit email code (then /login <code>); /login <token> or --browser",
311
304
  " /agents detailed sub-agent status: running/queued/done/errored + metrics",
312
305
  " /bg <task|stop id> spawn a background sub-agent, list, or stop one",
@@ -339,7 +332,7 @@ const REMOTE_SAFE_COMMANDS = [
339
332
  { name: "compact", description: "force-compact the conversation now" },
340
333
  { name: "remember", description: "store a note to recall in future sessions", args: "<note>" },
341
334
  { name: "memory", description: "show remembered notes", args: "[query]" },
342
- { name: "mcp", description: "count of fleet MCP tools this session" },
335
+ { name: "mcp", description: "fleet MCP tools: status · switch the layer on/off", args: "[on|off]" },
343
336
  { name: "whoami", description: "show signed-in identity" },
344
337
  { name: "agents", description: "detailed sub-agent status with metrics" },
345
338
  { name: "monitor", description: "toggle live event stream (tool decisions, turns, control)" },
@@ -385,7 +378,7 @@ function Root() {
385
378
  // Ref mirror of opMode so buildCapabilities() reflects the LIVE mode synchronously (a follower's mode
386
379
  // selector must light up the instant it changes, before React flushes the setOpMode state update).
387
380
  const opModeRef = useRef(opMode);
388
- const [thinkMode, setThinkMode] = useState("off"); // /think, /ultrathink badge
381
+ const [thinkMode, setThinkMode] = useState(settings.ui?.reasoning ?? "think"); // /think, /ultrathink badge; default "think" so the model's thoughts stream dim above the answer (settings.ui.reasoning / /think to change)
389
382
  const [elapsed, setElapsed] = useState(0); // live seconds since the current turn started (ticked by a
390
383
  const turnStartRef = useRef(0); // timer, so the clock advances even during a long reasoning
391
384
  // phase where no content tokens stream — that was the "timer stuck" bug (Ink only re-renders on deltas).
@@ -420,6 +413,7 @@ function Root() {
420
413
  // Gates the exit-time picker below — plan mode toggled on/off with no proposal stays silent.
421
414
  const planProposedRef = useRef(false);
422
415
  const [planExitPicker, setPlanExitPicker] = useState(null);
416
+ const [artifactsPicker, setArtifactsPicker] = useState(null);
423
417
  const alwaysAllowRef = useRef(new Set());
424
418
  // Remembers the email a `/login <email>` sent a 6-digit code to, so the follow-up `/login <code>`
425
419
  // knows which address to verify against — the in-session twin of the shell's email-code login.
@@ -458,14 +452,16 @@ function Root() {
458
452
  if (!sessionRef.current) {
459
453
  sessionRef.current = new Session({
460
454
  systemPrompt: SYSTEM_PROMPT,
455
+ thinkMode, // start in the SAME mode the badge shows (settings.ui.reasoning, default "think") — it was only ever the badge that defaulted on
461
456
  router: buildRouter(),
462
457
  mcp: settings.mcp,
463
458
  mcpHub: embodimentHub, // scoped chauffeur hub when embodiment is on (undefined otherwise → no change)
464
459
  maxTokens: settings.maxTokens,
465
460
  maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling (total tokens); undefined → no cap
466
- maxRounds: settings.autonomy?.maxRounds, // soft per-turn round budget (default 40) — a real build isn't cut off at 10
461
+ maxRounds: settings.autonomy?.maxRounds, // soft per-turn round budget (default 200) — a real build isn't cut off at 10
462
+ sleepConsolidation: settings.autonomy?.sleepConsolidation, // idle "dreaming": consolidate transcript→memory + run the flywheel while the owner is away (0.1.177 — was never threaded through, so it never fired)
467
463
  compactionThreshold: compactionThreshold(settings), // settings.compaction.threshold / KODE_COMPACTION_THRESHOLD; undefined → 0.85
468
- compactionCeilingTokens: compactionCeilingTokens(settings, settings.endpoints.aurora.ctxWindow), // explicit setting/env wins; else a RAM-aware safe default caps context below the box's swap cliff (the "88 tok/6min" stall)
464
+ compactionCeilingTokens: compactionCeilingTokens(settings, settings.endpoints.aurora.ctxWindow, "interactive"), // INTERACTIVE mode ⇒ the tight ceiling (~24k) so each owner-facing reply decodes fast; compaction.ceilingTokens/env override, then the RAM-aware clamp. Headless autonomy uses the separate high ceiling (session-factory.ts)
469
465
  temperature: settings.temperature,
470
466
  recall: settings.memory.recall,
471
467
  models: settings.models, // /model registry overrides (router/models.ts has the built-in defaults)
@@ -626,8 +622,8 @@ function Root() {
626
622
  // Backstop the slash-/ESC-quit paths: an ordinary terminal close or `kill` must still tear down any
627
623
  // spawned stdio MCP subprocesses (session.shutdown), or they orphan. exit runs sync; SIGTERM exits after.
628
624
  useEffect(() => {
629
- const onExit = () => { bgRef.current?.dispose(); session.shutdown(); disposeShellSession(); };
630
- const onTerm = () => { bgRef.current?.dispose(); session.shutdown(); disposeShellSession(); process.exit(0); };
625
+ const onExit = () => { bgRef.current?.dispose(); session.shutdown(); disposeShellSession(); disposeBrowserNow(); };
626
+ const onTerm = () => { bgRef.current?.dispose(); session.shutdown(); disposeShellSession(); disposeBrowserNow(); process.exit(0); };
631
627
  process.once("exit", onExit);
632
628
  process.once("SIGTERM", onTerm);
633
629
  return () => { process.off("exit", onExit); process.off("SIGTERM", onTerm); };
@@ -737,7 +733,7 @@ function Root() {
737
733
  onRoute: (label, pct) => {
738
734
  setRoute(label);
739
735
  setCtxPct(pct);
740
- remoteRef.current?.setStatus(pct, label);
736
+ remoteRef.current?.setStatus(pct, label, session.sessionTokens());
741
737
  // GW-06 oracle seed (once, fire-and-forget): a fresh meter cold-starts at chars/4 (4.0) — measured
742
738
  // truth on agent traffic is ~2.15 (aurora-tier0/calibrate-token-meter.py), i.e. the gate fires LATE
743
739
  // for the first rounds. Seed ONE weight-1 observation from the endpoint's own tokenizer
@@ -798,6 +794,13 @@ function Root() {
798
794
  // tool box) that Ink can mis-erase, stamping the same "let me check…" line once per tool — the
799
795
  // redundancy. The prose already showed while it streamed; during execution we show the tool rows,
800
796
  // not a re-rendered copy of it. (onToolBatch also clears these once the batch fully settles.)
797
+ // BUT the model's THINKING before this batch ("why I'm running these tools") is worth keeping — so
798
+ // persist it as a dim, SETTLED thought ABOVE the tool rows before clearing. Settled entries render
799
+ // once into static scrollback (no live re-render), so this dodges the tall-live-frame mis-erase the
800
+ // clear guards against while surfacing the inter-batch reasoning the owner would otherwise lose.
801
+ const preThought = liveReasoning.current.trim();
802
+ if (preThought)
803
+ push({ kind: "message", message: { id: nextId(), role: "assistant", content: "", reasoning: preThought } });
801
804
  liveText.current = "";
802
805
  liveReasoning.current = "";
803
806
  setLive(null);
@@ -909,8 +912,9 @@ function Root() {
909
912
  const live = bg.list().filter((a) => a.status === "working" || a.status === "queued");
910
913
  if (live.length)
911
914
  push({ kind: "message", message: { id: nextId(), role: "system", content: `${live.length} sub-agent${live.length > 1 ? "s" : ""} still running — results post when done. /agents for status` } });
915
+ // H4 (audit-tools §1): transcripts hold bearer tokens — they were world-readable by default.
912
916
  try {
913
- writeFileSync(SESSION_FILE, JSON.stringify(session.snapshot()));
917
+ writeFileSync(SESSION_FILE, JSON.stringify(session.snapshot()), { mode: 0o600 });
914
918
  }
915
919
  catch { /* auto-save is best-effort */ }
916
920
  // Re-check capabilities after every turn: MCP discovery (first-turn only) may have just landed,
@@ -1040,6 +1044,69 @@ function Root() {
1040
1044
  });
1041
1045
  break;
1042
1046
  }
1047
+ case "artifacts": {
1048
+ // Browse + attach Compose (compose.casa) artifacts. Fetches the owner's library over Operator's
1049
+ // existing AuthGate token (src/compose/client.ts — the scoped HTTP API, never the unauth MCP),
1050
+ // renders the ArtifactPicker, and maps each row action to a Compose call. Attach fetches the
1051
+ // content and re-enters it as a framed user turn (the proven submitRef inject path) so the model
1052
+ // can use it. rename/pin/Shared are Phase 2/3 (need Compose backend work) — see the _ai-docs spec.
1053
+ const setPatch = (patch) => setArtifactsPicker((p) => (p ? { ...p, ...patch } : p));
1054
+ const load = async (fetcher) => {
1055
+ setPatch({ loading: true, error: undefined, note: undefined });
1056
+ try {
1057
+ setPatch({ items: await fetcher(), loading: false });
1058
+ }
1059
+ catch (e) {
1060
+ setPatch({ loading: false, error: e.message });
1061
+ }
1062
+ };
1063
+ const onIntent = async (intent) => {
1064
+ switch (intent.kind) {
1065
+ case "close":
1066
+ setArtifactsPicker(null);
1067
+ break;
1068
+ case "refresh":
1069
+ await load(() => compose.listMine());
1070
+ break;
1071
+ case "search":
1072
+ await load(() => (intent.query ? compose.search(intent.query) : compose.listMine()));
1073
+ break;
1074
+ case "copy": {
1075
+ const url = compose.viewUrl(intent.id);
1076
+ try {
1077
+ const c = execFile(process.platform === "darwin" ? "pbcopy" : process.platform === "win32" ? "clip" : "xclip");
1078
+ c.stdin?.end(url);
1079
+ }
1080
+ catch { /* best-effort; the url is shown below regardless */ }
1081
+ setPatch({ note: `copied ${url}` });
1082
+ break;
1083
+ }
1084
+ case "delete":
1085
+ try {
1086
+ await compose.del(intent.id);
1087
+ setPatch({ note: "deleted" });
1088
+ await load(() => compose.listMine());
1089
+ }
1090
+ catch (e) {
1091
+ setPatch({ error: e.message });
1092
+ }
1093
+ break;
1094
+ case "attach":
1095
+ try {
1096
+ const a = await compose.get(intent.id);
1097
+ setArtifactsPicker(null);
1098
+ submitRef.current(`[Attached Compose artifact: ${a.title} — ${compose.viewUrl(a.id)}]\n\n${a.content}`);
1099
+ }
1100
+ catch (e) {
1101
+ setPatch({ error: e.message });
1102
+ }
1103
+ break;
1104
+ }
1105
+ };
1106
+ setArtifactsPicker({ items: [], loading: true, onIntent });
1107
+ void load(() => compose.listMine());
1108
+ break;
1109
+ }
1043
1110
  case "route":
1044
1111
  if (s.pinRoute(arg || "auto"))
1045
1112
  sys(arg && arg !== "auto" ? `routing pinned to ${arg}` : "routing set to auto (by size)");
@@ -1211,8 +1278,22 @@ function Root() {
1211
1278
  break;
1212
1279
  }
1213
1280
  case "mcp": {
1214
- const n = s.mcpToolCount();
1215
- sys(n > 0 ? `${n} fleet MCP tools available this session` : "no MCP tools (enable with KODE_TSI_MCP=1, then send a message to discover)");
1281
+ const a = (arg ?? "").trim().toLowerCase();
1282
+ if (a === "on") {
1283
+ sys("enabling MCP tools…");
1284
+ const n = await s.enableMcp();
1285
+ saveSettings({ mcp: true });
1286
+ sys(n > 0 ? `MCP on · ${n} fleet tools available (saved — on for new sessions too)` : "MCP on (saved), but no tools were discovered — the MCP gateway may be unreachable; it retries next session");
1287
+ }
1288
+ else if (a === "off") {
1289
+ saveSettings({ mcp: false });
1290
+ sys("MCP off for new sessions (saved) — tools already loaded stay until you restart");
1291
+ }
1292
+ else {
1293
+ const n = s.mcpToolCount();
1294
+ sys(n > 0 ? `${n} fleet MCP tools available this session · /mcp off to disable for new sessions`
1295
+ : settings.mcp ? "MCP is on — tools are discovered when you send your first message" : "no MCP tools loaded — /mcp on to enable them");
1296
+ }
1216
1297
  break;
1217
1298
  }
1218
1299
  case "endpoints": {
@@ -1268,7 +1349,8 @@ function Root() {
1268
1349
  // The human-supervisor view of the frozen event stream: recent tool decisions + control events
1269
1350
  // (tier denials, signature lines, RC) straight from the audit JSONL. Read-only.
1270
1351
  const n = Math.max(1, Math.min(50, Number(arg) || 15));
1271
- const file = (process.env.KODE_EVENTS_FILE || process.env.KODE_AUDIT_FILE || join(homedir(), ".axe", "operator", "events.jsonl"));
1352
+ const rawFile = defaultEventsFile();
1353
+ const file = rawFile.startsWith("~/") ? join(homedir(), rawFile.slice(2)) : rawFile;
1272
1354
  let lines = [];
1273
1355
  try {
1274
1356
  lines = readFileSync(file, "utf8").trim().split("\n").filter(Boolean);
@@ -1356,7 +1438,7 @@ function Root() {
1356
1438
  const server = join(dirname(fileURLToPath(import.meta.url)), "..", "dashboard", "server.mjs");
1357
1439
  const child = spawn(process.execPath, [server], { detached: true, stdio: "ignore", env: { ...process.env, PORT: String(port) } });
1358
1440
  child.unref();
1359
- sys(`launched the swarm console → ${url} — live-tailing ~/.axe/operator/events.jsonl (every Operator session, zero config). Open it in a browser.`);
1441
+ sys(`launched the swarm console → ${url} — live-tailing ${defaultEventsFile()} (every Operator session, zero config). Open it in a browser.`);
1360
1442
  }
1361
1443
  catch (e) {
1362
1444
  sys(`could not launch the dashboard: ${e.message}`);
@@ -1561,7 +1643,7 @@ function Root() {
1561
1643
  ? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
1562
1644
  : `${spin} ${fmtMeta(elapsed, liveTok)}`
1563
1645
  : metrics;
1564
- return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, liveTools: liveTools, route: route, ctxPct: ctxPct, version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker, onApprovalDecide: (allow, always) => {
1646
+ return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, liveTools: liveTools, route: route, ctxPct: ctxPct, version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, onApprovalDecide: (allow, always) => {
1565
1647
  const cur = approval;
1566
1648
  if (cur)
1567
1649
  settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
@@ -1581,7 +1663,19 @@ if (process.argv.includes("--help")) {
1581
1663
  }
1582
1664
  if (process.argv[2] === "auth") {
1583
1665
  const { runAuth } = await import("./auth/commands.js");
1584
- process.exit(await runAuth(process.argv.slice(3)));
1666
+ process.exit(await runAuth(process.argv.slice(3), settings));
1667
+ }
1668
+ // `operator audit verify|tail` and `operator doctor` — the enterprise review surface: prove the audit trail is
1669
+ // intact, and show exactly what policy/seat/home posture is in force. Plain console, no TTY needed.
1670
+ if (process.argv[2] === "audit" || process.argv[2] === "doctor") {
1671
+ const { runEnterpriseCli } = await import("./enterprise/cli.js");
1672
+ process.exit(await runEnterpriseCli(process.argv.slice(2), settings, { version: VERSION, scaffold: HOME_SCAFFOLD }));
1673
+ }
1674
+ // `operator vault ...` — owner-side credential store for the browser (HV3-02b). The secret path
1675
+ // never crosses argv or model context: keychain prompt on macOS, stdin fallback elsewhere.
1676
+ if (process.argv[2] === "vault") {
1677
+ const { runVault } = await import("./vault/cli.js");
1678
+ process.exit(await runVault(process.argv.slice(3)));
1585
1679
  }
1586
1680
  // `operator update` (bareword) and `operator --update` both self-update.
1587
1681
  if (process.argv[2] === "update" || process.argv.includes("--update")) {
@@ -1601,7 +1695,7 @@ if (process.argv[2] === "update" || process.argv.includes("--update")) {
1601
1695
  // The Ink shell needs a real terminal (raw-mode keyboard). Fail clearly instead of crashing deep
1602
1696
  // in useInput when piped/non-interactive — for scripted use, drive Session (src/session.ts) directly.
1603
1697
  if (!process.stdin.isTTY) {
1604
- process.stderr.write("kode-tsi needs an interactive terminal (TTY). For scripted turns, import { Session } from kode-tsi.\n");
1698
+ process.stderr.write("Operator needs an interactive terminal (TTY). For a scripted turn, run `operator run \"<task>\"`.\n");
1605
1699
  process.exit(1);
1606
1700
  }
1607
1701
  // Boot masthead (design #29) — printed ONCE to stdout before Ink mounts, so the big gradient wordmark
@@ -1621,12 +1715,19 @@ if (FULLSCREEN) {
1621
1715
  }
1622
1716
  else {
1623
1717
  process.stdout.write(mastheadLines(`300K · v${VERSION}`).join("\n") + "\n");
1624
- // One-time hint when the terminal can't render clickable links, so the owner knows a supporting
1625
- // terminal (iTerm2/Ghostty/Kitty/WezTerm) makes URLs + artifact links clickable. Empty (skipped) when
1626
- // links already work. Dim, single line, inline-only — never mid-stream.
1627
- const linkHint = hyperlinkHint();
1628
- if (linkHint)
1629
- process.stdout.write(`\x1b[2m tip: ${linkHint}\x1b[22m\n`);
1718
+ // ONE-TIME ONLY: on a terminal without clickable links / copy-on-select (Terminal.app, or an unknown one),
1719
+ // point the owner at the terminals Operator is built for — then persist the flag so it NEVER shows again.
1720
+ // This is a single first-run pointer, not the per-boot tip that was removed. iTerm2/Ghostty/Kitty/WezTerm
1721
+ // are the standard: OSC 8 links + inline artifacts, and highlight-to-copy work there (Ghostty/iTerm2/WezTerm
1722
+ // do copy-on-select by default; Kitty needs `copy_on_select clipboard`). Terminal.app supports neither.
1723
+ if (!caps().osc8 && !settings.ui?.seenTerminalRecommend) {
1724
+ process.stdout.write("\x1b[2m Operator runs best in iTerm2 · Ghostty · Kitty · WezTerm — clickable links + artifacts and\n" +
1725
+ " highlight-to-copy work there; Terminal.app supports neither. (Shown once.)\x1b[22m\n");
1726
+ try {
1727
+ saveSettings({ ui: { ...settings.ui, seenTerminalRecommend: true } });
1728
+ }
1729
+ catch { /* best-effort; a write failure just re-shows next boot */ }
1730
+ }
1630
1731
  }
1631
1732
  const inkInstance = render(_jsx(Root, {}));
1632
1733
  if (FULLSCREEN)
@@ -0,0 +1,56 @@
1
+ // Compose (compose.casa) HTTP client — the data source for the /artifacts browser. We talk to the
2
+ // properly-scoped HTTP API with Operator's existing AuthGate Bearer token (loadCredentials), NOT the
3
+ // compose MCP: that MCP is mounted unauthenticated and its list/search/delete have no ownership scoping
4
+ // (they act on every artifact in the system), so it is unsafe to build "Mine" on. `/api/mine` is
5
+ // owner-scoped; `/api/list?q=` is the scoped search (NOT `/api/search`, which is global + unscoped).
6
+ // Base is overridable for tests/local via KODE_COMPOSE_URL.
7
+ import { loadCredentials } from "../auth/store.js";
8
+ const BASE = (process.env.KODE_COMPOSE_URL ?? "https://compose.casa").replace(/\/+$/, "");
9
+ export class ComposeError extends Error {
10
+ status;
11
+ constructor(message, status) {
12
+ super(message);
13
+ this.status = status;
14
+ this.name = "ComposeError";
15
+ }
16
+ }
17
+ /** The public view/share URL for an artifact — a pure string, no network call (the "copy url" action). */
18
+ export function viewUrl(id) {
19
+ return `${BASE}/v/${id}`;
20
+ }
21
+ async function authHeader() {
22
+ const creds = await loadCredentials();
23
+ if (!creds?.token)
24
+ throw new ComposeError("not signed in — run /login to connect to compose.casa", 401);
25
+ return `Bearer ${creds.token}`;
26
+ }
27
+ async function request(method, path) {
28
+ let res;
29
+ try {
30
+ res = await fetch(`${BASE}${path}`, { method, headers: { Authorization: await authHeader(), Accept: "application/json" } });
31
+ }
32
+ catch (e) {
33
+ throw new ComposeError(`compose.casa unreachable: ${e.message}`);
34
+ }
35
+ if (!res.ok) {
36
+ const hint = res.status === 401 ? " — token expired? run /login" : "";
37
+ throw new ComposeError(`compose ${method} ${path} → ${res.status}${hint}`, res.status);
38
+ }
39
+ return res;
40
+ }
41
+ /** The owner's library — the real "Mine" tab (AuthGate-scoped). */
42
+ export async function listMine() {
43
+ return (await request("GET", "/api/mine").then((r) => r.json()));
44
+ }
45
+ /** Scoped title+content search (caller's own artifacts), via /api/list?q= — never the global /api/search. */
46
+ export async function search(q) {
47
+ return (await request("GET", `/api/list?q=${encodeURIComponent(q)}`).then((r) => r.json()));
48
+ }
49
+ /** One artifact's content + metadata (the "attach" fetch). */
50
+ export async function get(id) {
51
+ return (await request("GET", `/api/${encodeURIComponent(id)}`).then((r) => r.json()));
52
+ }
53
+ /** Delete one artifact (owner-checked server-side). */
54
+ export async function del(id) {
55
+ await request("DELETE", `/api/${encodeURIComponent(id)}`);
56
+ }
@@ -9,8 +9,8 @@
9
9
  // is deliberately IGNORED here. Only brand_name / gate_title / domain / logo are adopted. Best-effort,
10
10
  // never throws.
11
11
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
12
- import { homedir } from "node:os";
13
- import { join, dirname } from "node:path";
12
+ import { dirname } from "node:path";
13
+ import { operatorPath } from "./home.js";
14
14
  // CLI defaults — used offline and on first run. brand_color is the CLI's violet accent, NOT the tenant teal.
15
15
  export const BRAND_DEFAULT = {
16
16
  brand_name: "Operator",
@@ -22,7 +22,7 @@ export const BRAND_DEFAULT = {
22
22
  const BRAND_URL = process.env.AXE_BRAND_URL ?? "https://authgate.cloud/api/apps/operator/brand";
23
23
  const CACHE_TTL_MS = 60 * 60 * 1000; // 1h — brand rarely changes; keeps launch-time refreshes rare
24
24
  const FETCH_TIMEOUT_MS = 4000;
25
- function cachePath() { return join(homedir(), ".axe", "operator", "brand-cache.json"); }
25
+ function cachePath() { return operatorPath("brand-cache.json"); }
26
26
  function readCache() {
27
27
  try {
28
28
  return JSON.parse(readFileSync(cachePath(), "utf8"));