@0perator/operator 0.1.360-next.2 → 0.2.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.
Files changed (104) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/commands.js +7 -3
  3. package/dist/auth/identity.js +1 -0
  4. package/dist/auth/staff.js +55 -0
  5. package/dist/autonomy/delegate-mode.js +159 -0
  6. package/dist/autonomy/delegate.js +42 -15
  7. package/dist/autonomy/headless.js +7 -4
  8. package/dist/autonomy/index.js +2 -4
  9. package/dist/autonomy/session-factory.js +13 -12
  10. package/dist/autonomy/subagent-model.js +17 -7
  11. package/dist/background/capacity.js +136 -0
  12. package/dist/background/evidence.js +42 -0
  13. package/dist/background/index.js +336 -45
  14. package/dist/background/lane-phase.js +60 -0
  15. package/dist/background/lane-summary.js +151 -0
  16. package/dist/background/notices.js +12 -3
  17. package/dist/background/resume.js +125 -0
  18. package/dist/background/synthesis.js +25 -0
  19. package/dist/browser/engine.js +163 -0
  20. package/dist/browser/session.js +130 -140
  21. package/dist/bus/inbox.js +150 -6
  22. package/dist/cli.js +343 -86
  23. package/dist/config/features.js +3 -3
  24. package/dist/config/persona.js +29 -3
  25. package/dist/config/settings.js +262 -21
  26. package/dist/config/staff-prompt.js +12 -0
  27. package/dist/engine/agent.js +52 -41
  28. package/dist/engine/aurora.js +40 -8
  29. package/dist/engine/batch-scheduler.js +4 -13
  30. package/dist/engine/compaction.js +2 -2
  31. package/dist/engine/continuation.js +30 -32
  32. package/dist/engine/decision-points.js +2 -3
  33. package/dist/engine/fanout.js +16 -0
  34. package/dist/engine/loop-guard.js +26 -83
  35. package/dist/engine/messages.js +2 -2
  36. package/dist/engine/moa.js +18 -2
  37. package/dist/engine/native-vision-node.js +72 -0
  38. package/dist/engine/native-vision.js +103 -0
  39. package/dist/engine/selfheal.js +1 -1
  40. package/dist/engine/toolcalls.js +6 -6
  41. package/dist/engine/verify-gate.js +37 -7
  42. package/dist/gateway-cli.js +14 -3
  43. package/dist/index.js +3 -0
  44. package/dist/mcp/phone-server.js +30 -0
  45. package/dist/memory/live-progress.js +4 -5
  46. package/dist/moa/codeact-lane.js +98 -0
  47. package/dist/moa/codeact-sandbox.js +409 -0
  48. package/dist/moa/codeact.js +140 -0
  49. package/dist/permissions/artifact-visibility.js +10 -0
  50. package/dist/permissions/index.js +33 -17
  51. package/dist/permissions/signature.js +5 -0
  52. package/dist/permissions/tier.js +4 -2
  53. package/dist/phone-cli.js +65 -0
  54. package/dist/products/craft.js +2 -2
  55. package/dist/remote/grants.js +119 -0
  56. package/dist/remote/host.js +63 -6
  57. package/dist/router/models.js +29 -29
  58. package/dist/selfimprove/index.js +9 -7
  59. package/dist/services/preflight.js +35 -91
  60. package/dist/session.js +173 -46
  61. package/dist/skills/install-guard.js +68 -0
  62. package/dist/skills/install.js +67 -0
  63. package/dist/toolchain/manifest.json +13 -13
  64. package/dist/tools/background-result.js +1 -1
  65. package/dist/tools/classes.js +103 -0
  66. package/dist/tools/contract.js +1 -1
  67. package/dist/tools/craft.js +13 -2
  68. package/dist/tools/deferred.js +1 -0
  69. package/dist/tools/device/android.js +227 -0
  70. package/dist/tools/device/classify.js +127 -0
  71. package/dist/tools/device/deps.js +69 -0
  72. package/dist/tools/device/desktop.js +82 -0
  73. package/dist/tools/device/harness.js +262 -0
  74. package/dist/tools/device/iphone.js +206 -0
  75. package/dist/tools/device/mirroring-jxa.js +146 -0
  76. package/dist/tools/device/setup.js +90 -0
  77. package/dist/tools/device/tools.js +70 -0
  78. package/dist/tools/device/types.js +19 -0
  79. package/dist/tools/executor.js +25 -15
  80. package/dist/tools/generation-gateway.js +94 -0
  81. package/dist/tools/registry.js +95 -155
  82. package/dist/ui/App.js +18 -6
  83. package/dist/ui/ApprovalPrompt.js +10 -4
  84. package/dist/ui/BgPanel.js +17 -12
  85. package/dist/ui/Header.js +1 -6
  86. package/dist/ui/StatusRule.js +18 -7
  87. package/dist/ui/ToolStep.js +3 -3
  88. package/dist/ui/Transcript.js +36 -14
  89. package/dist/ui/UpdatePrompt.js +40 -0
  90. package/dist/ui/batchLine.js +4 -4
  91. package/dist/ui/editdiff.js +2 -4
  92. package/dist/ui/format.js +4 -20
  93. package/dist/ui/liveTools.js +3 -3
  94. package/dist/ui/modelPicker.js +1 -1
  95. package/dist/ui/opsMode.js +20 -0
  96. package/dist/ui/slashCommands.js +1 -0
  97. package/dist/ui/types.js +0 -2
  98. package/dist/update-check.js +145 -0
  99. package/dist/update.js +59 -15
  100. package/dist/util/slash.js +2 -2
  101. package/package.json +4 -2
  102. package/src/tools/device/NOTICE +37 -0
  103. package/dist/browser/cdp.js +0 -271
  104. package/dist/tools/mutating.js +0 -15
package/dist/session.js CHANGED
@@ -6,6 +6,11 @@ import { recordTruncation } from "./observability/blackbox.js";
6
6
  import { Conversation, placeSessionContext, SESSION_CONTEXT_OPEN, SESSION_CONTEXT_CLOSE, SESSION_CONTEXT_REQUEST_LINE } from "./engine/messages.js";
7
7
  import { scratchDirFor } from "./config/scratch.js";
8
8
  import { homedir } from "node:os";
9
+ import { detectVision, markVisionRejected } from "./engine/native-vision.js";
10
+ import { extractImagePaths } from "./engine/native-vision-node.js";
11
+ import { planFanOut } from "./engine/fanout.js";
12
+ import { withCodeActDelegateSchema } from "./moa/codeact-lane.js";
13
+ import { codeActEnabled } from "./moa/codeact.js";
9
14
  import { chat, health, reachable, gateKey, isRemoteBase, shipsLlamaCacheKnobs, requiresOperatorToken, operatorTrustedUrl } from "./engine/aurora.js";
10
15
  import { claimSlot, releaseSlot } from "./engine/kv-slot.js";
11
16
  import { randomUUID } from "node:crypto";
@@ -14,23 +19,25 @@ import { compact, compactionSplit, fitToWindow, turnStarts, SUMMARY_INSTRUCTION,
14
19
  import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
15
20
  import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
16
21
  import { engineRouter } from "./engine/router-adapter.js";
17
- import { appendFileSync, mkdirSync } from "node:fs";
22
+ import { appendFileSync, existsSync, mkdirSync, realpathSync } from "node:fs";
18
23
  import { dirname } from "node:path";
19
24
  import { operatorPath } from "./config/home.js";
20
25
  import { moaTeam, plannerBrief } from "./engine/moa.js";
21
26
  import { routeTurn } from "./classifier/route.js";
22
27
  import { engineNote, isStatusAsk, STATUS_FIRST_NOTE } from "./engine/continuation.js";
23
28
  import { withDelegateDefault } from "./autonomy/delegate.js";
29
+ import { withDelegateGuard } from "./autonomy/delegate-mode.js";
24
30
  import { routeShadowTurn, shadowPrompt } from "./moa/shadow.js"; // MOA phase-0 observability (KODE_MOA_SHADOW)
25
31
  import { AuroraRouter } from "./router/router.js";
26
32
  import { operatorAgentPersona } from "./config/operator-harness.js";
27
33
  import { progressDeadline, summaryCeilingMs, DeadlineError } from "./engine/progress-deadline.js";
28
- import { modelRegistry, findModel, fallbackProfile, selectModel, visibleModels, endpointBase, profileEndpoint, fmtCtx, MIN_CONTEXT_PIN, AGENT_CTX_FLOOR, AGENT_CTX_TARGET, DEFAULT_MODEL_ID, LEAN_HARNESS_CTX } from "./router/models.js";
34
+ import { modelRegistry, findModel, fallbackProfile, selectModel, visibleModels, endpointBase, profileEndpoint, fmtCtx, MIN_CONTEXT_PIN, AGENT_CTX_FLOOR, AGENT_CTX_TARGET, CHAIN_MODEL_ID, LEAN_HARNESS_CTX, resolveModel } from "./router/models.js";
29
35
  import { probeServed, usableCtx } from "./router/discovery.js";
30
36
  import { FAST_START_INSTRUCTION, parseFastStartReply } from "./engine/fast-start.js";
31
37
  import { askFrontDoor, recentTurns } from "./engine/front-door.js";
32
38
  import { getByoToken, hasByoToken } from "./auth/byo.js";
33
39
  import { Executor } from "./tools/executor.js";
40
+ import { autoDeliverReport, autoDeliverFailure, wakeRoot } from "./bus/inbox.js";
34
41
  import { toSchemas, registry, disposeShellSessionKey, requestShellDetach, cloudAgentToolsFor, mdocToolsFor, craftToolsFor, renderActiveTasks, getAgentTasks, taskPlanRevision, openTaskCount } from "./tools/registry.js";
35
42
  import { isFeatureEnabled } from "./config/features.js";
36
43
  import { MemoryStore } from "./memory/index.js";
@@ -94,12 +101,12 @@ export function renderBudgetBlock(b) {
94
101
  /** A brief shorter than this is not a brief (10/31: a sub-agent was spawned with the objective "agent"). 12 refused a
95
102
  * complete 11-word brief in the e2e ("Create the file …/nova.md containing exactly three lines: red, green, blue"). */
96
103
  const MIN_BRIEF_WORDS = 5;
97
- function makeSpawnTool(handler) {
104
+ export function makeSpawnTool(handler, slots) {
98
105
  return {
99
106
  name: "spawn_agent",
100
107
  safe: false,
101
108
  description: "Spawn sub-agents: isolated sessions, each with its own shell, on the sub-agent model (the result says which). " +
102
- "One `tasks` entry = one sub-agent; several run in parallel (2 running + 2 queued by default). Make THIS call in " +
109
+ "One `tasks` entry = one sub-agent; several run in parallel as capacity allows. Make THIS call in " +
103
110
  "the same round you decide to delegate, and in that message tell the owner who you are sending and why (one line " +
104
111
  "per agent). You stay the lead: do what does NOT depend on them; never redo, re-spawn or poll for a step one is " +
105
112
  "working on — each report, and a STUCK notice if one stalls, arrives as a message at the start of a later turn. " +
@@ -112,7 +119,8 @@ function makeSpawnTool(handler) {
112
119
  "RULES: the sub-agent knows NOTHING of this conversation — brief it as a spec: **Objective** · **Context** " +
113
120
  "(every path, id, fact) · **Deliverable** · **Constraints** · **Done**. A file deliverable needs role code-edit or " +
114
121
  "generic. A report is a SELF-REPORT — open what it produced and check it against Done before you tell the owner. " +
115
- "SINGLE WRITER: keep file edits on one agent. Ask for a CONCISE report (~1-2k tokens) listing the files it wrote.",
122
+ "SINGLE WRITER: keep file edits on one agent. Ask for a CONCISE report (~1-2k tokens) listing the files it wrote. " +
123
+ "You wake when every agent not in `optional` has reported. Give each agent its own slice of a large input.",
116
124
  parameters: {
117
125
  type: "object",
118
126
  properties: {
@@ -122,6 +130,8 @@ function makeSpawnTool(handler) {
122
130
  agent: { type: "string", description: "optional repo-local persona from .operator/agents/ (listed under 'Repo-local harness')" },
123
131
  names: { type: "array", items: { type: "string" }, description: "a short first name for each sub-agent, same order as `tasks` (you choose them, e.g. Nova, Atlas) — the owner sees and steers them by name" },
124
132
  name: { type: "string", description: "the name for a single `task`" },
133
+ optional: { type: "array", items: { type: "string" }, description: "names not waited on (reported missing if late)" },
134
+ deadline_minutes: { type: "number", description: "due time, shown on each lane" },
125
135
  },
126
136
  required: ["tasks"],
127
137
  },
@@ -145,11 +155,25 @@ function makeSpawnTool(handler) {
145
155
  const frame = (task) => !agent ? task : persona
146
156
  ? `You are acting as the "${agent}" sub-agent for this repo. Follow this persona:\n\n${persona}\n\n---\nYour task:\n${task}`
147
157
  : `${task}\n\n(note: no .operator/agents/${agent}.md persona found — ran without it)`;
158
+ const optional = new Set(Array.isArray(args.optional) ? args.optional.map((n) => String(n ?? "").trim().toLowerCase()) : []);
159
+ const mins = Number(args.deadline_minutes);
160
+ const opts = (i) => ({
161
+ ...(names[i] && optional.has(names[i].toLowerCase()) ? { optional: true } : {}),
162
+ ...(Number.isFinite(mins) && mins > 0 ? { deadlineMs: Math.round(mins * 60_000) } : {}),
163
+ });
148
164
  if (briefs.length === 1)
149
- return handler(frame(briefs[0]), role, names[0] || undefined);
165
+ return handler(frame(briefs[0]), role, names[0] || undefined, opts(0));
166
+ const free = role === "code-edit" ? undefined : slots?.();
167
+ if (free !== undefined) {
168
+ const { spawn } = planFanOut(briefs.map(() => ({ kind: "read" })), free);
169
+ const go = new Set(spawn);
170
+ return briefs.map((t, i) => `[${i + 1}/${briefs.length}] ${go.has(i)
171
+ ? handler(frame(t), role, names[i] || undefined, opts(i))
172
+ : `not spawned: no free lane on the sub-agent route — do this step yourself (${(names[i] || t).slice(0, 60)})`}`).join("\n");
173
+ }
150
174
  // Fan-out: one spawn per brief, in order; the manager queues past its running cap and refuses past the
151
175
  // in-flight cap — each line reports what happened to that brief, so a partial fan-out is never silent.
152
- return briefs.map((t, i) => `[${i + 1}/${briefs.length}] ${handler(frame(t), role, names[i] || undefined)}`).join("\n");
176
+ return briefs.map((t, i) => `[${i + 1}/${briefs.length}] ${handler(frame(t), role, names[i] || undefined, opts(i))}`).join("\n");
153
177
  },
154
178
  };
155
179
  }
@@ -381,13 +405,13 @@ export class Session {
381
405
  probing; // the latest served-window probe; a turn waits for it before checking the floor
382
406
  contextFloor;
383
407
  moaConfig;
384
- onDemand;
385
408
  frontDoor;
386
409
  frontDoorRoute; // the gateway's call on THIS turn (null = no answer; undefined = not asked), read by sendMoa
387
410
  classifier;
388
411
  fastStartConfig;
389
412
  fastStartEnabled;
390
- modelId = DEFAULT_MODEL_ID; // active /model selection
413
+ modelId = CHAIN_MODEL_ID; // active /model selection
414
+ modelNote; // the startup pick was a retired row: one line for the shell (takeModelNote)
391
415
  turnFellBack = false; // this turn's model fallback took over (turnModel): its rounds run on the default row
392
416
  executor;
393
417
  shellKey; // this session's persistent-shell key (see disposeShell)
@@ -437,6 +461,8 @@ export class Session {
437
461
  owner;
438
462
  temperature;
439
463
  ctrl = null;
464
+ /** The image files this turn's message carries natively (nativeImagesFor); empty when the model cannot see them. */
465
+ turnImages = [];
440
466
  memory;
441
467
  wantRecall;
442
468
  recallBlock = ""; // memory recalled on the first turn, folded into the system prompt thereafter
@@ -496,9 +522,9 @@ export class Session {
496
522
  // here only when the flag resolves on — so both dispatch (executor) and the advertised schemas include them iff enabled.
497
523
  const cloudTools = cloudAgentToolsFor({ features: cfg.features });
498
524
  const mdocTools = mdocToolsFor({ features: cfg.features }); // flag-gated product tools (feature `mdoc`, default OFF)
499
- const craftTools = craftToolsFor({ features: cfg.features }); // flag-gated product tools (feature `craft`, default OFF)
525
+ const craftTools = craftToolsFor({ features: cfg.features }); // artifact library (always) + craft_create (feature `craft`)
500
526
  if (cfg.spawnAgent)
501
- reg.set("spawn_agent", makeSpawnTool(cfg.spawnAgent));
527
+ reg.set("spawn_agent", makeSpawnTool(cfg.spawnAgent, cfg.spawnSlots));
502
528
  if (cfg.messageAgent)
503
529
  reg.set("message_agent", makeMessageTool(cfg.messageAgent));
504
530
  if (cfg.agentStatus)
@@ -534,6 +560,12 @@ export class Session {
534
560
  }
535
561
  for (const name of cfg.toolDeny ?? [])
536
562
  reg.delete(name);
563
+ for (const t of cfg.extraTools ?? [])
564
+ reg.set(t.name, t);
565
+ // The MoA CodeAct lane (moa/codeact.ts): only while it is on does delegate_task offer it, so the schema is unchanged off.
566
+ const dt = reg.get("delegate_task");
567
+ if (dt && cfg.moa && codeActEnabled(cfg.moa.codeact))
568
+ reg.set("delegate_task", withCodeActDelegateSchema(dt));
537
569
  this.executor = new Executor(reg, cfg.cwd, cfg.sessionId);
538
570
  this.shellKey = this.executor.shellKey; // for disposeShell() on teardown
539
571
  this.localSchemas = toSchemas(reg);
@@ -550,7 +582,6 @@ export class Session {
550
582
  this.registry = modelRegistry(cfg.models);
551
583
  this.isOwner = (cfg.eventActor?.tier ?? "admin") === "admin"; // set before the startup setModel so a persisted owner-only activeModel resolves for the owner
552
584
  this.moaConfig = cfg.moa;
553
- this.onDemand = cfg.onDemand;
554
585
  this.frontDoor = cfg.frontDoor;
555
586
  this.classifier = cfg.classifier;
556
587
  this.fastStartConfig = cfg.fastStart;
@@ -558,9 +589,11 @@ export class Session {
558
589
  // Apply the persisted /model choice, unless a router was explicitly injected (tests / bg agents
559
590
  // pinned to a fixed endpoint) — an injected router owns routing, /model doesn't override it. The shell's own
560
591
  // chain is injected too, so it opts in: without that every interactive session started on the default model.
561
- if ((!cfg.router || cfg.applyActiveModel) && cfg.activeModel && cfg.activeModel !== DEFAULT_MODEL_ID) {
562
- if (!this.setModel(cfg.activeModel).ok)
563
- this.modelId = DEFAULT_MODEL_ID; // unavailable at startup → quiet fallback
592
+ if ((!cfg.router || cfg.applyActiveModel) && cfg.activeModel && cfg.activeModel !== CHAIN_MODEL_ID) {
593
+ const r = this.setModel(cfg.activeModel);
594
+ if (!r.ok)
595
+ this.modelId = CHAIN_MODEL_ID; // unavailable at startup → quiet fallback
596
+ this.modelNote = r.note;
564
597
  }
565
598
  this.systemPrompt = cfg.systemPrompt;
566
599
  this.maxTokens = cfg.maxTokens ?? 32768; // == settings DEFAULTS.maxTokens (session-defaults.test.mts locks the pair); ACP/headless callers that omit cfg used to silently get a tight 2048 cap. clampMaxTokens still trims to the live window.
@@ -626,7 +659,7 @@ export class Session {
626
659
  sessionContextBlock() {
627
660
  const cwd = this.cwd ?? process.cwd();
628
661
  return `${SESSION_CONTEXT_OPEN}Working directory: ${cwd}\nScratch dir: ${scratchDirFor(cwd)}\nRelative paths and shell ` +
629
- `commands resolve in the working directory. This is authoritative over any working dir named elsewhere; files a ` +
662
+ `commands resolve in the working directory. This is authoritative over any working dir named elsewhere (except a turn the harness itself roots in a brief's worktree); files a ` +
630
663
  `task creates go there unless the owner names another path.${homeDirNote(cwd)}${SESSION_CONTEXT_REQUEST_LINE}${SESSION_CONTEXT_CLOSE}`;
631
664
  }
632
665
  /** The effective system prompt: the base persona plus any memory recalled this session. Injected as ONE system
@@ -686,7 +719,14 @@ export class Session {
686
719
  : this.policy;
687
720
  const approve = this.planMode ? undefined : this.approve; // no approver in plan mode = hard read-only
688
721
  const base = withPermissions(withMcp(this.executor, this.hub), policy, { approve, sink: this.eventSink, actor: this.eventActor, session: this.sessionId });
689
- const hooked = withHooks(base, this.hooks, { cwd: this.cwd ?? process.cwd(), session: this.sessionId ?? "" });
722
+ // Delegate mode's fence sits above the gate: a call it refuses never asks the owner to approve it. Off = pass-through.
723
+ const guarded = withDelegateGuard(base, { cwd: this.cwd ?? process.cwd(), exists: existsSync, realpath: (p) => { try {
724
+ return realpathSync(p);
725
+ }
726
+ catch {
727
+ return p;
728
+ } } });
729
+ const hooked = withHooks(guarded, this.hooks, { cwd: this.cwd ?? process.cwd(), session: this.sessionId ?? "" });
690
730
  if (this.nativeDeferred)
691
731
  return withNativeDeferred(hooked, this.nativeDeferred);
692
732
  return this.deferred ? withDeferred(hooked, this.deferred) : hooked;
@@ -796,7 +836,13 @@ export class Session {
796
836
  * selected endpoint's. */
797
837
  healthTarget() {
798
838
  const planner = findModel(this.liveRegistry(), this.modelId)?.kind === "orchestrated" ? moaTeam(this.moaConfig)?.planner : undefined;
799
- return planner ? endpointBase(planner.endpoint) : this.inner.base;
839
+ if (!planner)
840
+ return this.inner.base;
841
+ if (planner.endpoint)
842
+ return endpointBase(planner.endpoint);
843
+ const row = resolveModel(this.liveRegistry(), planner.id);
844
+ const ep = row ? profileEndpoint(row) : undefined;
845
+ return ep ? endpointBase(ep) : this.inner.base;
800
846
  }
801
847
  /** Is the endpoint the current model talks to reachable? Lets the shell fail clearly before a turn. Probes the
802
848
  * way reachable() does, because a non-default model's endpoint is often the portal router, which has /healthz
@@ -845,7 +891,7 @@ export class Session {
845
891
  if (p?.kind !== "single")
846
892
  return undefined;
847
893
  let base, model;
848
- if (p.id === DEFAULT_MODEL_ID) {
894
+ if (p.id === CHAIN_MODEL_ID) {
849
895
  const r = this.chain ?? this.inner;
850
896
  base = r.base;
851
897
  model = r.model;
@@ -1152,18 +1198,47 @@ export class Session {
1152
1198
  * to. "moa" has no endpoint of its own; send() special-cases it (sendMoa) instead. Returns an
1153
1199
  * error instead of throwing, so the shell can show it inline: an unknown id, or "moa" selected
1154
1200
  * with no settings.moa configured. */
1201
+ /** `/delegate planner`: a /model id plans MoA turns (moa.plannerModel), with `specialist` as the executor when given.
1202
+ * "" clears it back to moa.planner. Applies from the next MoA turn (sendMoa reads the team per turn). Refused when
1203
+ * the id cannot run: unknown, no endpoint of its own, or a provider row whose key is not stored. */
1204
+ setMoaPlanner(plannerModel, specialist) {
1205
+ for (const id of [plannerModel, specialist]) {
1206
+ if (!id)
1207
+ continue;
1208
+ const p = selectModel(this.liveRegistry(), id, hasByoToken, this.isOwner);
1209
+ if (p.error || p.profile?.kind !== "single")
1210
+ return { ok: false, error: p.error ?? `"${id}" has no endpoint of its own` };
1211
+ }
1212
+ this.moaConfig = { ...this.moaConfig, plannerModel, ...(specialist ? { specialist: { id: specialist } } : {}) };
1213
+ return { ok: true };
1214
+ }
1215
+ moaTeam() {
1216
+ return moaTeam(this.moaConfig);
1217
+ }
1218
+ /** The line a retired startup pick earned (a persisted activeModel of a retired row), once. */
1219
+ takeModelNote() {
1220
+ const n = this.modelNote;
1221
+ this.modelNote = undefined;
1222
+ return n;
1223
+ }
1155
1224
  setModel(id) {
1156
- const { profile, error } = selectModel(this.liveRegistry(), id, hasByoToken, this.isOwner);
1225
+ const { profile, error, retired } = selectModel(this.liveRegistry(), id, hasByoToken, this.isOwner);
1157
1226
  if (error || !profile)
1158
1227
  return { ok: false, error };
1159
1228
  this.decodeSamples = []; // another model's rate says nothing about this one
1160
- if (profile.kind === "orchestrated" && !moaTeam(this.moaConfig)) {
1161
- return { ok: false, error: `MOA needs a "moa" block (planner + specialist) in settings.json` };
1229
+ if (profile.kind === "orchestrated") {
1230
+ const team = moaTeam(this.moaConfig);
1231
+ if (!team)
1232
+ return { ok: false, error: `MOA needs a "moa" block (planner + specialist) in settings.json` };
1233
+ if (!team.planner.endpoint) { // a /model id as the planner: it must resolve, and a provider row needs its key stored
1234
+ const p = selectModel(this.liveRegistry(), team.planner.id, hasByoToken, this.isOwner);
1235
+ if (p.error || p.profile?.kind !== "single")
1236
+ return { ok: false, error: `MoA planner: ${p.error ?? `"${team.planner.id}" has no endpoint of its own`}` };
1237
+ }
1162
1238
  }
1163
- if (profile.kind === "single" && profile.id === DEFAULT_MODEL_ID && this.chain) {
1164
- // The default local model IS the shell's endpoint chain (the gateway's published port + its failover
1165
- // legs). Restore it rather than rebuilding from the profile's static :8097 endpoint, which no longer
1166
- // answers on a gateway box — otherwise /model away-and-back lands on a dead port.
1239
+ if (profile.kind === "single" && profile.id === CHAIN_MODEL_ID && this.chain) {
1240
+ // The chain row IS the shell's endpoint chain (the router's `main`, then the fleet and cloud legs). Restore it
1241
+ // rather than rebuilding from the row's own two legs, so /model away-and-back keeps every failover leg.
1167
1242
  this.inner = this.chain;
1168
1243
  this.router = this.wrap(this.inner);
1169
1244
  }
@@ -1176,15 +1251,15 @@ export class Session {
1176
1251
  // before the first turn on it, so compaction sizes to it and the floor can be checked.
1177
1252
  if (profile.kind === "single" && !profile.byo)
1178
1253
  void this.probeServedContext().catch(() => undefined);
1179
- return { ok: true };
1254
+ return { ok: true, ...(retired ? { note: `${retired.label} (${retired.id}) is retired — ${profile.label} answers instead; /model picks another` } : {}) };
1180
1255
  }
1181
1256
  /** Re-point this session at a freshly built endpoint chain. The interactive shell constructs the Session at
1182
1257
  * first render, BEFORE the boot lever has resolved the gateway's dynamic port (server.json) — the chain must
1183
1258
  * follow that resolution or health() and every turn probe "" (unset — auto-discover). Same swap setModel does. A
1184
- * non-default /model pick keeps owning routing; the chain then waits for `/model operator-1m`. */
1259
+ * non-default /model pick keeps owning routing; the chain then waits for `/model main`. */
1185
1260
  useRouter(router) {
1186
1261
  this.chain = router;
1187
- if (this.modelId !== DEFAULT_MODEL_ID)
1262
+ if (this.modelId !== CHAIN_MODEL_ID)
1188
1263
  return;
1189
1264
  this.inner = router;
1190
1265
  this.router = this.wrap(this.inner);
@@ -1235,13 +1310,13 @@ export class Session {
1235
1310
  // A small-context active model (e.g. a self-hosted 8K Venice) can't summarize its OWN overflow — the
1236
1311
  // [system + tools + span] summarize request itself exceeds the window, so compaction frees nothing and
1237
1312
  // the session walls ("compaction can't free enough space"). Route the summarizer to the large-context
1238
- // DEFAULT (Aurora/operator-1m, 300K) instead: it loses the live-turn's prefix-cache reuse (Aurora's
1313
+ // chain row (the router's `main`, 262K) instead: it loses the live-turn's prefix-cache reuse (its
1239
1314
  // prefix differs from the small model's), but that trade is what lets a small model compact continuously
1240
1315
  // and run autonomously for hours. A large active model keeps the cache-safe same-endpoint path.
1241
1316
  let sumBase = this.lastBase ?? this.inner.base;
1242
1317
  let sumModel = this.lastModel ?? this.inner.model;
1243
1318
  if (this.inner.ctxLimit() < LEAN_HARNESS_CTX) {
1244
- const big = findModel(this.registry, DEFAULT_MODEL_ID);
1319
+ const big = findModel(this.registry, CHAIN_MODEL_ID);
1245
1320
  if (big?.endpoint) {
1246
1321
  sumBase = endpointBase(big.endpoint);
1247
1322
  sumModel = big.model ?? big.id;
@@ -1497,16 +1572,10 @@ export class Session {
1497
1572
  // would otherwise no-op — this.ctrl was null until execute(). execute() reuses this same controller.
1498
1573
  this.ctrl = new AbortController();
1499
1574
  try {
1500
- const front = await this.viaFrontDoor(text, h); // before onDemand: a message the fast model answers never loads Aurora
1575
+ this.turnImages = await this.nativeImagesFor(text);
1576
+ const front = await this.viaFrontDoor(text, h);
1501
1577
  if (front)
1502
1578
  return front;
1503
- if (this.onDemand && this.modelId === DEFAULT_MODEL_ID) {
1504
- const fresh = await this.onDemand(this.ctrl.signal);
1505
- if (fresh)
1506
- this.useRouter(fresh);
1507
- if (this.ctrl.signal.aborted)
1508
- return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1509
- }
1510
1579
  await this.maybeRecall(text); // fold past-session memory into the system prompt on the first turn
1511
1580
  if (this.ctrl.signal.aborted)
1512
1581
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
@@ -1526,10 +1595,40 @@ export class Session {
1526
1595
  }
1527
1596
  finally {
1528
1597
  this.ctrl = null; // execute() nulls on its own path too; this also covers the maybeRecall-abort early return
1598
+ this.turnImages = [];
1529
1599
  this.wakeTurn = false;
1530
1600
  this.turnThinkOff = false;
1531
1601
  }
1532
1602
  }
1603
+ /** The image files in the owner's message that go to the model as pictures, not through image_analyze: only when the
1604
+ * model answering can see (the profile says so, else its server does; an unknown is tried, and a server that turns
1605
+ * the image down puts it back on the tool). Never for a sub-agent, a wake turn or a remote url. */
1606
+ async nativeImagesFor(text) {
1607
+ if (this.background || this.wakeTurn)
1608
+ return [];
1609
+ const paths = extractImagePaths(text);
1610
+ if (!paths.length)
1611
+ return [];
1612
+ const p = findModel(this.liveRegistry(), this.modelId);
1613
+ if (p?.kind !== "single" || p.transport === "anthropic" || p.vision === false)
1614
+ return [];
1615
+ if (p.vision === true || p.byo)
1616
+ return paths;
1617
+ let base, model;
1618
+ if (p.id === CHAIN_MODEL_ID) {
1619
+ const r = this.chain ?? this.inner;
1620
+ base = r.base;
1621
+ model = r.model;
1622
+ }
1623
+ else {
1624
+ const ep = p.endpoints?.[0] ?? p.endpoint;
1625
+ if (!ep)
1626
+ return [];
1627
+ base = endpointBase(ep);
1628
+ model = p.endpointModels?.[0] ?? p.model ?? p.id;
1629
+ }
1630
+ return (await detectVision(base, model)) === "no" ? [] : paths;
1631
+ }
1533
1632
  /** Speed-aware compaction: the last measured turns decoded under compaction.minDecodeTps at a request big enough
1534
1633
  * for compaction to help, so compact now, before this turn's first request. The samples are cleared either way, so
1535
1634
  * the next trigger needs two fresh slow turns. A failed summarizer leaves the conversation as it was. */
@@ -1564,13 +1663,13 @@ export class Session {
1564
1663
  this.frontDoorRoute = undefined;
1565
1664
  const fd = this.frontDoor;
1566
1665
  const active = findModel(this.liveRegistry(), this.modelId);
1567
- if (!fd || (this.modelId !== DEFAULT_MODEL_ID && active?.kind !== "orchestrated"))
1568
- return null;
1666
+ if (!fd || (this.modelId !== CHAIN_MODEL_ID && active?.kind !== "orchestrated") || this.turnImages.length)
1667
+ return null; // the fast model sees no pictures
1569
1668
  const t0 = Date.now();
1570
1669
  // The gateway's front door is configured on the default model's route; `name` is the model as the owner knows it
1571
1670
  // (activeModelBlock), so a MOA session is MOA to the fast model too.
1572
1671
  const name = active ? `${active.label}${active.params ? ` ${active.params}` : ""}` : this.modelId;
1573
- const d = await askFrontDoor(fd, { model: DEFAULT_MODEL_ID, name, messages: [...recentTurns(this.convo.all), { role: "user", content: text }] }, this.ctrl?.signal);
1672
+ const d = await askFrontDoor(fd, { model: CHAIN_MODEL_ID, name, messages: [...recentTurns(this.convo.all), { role: "user", content: text }] }, this.ctrl?.signal);
1574
1673
  if (this.ctrl?.signal.aborted)
1575
1674
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1576
1675
  this.frontDoorRoute = d?.route ?? null;
@@ -1596,12 +1695,16 @@ export class Session {
1596
1695
  // specialist with the full prompt.
1597
1696
  const fd = this.frontDoorRoute;
1598
1697
  const route = fd === undefined && this.classifier && this.classifier.mode !== "off" ? await routeTurn(text, this.classifier.endpoint) : null;
1599
- const specialist = route?.route === "direct" ? this.liveRegistry().find((m) => m.id === team.specialist && m.kind === "single") : undefined;
1698
+ const specialistRow = route?.route === "direct" ? resolveModel(this.liveRegistry(), team.specialist) : undefined;
1699
+ const specialist = specialistRow?.kind === "single" ? specialistRow : undefined;
1600
1700
  this.telemetry.record({ type: "moa", planner: team.planner.id, specialist: team.specialist, route: specialist ? "direct" : route || fd === "work" ? "planned" : "unrouted", pDirect: route?.pDirect });
1601
1701
  if (specialist)
1602
1702
  return this.execute(text, h, this.wrap(this.routerForProfile(specialist)), this.sysWithThink(), specialist.id);
1603
- const plannerRouter = this.wrap(new AuroraRouter([
1604
- { name: team.planner.id, base: endpointBase(team.planner.endpoint), model: team.planner.model, ctxLimit: this.inner.ctxLimit() },
1703
+ const plannerRow = team.planner.endpoint ? undefined : resolveModel(this.liveRegistry(), team.planner.id);
1704
+ if (!team.planner.endpoint && plannerRow?.kind !== "single")
1705
+ throw new Error(`MoA planner "${team.planner.id}" is not a /model id with an endpoint`);
1706
+ const plannerRouter = this.wrap(plannerRow?.kind === "single" ? this.routerForProfile(plannerRow) : new AuroraRouter([
1707
+ { name: team.planner.id, base: endpointBase(team.planner.endpoint), model: team.planner.model ?? team.planner.id, ctxLimit: this.inner.ctxLimit() },
1605
1708
  ]));
1606
1709
  const sys = `${this.sysWithThink() ?? ""}\n\n## MOA: planner\n${plannerBrief(team)}`;
1607
1710
  return withDelegateDefault(team.specialist, () => this.execute(text, h, plannerRouter, sys, team.planner.id));
@@ -1676,6 +1779,8 @@ export class Session {
1676
1779
  * and system prompt they pass in. */
1677
1780
  async execute(text, h, router, sys, routeLabel) {
1678
1781
  this.executor.resetTurn(); // clear the host executor's per-turn loop guard before this turn
1782
+ // A wake turn whose brief named a contained worktree runs there for this turn only (Codex --cd / Claude Code worktree isolation).
1783
+ this.executor.setTurnRoot(wakeRoot(text) ?? undefined);
1679
1784
  this.lastSys = sys; // remember the EXACT system prompt this turn sends, so cache-safe compaction reuses it verbatim
1680
1785
  // Reuse the controller send() already armed (so esc during maybeRecall / MOA fan-out is live); create one
1681
1786
  // only if execute() is somehow entered without send() arming it (defensive — every caller goes via send).
@@ -1683,6 +1788,7 @@ export class Session {
1683
1788
  this.ctrl = controller;
1684
1789
  this.turnHandlers = h; // a mid-turn compaction's summarizer reports its read through this turn's handlers
1685
1790
  const _t0 = performance.now();
1791
+ const wallT0 = Date.now(); // wall clock, for the bus: did this turn reply to its sender (autoDeliverReport)
1686
1792
  // Snapshot the conversation length so we can slice out THIS turn's steps (user + assistant/tool messages)
1687
1793
  // for the flywheel row — the per-step structure SRFT credit assignment needs. runTurn pushes the user
1688
1794
  // message itself, so everything from here on is this turn's.
@@ -1702,6 +1808,8 @@ export class Session {
1702
1808
  try {
1703
1809
  const res = await runTurn(text, this.convo, {
1704
1810
  ownerText,
1811
+ images: this.turnImages,
1812
+ onImagesRejected: (ep) => markVisionRejected(ep.base, ep.model),
1705
1813
  router,
1706
1814
  tools: this.liveTools, // read through at each call: a mid-turn /mode or Shift+Tab applies from the next tool call
1707
1815
  toolSchemas: this.allSchemas(),
@@ -1855,12 +1963,22 @@ export class Session {
1855
1963
  turn.recorded = true;
1856
1964
  const record = {
1857
1965
  input: text, content: res.content, rounds: res.rounds, toolCalls: res.toolCalls,
1858
- tokens: res.tokens, stopReason: res.stopReason, model: this.currentModel(),
1966
+ tokens: res.tokens, stopReason: res.stopReason, stopKind: res.stopKind, model: this.currentModel(),
1859
1967
  cwd: process.cwd(), durationMs: Math.round(performance.now() - _t0), unverified: res.unverified,
1860
1968
  steps: this.turnSteps(convoStart, text), task, loop: res.loop, lessonTs: turn.lessonTs,
1861
1969
  };
1862
1970
  const cfg = this.selfImproveCfg();
1863
1971
  this.learn(() => runSelfImprove(cfg, record)); // after any lesson a loop recovery is still writing
1972
+ // A woken turn owes its sender a report; when it ended without one, the harness delivers the final answer
1973
+ // (Claude Code returns a sub-agent's final message to its parent; `codex exec -o` writes it for the caller).
1974
+ try {
1975
+ const to = autoDeliverReport(ownerText, res.content ?? "", wallT0);
1976
+ if (to.length) {
1977
+ this.telemetry.record({ type: "auto_report", recipients: to.length });
1978
+ h.onAutoReport?.(to);
1979
+ }
1980
+ }
1981
+ catch { /* best-effort: a bus write failure never fails the turn */ }
1864
1982
  return { ...res, interrupted: false, durationMs: Math.round(performance.now() - _t0) };
1865
1983
  }
1866
1984
  catch (e) {
@@ -1870,8 +1988,16 @@ export class Session {
1870
1988
  const cfg = this.selfImproveCfg();
1871
1989
  if (r)
1872
1990
  this.learn(() => runSelfImprove(cfg, r));
1991
+ try {
1992
+ autoDeliverFailure(ownerText, "interrupted");
1993
+ }
1994
+ catch { /* best-effort */ }
1873
1995
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1874
1996
  }
1997
+ try {
1998
+ autoDeliverFailure(ownerText, "failed");
1999
+ }
2000
+ catch { /* best-effort */ }
1875
2001
  this.telemetry.record({ type: "error", where: "send", errorClass: Telemetry.errorClass(e) });
1876
2002
  throw e;
1877
2003
  }
@@ -1880,6 +2006,7 @@ export class Session {
1880
2006
  if (this.inflight === turn)
1881
2007
  this.inflight = undefined;
1882
2008
  this.turnHandlers = undefined;
2009
+ this.executor.setTurnRoot(undefined);
1883
2010
  }
1884
2011
  }
1885
2012
  /** The self-improvement sinks: the flywheel (settings.selfImprove → KODE_SELFIMPROVE) and the memory sink
@@ -0,0 +1,68 @@
1
+ // The guarded way a skill, plugin or connector from the AXE skills hub (Barracks) reaches a user's own Operator home.
2
+ // Fetch -> quarantine -> scan -> policy -> install or block, with an audit line either way. Provider- and model-agnostic:
3
+ // a skill is plain instructions, so nothing here knows or cares which model will read it. Pure decisions live here;
4
+ // the fetch and the CLI/TUI wiring are elsewhere. There is deliberately NO setting that turns the scanner off or lets a
5
+ // "dangerous" verdict through: the Hermes scanner can be disabled by a config switch (user reports), ours cannot.
6
+ import { createHash } from "node:crypto";
7
+ const RULES = [
8
+ { id: "pipe-to-shell", severity: "dangerous", re: /\b(?:curl|wget|fetch)\b[^\n|]*\|\s*(?:sudo\s+)?(?:ba|z|da)?sh\b/i },
9
+ { id: "decode-and-run", severity: "dangerous", re: /\bbase64\s+(?:-d|--decode)\b[^\n]*\|\s*(?:ba|z)?sh\b|\beval\s*\(\s*(?:atob|base64|Buffer\.from)/i },
10
+ { id: "credential-store-read", severity: "dangerous", re: /(?:~|\$HOME|\/Users\/[^/\s]+)?\/?\.(?:ssh|aws|gnupg|docker\/config\.json|kube\/config)\b|\bsecurity\s+find-(?:generic|internet)-password\b|\b(?:Login Data|Cookies\.sqlite|Local State)\b|\bid_(?:rsa|ed25519)\b/i },
11
+ { id: "exfiltration", severity: "dangerous", re: /\b(?:webhook\.site|requestbin|pipedream\.net|ngrok\.(?:io|app)|pastebin\.com|transfer\.sh|discord(?:app)?\.com\/api\/webhooks)\b/i },
12
+ { id: "destructive", severity: "dangerous", re: /\brm\s+-[a-z]*r[a-z]*\s+(?:\/|~\/?|\$HOME\/?)(?:\s|$|\*)|\bmkfs\b|\bdd\s+if=[^\n]*\bof=\/dev\/|:\(\)\s*\{\s*:\|:&\s*\};:/i },
13
+ { id: "persistence", severity: "dangerous", re: /\bcrontab\s+-|\/Library\/Launch(?:Agents|Daemons)\/|\bsystemctl\s+(?:--user\s+)?enable\b|\.(?:bashrc|zshrc|profile)\b[^\n]*(?:>>|tee\s+-a)/i },
14
+ { id: "prompt-override", severity: "dangerous", re: /\b(?:ignore|disregard|forget)\s+(?:all\s+|any\s+|your\s+|the\s+)?(?:previous|prior|above|system)\s+(?:instructions|prompt|rules)\b|\bdo\s+not\s+(?:tell|inform|mention\s+to)\s+the\s+user\b|\bwithout\s+(?:telling|informing)\s+the\s+user\b/i },
15
+ { id: "wallet-signing", severity: "dangerous", re: /\b(?:seed\s+phrase|mnemonic|private\s+key)\b[^\n]*\b(?:send|post|upload|sign|paste)\b|\b(?:send|post|upload|sign)\b[^\n]*\b(?:seed\s+phrase|mnemonic|private\s+key)\b/i },
16
+ { id: "hijack-any-request", severity: "caution", re: /\b(?:use|apply|invoke)\s+this\s+(?:skill\s+)?(?:for|on)\s+(?:any|every|all)\s+(?:request|task|query|prompt)s?\b|\balways\s+use\s+this\s+skill\b/i },
17
+ { id: "needs-credentials", severity: "caution", re: /\b(?:API_KEY|SECRET_KEY|ACCESS_TOKEN|PASSWORD|BEARER)\b|\bapi[-_ ]?key\b[^\n]*\b(?:paste|provide|enter|set)\b/i },
18
+ { id: "installs-software", severity: "caution", re: /\b(?:pip3?\s+install|npm\s+(?:i|install)\s+-g|brew\s+install|apt(?:-get)?\s+install|curl\s+[^\n|]*-o\b|wget\s+[^\n|]*-O\b)/i },
19
+ { id: "writes-outside-workspace", severity: "caution", re: /(?:>|tee)\s*(?:\/etc\/|\/usr\/|~\/\.|\$HOME\/\.)/i },
20
+ { id: "evades-bot-detection", severity: "caution", re: /\b(?:bypass|evade|defeat|solve)\b[^\n]*\b(?:captcha|bot[- ]detection|cloudflare|anti-?bot)\b|\bstealth\s+(?:mode|plugin)\b/i },
21
+ { id: "moves-money", severity: "caution", re: /\b(?:place|execute|submit)\s+(?:a\s+)?(?:trade|order)s?\b|\b(?:transfer|send|withdraw)\s+(?:funds|crypto|usdc|eth|btc)\b|\bcard\s+number\b/i },
22
+ { id: "obfuscation", severity: "caution", re: /[A-Za-z0-9+/]{200,}={0,2}|(?:\\x[0-9a-f]{2}){12,}/i },
23
+ ];
24
+ const excerpt = (s) => s.trim().replace(/\s+/g, " ").slice(0, 120);
25
+ /** Static analysis of a skill's text. Regex only: it finds the patterns that matter, it does not prove safety. */
26
+ export function scanContent(text) {
27
+ const findings = [];
28
+ const lines = text.split("\n");
29
+ for (let i = 0; i < lines.length && findings.length < 50; i++) {
30
+ for (const r of RULES)
31
+ if (r.re.test(lines[i]))
32
+ findings.push({ rule: r.id, severity: r.severity, line: i + 1, excerpt: excerpt(lines[i]) });
33
+ }
34
+ const verdict = findings.some((f) => f.severity === "dangerous") ? "dangerous" : findings.length ? "caution" : "safe";
35
+ return { verdict, findings };
36
+ }
37
+ export const sha256Hex = (text) => createHash("sha256").update(text, "utf8").digest("hex");
38
+ /** The pinned reference a client records and re-checks: name@version#sha256:<12 hex>. */
39
+ export const pinnedRef = (r, computed) => `${r.name}@${r.version ?? "0"}#sha256:${(r.checksum ?? computed).slice(0, 12)}`;
40
+ /** first-party and verified come from the hub's own record; anything else is community, quarantined until reviewed. */
41
+ export function trustOf(r) {
42
+ if (r.card?.verified === true && /^axe[:/]|first-party/i.test(r.card.source ?? ""))
43
+ return "first-party";
44
+ if (r.card?.verified === true && r.tenant_id !== "community-quarantine")
45
+ return "verified";
46
+ return "community";
47
+ }
48
+ /** The install policy. Order matters: the refusals that nothing can override come first. */
49
+ export function decideInstall(p) {
50
+ if (p.yanked)
51
+ return { action: "block", reasons: ["withdrawn upstream"] };
52
+ if (!p.checksumOk)
53
+ return { action: "block", reasons: ["content does not match the hub's checksum"] };
54
+ if (p.verdict === "dangerous")
55
+ return { action: "block", reasons: ["the scan found dangerous patterns"] };
56
+ if (p.trust === "community" && p.managed)
57
+ return { action: "block", reasons: ["your organisation's policy allows only reviewed items"] };
58
+ const reasons = [];
59
+ if (p.trust === "community")
60
+ reasons.push("not reviewed: it comes from a community source");
61
+ if (p.verdict === "caution")
62
+ reasons.push("the scan raised cautions");
63
+ if (p.unpinned)
64
+ reasons.push("the hub gave no checksum to verify against");
65
+ if (p.kind !== "skill")
66
+ reasons.push(`a ${p.kind} is installed switched off and needs your approval to turn on`);
67
+ return reasons.length ? { action: "confirm", reasons } : { action: "allow", reasons: ["reviewed, scanned clean and checksum verified"] };
68
+ }
@@ -0,0 +1,67 @@
1
+ // Install one hub record into the user's own Operator home, guarded and audited (policy in install-guard.ts).
2
+ // skills -> <home>/skills/<name>/SKILL.md
3
+ // plugins -> <home>/plugins/<name>/manifest.json (installed OFF)
4
+ // connectors -> <home>/connectors/<name>/manifest.json (installed OFF; turning one on is a separate, explicit step)
5
+ // Every attempt, allowed or blocked, appends one line to <home>/skills/.audit.jsonl (no content, no secrets).
6
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { decideInstall, pinnedRef, scanContent, sha256Hex, trustOf } from "./install-guard.js";
9
+ const SAFE_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
10
+ const dirFor = { skill: "skills", plugin: "plugins", connector: "connectors" };
11
+ export async function installFromHub(rec, o) {
12
+ const kind = o.kind ?? (rec.card?.kind === "plugin" || rec.card?.kind === "connector" ? rec.card.kind : "skill");
13
+ const now = (o.now?.() ?? new Date()).toISOString();
14
+ const computed = sha256Hex(rec.content ?? "");
15
+ const ref = pinnedRef(rec, computed);
16
+ const trust = trustOf(rec);
17
+ const { verdict, findings } = scanContent(rec.content ?? "");
18
+ const audit = (decision, reasons, confirmed) => {
19
+ try {
20
+ const dir = join(o.home, "skills");
21
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
22
+ appendFileSync(join(dir, ".audit.jsonl"), `${JSON.stringify({ ts: now, name: rec.name, kind, ref, sha256: computed, trust, verdict, rules: [...new Set(findings.map((f) => f.rule))], decision, reasons, ...(confirmed !== undefined ? { confirmed } : {}), userType: o.userType ?? "external", ...(o.source ? { source: o.source } : {}) })}\n`, { mode: 0o600 });
23
+ }
24
+ catch { /* an audit that cannot be written must not hide the install decision */ }
25
+ };
26
+ const refuse = (status, reasons) => { audit(status, reasons); return { status, ref, reasons, trust, verdict, findings }; };
27
+ if (!SAFE_NAME.test(rec.name) || rec.name.includes(".."))
28
+ return refuse("blocked", ["the name is not a plain identifier"]);
29
+ const decision = decideInstall({
30
+ verdict, trust, kind,
31
+ checksumOk: !rec.checksum || rec.checksum.toLowerCase() === computed,
32
+ unpinned: !rec.checksum,
33
+ yanked: !!rec.yanked_at,
34
+ managed: !!o.managed,
35
+ });
36
+ if (decision.action === "block")
37
+ return refuse("blocked", decision.reasons);
38
+ let confirmed;
39
+ if (decision.action === "confirm") {
40
+ confirmed = o.confirm ? await o.confirm({ name: rec.name, ref, trust, verdict, findings, reasons: decision.reasons }).catch(() => false) : false;
41
+ if (!confirmed)
42
+ return refuse("declined", decision.reasons);
43
+ }
44
+ // Stage in quarantine, then move into place: a half-written install never shows up as a usable skill.
45
+ const base = join(o.home, dirFor[kind]);
46
+ const stage = join(o.home, "skills", ".quarantine", `${rec.name}@${computed.slice(0, 12)}`);
47
+ const dest = join(base, rec.name);
48
+ rmSync(stage, { recursive: true, force: true });
49
+ mkdirSync(stage, { recursive: true, mode: 0o700 });
50
+ const enabled = kind === "skill";
51
+ if (kind === "skill")
52
+ writeFileSync(join(stage, "SKILL.md"), rec.content, { mode: 0o600 });
53
+ else
54
+ writeFileSync(join(stage, "manifest.json"), `${JSON.stringify({ name: rec.name, kind, version: rec.version ?? null, ref, sha256: computed, trust, enabled: false, installedAt: now, content: rec.content }, null, 2)}\n`, { mode: 0o600 });
55
+ writeFileSync(join(stage, ".install.json"), `${JSON.stringify({ ref, sha256: computed, trust, verdict, installedAt: now, source: o.source ?? null })}\n`, { mode: 0o600 });
56
+ mkdirSync(base, { recursive: true, mode: 0o700 });
57
+ rmSync(dest, { recursive: true, force: true });
58
+ renameSync(stage, dest);
59
+ if (existsSync(dest)) {
60
+ try {
61
+ chmodSync(dest, 0o700);
62
+ }
63
+ catch { /* best effort */ }
64
+ }
65
+ audit("installed", decision.reasons, confirmed);
66
+ return { status: "installed", path: dest, ref, trust, verdict, enabled };
67
+ }