@staix/agent-hub 0.36.0 → 0.37.0

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 (102) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +6 -2
  3. package/THIRD_PARTY_NOTICES.md +0 -18
  4. package/docs/agent-notes/README.md +13 -3
  5. package/docs/agent-notes/daemon.md +4 -4
  6. package/docs/agent-notes/local-worker.md +1 -0
  7. package/docs/agent-notes/models.md +2 -1
  8. package/docs/agent-notes/tasks.md +1 -1
  9. package/docs/agent-notes/tests.md +1 -2
  10. package/docs/contracts/companion-cli-v1.json +70 -0
  11. package/docs/design/adapters.md +43 -2
  12. package/docs/design/agent-hub-architecture.md +9 -1
  13. package/docs/design/guidance-probes.md +802 -0
  14. package/docs/design/model-routes.md +437 -12
  15. package/docs/dogfood.md +11 -13
  16. package/docs/events.md +20 -1
  17. package/docs/memory.md +3 -3
  18. package/docs/operations.md +112 -148
  19. package/docs/quickstart.md +9 -3
  20. package/docs/research.md +1 -1
  21. package/docs/sdlc.md +5 -3
  22. package/docs/security.md +21 -1
  23. package/docs/specs/2026-09-19-agent-hub-design.md +9 -7
  24. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  25. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  26. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +21 -6
  27. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  28. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  29. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  30. package/docs/verified.json +24 -24
  31. package/package.json +3 -4
  32. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  33. package/plugins/agent-hub/kimi-hook.js +2373 -1436
  34. package/plugins/agent-hub/server.js +2445 -1497
  35. package/src/adapters/channel-peer.ts +7 -1
  36. package/src/adapters/compat.ts +1 -1
  37. package/src/adapters/local-probe.ts +174 -0
  38. package/src/adapters/local-worker.ts +232 -21
  39. package/src/cli/console-state.ts +25 -6
  40. package/src/cli/console-versions.ts +99 -0
  41. package/src/cli/console.ts +13 -1
  42. package/src/cli/help.ts +2 -1
  43. package/src/cli/install-paths.ts +7 -2
  44. package/src/cli/main.ts +60 -4
  45. package/src/cli/runtime-version-warning.ts +2 -2
  46. package/src/cli/sdlc-output.ts +9 -5
  47. package/src/hub/config-apply.ts +4 -2
  48. package/src/hub/config-trust.ts +6 -1
  49. package/src/hub/control-client.ts +5 -2
  50. package/src/hub/daemon.ts +169 -9
  51. package/src/hub/events.ts +3 -2
  52. package/src/hub/guidance-probe-store.ts +713 -0
  53. package/src/hub/guidance-probes.ts +358 -0
  54. package/src/hub/inference.ts +18 -5
  55. package/src/hub/operational-authority.ts +13 -1
  56. package/src/hub/peers.ts +5 -0
  57. package/src/hub/ports.ts +1 -1
  58. package/src/hub/progress.ts +23 -16
  59. package/src/hub/report.ts +2 -0
  60. package/src/hub/research.ts +1 -0
  61. package/src/hub/restart.ts +7 -0
  62. package/src/hub/sdlc-release-authorization.ts +139 -17
  63. package/src/hub/sdlc-release-policy.ts +100 -0
  64. package/src/hub/sdlc-release.ts +59 -7
  65. package/src/hub/tasks.ts +317 -6
  66. package/src/local/probe-errors.ts +28 -0
  67. package/src/local/probe-sandbox.ts +224 -0
  68. package/src/local/probe-types.ts +108 -0
  69. package/src/local/probe-workspace.ts +237 -0
  70. package/src/local/sandbox.ts +71 -2
  71. package/src/local/tools.ts +135 -9
  72. package/src/models/route/advisor-trigger.ts +88 -0
  73. package/src/models/route/config.ts +21 -17
  74. package/src/models/route/conversation-view.ts +179 -0
  75. package/src/models/route/decision-evidence.ts +1 -1
  76. package/src/models/route/decision.ts +114 -19
  77. package/src/models/route/escalation-control.ts +30 -0
  78. package/src/models/route/hub-prompts.ts +97 -0
  79. package/src/models/route/judge-choice.ts +155 -0
  80. package/src/models/route/judge-replies.ts +102 -0
  81. package/src/models/route/labels.ts +14 -70
  82. package/src/models/route/observation-signals.ts +250 -0
  83. package/src/models/route/plan-execute-choice.ts +27 -0
  84. package/src/models/route/relay-selector.ts +2 -2
  85. package/src/models/route/runtime.ts +115 -52
  86. package/src/models/route/turn-state.ts +77 -0
  87. package/src/omniroute/client.ts +3 -0
  88. package/src/ui/plugin.ts +70 -20
  89. package/src/version.ts +4 -0
  90. package/templates/adec/README.md +32 -0
  91. package/templates/adec/ahub.plan-execute.json +23 -0
  92. package/templates/adec/ahub.stage.json +23 -0
  93. package/LICENSES/Apache-2.0.txt +0 -204
  94. package/src/models/route/advisor.ts +0 -102
  95. package/src/models/route/escalation.ts +0 -82
  96. package/src/models/route/judge.ts +0 -23
  97. package/src/models/route/normalize.ts +0 -103
  98. package/src/models/route/plan-execute.ts +0 -52
  99. package/src/models/route/prompts.ts +0 -8
  100. package/src/models/route/signals.ts +0 -247
  101. package/src/models/route/state.ts +0 -54
  102. package/src/models/route/text.ts +0 -61
@@ -6,8 +6,8 @@ import { HubRouteRuntime, type RouteEvent, type AdvisorEvent } from "../models/r
6
6
  import type { HubRoute } from "../models/route/config.ts";
7
7
  import type { RouteLabelEvent, RouteTurnOutcome } from "../models/route/labels.ts";
8
8
  import type { StaySwitchPolicy } from "../models/route/stage-fallback.ts";
9
- import type { ToolObservation } from "../models/route/signals.ts";
10
- import { randomUUID } from "node:crypto";
9
+ import type { NativeToolObservation as ToolObservation } from "../hub/progress.ts";
10
+ import { createHash, randomUUID } from "node:crypto";
11
11
  import { MAX_HOP, remoteEnvelope, renderDigest, replyAudience, replyParent, STANDING_INSTRUCTION, USER, type Envelope, type EnvelopeOpts, type PeerId } from "../hub/envelope.ts";
12
12
  import { CONDUCTOR_TOOL_NAMES, CONDUCTOR_TOOLS, TASK_TOOL_NAMES, TASK_TOOLS, profileTaskTools, SESSION_TITLE_TOOL } from "../hub/hub-tools.ts";
13
13
  import { BasePeer, type SessionTitleResult } from "../hub/peers.ts";
@@ -15,13 +15,22 @@ import type { PublishResult } from "../hub/bus.ts";
15
15
  import { profile, proxyEnv, type SandboxNetwork } from "../local/sandbox.ts";
16
16
  import type { DocReadPort } from "../local/doc-read.ts";
17
17
  import type { WebFetchPort } from "../local/web-fetch.ts";
18
- import { DOC_READ_SCHEMA, WEB_FETCH_SCHEMA, runTool, toolResultFailed, TOOL_SCHEMAS, touchedPaths, ApprovalWaitStop, type ToolApproval, type ApprovalProvenance, type ToolContext } from "../local/tools.ts";
18
+ import { DOC_READ_SCHEMA, WEB_FETCH_SCHEMA, runTool, toolResultFailed, TOOL_SCHEMAS, touchedPaths, ApprovalWaitStop, planProbeTool, requireProbeToolWrite,
19
+ type ProbeToolResourcePlan, type ToolApproval, type ApprovalProvenance, type ToolContext } from "../local/tools.ts";
19
20
  import type { Capture } from "../memory/capture.ts";
20
21
  import type { ChatMessage, ChatResult, OmniRoute, ToolCall } from "../omniroute/client.ts";
21
22
  import { safeModelLabel } from "../omniroute/usage.ts";
22
23
  import { effectiveLocalRoute } from "../hub/routing.ts";
23
24
  import type { ExecutionBudgetDecision } from "../hub/execution-budget.ts";
24
25
  import type { OwnedInputContext, OwnedInputObserver } from "./claude-print-child.ts";
26
+ import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
27
+ import { GUIDANCE_PROBE_MODEL, GUIDANCE_PROBE_SESSION_BYTES, guidanceProbeCanonical, probeHash, probeInteger,
28
+ type ProbeResourceCharges, type ProbeSlot, type ProbeStoredState } from "../hub/guidance-probes.ts";
29
+ import { ProbeLocalError, probeLocalEffect, probeObservedTokens, type ProbeLocalModelConfig, type ProbeLocalRequest,
30
+ type ProbeLocalResult, type ProbeLocalSession, type ProbePreparedLocalInput } from "../local/probe-types.ts";
31
+ import { requireProbeConfinement, type ProbeConfinement } from "../local/probe-sandbox.ts";
32
+ import { probeRelativePath, reserveProbeWorkspaceBytes } from "../local/probe-workspace.ts";
33
+ import { ProbeToolRefusal, formatProbeToolRefusal } from "../local/probe-errors.ts";
25
34
 
26
35
  export interface LocalOptions {
27
36
  /** Host-only choice sampled once at the next turn/review boundary. */
@@ -97,6 +106,75 @@ const system = (cwd: string, preamble = "") =>
97
106
  preamble,
98
107
  ].filter(Boolean).join("\n");
99
108
 
109
+ const probeSchemas = () => TOOL_SCHEMAS.filter(tool => ["read", "write", "edit"].includes(tool.function.name));
110
+ const probePolicy = () => `${system("/workspace")}\nThis is a private guidance probe. Only read, write and edit are available. Do not send messages, change sessions or invoke hub, package, shell or network operations.`;
111
+ const probeRoleInstruction = (role: Exclude<ProbeSlot["role"], "worker">): string => ({
112
+ proposal: "Propose one guidance revision using only this task and its admitted evidence. Return the proposed text for private host inspection.",
113
+ compose: "Compose one guidance revision from the admitted proposals and evidence. Return the proposed text for private host inspection.",
114
+ select: "Compare only the anonymous deliverables and admitted task sources. Return a reasoned private selection using their anonymous names.",
115
+ reflect: "Review only the admitted evidence from the closed round. Return bounded observations and unresolved questions for private host inspection.",
116
+ })[role];
117
+
118
+ function probeRuntimeHash(): string {
119
+ const sources = [import.meta.url, new URL("../local/probe-types.ts", import.meta.url), new URL("./local-probe.ts", import.meta.url),
120
+ new URL("../local/probe-workspace.ts", import.meta.url), new URL("../local/probe-sandbox.ts", import.meta.url),
121
+ new URL("../local/tools.ts", import.meta.url), new URL("../local/probe-errors.ts", import.meta.url),
122
+ new URL("../local/sandbox.ts", import.meta.url), new URL("../omniroute/client.ts", import.meta.url)].map(value => {
123
+ const file = openSync(new URL(value), constants.O_RDONLY | constants.O_NOFOLLOW);
124
+ try {
125
+ const before = fstatSync(file);
126
+ if (!before.isFile() || before.size > GUIDANCE_PROBE_SESSION_BYTES) throw new ProbeLocalError("invalid");
127
+ const buffer = Buffer.alloc(GUIDANCE_PROBE_SESSION_BYTES + 1), bytes = readSync(file, buffer, 0, buffer.length, 0), after = fstatSync(file);
128
+ if (bytes !== before.size || before.size !== after.size || before.ino !== after.ino || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs)
129
+ throw new ProbeLocalError("drift");
130
+ return createHash("sha256").update(buffer.subarray(0, bytes)).digest("hex");
131
+ } finally { closeSync(file); }
132
+ });
133
+ return probeHash(guidanceProbeCanonical({ engine: process.versions.bun ?? null, platform: process.platform, arch: process.arch, sources }));
134
+ }
135
+
136
+ /** Host preregistration helper; fingerprints actual trusted policy, code, tool schemas and frozen generation configuration. */
137
+ export function localProbeFingerprints(config: Readonly<ProbeLocalModelConfig>): {
138
+ systemPolicy: string; runtimeSha256: string; toolsetSha256: string; modelConfigSha256: string;
139
+ } {
140
+ if (!probeInteger(config.maxSteps) || !config.maxSteps || !probeInteger(config.maxOutputTokens) || !config.maxOutputTokens
141
+ || config.tokenUpperBound !== undefined && (!probeInteger(config.tokenUpperBound) || !config.tokenUpperBound)) throw new ProbeLocalError("invalid");
142
+ const modelConfig = { maxSteps: config.maxSteps, maxOutputTokens: config.maxOutputTokens,
143
+ ...(config.tokenUpperBound === undefined ? {} : { tokenUpperBound: config.tokenUpperBound }) };
144
+ return { systemPolicy: probePolicy(), runtimeSha256: probeRuntimeHash(), toolsetSha256: probeHash(guidanceProbeCanonical(probeSchemas())),
145
+ modelConfigSha256: probeHash(guidanceProbeCanonical(modelConfig)) };
146
+ }
147
+
148
+ /** Exact initial wire request, before any worker or materialization effect. Guidance is one explicit host slot. */
149
+ export function prepareLocalProbeInput(state: ProbeStoredState, slot: ProbeSlot, guidance: string,
150
+ files: ProbePreparedLocalInput["files"], config: Readonly<ProbeLocalModelConfig>): ProbePreparedLocalInput {
151
+ const actual = localProbeFingerprints(config), manifest = state.registration.manifest, snapshots = state.registration.snapshots;
152
+ if (manifest.limits.tokens !== undefined && config.tokenUpperBound === undefined) throw new ProbeToolRefusal("token_bound_unavailable");
153
+ if (manifest.runtime.runtimeSha256 !== actual.runtimeSha256 || manifest.runtime.toolsetSha256 !== actual.toolsetSha256
154
+ || manifest.runtime.modelConfigSha256 !== actual.modelConfigSha256 || snapshots.systemPolicy !== actual.systemPolicy
155
+ || manifest.model.requested !== GUIDANCE_PROBE_MODEL || manifest.model.expectedServed !== GUIDANCE_PROBE_MODEL) throw new ProbeLocalError("drift");
156
+ const rolePolicy = snapshots.dataPolicy.roles[slot.role];
157
+ if (!rolePolicy || files.length !== rolePolicy.dataIds.length || files.some(file => !rolePolicy.dataIds.includes(file.dataId))) throw new ProbeLocalError("invalid");
158
+ const visibleFiles = files.map(({ relative, sha256, bytes }) => ({ relative, sha256, bytes }));
159
+ const writes = snapshots.dataPolicy.allowedWrites.map(({ root, relative }) => {
160
+ if (!["scratch", "output"].includes(root) || !probeRelativePath(relative)) throw new ProbeLocalError("invalid");
161
+ return `/workspace/${root}/${relative}`;
162
+ });
163
+ const writeInstruction = writes.length ? `Admitted logical write targets: ${writes.join(", ")}. No other target is writable.`
164
+ : "No write target is admitted. Use only declared read inputs.";
165
+ const context = slot.role === "reflect" ? { role: slot.role, files: visibleFiles }
166
+ : slot.role === "select" ? { role: slot.role, task: snapshots.task, files: visibleFiles }
167
+ : { role: slot.role, task: snapshots.task, baselineContext: snapshots.baselineContext, files: visibleFiles,
168
+ ...((slot.role === "proposal" || slot.role === "compose") && snapshots.dataPolicy.roles[slot.role].improverContext
169
+ ? { improverContext: snapshots.improverContext ?? (() => { throw new ProbeLocalError("invalid"); })() } : {}) };
170
+ const requestFor = (slotGuidance: string): ProbeLocalRequest => ({ model: GUIDANCE_PROBE_MODEL,
171
+ messages: [{ role: "system", content: `${actual.systemPolicy}\n${writeInstruction}` }, { role: "system", content: slot.role === "worker" ? slotGuidance : probeRoleInstruction(slot.role) }, { role: "user", content: JSON.stringify(context) }],
172
+ tools: probeSchemas(), max_tokens: config.maxOutputTokens, stream: false });
173
+ const request = requestFor(guidance), inputFrame = JSON.stringify(request);
174
+ return { inputFrame, inputSha256: probeHash(inputFrame), nonGuidanceInputSha256: probeHash(JSON.stringify(requestFor(""))),
175
+ request: JSON.parse(inputFrame) as ProbeLocalRequest, role: slot.role, files };
176
+ }
177
+
100
178
  /** Hub-native agent loop: the hub owns every model call, so it can choose the model per call (L2) and the gateway (L3). */
101
179
  export class LocalPeer extends BasePeer {
102
180
  readonly hubNative = true;
@@ -138,12 +216,24 @@ export class LocalPeer extends BasePeer {
138
216
  private currentObserverInputContext: OwnedInputContext | undefined;
139
217
  private observerInputReleasedId: string | undefined;
140
218
  private readonly sandboxProfile: string; // built once: profile() spawns git and must stay off the per-call path
219
+ private probeSession: ProbeLocalSession | undefined;
220
+ private probePromise: Promise<ProbeLocalResult> | undefined;
221
+ private probeStarted = false;
222
+ private probeStopping = false;
223
+ private probeCalls = 0;
224
+ private probeServedModel: string | null = null;
225
+ private probeServedExact = false;
226
+ private probeUsageKnown = true;
227
+ private probeToolPlan: ProbeToolResourcePlan | undefined;
228
+ private readonly probePermits = new Set<Promise<unknown>>();
141
229
  /** What served the last call, for `ahub status`. */
142
230
  lastServedBy = "";
143
231
 
144
232
  constructor(
145
233
  id: PeerId,
146
234
  private readonly opts: LocalOptions,
235
+ private readonly probeConfinement?: ProbeConfinement,
236
+ private readonly probeFixture?: "fixture_only",
147
237
  ) {
148
238
  super(id, opts.watchdogMs);
149
239
  this.routes = new HubRouteRuntime({
@@ -171,7 +261,7 @@ export class LocalPeer extends BasePeer {
171
261
  onAdvisor: event => this.opts.onAdvisor?.(event),
172
262
  onRouteOutcome: event => this.opts.onRouteOutcome?.(event),
173
263
  });
174
- this.sandboxProfile = profile(opts.cwd, opts.tools.bashNetwork ?? false, opts.tools.readAllow, opts.tools.deny, opts.tools.readOnly);
264
+ this.sandboxProfile = probeConfinement?.profile ?? profile(opts.cwd, opts.tools.bashNetwork ?? false, opts.tools.readAllow, opts.tools.deny, opts.tools.readOnly);
175
265
  }
176
266
 
177
267
  private decisionContext(): { pii: boolean; private: boolean; excluded: boolean } {
@@ -186,11 +276,13 @@ export class LocalPeer extends BasePeer {
186
276
  }
187
277
 
188
278
  async start(): Promise<void> {
279
+ if (this.probeConfinement) throw new ProbeLocalError("invalid");
189
280
  this.opts.capture?.init(this.sessionId, "agent-hub local worker session");
190
281
  this.setState("idle");
191
282
  }
192
283
 
193
284
  async stop(reason?: string): Promise<void> {
285
+ if (this.probeConfinement) return this.stopProbe();
194
286
  this.endRouteTurn(this.labelTurnId, "failed");
195
287
  if (this.activeDeliveryId) this.delivery({ id: this.activeDeliveryId, state: "needs_review", reason: reason ?? "turn stopped before settlement" });
196
288
  this.activeDeliveryId = undefined;
@@ -201,8 +293,59 @@ export class LocalPeer extends BasePeer {
201
293
  await this.opts.capture?.end();
202
294
  }
203
295
 
296
+ /** A host-owned private instance shares this loop, never ordinary delivery or observer settlement. */
297
+ async runProbe(session: ProbeLocalSession, signal: AbortSignal): Promise<ProbeLocalResult> {
298
+ if (!this.probeConfinement || this.probeStarted || this.probePromise || this.state !== "offline" || this.history.length || this.title || this.activeDeliveryId || signal.aborted
299
+ || session.purpose !== "guidance_probe" || session.confinement !== this.probeConfinement || session.workspace !== this.probeConfinement.workspace
300
+ || session.workspace.root !== this.opts.cwd || this.opts.fixedModel !== GUIDANCE_PROBE_MODEL || this.opts.maxSteps !== session.config.maxSteps
301
+ || session.prepared.inputSha256 !== probeHash(session.prepared.inputFrame) || JSON.stringify(session.prepared.request) !== session.prepared.inputFrame)
302
+ return Promise.reject(new ProbeLocalError("invalid"));
303
+ if (!this.probeFixture) requireProbeConfinement(this.probeConfinement, session.workspace);
304
+ session.accounting.current();
305
+ this.probeStarted = true; this.probeSession = session;
306
+ const turn = ++this.turn, controller = new AbortController(); this.abort = controller;
307
+ const cancel = () => controller.abort(); signal.addEventListener("abort", cancel, { once: true });
308
+ const msgs: ChatMessage[] = JSON.parse(JSON.stringify(session.prepared.request.messages.slice(1))) as ChatMessage[];
309
+ const progress = { sideEffects: 0, last: "", answerComplete: false };
310
+ this.probePromise = Promise.resolve().then(async () => {
311
+ session.accounting.current();
312
+ const answer = await this.run([], turn, msgs, progress, { pii: false }, {}, { excluded: false });
313
+ if (signal.aborted || controller.signal.aborted || this.probeStopping || turn !== this.turn) throw new ProbeLocalError("interrupted");
314
+ await session.reserve({ outputBytes: Buffer.byteLength(answer, "utf8") }, "probe-final-output");
315
+ return { answer, complete: progress.answerComplete, servedModel: this.probeServedModel,
316
+ servedModelExact: this.probeServedExact, usageKnown: this.probeUsageKnown };
317
+ }).catch(error => {
318
+ if (error instanceof ProbeToolRefusal && error.code === "token_ceiling") {
319
+ if (signal.aborted || controller.signal.aborted || this.probeStopping || turn !== this.turn) throw new ProbeLocalError("interrupted");
320
+ try { session.accounting.current(); } catch { throw new ProbeLocalError("interrupted"); }
321
+ return { answer: "", complete: false, servedModel: this.probeServedModel, servedModelExact: this.probeServedExact,
322
+ usageKnown: this.probeCalls > 0 && this.probeUsageKnown, refusal: "token_ceiling" as const, reason: formatProbeToolRefusal(error) };
323
+ }
324
+ throw error instanceof ProbeLocalError ? error : new ProbeLocalError("interrupted");
325
+ })
326
+ .finally(async () => {
327
+ signal.removeEventListener("abort", cancel); this.clearWatchdog();
328
+ await Promise.allSettled([...this.probePermits]);
329
+ this.probeSession = undefined;
330
+ });
331
+ return this.probePromise;
332
+ }
333
+
334
+ /** No timeout is success: the outer owner may bound this join and retain its handle on uncertainty. */
335
+ async stopProbe(): Promise<void> {
336
+ this.probeStopping = true; this.turn++; this.abort?.abort(); this.clearWatchdog();
337
+ if (this.probePromise) await this.probePromise.catch(() => {});
338
+ await this.probeConfinement?.stop();
339
+ }
340
+
341
+ /** Private adapter bookkeeping, not an ordinary usage/status observer. */
342
+ probeObservation(): Pick<ProbeLocalResult, "servedModel" | "servedModelExact" | "usageKnown"> {
343
+ return { servedModel: this.probeServedModel, servedModelExact: this.probeServedExact, usageKnown: this.probeUsageKnown };
344
+ }
345
+
204
346
  /** Resolves once the turn is claimed; a turn that cannot reach any model hands the envelopes back through onFailed. */
205
347
  async deliver(envs: Envelope[], deliveryId?: string): Promise<void> {
348
+ if (this.probeConfinement) throw new ProbeLocalError("invalid");
206
349
  if (this.state !== "idle") {
207
350
  if (deliveryId) this.delivery({ id: deliveryId, state: "failed_safe", reason: `${this.id} is ${this.state}` });
208
351
  throw new Error(`${this.id} is ${this.state}`);
@@ -296,6 +439,7 @@ export class LocalPeer extends BasePeer {
296
439
  }
297
440
 
298
441
  protected override onWatchdog(): void {
442
+ if (this.probeConfinement) { this.probeStopping = true; this.turn++; this.abort?.abort(); this.clearWatchdog(); return; }
299
443
  this.endRouteTurn(this.labelTurnId, "failed");
300
444
  if (this.activeDeliveryId) this.delivery({ id: this.activeDeliveryId, state: "needs_review", reason: "turn watchdog timeout", failureCause: "timeout" });
301
445
  this.activeDeliveryId = undefined;
@@ -322,6 +466,7 @@ export class LocalPeer extends BasePeer {
322
466
  // Remote text/tool output is never memory evidence, even beside ordinary local work in the same turn.
323
467
  const remoteTurn = envs.some(remoteEnvelope);
324
468
  const capture = policy?.pii || remoteTurn ? undefined : this.opts.capture;
469
+ const activeCapture = this.probeConfinement ? undefined : capture;
325
470
  // Unknown gateway state is never permission to send PII.
326
471
  if (policy?.pii && !(await this.opts.omni.onCampus())) {
327
472
  return "Refused: this is a PII task and the only reachable gateway is off campus (Cloudflare Access). Connect the VPN and assign it again.";
@@ -330,7 +475,9 @@ export class LocalPeer extends BasePeer {
330
475
  this.routePii = !!policy?.pii;
331
476
  this.routeReviewScope = reviewScope;
332
477
  if (turn !== this.turn || turnSignal.aborted) return "";
333
- const fixedPrompt = this.turnRecordPrompt(system(this.opts.cwd, this.opts.preamble));
478
+ const fixedPrompt = this.probeConfinement
479
+ ? this.probeSession?.prepared.request.messages[0]?.content ?? (() => { throw new ProbeLocalError("invalid"); })()
480
+ : this.turnRecordPrompt(system(this.opts.cwd, this.opts.preamble));
334
481
  const ctx = this.toolContext(envs, turnSignal, !!policy?.pii, reply);
335
482
  let usedTools = false;
336
483
  let captureInvocation = 0;
@@ -338,23 +485,23 @@ export class LocalPeer extends BasePeer {
338
485
  this.elide(msgs);
339
486
  const res = await this.call(msgs, policy, envs, selection, fixedPrompt);
340
487
  if (turn !== this.turn) return "";
341
- this.touch();
488
+ if (!this.probeConfinement) this.touch();
342
489
  msgs.push(res.message);
343
490
  progress.last = res.message.content?.trim() || progress.last;
344
491
  if (!res.message.tool_calls?.length) {
345
492
  const concluded = await this.conclude(msgs, policy, turn, step, maxSteps, progress.last, turnSignal, res.routeDecision, selection, fixedPrompt);
346
493
  if (turn !== this.turn) return "";
347
494
  if (concluded === undefined) continue;
348
- if (usedTools && !reviewScope.excluded) capture?.summarize(concluded.answer);
495
+ if (usedTools && !reviewScope.excluded) activeCapture?.summarize(concluded.answer);
349
496
  progress.answerComplete = concluded.complete;
350
497
  return concluded.answer;
351
498
  }
352
- if (res.message.tool_calls.some(call => call.function.name.replace(/^mcp__[^ ]+__/, "") === "hub_review" && reviewCaptureExcluded(call.function.name, call.function.arguments))) reviewScope.excluded = true;
499
+ if (!this.probeConfinement && res.message.tool_calls.some(call => call.function.name.replace(/^mcp__[^ ]+__/, "") === "hub_review" && reviewCaptureExcluded(call.function.name, call.function.arguments))) reviewScope.excluded = true;
353
500
  const results: ChatMessage[] = [];
354
501
  try {
355
502
  for (const call of res.message.tool_calls) {
356
503
  // A tool has its own timeout (bash up to 600 s) and an approval can take 120 s: neither is the model going silent.
357
- const alive = setInterval(() => this.state === "busy" && turn === this.turn && this.touch(), 30_000);
504
+ const alive = this.probeConfinement ? undefined : setInterval(() => this.state === "busy" && turn === this.turn && this.touch(), 30_000);
358
505
  const name = call.function.name;
359
506
  try {
360
507
  await this.requireBudget(envs, "tool_calls");
@@ -362,14 +509,27 @@ export class LocalPeer extends BasePeer {
362
509
  } catch (error) { clearInterval(alive); throw error; }
363
510
  const taskToolName = name.replace(/^mcp__[^ ]+__/, "");
364
511
  const reviewNoteWrite = taskToolName === "hub_remember" || taskToolName === "hub_task_propose";
365
- const running = reviewScope.excluded && reviewNoteWrite
512
+ const toolRun = () => this.probeConfinement && !["read", "write", "edit"].includes(name)
513
+ ? Promise.resolve(formatProbeToolRefusal(new ProbeToolRefusal("tool_unavailable")))
514
+ : reviewScope.excluded && reviewNoteWrite
366
515
  ? Promise.resolve("error: anchored review in this batch; save notes in a later turn")
367
516
  : (TASK_TOOL_NAMES.has(name) || CONDUCTOR_TOOL_NAMES.has(name)) && this.opts.taskTool
368
517
  ? this.opts.taskTool(name, safeParse(call.function.arguments), { pii: !!policy?.pii, signal: turnSignal }).catch((e: Error) => `error: ${e.message}`)
369
518
  : runTool(name, call.function.arguments, ctx);
370
- const output = await running.finally(() => clearInterval(alive));
519
+ const probe = this.probeSession;
520
+ const running = probe ? (async () => {
521
+ try {
522
+ const plan = planProbeTool(name, call.function.arguments, ctx);
523
+ if (!this.probeFixture) reserveProbeWorkspaceBytes(probe.workspace, plan.scratchBytes + plan.outputBytes);
524
+ this.probeToolPlan = plan;
525
+ const charges: ProbeResourceCharges = { scratchBytes: plan.scratchBytes, outputBytes: plan.outputBytes };
526
+ return await probeLocalEffect(probe.accounting, "tool_calls", JSON.stringify({ name, arguments: call.function.arguments }), charges, undefined,
527
+ async () => ({ value: await toolRun(), usage: 1 }));
528
+ } catch (error) { if (error instanceof ProbeToolRefusal) return formatProbeToolRefusal(error); throw error; }
529
+ })() : toolRun();
530
+ const output = await running.finally(() => { clearInterval(alive); if (probe) this.probeToolPlan = undefined; });
371
531
  if (turn !== this.turn) return "";
372
- this.touch();
532
+ if (!this.probeConfinement) this.touch();
373
533
  usedTools = true;
374
534
  if (SIDE_EFFECTS.has(call.function.name) && !output.startsWith("error:")) progress.sideEffects++;
375
535
  const result: ChatMessage = { role: "tool", tool_call_id: call.id, content: output, is_error: toolResultFailed(name, output) };
@@ -379,26 +539,36 @@ export class LocalPeer extends BasePeer {
379
539
  // Hub tool arguments/results are not capture evidence; Tasks owns its screened memory writes.
380
540
  // doc_read text is converted document content (a converter can surface hidden text), never memory evidence: not captured, whatever the turn.
381
541
  // web_fetch text is a third party's page and its URL is the model's own request: neither is memory evidence either (#515b).
382
- if (!reviewScope.excluded && name !== "hub_send" && name !== "doc_read" && name !== "web_fetch" && !TASK_TOOL_NAMES.has(name) && !CONDUCTOR_TOOL_NAMES.has(name)) capture?.observe({ tool: call.function.name, args: call.function.arguments, output, id: call.id, sourceId: `${this.sessionId}.${turn}.${step}.${captureInvocation++}`, paths: touchedPaths(call.function.name, safeParse(call.function.arguments)) });
542
+ if (!reviewScope.excluded && name !== "hub_send" && name !== "doc_read" && name !== "web_fetch" && !TASK_TOOL_NAMES.has(name) && !CONDUCTOR_TOOL_NAMES.has(name)) activeCapture?.observe({ tool: call.function.name, args: call.function.arguments, output, id: call.id, sourceId: `${this.sessionId}.${turn}.${step}.${captureInvocation++}`, paths: touchedPaths(call.function.name, safeParse(call.function.arguments)) });
383
543
  }
384
- } finally { if (results.length) this.routes.observeResults(res.routeDecision, res.message, results); }
544
+ } finally { if (results.length && !this.probeConfinement) this.routes.observeResults(res.routeDecision, res.message, results); }
385
545
  }
386
- if (usedTools && !reviewScope.excluded) capture?.summarize(progress.last);
387
- this.opts.onLimit?.("steps");
546
+ if (usedTools && !reviewScope.excluded) activeCapture?.summarize(progress.last);
547
+ if (!this.probeConfinement) this.opts.onLimit?.("steps");
388
548
  return `(stopped after ${maxSteps} steps) ${progress.last}`.trim();
389
549
  }
390
550
 
391
551
  /** The base tools, plus `doc_read` and `web_fetch` only when the project opted in (`local.doc_read`, `local.web_fetch.allow`; both off by default). */
392
- private toolSchemas() { const extra = [...(this.opts.tools.docRead ? [DOC_READ_SCHEMA] : []), ...(this.opts.tools.webFetch ? [WEB_FETCH_SCHEMA] : [])]; return extra.length ? [...TOOL_SCHEMAS, ...extra] : TOOL_SCHEMAS; }
552
+ private toolSchemas() { if (this.probeConfinement) return probeSchemas(); const extra = [...(this.opts.tools.docRead ? [DOC_READ_SCHEMA] : []), ...(this.opts.tools.webFetch ? [WEB_FETCH_SCHEMA] : [])]; return extra.length ? [...TOOL_SCHEMAS, ...extra] : TOOL_SCHEMAS; }
393
553
 
394
554
  private toolContext(envs: Envelope[], turnSignal: AbortSignal, pii: boolean, reply: EnvelopeOpts): ToolContext {
395
555
  const executionGeneration=this.turn;
396
- return {
556
+ const probe = this.probeSession;
557
+ const context: ToolContext = {
397
558
  ...(this.opts.tools.docRead ? { docRead: { ...this.opts.tools.docRead, pii } } : {}),
398
559
  ...(this.opts.tools.webFetch ? { webFetch: { ...this.opts.tools.webFetch, pii } } : {}),
399
560
  cwd: this.opts.cwd,
400
561
  deny: this.opts.tools.deny,
401
562
  readOnly: this.opts.tools.readOnly,
563
+ ...(probe ? { probe: { root: probe.workspace.root, writableRoots: probe.workspace.allowedWrites,
564
+ current: () => {
565
+ if (turnSignal.aborted || this.probeStopping) throw new ProbeToolRefusal("authority_stopped");
566
+ probe.accounting.current(); if (!this.probeFixture) requireProbeConfinement(probe.confinement, probe.workspace);
567
+ },
568
+ reserveWrite: async (bytes: number, canonicalPath: string) => {
569
+ if (!this.probeToolPlan) throw new ProbeLocalError("invalid");
570
+ requireProbeToolWrite(this.probeToolPlan, bytes, canonicalPath, context);
571
+ } } } : {}),
402
572
  permit: async (title, tool, _signal, canonicalTarget, _observe, originalPath, input, policy) => {
403
573
  if (turnSignal.aborted) return "aborted";
404
574
  const generation = this.turn;
@@ -412,14 +582,17 @@ export class LocalPeer extends BasePeer {
412
582
  if (provenance.source === "person") this.approvalExpiries = 0;
413
583
  if (provenance.source === "expired" && provenance.eligibleExpiry !== false && ++this.approvalExpiries >= 2) {
414
584
  this.approvalStopReason = "Local turn stopped after two unanswered approvals; no person answered. Do not retry the calls; inspect prior work before handoff or stopping.";
415
- try { this.opts.onApprovalStop?.(this.approvalStopReason); } catch { /* stop remains authoritative */ }
585
+ try { if (!this.probeConfinement) this.opts.onApprovalStop?.(this.approvalStopReason); } catch { /* stop remains authoritative */ }
416
586
  }
417
587
  };
418
588
  const picked = await new Promise<ToolApproval>((resolve, reject) => {
419
589
  const finish = (decision: ToolApproval) => { turnSignal.removeEventListener("abort", onAbort); resolve(decision); };
420
590
  const onAbort = () => finish("aborted");
421
591
  turnSignal.addEventListener("abort", onAbort, { once: true });
422
- this.opts.tools.permit(title, tool, turnSignal, canonicalTarget, observe, originalPath, input, policy).then(finish, (error) => { turnSignal.removeEventListener("abort", onAbort); reject(error); });
592
+ const asking = this.opts.tools.permit(title, tool, turnSignal, canonicalTarget, observe, originalPath, input, policy);
593
+ if (this.probeConfinement) this.probePermits.add(asking);
594
+ void asking.then(finish, (error) => { turnSignal.removeEventListener("abort", onAbort); reject(error); })
595
+ .finally(() => { this.probePermits.delete(asking); });
423
596
  });
424
597
  if (generation !== this.turn || (turnSignal.aborted && picked !== "expired")) return "aborted";
425
598
  // Legacy permit callbacks can represent a person's denial without provenance. A true
@@ -430,15 +603,17 @@ export class LocalPeer extends BasePeer {
430
603
  },
431
604
  shellExecutionCheck: input=>turnSignal.aborted||executionGeneration!==this.turn?"aborted":this.opts.tools.shellExecutionCheck?.(input)??"valid",
432
605
  sandboxProfile: this.sandboxProfile,
433
- sandboxEnv: { ...proxyEnv(this.opts.tools.bashNetwork ?? false), AGENTHUB_PEER_ID: this.id },
606
+ sandboxEnv: this.probeConfinement ? { ...this.probeConfinement.env } : { ...proxyEnv(this.opts.tools.bashNetwork ?? false), AGENTHUB_PEER_ID: this.id },
434
607
  signal: turnSignal,
435
608
  send: (text, to) => {
609
+ if (this.probeConfinement) return "error: messaging unavailable in guidance probe";
436
610
  const result = this.onMessage?.(text, pii ? reply : { inReplyTo: replyParent(envs), to: to?.length ? to : replyAudience(envs) }) as PublishResult | string | undefined;
437
611
  if (typeof result === "string") return `not sent: ${result}`;
438
612
  if (result?.dropped === "hop") return `not delivered: reply chain reached the hop cap (${MAX_HOP}); send a new message without reply_to`;
439
613
  return pii ? "sent to the console user only (PII task)" : "sent";
440
614
  },
441
615
  };
616
+ return context;
442
617
  }
443
618
 
444
619
  private reportBudgetStop(e: Error, msgs: ChatMessage[], progress: { sideEffects: number; last: string }, reply: EnvelopeOpts, privateHistory: boolean, deliveryId?: string, remoteTurn = false, reviewTurn = false): void {
@@ -455,6 +630,7 @@ export class LocalPeer extends BasePeer {
455
630
  }
456
631
 
457
632
  private async requireBudget(envs: Envelope[], unit: "model_calls" | "tool_calls"): Promise<void> {
633
+ if (this.probeConfinement) return;
458
634
  if (!this.opts.admitBudget) return;
459
635
  const decisions = await this.opts.admitBudget(envs, unit);
460
636
  const denied = decisions.find((decision) => !decision.allowed);
@@ -482,6 +658,7 @@ export class LocalPeer extends BasePeer {
482
658
 
483
659
  /** Hub-owned in-process policy, with a fixed OmniRoute alias as fallback. */
484
660
  private async call(turnMsgs: ChatMessage[], policy: { route?: string; fixedModel?: string; pii?: boolean; task?: string } | undefined, envs: Envelope[], selection?: ModelOverrideSelection, fixedPrompt = system(this.opts.cwd, this.opts.preamble)): Promise<ChatResult> {
661
+ if (this.probeConfinement) return this.callProbe(turnMsgs, fixedPrompt);
485
662
  const { omni } = this.opts;
486
663
  const route = selection?.model === undefined ? effectiveLocalRoute(this.opts.route, policy?.route, policy?.fixedModel) : undefined;
487
664
  if (route && !route.startsWith("hub/") && !this.warnedLegacyRoutes.has(route)) {
@@ -504,7 +681,38 @@ export class LocalPeer extends BasePeer {
504
681
  return res;
505
682
  }
506
683
 
684
+ private async callProbe(turnMsgs: ChatMessage[], fixedPrompt: string): Promise<ChatResult> {
685
+ const probe = this.probeSession;
686
+ if (!probe || this.probeStopping || this.abort?.signal.aborted) throw new ProbeToolRefusal("authority_stopped");
687
+ probe.accounting.current();
688
+ if (!this.probeFixture) requireProbeConfinement(probe.confinement, probe.workspace);
689
+ const body = JSON.parse(JSON.stringify({ model: GUIDANCE_PROBE_MODEL,
690
+ messages: [{ role: "system", content: fixedPrompt }, ...turnMsgs.map(({ is_error: _internal, ...message }) => message)], tools: probe.prepared.request.tools,
691
+ max_tokens: probe.config.maxOutputTokens, stream: false })) as ProbeLocalRequest;
692
+ const frame = JSON.stringify(body), first = this.probeCalls === 0;
693
+ if (first && frame !== probe.prepared.inputFrame) throw new ProbeLocalError("drift");
694
+ // ponytail: byte-level BPE input tokens are bounded by exact framed UTF-8 bytes; add the output-token cap.
695
+ // Recheck every request; upgrade to a pinned tokenizer-measured whole-call bound when available.
696
+ const upper = probe.config.tokenUpperBound, inputBytes = Buffer.byteLength(frame, "utf8");
697
+ if (upper !== undefined && (probe.config.maxOutputTokens > upper || inputBytes > upper - probe.config.maxOutputTokens))
698
+ throw new ProbeToolRefusal("token_ceiling");
699
+ const result = await probeLocalEffect(probe.accounting, "model_calls", frame, first ? undefined : { inputBytes },
700
+ probe.config.tokenUpperBound, async signal => {
701
+ if (signal.aborted || this.abort?.signal.aborted) throw new ProbeLocalError("interrupted");
702
+ const value = await this.opts.omni.chat(body, { signal: this.abort!.signal });
703
+ return { value, usage: probeObservedTokens(value) };
704
+ });
705
+ this.probeCalls++;
706
+ this.probeServedModel = result.servedModel ?? null;
707
+ this.probeServedExact = result.servedModelExact === true;
708
+ this.probeUsageKnown = this.probeUsageKnown && probeObservedTokens(result) !== null;
709
+ if (!this.probeUsageKnown) throw new ProbeLocalError("usage");
710
+ if (result.servedModel !== GUIDANCE_PROBE_MODEL || result.servedModelExact !== true) throw new ProbeLocalError("model");
711
+ return result;
712
+ }
713
+
507
714
  private releaseObserverInput(context: OwnedInputContext | undefined, envs: Envelope[]): void {
715
+ if (this.probeConfinement) return;
508
716
  if (!context || this.currentObserverInputContext !== context || this.observerInputReleasedId === context.inputId) return;
509
717
  this.observerInputReleasedId = context.inputId;
510
718
  try { this.opts.inputReleased?.(context, envs); } catch { /* observer metadata never changes the local model result */ }
@@ -548,6 +756,7 @@ export class LocalPeer extends BasePeer {
548
756
  }
549
757
 
550
758
  private async conclude(msgs: ChatMessage[], policy: { route?: string; fixedModel?: string; pii: boolean } | undefined, turn: number, step: number, maxSteps: number, answer: string, signal: AbortSignal, decisionId?: string, selection?: ModelOverrideSelection, fixedPrompt = system(this.opts.cwd, this.opts.preamble)): Promise<{ answer: string; complete: boolean } | undefined> {
759
+ if (this.probeConfinement) return { answer, complete: true };
551
760
  const route = selection?.model === undefined ? effectiveLocalRoute(this.opts.route, policy?.route, policy?.fixedModel) : undefined, config = this.hubConfig(route);
552
761
  if (!route || !config) return { answer, complete: true };
553
762
  const messages: ChatMessage[] = [{ role: "system", content: fixedPrompt }, ...this.history, ...msgs];
@@ -559,6 +768,7 @@ export class LocalPeer extends BasePeer {
559
768
  }
560
769
 
561
770
  private observeTool(call: ToolCall, output: string, policy: { pii: boolean; task?: string } | undefined, nativeTurn: string): void {
771
+ if (this.probeConfinement) return;
562
772
  if (policy?.pii || call.function.name === "doc_read" || call.function.name === "web_fetch") return; // document and web text: no research observation carries it
563
773
  try {
564
774
  const command = safeParse(call.function.arguments).command;
@@ -567,6 +777,7 @@ export class LocalPeer extends BasePeer {
567
777
  }
568
778
 
569
779
  private recordUsage(res: ChatResult, requestedModel: string, task?: number): void {
780
+ if (this.probeConfinement) return;
570
781
  try {
571
782
  this.opts.onUsage?.({
572
783
  id: randomUUID(),
@@ -16,6 +16,7 @@ import { windowKind } from "../hub/window-kind.ts";
16
16
  import { ownerIsolationText, taskHolderText } from "./role-holders.ts";
17
17
  import { USAGE_DROP, USAGE_HEAD, usageCells, usageDetail, usagePeers, usageTaskLines, type UsageState } from "./console-usage.ts";
18
18
  import type { RoomStatusView } from "../rooms/status.ts";
19
+ import { peerHubVersion, type ConsoleVersions } from "./console-versions.ts";
19
20
 
20
21
  export interface Approval {
21
22
  id: string; peer: string; title: string; expiresAt: number;
@@ -39,6 +40,8 @@ export interface ConsoleState {
39
40
  pendingRestart?: { key: string; reason: string }[];
40
41
  retainedConfig?: { key: string; reason: string }[];
41
42
  features?: readonly string[];
43
+ /** #1385: the agent-hub versions in play, and the native agent CLIs the hub has not verified (status `agentDrift`). */
44
+ versions?: ConsoleVersions; agentDrift?: readonly { id: string; version: string; state: string; receipt: string }[];
42
45
  /** #1053 T4: the open questions the hub reported (the person's text, shown here only) and the answer being built; `A` starts it. */
43
46
  questions?: QuestionView[]; questionFlow?: QuestionFlow; questionsSeen?: string[];
44
47
  /** Older embedding callers omit choices and retain the original STAI/off toggle. */
@@ -364,14 +367,28 @@ export function budgetFields(budget: any, now: number): [string, unknown][] {
364
367
  return [["quota", lines.length ? lines : typeof budget.note === "string" ? budget.note : "no reading"], ...(lines.length && typeof budget.note === "string" ? [["quota note", budget.note] as [string, unknown]] : [])];
365
368
  }
366
369
  /** #784 AC3: the Peers detail carries the planner WIP split as one line (`1 of 2: active 1, review-wait 0, reserved 0`); a hub that sends none adds nothing. */
370
+ /** #1385: one line above the peer table: the running daemon, this console, the global CLI and the plugin, older ones in attention, then the peers that load another version. */
371
+ function versionsLine(s: ConsoleState): Span[] {
372
+ const v = s.versions!;
373
+ const parts: Span[] = [span("agent-hub", "info")];
374
+ for (const [label, value, key] of [["daemon", v.daemon, undefined], ["console", v.cli, "cli"], ["global", v.global, "global"], ["plugin", v.plugin, "plugin"]] as const) {
375
+ const older = !!key && v.older.includes(key);
376
+ parts.push(span(` ${label} ${value ?? "unknown"}${older ? " (older)" : ""}`, older ? "attention" : value ? undefined : "muted"));
377
+ }
378
+ const differing = Object.entries(s.peers).filter(([id, peer]) => peerHubVersion({ id, ...peer }, v.daemon).differs).map(([id]) => id);
379
+ if (differing.length) parts.push(span(` ${plural(differing.length, "peer")} on another version: ${differing.join(", ")}`, "attention"));
380
+ return parts;
381
+ }
367
382
  function peerDetailRow(s: ConsoleState, row: any, now: number): Record<string, unknown> {
368
383
  const wip = s.taskWip?.[row.id];
369
384
  const split = wip && [wip.active, wip.reviewWait, wip.reserved].every(n => Number.isSafeInteger(n)) ? `${wip.wip} of ${wip.wipLimit}: active ${wip.active}, review-wait ${wip.reviewWait}, reserved ${wip.reserved}` : undefined;
370
385
  const isolation = ownerIsolationText(row.ownerIsolation, row.ownerIsolationNote);
371
- const { standbySessions, ...fields } = row;
386
+ const { standbySessions, ahub: _ahub, ahubTools: _tools, ...fields } = row;
387
+ const hub = peerHubVersion(row, s.versions?.daemon).detail;
388
+ const drift = s.agentDrift?.find(agent => agent.id === row.id);
372
389
  const standby = Array.isArray(standbySessions) ? standbySessions.filter((session: any) => session && typeof session.id === "string").map((session: any) =>
373
390
  `${typeof session.pid === "number" ? `pid ${session.pid}` : "pid unknown"}; session ${session.id}${typeof session.since === "number" ? `; waiting since ${relative(session.since, now)}` : ""}`) : [];
374
- return { ...fields, ...(standby.length ? { "standing by": standby } : {}), ...(isolation ? { ownerIsolation: isolation } : {}), ...(split ? { "planner WIP": split } : {}) };
391
+ return { ...fields, ...(hub ? { "agent-hub": hub } : {}), ...(drift ? { "agent CLI": `${drift.version} ${drift.state}; last receipt ${drift.receipt}` } : {}), ...(standby.length ? { "standing by": standby } : {}), ...(isolation ? { ownerIsolation: isolation } : {}), ...(split ? { "planner WIP": split } : {}) };
375
392
  }
376
393
  const detailLines = (detail: Detail, columns: number, now: number, task = false): Span[][] => {
377
394
  if (typeof detail === "string") return wrap(detail, columns).map(text => [span(text)]);
@@ -962,7 +979,7 @@ export function activeNotice(s: Pick<ConsoleState, "notice" | "noticeAt" | "noti
962
979
  return !!s.notice && now - (s.noticeAt ?? now) < (s.noticeMs ?? NOTICE_MS);
963
980
  }
964
981
  export const TABLES: Record<number, string[]> = {
965
- 1: ["PEER", "STATE", "LINK", "Q", "!", "WIP", "REVIEW", "PAUSE", "QUOTA", "MODEL", "DOING"],
982
+ 1: ["PEER", "STATE", "LINK", "AHUB", "Q", "!", "WIP", "REVIEW", "PAUSE", "QUOTA", "MODEL", "DOING"],
966
983
  2: ["ID", "PEER", "LEFT", "TITLE"],
967
984
  3: ["ID", "STATE", "OWNER", "REVIEWER", "CLASS", "AGE", "TITLE", "STAGE"],
968
985
  4: ["ID", "PEER", "STATE", "REV", "AGE"],
@@ -989,6 +1006,7 @@ export function cells(s: ConsoleState, row: any, selected: boolean, now: number,
989
1006
  return [id(row.planner ? `${row.id} (planner)` : row.id, row.state === "offline" ? undefined : "info"), span(`${row.rostered === false ? `${row.state} off roster` : row.state}${Array.isArray(row.standbySessions) && row.standbySessions.length ? ` +standby:${row.standbySessions.length}` : ""}`, stateTone(row.state)),
990
1007
  ...(showPermissionModes(s) ? [span(row.permissionMode && row.permissionMode !== "ask" ? row.permissionMode : "-", row.permissionMode === "never-ask" ? "attention" : undefined)] : []),
991
1008
  span(row.pullOnly && definitionOf(row.id)?.attach?.pullOnlyForms?.includes("tui") ? "pull-only" : row.toolsOnly ? "tools-only" : row.attached === false ? "detached" : "attached", row.toolsOnly ? "attention" : undefined),
1009
+ ((hub) => span(hub.cell, hub.differs ? "attention" : hub.cell === "-" || hub.unknown ? "muted" : undefined))(peerHubVersion(row, s.versions?.daemon)),
992
1010
  span(count(row.queued)), span(count(row.queuedImportant), row.queuedImportant ? "attention" : undefined),
993
1011
  span(wip ? `${wip.wip}/${wip.wipLimit}` : "-", wip && wip.wip >= wip.wipLimit ? "attention" : undefined),
994
1012
  span(count(row.needsReview), row.needsReview ? "failure" : undefined), span(paused, paused === "-" ? undefined : "attention"),
@@ -1065,10 +1083,10 @@ export function table(head: string[], rows: Span[][], columns: number, explicitW
1065
1083
  }));
1066
1084
  }
1067
1085
  /** Keep the status/quota columns visible instead of clipping them behind optional peer metadata. */
1068
- function optionalTable(head: string[], rows: Span[][], columns: number, drop = ["DOING", "MODEL", "WIP", "PAUSE", "REVIEW", "LINK", "Q", "!", "MODE"]): Span[][] {
1086
+ function optionalTable(head: string[], rows: Span[][], columns: number, drop = ["DOING", "MODEL", "WIP", "PAUSE", "REVIEW", "AHUB", "LINK", "Q", "!", "MODE"]): Span[][] {
1069
1087
  const cap = Math.max(24, Math.floor(columns / 3));
1070
1088
  const widths = head.map((name, i) => Math.min(cap, rows.reduce((max, row) => Math.max(max, Bun.stringWidth(flat(row[i]?.text ?? ""))), name.length)));
1071
- const keep = head.map((_, i) => i).filter(i => head[i] !== "DOING" || rows.some(row => row[i]?.text !== "-")); // #878: shown once a peer has one
1089
+ const keep = head.map((_, i) => i).filter(i => !["DOING", "AHUB"].includes(head[i]!) || rows.some(row => row[i]?.text !== "-")); // #878, #1385: shown once a peer has one
1072
1090
  const total = () => keep.reduce((sum, i) => sum + widths[i]!, 0) + 2 * (keep.length - 1);
1073
1091
  for (const name of drop) {
1074
1092
  if (total() <= columns - 2) break;
@@ -1285,7 +1303,7 @@ export function renderConsoleLines(s: ConsoleState, columns: number, rows = 24,
1285
1303
  const selectedTask = s.panel === 3 ? data[at] : undefined;
1286
1304
  const holders = selectedTask && (selectedTask.planner !== undefined || selectedTask.plannerReason !== undefined)
1287
1305
  ? fieldLines((["planner", "owner", "reviewer"] as const).map((role): [string, unknown] => [role, taskHolderText(selectedTask, role)]), columns, now).flat() : [];
1288
- const capacity = Math.max(1, s.panel === 2 ? Math.min(Math.floor(height / 2) - 1, height - 3 - tail.length) : s.panel === 7 ? height - 2 - taskLines.length : height - (s.panel === 3 ? 2 + holders.length : 1)); const start = Math.max(0, at - capacity + 1);
1306
+ const capacity = Math.max(1, s.panel === 2 ? Math.min(Math.floor(height / 2) - 1, height - 3 - tail.length) : s.panel === 7 ? height - 2 - taskLines.length : height - (s.panel === 3 ? 2 + holders.length : s.panel === 1 && s.versions ? 2 : 1)); const start = Math.max(0, at - capacity + 1);
1289
1307
  const stages = new Map(progress.stages.map(stage => [stage.id, stage]));
1290
1308
  const cellRows = head ? data.map((row, i) => cells(s, row, i === at, now, stages)) : [];
1291
1309
  const rowsOf = head ? s.panel === 7 ? optionalTable(head, cellRows, columns, USAGE_DROP) : s.panel === 1 ? optionalTable(head, cellRows, columns) : s.panel === 3 && s.backlogView ? optionalTable(head, cellRows, columns, ["AGE", "CLASS", "DEPS", "PRI"]) : table(head, cellRows, columns) : undefined;
@@ -1304,6 +1322,7 @@ export function renderConsoleLines(s: ConsoleState, columns: number, rows = 24,
1304
1322
  : `usage through ${s.usage.at ? relative(s.usage.at, now) : "now"}: today is the UTC day, 7d the last seven UTC days`;
1305
1323
  lines.push(fitLine([span(note, s.usage?.problem ? "failure" : !s.usage?.life || s.usage.behind ? "attention" : "info")], columns));
1306
1324
  }
1325
+ if (s.panel === 1 && s.versions) lines.push(fitLine(versionsLine(s), columns));
1307
1326
  if (s.panel === 8 && s.rooms === null) lines.push(fitLine([span("Room status unavailable", "attention")], columns));
1308
1327
  if (s.panel === 3 && s.backlogView) {
1309
1328
  lines.push(fitLine([span(s.tasksKnown === false ? "backlog loading..." : `backlog ${data.length}`, s.tasksKnown === false ? "attention" : "info")], columns));