@0perator/operator 0.1.355-next.0 → 0.1.355-next.1

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.
package/dist/cli.js CHANGED
@@ -51,7 +51,7 @@ import { modelCtxFor, leanHarnessFor, selectModel, modelRegistry, fmtCtx, shortN
51
51
  import { fetchPortalModels, offlineNote, portalIdFor } from "./router/portal.js";
52
52
  import { fetchFreeModels } from "./router/free-models.js";
53
53
  import { describeTurnError } from "./engine/net-error.js";
54
- import { fallbackNotice, recoveryLine } from "./engine/continuation.js";
54
+ import { fallbackNotice, primaryRecoveredLine, recoveryLine } from "./engine/continuation.js";
55
55
  import { hasByoToken, setByoToken } from "./auth/byo.js";
56
56
  import { getDiscoveredModels } from "./router/discovery.js";
57
57
  import { disposeShellSession, getAgentTasks, registry } from "./tools/registry.js";
@@ -229,6 +229,28 @@ try {
229
229
  setOperatorToken(process.env.KODE_OPERATOR_TOKEN || creds?.token || undefined);
230
230
  }
231
231
  catch { /* auth is optional — a local engine needs none */ }
232
+ // First-run sign-in. The very first interactive launch with no stored token shows the two-choice screen
233
+ // (1 sign in with your account · 2 use an API token) BEFORE the session mounts, like Codex / Claude Code.
234
+ // Strictly gated so nothing else changes: only a real TTY on a bare `operator` launch (no subcommand), only
235
+ // when there is no token at all. A headless `operator run`, any `operator <sub>`, a piped stdin, or an
236
+ // OPERATOR_TOKEN / KODE_OPERATOR_TOKEN in the environment all skip it — the headless path stays byte-identical.
237
+ const sub0 = process.argv[2];
238
+ const envToken = process.env.OPERATOR_TOKEN || process.env.KODE_OPERATOR_TOKEN;
239
+ const firstRunEligible = !bootCreds && !envToken && (!sub0 || sub0.startsWith("-"))
240
+ && !process.argv.includes("--version") && !process.argv.includes("-V") && !process.argv.includes("--help")
241
+ && process.stdin.isTTY && process.stdout.isTTY;
242
+ if (firstRunEligible) {
243
+ try {
244
+ const { firstRunSignIn } = await import("./auth/commands.js");
245
+ const token = await firstRunSignIn(settings);
246
+ if (token) {
247
+ bootCreds = { token };
248
+ const { setOperatorToken } = await import("./engine/aurora.js");
249
+ setOperatorToken(token);
250
+ }
251
+ }
252
+ catch { /* sign-in is best-effort at boot — a failure must never block the session from starting */ }
253
+ }
232
254
  // Seat resolution (enterprise SSO/RBAC readiness): with a managed auth policy deployed, the verified identity
233
255
  // decides the widest tier this process may hold (it can only NARROW, never widen). With no managed policy this
234
256
  // is a no-op and touches no network. `operator auth …` / --version / --help skip it (they must work signed-out).
@@ -557,7 +579,7 @@ const HELP = [
557
579
  " /memory [query] show remembered notes (all, or matching query)",
558
580
  " /allow <tool:args> auto-allow a tool+args glob pattern in gated mode (e.g. bash:npm test*)",
559
581
  " /skill <name|off> activate a skill as a system-prompt directive (/skill off to deactivate)",
560
- " /mcp [on|off] fleet MCP: status · on/off (saved) · /mcp reload (from disk) · /mcp add powertools <root>",
582
+ " /mcp [list|on|off] MCP servers and their tools (pick a server to browse its tools) · on/off (saved) · /mcp reload (from disk) · /mcp add powertools <root>",
561
583
  " /login · /logout · /whoami /login opens the browser to approve; or /login <email> for a 6-digit code (then /login <code>); /login <token>",
562
584
  " /agents [id] detailed sub-agent status, or /agents <id> for a deep view + controls (msg/stop/report)",
563
585
  " @Name <text> message a running sub-agent directly — no main-model turn (@Name stop · @all stop)",
@@ -1532,6 +1554,14 @@ function Root() {
1532
1554
  lastFallbackRef.current = key;
1533
1555
  sys(`⚠ ${fallbackFrom} is unavailable — this answer came from ${backend ?? "another backend"} (gateway fallback)`);
1534
1556
  },
1557
+ onPrimaryRestored: (backend) => {
1558
+ // The primary answered again after we'd been on a fallback: clear the degraded state and say so ONCE, so a
1559
+ // slow fallback stretch is visibly temporary, never a silent permanent pin (the 2026-11-06 Aurora-restart case).
1560
+ if (!lastFallbackRef.current)
1561
+ return;
1562
+ lastFallbackRef.current = undefined;
1563
+ sys(primaryRecoveredLine(backend));
1564
+ },
1535
1565
  onFallback: (e) => sys(fallbackNotice(e)), // every leg of the model failed: which model answered this turn, and why
1536
1566
  onCompaction: (e) => {
1537
1567
  if (!e.skipped) {
@@ -2502,36 +2532,27 @@ function Root() {
2502
2532
  // /login <token> pastes a personal access token (unchanged)
2503
2533
  // /login --browser the explicit device-grant fallback (unchanged behaviour)
2504
2534
  const a = (arg ?? "").trim();
2505
- const { signupStart, signupVerify, verifyToken, authBase } = await import("./auth/client.js");
2535
+ const { signupStart, signupVerify, authBase } = await import("./auth/client.js");
2506
2536
  const { isBetaRefusal, privateBetaMessage } = await import("./auth/beta.js");
2507
2537
  const { classifyLoginArg } = await import("./auth/login-intent.js");
2508
2538
  const { saveCredentials } = await import("./auth/store.js");
2539
+ const { signInWithBrowser, signInWithToken } = await import("./auth/sign-in.js");
2540
+ const { openBrowser } = await import("./auth/commands.js");
2509
2541
  const { setOperatorToken } = await import("./engine/aurora.js");
2510
2542
  const intent = classifyLoginArg(a);
2511
2543
  if (intent !== "empty")
2512
2544
  loginEmptyRetryRef.current = false;
2545
+ // In-session IO: sys lines for output, the system opener for the browser. No poll dots in the TUI —
2546
+ // a single "Waiting for approval…" line is clearer than a growing dot run next to the transcript.
2547
+ const inkIO = { log: (m) => sys(m), error: (m) => sys(m), ask: async () => "", openBrowser };
2513
2548
  const runBrowserLogin = async () => {
2514
- const { requestDeviceCode, awaitApproval } = await import("./auth/client.js");
2515
- const { openBrowser } = await import("./auth/commands.js");
2516
- try {
2517
- const dc = await requestDeviceCode();
2518
- const opened = openBrowser(dc.verification_uri_complete ?? dc.verification_uri);
2519
- sys(`◔ sign-in: ${opened ? "opened the browser to" : "open"} ${dc.verification_uri} and approve with code \x1b[1m${dc.user_code}\x1b[0m — waiting… (if no browser opened, open that URL yourself)`);
2520
- const r = await awaitApproval(dc);
2521
- if (r.state === "approved") {
2522
- await saveCredentials({ token: r.token, user: r.account.external_id, host: authBase(), issuedAt: Date.now() });
2523
- setOperatorToken(r.token);
2524
- setAuthUser(r.account.email ?? r.account.external_id);
2525
- sys(`✓ Authenticated as ${r.account.email ?? r.account.external_id}`);
2526
- }
2527
- else if (r.state === "denied")
2528
- sys(`sign-in not approved — ${privateBetaMessage("your account")}`);
2529
- else
2530
- sys(`sign-in ${r.state} — try /login <email> to sign in by code instead`);
2531
- }
2532
- catch (e) {
2533
- sys(`sign-in failed: ${e instanceof Error ? e.message : String(e)} — try /login <email>`);
2549
+ const r = await signInWithBrowser(inkIO);
2550
+ if (r.ok && r.account && r.token) {
2551
+ setOperatorToken(r.token);
2552
+ setAuthUser(r.account.email ?? r.account.external_id);
2534
2553
  }
2554
+ else if (!r.ok && r.reason !== "denied")
2555
+ sys("try /login <email> to sign in by code instead");
2535
2556
  };
2536
2557
  if (intent === "browser") {
2537
2558
  await runBrowserLogin();
@@ -2594,16 +2615,14 @@ function Root() {
2594
2615
  sys(`couldn't start sign-in (${started.error})`);
2595
2616
  break;
2596
2617
  }
2597
- // Otherwise treat it as a pasted personal access token.
2598
- const acct = await verifyToken(a);
2599
- if (!acct) {
2600
- sys("that token was rejected — did you mean /login <email>?");
2601
- break;
2618
+ // Otherwise treat it as a pasted personal access token (trimmed of stray whitespace/dots in sign-in.ts).
2619
+ const rtok = await signInWithToken(a, inkIO);
2620
+ if (rtok.ok && rtok.account && rtok.token) {
2621
+ setOperatorToken(rtok.token);
2622
+ setAuthUser(rtok.account.email ?? rtok.account.external_id);
2602
2623
  }
2603
- await saveCredentials({ token: a, user: acct.external_id, host: authBase(), issuedAt: Date.now() });
2604
- setOperatorToken(a);
2605
- setAuthUser(acct.email ?? acct.external_id);
2606
- sys(`signed in as ${acct.email ?? acct.external_id}`);
2624
+ else if (!rtok.ok)
2625
+ sys("did you mean /login <email>?");
2607
2626
  break;
2608
2627
  }
2609
2628
  case "mcp": {
@@ -2658,8 +2677,28 @@ function Root() {
2658
2677
  }
2659
2678
  }
2660
2679
  else {
2661
- const n = s.mcpToolCount();
2662
- const servers = s.mcpServers();
2680
+ let n = s.mcpToolCount();
2681
+ let servers = s.mcpServers();
2682
+ if ((a === "" || a === "list") && !servers.length && settings.mcp) {
2683
+ sys("discovering MCP servers…");
2684
+ n = await s.enableMcp();
2685
+ servers = s.mcpServers();
2686
+ }
2687
+ if ((a === "" || a === "list") && servers.length) {
2688
+ sys(`${n} MCP tools across ${servers.length} server${servers.length === 1 ? "" : "s"} · /mcp reload · /mcp off`);
2689
+ const rows = servers.map((sv) => `${sv.name} · ${sv.tools.length} tool${sv.tools.length === 1 ? "" : "s"}`);
2690
+ openPicker("MCP servers: pick one to see its tools", rows, servers, (ans) => {
2691
+ if (!("entry" in ans))
2692
+ return;
2693
+ const sv = ans.entry;
2694
+ const toolRows = sv.tools.map((t) => {
2695
+ const d = (t.description ?? "").replace(/\s+/g, " ").trim();
2696
+ return d ? `${t.name} · ${d.length > 90 ? d.slice(0, 89) + "…" : d}` : t.name;
2697
+ });
2698
+ openPicker(`${sv.name}: ${sv.tools.length} tool${sv.tools.length === 1 ? "" : "s"} (Esc closes)`, toolRows, sv.tools, () => { });
2699
+ });
2700
+ break;
2701
+ }
2663
2702
  const inv = servers.length
2664
2703
  ? "\n" + servers.map((sv) => ` · ${sv.name}: ${sv.tools.map((t) => t.name).join(", ") || "(no tools)"}`).join("\n")
2665
2704
  : "";
@@ -42,6 +42,22 @@ export const FEATURES = {
42
42
  default: false,
43
43
  description: "Advertise a fixed core tool set + tool_search/tool_call; the rest are found and run on demand (smaller cached prefix)",
44
44
  },
45
+ /** mdoc product (products/mdoc.ts): the model-docs tenant on the shared product rails — versioned, scope-gated
46
+ * knowledge (decisions/specs/handoffs/conventions/chips) models read + write via mdoc_* tools. Default OFF so
47
+ * it never bloats the stock prompt prefix; on, the session registers the five mdoc tools (reads safe, mdoc_put
48
+ * admin-gated like artifact writers). SPEC: _ai-docs/specs/2026-11-06-operator-api-products-craft-mdoc.md. */
49
+ mdoc: {
50
+ default: false,
51
+ description: "The mdoc model-docs product: versioned, scope-gated knowledge models retrieve and version (mdoc_* tools)",
52
+ },
53
+ /** craft product (products/craft.ts): the hosted, account-owned, shareable surface (page/deck/doc/board/app)
54
+ * on the shared product rails — the promotion of artifact_create into a first-class owned, versioned product.
55
+ * Default OFF so it never bloats the stock prompt prefix; on, the session registers the four craft_* tools
56
+ * (reads safe, craft_create/update admin-gated like artifact writers). SPEC: products-craft-mdoc. */
57
+ craft: {
58
+ default: false,
59
+ description: "The craft product: hosted, account-owned, versioned, shareable pages/decks/docs/boards (craft_* tools)",
60
+ },
45
61
  };
46
62
  /** Env var that overrides one feature: camelCase → UPPER_SNAKE, e.g. classifierGate → KODE_FEATURE_CLASSIFIER_GATE. */
47
63
  export function featureEnvName(name) {
@@ -6,7 +6,7 @@ import { chat, endpointSlots, getOperatorToken, requiresOperatorToken, StreamSer
6
6
  import { parseToolArgs } from "./json-repair.js";
7
7
  import { buildMessages } from "./messages.js";
8
8
  import { recoverToolCalls, cleanAssistantProse } from "./toolcalls.js";
9
- import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampMaxTokens, outputRoom, headroomTargetRatio, effectiveCeilingTokens, fullRequestEstimate, TOOL_CALL_HEADROOM_TOKENS } from "./compaction.js";
9
+ import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampMaxTokens, outputRoom, headroomTargetRatio, effectiveCeilingTokens, fullRequestEstimate, compactionAction, TOOL_CALL_HEADROOM_TOKENS } from "./compaction.js";
10
10
  import { globalTokenMeter, endpointKey, requestChars } from "./token-meter.js";
11
11
  import { classifyFailure, failureCause, servedContextLimit, outputCeilingLimit, learnOutputCeiling, learnedOutputCeiling, backoffMs, sleep } from "./selfheal.js";
12
12
  import { hostOf } from "./net-error.js";
@@ -1142,27 +1142,37 @@ export async function runTurn(userInput, conversation, opts) {
1142
1142
  resetLoop(kind, cOpts);
1143
1143
  }
1144
1144
  if (shouldProactivelyCompact(conversation.all, cOpts)) {
1145
- // Compact (evict + summarize old turns), then GUARANTEE fit: when the bulk is inside the kept recent
1146
- // turns (one turn that dumped huge tool output), fitToWindow elides the largest tool outputs in place
1147
- // so a request is NEVER dispatched over the current endpoint's window. Layer-3 backstop; Layer 1
1148
- // (servedContextLimit, in the catch below) keeps that window itself honest after a learned n_ctx.
1149
- // Once a summarizer failed on a ceiling-only trigger, later rounds of this turn only shed tool outputs:
1150
- // the over-window case always retries, a soft speed ceiling must not add a failing request per round.
1151
- const beforeLen = conversation.all.length;
1152
- const before = fullRequestEstimate(conversation.all, cOpts);
1153
- const overWindow = needsCompaction(conversation.all, cOpts);
1154
- let skipped = overWindow ? undefined : ceilingSummaryFailed;
1155
- const evicted = skipped ? conversation.all : await compactSignalled(conversation.all, { ...cOpts, onSkip: (r) => { skipped = r; } }, before);
1156
- if (!overWindow)
1157
- ceilingSummaryFailed = skipped;
1158
- conversation.replaceAll(fitToWindow(evicted, cOpts));
1159
- const after = fullRequestEstimate(conversation.all, cOpts);
1160
- if (skipped || after < before)
1161
- opts.onCompaction?.({ before, after, ceiling: effectiveCeilingTokens(cOpts), skipped });
1162
- // Rehydrate: if compaction actually evicted turns, re-surface the plan + recently-touched files so the
1163
- // model re-reads current state instead of acting on the now-summarized (stale) earlier reads.
1164
- if (conversation.all.length < beforeLen && !resetNow)
1165
- engineUser(rehydrationNote(touchedFiles)); // after a reset its digest is this turn's current account — "re-read everything" would undo it
1145
+ // Tiered compaction: decide shed vs compact before doing any work.
1146
+ const action = compactionAction(conversation.all, cOpts);
1147
+ if (action === "shed") {
1148
+ // Shed tool outputs on a copy — no LLM summarize request.
1149
+ const before = fullRequestEstimate(conversation.all, cOpts);
1150
+ conversation.replaceAll(fitToWindow(conversation.all, cOpts));
1151
+ opts.onCompaction?.({ before, after: fullRequestEstimate(conversation.all, cOpts), ceiling: effectiveCeilingTokens(cOpts) });
1152
+ }
1153
+ else {
1154
+ // Compact (evict + summarize old turns), then GUARANTEE fit: when the bulk is inside the kept recent
1155
+ // turns (one turn that dumped huge tool output), fitToWindow elides the largest tool outputs in place
1156
+ // so a request is NEVER dispatched over the current endpoint's window. Layer-3 backstop; Layer 1
1157
+ // (servedContextLimit, in the catch below) keeps that window itself honest after a learned n_ctx.
1158
+ // Once a summarizer failed on a ceiling-only trigger, later rounds of this turn only shed tool outputs:
1159
+ // the over-window case always retries, a soft speed ceiling must not add a failing request per round.
1160
+ const beforeLen = conversation.all.length;
1161
+ const before = fullRequestEstimate(conversation.all, cOpts);
1162
+ const overWindow = needsCompaction(conversation.all, cOpts);
1163
+ let skipped = overWindow ? undefined : ceilingSummaryFailed;
1164
+ const evicted = skipped ? conversation.all : await compactSignalled(conversation.all, { ...cOpts, onSkip: (r) => { skipped = r; } }, before);
1165
+ if (!overWindow)
1166
+ ceilingSummaryFailed = skipped;
1167
+ conversation.replaceAll(fitToWindow(evicted, cOpts));
1168
+ const after = fullRequestEstimate(conversation.all, cOpts);
1169
+ if (skipped || after < before)
1170
+ opts.onCompaction?.({ before, after, ceiling: effectiveCeilingTokens(cOpts), skipped });
1171
+ // Rehydrate: if compaction actually evicted turns, re-surface the plan + recently-touched files so the
1172
+ // model re-reads current state instead of acting on the now-summarized (stale) earlier reads.
1173
+ if (conversation.all.length < beforeLen && !resetNow)
1174
+ engineUser(rehydrationNote(touchedFiles)); // after a reset its digest is this turn's current account — "re-read everything" would undo it
1175
+ }
1166
1176
  }
1167
1177
  // Intra-turn output-headroom guard (task #14's third leg — _ai-docs 2026-10-19): the proactive gate
1168
1178
  // above keeps the PROMPT under threshold, but near the window (or on a small endpoint) the leftover
@@ -450,8 +450,11 @@ async function* streamDeltas(messages, o) {
450
450
  throw err;
451
451
  }
452
452
  const fallbackFrom = res.headers.get("x-0perator-fallback");
453
+ const servedBackend = res.headers.get("x-0perator-backend");
453
454
  if (fallbackFrom)
454
- o.onServed?.({ backend: res.headers.get("x-0perator-backend") ?? undefined, fallbackFrom });
455
+ o.onServed?.({ backend: servedBackend ?? undefined, fallbackFrom });
456
+ else if (servedBackend)
457
+ o.onPrimaryRestored?.(servedBackend); // primary answered (no fallback header) — lets the caller clear a degraded state and say "back on X"
455
458
  const reader = res.body.getReader();
456
459
  const dec = new TextDecoder();
457
460
  let buf = "";
@@ -134,13 +134,33 @@ export function shouldProactivelyCompact(conversation, opts) {
134
134
  return ceiling !== undefined && fullRequestEstimate(conversation, opts) >= ceiling;
135
135
  }
136
136
  /** Where a ceiling-triggered shed stops: fixed + CEILING_HYSTERESIS of the conversation budget. */
137
- function ceilingTargetTokens(opts) {
137
+ export function ceilingTargetTokens(opts) {
138
138
  const ceiling = effectiveCeilingTokens(opts);
139
139
  if (ceiling === undefined)
140
140
  return undefined;
141
141
  const fixed = fixedRequestTokens(opts);
142
142
  return fixed + Math.floor((ceiling - fixed) * CEILING_HYSTERESIS);
143
143
  }
144
+ /** Tiered compaction decision: at a soft speed-ceiling trip, prefer shedding tool outputs (cheap,
145
+ * lossless for convo text, spill-recoverable) over an LLM summarize request; escalate to compact
146
+ * only when shedding alone cannot reach the ceiling target. Hard over-window trips always compact. */
147
+ export function compactionAction(conversation, opts) {
148
+ if (!shouldProactivelyCompact(conversation, opts))
149
+ return "none";
150
+ const est = fullRequestEstimate(conversation, opts);
151
+ const hardLimit = opts.ctxWindow * (opts.threshold ?? 0.7);
152
+ if (est >= hardLimit)
153
+ return "compact";
154
+ const target = ceilingTargetTokens(opts);
155
+ // Dry-run the shed WITHOUT the spill sink: the decision phase must not write files for content the
156
+ // action phase will spill again (Forge review #223 — orphaned spill files on the hot path).
157
+ if (target !== undefined && target > 0) {
158
+ const probe = fullRequestEstimate(fitToWindow([...conversation], { ...opts, spill: undefined }), opts);
159
+ if (probe <= target)
160
+ return "shed";
161
+ }
162
+ return "compact";
163
+ }
144
164
  /** Last-resort shrink that GUARANTEES a request fits a known-real window. compact() evicts OLD turns; when
145
165
  * the over-budget bulk lives INSIDE the kept turns — one turn that dumped tens of KB of tool output (a
146
166
  * trace, a big file read, a `dis` dump) — eviction can't shed it and the request 400s again on a small
@@ -218,6 +218,11 @@ export function recoveryLine(s) {
218
218
  export function fallbackNotice(e) {
219
219
  return `⚠ ${e.line}`;
220
220
  }
221
+ /** Shown when the primary recovers after the session had been served from a fallback — so a degraded stretch
222
+ * reads as temporary, never a silent permanent downgrade. `primary` is the box that answered (x-0perator-backend). */
223
+ export function primaryRecoveredLine(primary) {
224
+ return `✓ ${primary} is back — answers are served from it again`;
225
+ }
221
226
  /** A turn nothing answered — every leg of the owner's model and of its fallback failed, or finished with nothing in the
222
227
  * reply: each leg's cause in the order tried, and what the next turn does. `note` stays in history (the next turn's model
223
228
  * reads it, isEngineFinal keys on it); `display` is what the owner reads. Never "want me to try again?". */
@@ -0,0 +1,137 @@
1
+ // Craft product handlers — the hosted, account-owned, shareable surface (page / deck / doc / board / dashboard /
2
+ // app) on the shared product rails (SPEC products-craft-mdoc §craft). The promotion of artifact_create into a
3
+ // first-class, owned, versioned, addressable product.
4
+ //
5
+ // Same broker shape as artifactCreate: an env-configurable base, the op_ bearer (the ONLY credential sent, never
6
+ // logged), graceful when the surface is down. Account-ownership, ACL, versioning and the change-feed/revoke
7
+ // guarantee live SERVER-SIDE on the hosted surface (the shared-contract backend); this client brokers and never
8
+ // owns the ACL. Scope + types come from the canonical rails (store.ts / scope.ts) — not redefined here.
9
+ import { readFileSync } from "node:fs";
10
+ import { domainInScope, DOMAIN_DENIED } from "./scope.js";
11
+ import { operatorPath } from "../config/home.js";
12
+ const CRAFT_DOMAIN = "craft";
13
+ const str = (v, fallback = "") => (v === undefined || v === null ? fallback : String(v));
14
+ /** Hosted-surface base — env-configurable, no host surfaced in any user-read string. */
15
+ function craftBase() {
16
+ return (process.env.KODE_CRAFT_URL || process.env.KODE_CRAFTBOARD_URL || "https://craftboard.axe.onl").replace(/\/$/, "");
17
+ }
18
+ /** The signed-in operator bearer — the ONLY credential sent; never logged. */
19
+ function operatorToken() {
20
+ return process.env.KODE_OPERATOR_TOKEN || process.env.OPERATOR_TOKEN || process.env.KODE_CRAFT_TOKEN || undefined;
21
+ }
22
+ /** This key's scope atoms (AuthGate authz, e.g. "domain:craft") — same source + shape mdoc's resolveActor uses:
23
+ * the cached identity's claims.scopes, with an env override. Empty ⇒ unrestricted (legacy key); domainInScope
24
+ * applies the `domain:` rule. */
25
+ function resolveScopes() {
26
+ const env = process.env.KODE_OPERATOR_SCOPES;
27
+ if (env !== undefined)
28
+ return env.split(/[,\s]+/).filter(Boolean);
29
+ try {
30
+ const c = JSON.parse(readFileSync(operatorPath("identity.json"), "utf8"));
31
+ return c.claims?.scopes ?? [];
32
+ }
33
+ catch {
34
+ return [];
35
+ }
36
+ }
37
+ const CRAFT_TYPES = /^(page|deck|doc|board|dashboard|app|svg|markdown|canvas|html)$/;
38
+ /** One brokered call to the hosted Craft object API. Carries the op_ bearer; graceful on any failure; never throws. */
39
+ async function craftCall({ method, path, body, timeoutMs = 30_000 }) {
40
+ if (!domainInScope(resolveScopes(), CRAFT_DOMAIN))
41
+ return { ok: false, error: `${DOMAIN_DENIED}: this key is not scoped for the Craft product` };
42
+ const token = operatorToken();
43
+ if (!token)
44
+ return { ok: false, error: "not signed in — Craft needs an Operator account (run `operator auth login`)" };
45
+ const base = craftBase();
46
+ const ctrl = new AbortController();
47
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
48
+ try {
49
+ const res = await fetch(`${base}${path}`, {
50
+ method, signal: ctrl.signal,
51
+ headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", Authorization: `Bearer ${token}` },
52
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
53
+ });
54
+ if (res.status === 401 || res.status === 403)
55
+ return { ok: false, error: `the Craft surface refused this request (${res.status}) — your key may not be scoped for Craft, or you lack access to this object.` };
56
+ if (!res.ok)
57
+ return { ok: false, error: `the Craft surface returned ${res.status} — it may be down or moved.` };
58
+ const json = (await res.json().catch(() => ({})));
59
+ return { ok: true, json };
60
+ }
61
+ catch (e) {
62
+ const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
63
+ return { ok: false, error: `could not reach the Craft surface (${msg})` };
64
+ }
65
+ finally {
66
+ clearTimeout(timer);
67
+ }
68
+ }
69
+ function viewUrlOf(json) {
70
+ const direct = str(json.viewUrl || json.url);
71
+ if (direct)
72
+ return direct;
73
+ const rel = str(json.path).match(/\/v\/[A-Za-z0-9_-]+/); // the surface returns a relative "/v/<id>"
74
+ return rel ? `${craftBase()}${rel[0]}` : undefined;
75
+ }
76
+ export async function craftCreate(args) {
77
+ const content = str(args.content);
78
+ if (!content)
79
+ return "error: craft_create needs `content` (the page/deck/doc body — HTML, SVG, or markdown)";
80
+ const typeIn = str(args.type).toLowerCase();
81
+ const type = CRAFT_TYPES.test(typeIn) ? typeIn : "page";
82
+ const title = str(args.title) || "Operator craft";
83
+ const r = await craftCall({ method: "POST", path: "/api/v1/craft", body: { type, title, content } });
84
+ if (!r.ok)
85
+ return `error: ${r.error}`;
86
+ const id = str(r.json.id);
87
+ const url = viewUrlOf(r.json);
88
+ return url ? `created craft ${id} → ${url}` : (id ? `created craft ${id} (no URL returned)` : "craft created (no id returned)");
89
+ }
90
+ export async function craftUpdate(args) {
91
+ const id = str(args.id);
92
+ if (!id)
93
+ return "error: craft_update needs `id` (from craft_create / craft_list)";
94
+ const patch = {};
95
+ if (str(args.content))
96
+ patch.content = str(args.content);
97
+ if (str(args.title))
98
+ patch.title = str(args.title);
99
+ if (str(args.visibility))
100
+ patch.visibility = str(args.visibility); // server validates against the shared Visibility set
101
+ if (Object.keys(patch).length === 0)
102
+ return "error: craft_update needs at least one of `content`, `title`, `visibility`";
103
+ if (str(args.expected_version))
104
+ patch.expectedVersion = str(args.expected_version); // optimistic concurrency
105
+ const r = await craftCall({ method: "PATCH", path: `/api/v1/craft/${encodeURIComponent(id)}`, body: patch });
106
+ if (!r.ok)
107
+ return `error: ${r.error}`;
108
+ if (str(r.json.conflict))
109
+ return `error: craft ${id} changed since you read it (expected ${str(args.expected_version)}, live ${str(r.json.version)}) — craft_get it again, reapply, retry.`;
110
+ const url = viewUrlOf(r.json);
111
+ return `updated craft ${id}${str(r.json.version) ? ` → version ${str(r.json.version)}` : ""}${url ? ` · ${url}` : ""}`;
112
+ }
113
+ export async function craftList(args) {
114
+ const limit = Math.min(Math.max(Number(args.limit) || 20, 1), 100);
115
+ const r = await craftCall({ method: "GET", path: `/api/v1/craft?limit=${limit}`, timeoutMs: 15_000 });
116
+ if (!r.ok)
117
+ return `error: ${r.error}`;
118
+ const items = Array.isArray(r.json.items) ? r.json.items : [];
119
+ if (!items.length)
120
+ return "no craft yet — make one with craft_create";
121
+ return items.map((it) => `${str(it.id)} · ${str(it.type) || "page"} · ${str(it.title) || "(untitled)"} · ${str(it.visibility) || "private"}${viewUrlOf(it) ? ` · ${viewUrlOf(it)}` : ""}`).join("\n");
122
+ }
123
+ export async function craftGet(args) {
124
+ const id = str(args.id);
125
+ if (!id)
126
+ return "error: craft_get needs `id`";
127
+ const r = await craftCall({ method: "GET", path: `/api/v1/craft/${encodeURIComponent(id)}`, timeoutMs: 15_000 });
128
+ if (!r.ok)
129
+ return `error: ${r.error}`;
130
+ const j = r.json;
131
+ const url = viewUrlOf(j);
132
+ const head = `craft ${str(j.id)} · ${str(j.type) || "page"} · ${str(j.title) || "(untitled)"} · ${str(j.visibility) || "private"} · owner ${str(j.owner)} · v${str(j.version)}`;
133
+ const body = str(j.content);
134
+ return `${head}${url ? `\n${url}` : ""}${body ? `\n\n${body.length > 4000 ? body.slice(0, 4000) + "\n… (truncated; craft_get returns the current version)" : body}` : ""}`;
135
+ }
136
+ // Exposed for tests (pure helpers that don't touch the network).
137
+ export const _internal = { craftBase, viewUrlOf, resolveScopes };
@@ -0,0 +1,101 @@
1
+ // mdoc — the model-docs product (spec §"mdoc"). The structured, versioned, scope-gated knowledge tier that
2
+ // agents READ and WRITE at runtime: decision logs, specs, handoffs, conventions, and roledrobe Chip deltas.
3
+ // A roledrobe Chip IS an mdoc of type "chip" (its delta + conformance record) — one surface, gated by
4
+ // domain:mdoc, metered, versioned, retrievable by the amplifier at delegation time.
5
+ //
6
+ // Default read path: TOOL-FIRST (the model calls mdoc_search / mdoc_get). A clean seam is left for an
7
+ // optional automatic retrieval hook (retrieve() below) but auto-RAG is NOT wired — that is an owner decision.
8
+ //
9
+ // NODE-SIDE ONLY — loaded lazily from tools/mdoc.ts, never in the neutral bundle.
10
+ import { createHash } from "node:crypto";
11
+ import { readFileSync } from "node:fs";
12
+ import { operatorPath } from "../config/home.js";
13
+ import { ProductStore } from "./store.js";
14
+ import { domainInScope, can, DOMAIN_DENIED } from "./scope.js";
15
+ export const MDOC_DOMAIN = "mdoc";
16
+ export const MDOC_TYPES = ["decision", "spec", "handoff", "convention", "chip"];
17
+ const store = () => new ProductStore(MDOC_DOMAIN);
18
+ /** The signed-in actor, or the local owner. Reads the identity cache AuthGate's verify writes; absent a
19
+ * token (single-user) the owner is "local-owner" with no scope restriction (all domains). Injectable for tests. */
20
+ export function resolveActor() {
21
+ try {
22
+ const raw = readFileSync(operatorPath("identity.json"), "utf8");
23
+ const c = JSON.parse(raw);
24
+ const sub = c.claims?.sub ?? c.sub;
25
+ if (sub)
26
+ return { account: sub, scopes: c.claims?.scopes ?? [] };
27
+ }
28
+ catch { /* no identity cache => local owner */ }
29
+ return { account: "local-owner", scopes: [] };
30
+ }
31
+ function gate(actor) {
32
+ if (!domainInScope(actor.scopes, MDOC_DOMAIN))
33
+ throw new Error(DOMAIN_DENIED);
34
+ }
35
+ export function mdocPut(actor, args) {
36
+ gate(actor);
37
+ const type = (args.type && MDOC_TYPES.includes(args.type)) ? args.type : "decision";
38
+ const meta = { title: args.title ?? args.id, tags: args.tags ?? [] };
39
+ const { object } = store().put({
40
+ owner: actor.account, id: args.id, content: args.content, author: actor.account,
41
+ type, visibility: args.visibility ?? "private", meta, note: args.note, expect: args.expect,
42
+ });
43
+ return object;
44
+ }
45
+ export function mdocGet(actor, id, version) {
46
+ gate(actor);
47
+ const s = store();
48
+ const obj = s.load(actor.account, id);
49
+ if (!obj || !can(actor.account, "read", obj))
50
+ return null;
51
+ const content = s.content(actor.account, version ?? obj.current);
52
+ if (content === null)
53
+ return null;
54
+ return { object: obj, content };
55
+ }
56
+ export function mdocList(actor, opts = {}) {
57
+ gate(actor);
58
+ return store().list(actor.account)
59
+ .filter((o) => can(actor.account, "list", o))
60
+ .filter((o) => (opts.type ? o.type === opts.type : true));
61
+ }
62
+ /** Own-scope keyword search over title, tags and the current content. The seam where a semantic index
63
+ * (embeddings) would slot in later; keyword is the honest v1. */
64
+ export function mdocSearch(actor, query, opts = {}) {
65
+ gate(actor);
66
+ const q = query.trim().toLowerCase();
67
+ const terms = q.split(/\s+/).filter(Boolean);
68
+ const s = store();
69
+ const hits = [];
70
+ for (const o of s.list(actor.account)) {
71
+ if (!can(actor.account, "read", o))
72
+ continue;
73
+ if (opts.type && o.type !== opts.type)
74
+ continue;
75
+ const meta = o.meta;
76
+ const body = s.content(actor.account, o.current) ?? "";
77
+ const hay = `${meta.title}\n${(meta.tags ?? []).join(" ")}\n${body}`.toLowerCase();
78
+ const score = terms.reduce((n, t) => n + (hay.includes(t) ? 1 : 0), 0);
79
+ if (!terms.length || score > 0) {
80
+ const at = body.toLowerCase().indexOf(terms[0] ?? "");
81
+ const snippet = at >= 0 ? body.slice(Math.max(0, at - 40), at + 120) : body.slice(0, 160);
82
+ hits.push({ object: o, snippet, score });
83
+ }
84
+ }
85
+ return hits.sort((a, b) => b.score - a.score || b.object.updatedAt - a.object.updatedAt)
86
+ .slice(0, opts.limit ?? 10)
87
+ .map(({ object, snippet }) => ({ object, snippet }));
88
+ }
89
+ export function mdocHistory(actor, id) {
90
+ gate(actor);
91
+ const obj = store().load(actor.account, id);
92
+ if (!obj || !can(actor.account, "read", obj))
93
+ return null;
94
+ return obj.versions;
95
+ }
96
+ /** Seam for an optional automatic-retrieval hook (NOT wired by default — tool-first is the default read
97
+ * path). The engine could call this to pull relevant mdocs into context; it enforces the same gate. */
98
+ export function retrieve(actor, query, limit = 3) {
99
+ return mdocSearch(actor, query, { limit }).map((h) => ({ id: h.object.id, type: h.object.type, snippet: h.snippet }));
100
+ }
101
+ export const _test = { contentHash: (s) => createHash("sha256").update(s).digest("hex").slice(0, 16) };
@@ -0,0 +1,36 @@
1
+ /** The AuthGate per-key scope rule (item 2): a `domain:` atom restricts the key to named products; a key
2
+ * with NO `domain:` atom is unrestricted (every legacy token keeps full access). `domain:*` = all. */
3
+ export function domainInScope(scopes, product) {
4
+ const domains = (scopes ?? []).filter((s) => s.startsWith("domain:")).map((s) => s.slice(7));
5
+ if (domains.length === 0)
6
+ return true; // no domain atom => all domains (backward compatible)
7
+ return domains.includes("*") || domains.includes(product);
8
+ }
9
+ /** Object-level authorization. `actor` is an ACCOUNT id (never a key). The owner can do anything; an editor
10
+ * grant can read+write; a reader grant / an open visibility can read+list. Ownership is the account, so a
11
+ * different key for the SAME account has the same rights, and a key for a different account does not. */
12
+ export function can(actor, action, obj) {
13
+ if (!actor)
14
+ return action === "read" || action === "list" ? obj.visibility === "public" || obj.visibility === "link" : false;
15
+ if (actor === obj.owner)
16
+ return true;
17
+ const role = obj.grants[actor];
18
+ switch (action) {
19
+ case "read":
20
+ case "list":
21
+ if (role === "reader" || role === "editor")
22
+ return true;
23
+ return obj.visibility === "public" || obj.visibility === "link"
24
+ || (obj.visibility === "people" && role !== undefined);
25
+ case "write":
26
+ return role === "editor";
27
+ case "delete":
28
+ case "share":
29
+ return false; // owner-only (handled above)
30
+ default:
31
+ return false;
32
+ }
33
+ }
34
+ /** The one reason string a surface returns when the domain gate denies — mirrors the model_not_in_scope
35
+ * shape so clients can branch on it. */
36
+ export const DOMAIN_DENIED = "domain_not_in_scope";