@staix/agent-hub 0.38.0 → 0.40.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 (195) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/README.md +28 -12
  3. package/docs/adding-an-ai-tool.md +7 -5
  4. package/docs/agent-notes/README.md +23 -0
  5. package/docs/agent-notes/adapters.md +9 -5
  6. package/docs/agent-notes/benchmarks.md +2 -0
  7. package/docs/agent-notes/budget.md +9 -0
  8. package/docs/agent-notes/bus.md +1 -0
  9. package/docs/agent-notes/daemon.md +21 -9
  10. package/docs/agent-notes/local-worker.md +4 -2
  11. package/docs/agent-notes/security-review.md +56 -0
  12. package/docs/agent-notes/tasks.md +22 -6
  13. package/docs/agent-notes/tests.md +10 -9
  14. package/docs/contracts/companion-cli-v1.json +4 -0
  15. package/docs/design/adapters.md +142 -0
  16. package/docs/design/agent-hub-architecture.md +46 -1
  17. package/docs/design/agent-hub.md +10 -0
  18. package/docs/design/bus.md +7 -0
  19. package/docs/design/cli-output.md +183 -0
  20. package/docs/design/execution-reference.md +6 -1
  21. package/docs/design/roadmap.md +191 -0
  22. package/docs/design/task-board.md +185 -5
  23. package/docs/dogfood.md +30 -9
  24. package/docs/events.md +7 -7
  25. package/docs/memory.md +5 -5
  26. package/docs/operations.md +315 -54
  27. package/docs/profiles.md +101 -8
  28. package/docs/quickstart.md +47 -6
  29. package/docs/research.md +6 -3
  30. package/docs/roles.md +52 -0
  31. package/docs/sdlc.md +190 -2
  32. package/docs/security.md +90 -15
  33. package/docs/text-projection.md +1 -0
  34. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  35. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  36. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  37. package/docs/verification/2026-11-14-codex-0169-reviewer-isolation.md +70 -0
  38. package/docs/verification/2026-11-14-codex-0169-reviewer-tool-call.md +48 -0
  39. package/docs/verification/2026-11-14-pi-152-compat.md +45 -0
  40. package/docs/verification/2026-11-15-0.40.0.md +39 -0
  41. package/docs/verification/2026-11-16-pi-loopback-1447.md +39 -0
  42. package/docs/verification/pi-152-model-free.ts +57 -0
  43. package/docs/verification/pi-152-native.mjs +21 -0
  44. package/docs/verified.json +48 -25
  45. package/package.json +4 -4
  46. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  47. package/plugins/agent-hub/kimi-hook.js +2266 -530
  48. package/plugins/agent-hub/kimi-review-policy-worker.js +16 -11
  49. package/plugins/agent-hub/server.js +2423 -645
  50. package/src/adapters/acp-model-policy.ts +1 -1
  51. package/src/adapters/acp-session-model.ts +35 -0
  52. package/src/adapters/acp.ts +14 -0
  53. package/src/adapters/agy/definition.ts +2 -2
  54. package/src/adapters/agy/hooks.ts +7 -0
  55. package/src/adapters/claude-channel.ts +1 -1
  56. package/src/adapters/claude-implementer.ts +8 -0
  57. package/src/adapters/claude-print-child.ts +26 -2
  58. package/src/adapters/claude-print.ts +4 -0
  59. package/src/adapters/codex-appserver.ts +90 -16
  60. package/src/adapters/codex-review-isolation.ts +63 -17
  61. package/src/adapters/compat.ts +10 -10
  62. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  63. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  64. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  65. package/src/adapters/definitions/builtin-metadata.ts +12 -12
  66. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  67. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  68. package/src/adapters/definitions/native-config-policy.ts +1 -1
  69. package/src/adapters/definitions/native-quota.ts +122 -0
  70. package/src/adapters/definitions/native-recovery.ts +3 -0
  71. package/src/adapters/definitions/qwen.ts +2 -2
  72. package/src/adapters/kimi-review.ts +23 -0
  73. package/src/adapters/kimi-wire-usage.ts +39 -16
  74. package/src/adapters/local-worker.ts +9 -4
  75. package/src/adapters/pi-state-model.ts +12 -0
  76. package/src/adapters/pi.ts +76 -11
  77. package/src/adapters/print-result-model.ts +24 -0
  78. package/src/adapters/registry-types.ts +12 -2
  79. package/src/adapters/registry.ts +19 -2
  80. package/src/adapters/reviewer-print.ts +132 -16
  81. package/src/adapters/role-eligibility.ts +99 -0
  82. package/src/adapters/same-directory.ts +16 -0
  83. package/src/cli/agy-mcp.ts +18 -7
  84. package/src/cli/answer-args.ts +11 -3
  85. package/src/cli/console-question.ts +1 -1
  86. package/src/cli/console-state.ts +98 -11
  87. package/src/cli/console.ts +6 -2
  88. package/src/cli/error-format.ts +19 -0
  89. package/src/cli/free-text.ts +20 -0
  90. package/src/cli/handoff-args.ts +1 -1
  91. package/src/cli/help.ts +350 -30
  92. package/src/cli/identity-audit.ts +8 -7
  93. package/src/cli/identity.ts +27 -4
  94. package/src/cli/init-prompt.ts +31 -2
  95. package/src/cli/init-roles.ts +156 -0
  96. package/src/cli/init-settings.ts +24 -2
  97. package/src/cli/init.ts +232 -17
  98. package/src/cli/main.js +2 -2
  99. package/src/cli/main.ts +250 -69
  100. package/src/cli/model.ts +1 -1
  101. package/src/cli/output-standard.ts +56 -0
  102. package/src/cli/output.ts +199 -9
  103. package/src/cli/preview.ts +1 -1
  104. package/src/cli/recovery-launch.ts +114 -0
  105. package/src/cli/recovery-package.ts +14 -7
  106. package/src/cli/recovery-version-preflight.ts +104 -0
  107. package/src/cli/roadmap.ts +215 -0
  108. package/src/cli/role-doctor.ts +39 -0
  109. package/src/cli/sdlc-output.ts +66 -1
  110. package/src/cli/smoke-pty-bridge.ts +7 -24
  111. package/src/cli/study-output.ts +54 -0
  112. package/src/cli/study.ts +14 -1
  113. package/src/cli/task-output.ts +3 -1
  114. package/src/cli/terminal-recovery.ts +14 -0
  115. package/src/cli/upgrade-presentation-flags.ts +2 -2
  116. package/src/cli/upgrade-presentation.ts +4 -0
  117. package/src/cli/upgrade-restore-state.ts +12 -3
  118. package/src/cli/upgrade-runtime.ts +40 -2
  119. package/src/cli/upgrade.ts +8 -4
  120. package/src/hub/advisor-survey.ts +139 -0
  121. package/src/hub/audit-source.ts +66 -0
  122. package/src/hub/board.ts +677 -15
  123. package/src/hub/budget.ts +54 -4
  124. package/src/hub/bus.ts +9 -0
  125. package/src/hub/check-runner.ts +3 -4
  126. package/src/hub/ci-watch.ts +19 -4
  127. package/src/hub/conductor.ts +14 -8
  128. package/src/hub/config-apply.ts +2 -1
  129. package/src/hub/config-edit-host.ts +77 -5
  130. package/src/hub/considered-findings.ts +47 -0
  131. package/src/hub/control-client.ts +1 -1
  132. package/src/hub/daemon.ts +585 -98
  133. package/src/hub/deliverable-files.ts +17 -1
  134. package/src/hub/dogfood-profile.ts +3 -2
  135. package/src/hub/events.ts +25 -4
  136. package/src/hub/execution-reference.ts +1 -1
  137. package/src/hub/folder-trigger.ts +11 -4
  138. package/src/hub/github-import.ts +81 -0
  139. package/src/hub/hub-tools.ts +117 -20
  140. package/src/hub/install-policy.ts +23 -0
  141. package/src/hub/kimi-usage.ts +34 -2
  142. package/src/hub/lifecycle-schema.ts +3 -3
  143. package/src/hub/memory-profile.ts +9 -1
  144. package/src/hub/memory-sync-state.ts +1 -0
  145. package/src/hub/model-overrides.ts +2 -1
  146. package/src/hub/no-writes.ts +5 -0
  147. package/src/hub/operational-authority.ts +8 -1
  148. package/src/hub/operational-view.ts +6 -2
  149. package/src/hub/peers.ts +2 -0
  150. package/src/hub/pi-failure.ts +7 -0
  151. package/src/hub/plan-conformance.ts +20 -2
  152. package/src/hub/question-desk.ts +26 -7
  153. package/src/hub/questions.ts +33 -5
  154. package/src/hub/quota-account.ts +34 -0
  155. package/src/hub/recovery-policy.ts +18 -4
  156. package/src/hub/research-evidence.ts +51 -3
  157. package/src/hub/research.ts +77 -13
  158. package/src/hub/restart.ts +21 -0
  159. package/src/hub/review-budget.ts +88 -0
  160. package/src/hub/review-findings.ts +93 -12
  161. package/src/hub/reviewer-pool-config.ts +6 -2
  162. package/src/hub/reviewer-pool.ts +39 -6
  163. package/src/hub/roadmap-triage.ts +86 -0
  164. package/src/hub/roadmap-unplaced.ts +169 -0
  165. package/src/hub/roadmap-view.ts +83 -0
  166. package/src/hub/roadmap.ts +127 -0
  167. package/src/hub/routing.ts +7 -3
  168. package/src/hub/sdlc-merge.ts +6 -5
  169. package/src/hub/sdlc-queue.ts +17 -7
  170. package/src/hub/sdlc-release.ts +1 -1
  171. package/src/hub/sdlc.ts +47 -8
  172. package/src/hub/security-audit.ts +178 -0
  173. package/src/hub/security-pass.ts +115 -0
  174. package/src/hub/settings.ts +11 -5
  175. package/src/hub/source-read.ts +80 -2
  176. package/src/hub/sources.ts +57 -9
  177. package/src/hub/specs-task.ts +7 -0
  178. package/src/hub/startup-event-seeds.ts +5 -3
  179. package/src/hub/startup-timing.ts +1 -0
  180. package/src/hub/synthesis-readiness.ts +279 -0
  181. package/src/hub/task-sweep.ts +29 -2
  182. package/src/hub/task-worktree.ts +37 -0
  183. package/src/hub/tasks.ts +1464 -76
  184. package/src/hub/text-projection.ts +11 -1
  185. package/src/memory/capture.ts +2 -1
  186. package/src/pi/dependency-publish.ts +50 -0
  187. package/src/pi/extension.ts +1 -1
  188. package/src/pi/launch.ts +1 -1
  189. package/src/pi/task-dependencies.ts +249 -0
  190. package/src/ui/index.html +56 -13
  191. package/src/ui/office-model.ts +11 -3
  192. package/src/ui/office-space.ts +50 -30
  193. package/src/ui/plugin-questions.ts +5 -0
  194. package/src/ui/plugin.ts +27 -12
  195. package/templates/config.json +1 -1
@@ -38,6 +38,11 @@ export interface LocalOptions {
38
38
  profile?: import("../hub/profiles.ts").ProfileSelection;
39
39
  sdlcStages?: readonly string[];
40
40
  sdlcCriteria?: boolean;
41
+ /** #1403 A4: the lifecycle is on and `[security]` is configured, so `hub_audit_report` is listed. */
42
+ sdlcAudit?: boolean;
43
+ sdlcSurvey?: boolean;
44
+ /** #1454: the idle sweep is on, so `hub_task_wait` is published. */
45
+ taskWait?: boolean;
41
46
  /** Host-owned conditional instruction, sampled once per delivered turn. */
42
47
  titlePreface?: () => string | undefined;
43
48
  cwd: string;
@@ -243,7 +248,7 @@ export class LocalPeer extends BasePeer {
243
248
  await this.requireBudget(envs, "model_calls");
244
249
  if (generation !== this.turn) throw new Error("route belongs to an ended turn");
245
250
  if (signal.aborted) throw new Error("turn cancelled before model request");
246
- const tools = judge ? undefined : [...this.toolSchemas(), ...(this.opts.taskTool ? [...profileTaskTools(this.opts.profile, this.opts.sdlcStages, this.opts.sdlcCriteria).filter(tool => tool.name !== "hub_delivery_retry"), ...CONDUCTOR_TOOLS].concat(SESSION_TITLE_TOOL).map(asFunction) : [])];
251
+ const tools = judge ? undefined : [...this.toolSchemas(), ...(this.opts.taskTool ? [...profileTaskTools(this.opts.profile, this.opts.sdlcStages, this.opts.sdlcCriteria, this.opts.sdlcAudit, this.opts.sdlcSurvey, this.opts.taskWait).filter(tool => tool.name !== "hub_delivery_retry"), ...CONDUCTOR_TOOLS].concat(SESSION_TITLE_TOOL).map(asFunction) : [])];
247
252
  this.releaseObserverInput(this.currentObserverInputContext, envs);
248
253
  const result = await this.opts.omni.chat({ model, messages, ...(tools ? { tools } : {}), ...(judge ? { max_tokens: maxTokens ?? 2048 } : {}) }, { signal, ...(pii ? { onCampusOnly: true } : {}) });
249
254
  this.recordUsage(result, model, task);
@@ -496,7 +501,7 @@ export class LocalPeer extends BasePeer {
496
501
  progress.answerComplete = concluded.complete;
497
502
  return concluded.answer;
498
503
  }
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;
504
+ if (!this.probeConfinement && res.message.tool_calls.some(call => (call.function.name.replace(/^mcp__[^ ]+__/, "") === "hub_evidence_read" || call.function.name.replace(/^mcp__[^ ]+__/, "") === "hub_review" && reviewCaptureExcluded(call.function.name, call.function.arguments)))) reviewScope.excluded = true;
500
505
  const results: ChatMessage[] = [];
501
506
  try {
502
507
  for (const call of res.message.tool_calls) {
@@ -535,7 +540,7 @@ export class LocalPeer extends BasePeer {
535
540
  const result: ChatMessage = { role: "tool", tool_call_id: call.id, content: output, is_error: toolResultFailed(name, output) };
536
541
  msgs.push(result); results.push(result);
537
542
  if (this.approvalStopReason) { this.abort?.abort(); throw new ApprovalWaitStop(this.approvalStopReason); }
538
- if (!remoteTurn && !reviewScope.excluded && name !== "hub_set_title" && name !== "hub_ask" && !reviewCaptureExcluded(name, call.function.arguments)) this.observeTool(call, output, policy, `${this.sessionId}.${turn}.${step}`);
543
+ if (!remoteTurn && !reviewScope.excluded && name !== "hub_set_title" && name !== "hub_ask" && name !== "hub_ask_answer" && !reviewCaptureExcluded(name, call.function.arguments)) this.observeTool(call, output, policy, `${this.sessionId}.${turn}.${step}`);
539
544
  // Hub tool arguments/results are not capture evidence; Tasks owns its screened memory writes.
540
545
  // doc_read text is converted document content (a converter can surface hidden text), never memory evidence: not captured, whatever the turn.
541
546
  // web_fetch text is a third party's page and its URL is the model's own request: neither is memory evidence either (#515b).
@@ -667,7 +672,7 @@ export class LocalPeer extends BasePeer {
667
672
  }
668
673
  const fixedModel = selection?.model ?? policy?.fixedModel ?? this.opts.fixedModel;
669
674
  const task = policy?.task === undefined ? undefined : Number(policy.task);
670
- const tools = [...this.toolSchemas(), ...(this.opts.taskTool ? [...profileTaskTools(this.opts.profile, this.opts.sdlcStages, this.opts.sdlcCriteria).filter(tool => tool.name !== "hub_delivery_retry"), ...CONDUCTOR_TOOLS].concat(SESSION_TITLE_TOOL).map(asFunction) : [])];
675
+ const tools = [...this.toolSchemas(), ...(this.opts.taskTool ? [...profileTaskTools(this.opts.profile, this.opts.sdlcStages, this.opts.sdlcCriteria, this.opts.sdlcAudit, this.opts.sdlcSurvey, this.opts.taskWait).filter(tool => tool.name !== "hub_delivery_retry"), ...CONDUCTOR_TOOLS].concat(SESSION_TITLE_TOOL).map(asFunction) : [])];
671
676
  const signal = this.abort!.signal;
672
677
  const messages: ChatMessage[] = [{ role: "system", content: fixedPrompt }, ...this.history, ...turnMsgs];
673
678
  const routed = await this.hubCall(route, messages, policy, signal);
@@ -0,0 +1,12 @@
1
+ import { safeModelLabel } from "../omniroute/usage.ts";
2
+
3
+ /**
4
+ * #1402 T4: the model id in a Pi `get_state` reply's data (`data.model.id`, a model descriptor). Pi 1.5.2 reports the placeholder id `unknown` (provider `unknown`) when no model is selected, which names no
5
+ * model. A value `safeModelLabel` refuses, a missing descriptor or a non-object names none, so nothing is guessed and no alias is expanded.
6
+ */
7
+ export function stateModelId(state: unknown): string | undefined {
8
+ const data = state && typeof state === "object" && !Array.isArray(state) ? state as Record<string, unknown> : undefined;
9
+ const model = data?.model && typeof data.model === "object" && !Array.isArray(data.model) ? data.model as Record<string, unknown> : undefined;
10
+ const id = safeModelLabel(model?.id);
11
+ return id !== undefined && id.toLowerCase() !== "unknown" ? id : undefined;
12
+ }
@@ -17,6 +17,8 @@ import { piToolStepCeiling, type PiToolStepCeiling } from "../pi/ceiling.ts";
17
17
  import type { ExecutionBudgetDecision, ExecutionUnit } from "../hub/execution-budget.ts";
18
18
  import { QuestionWaitDetached } from "../hub/question-detach.ts";
19
19
  import type { StartForm } from "./registry-types.ts";
20
+ import { stateModelId } from "./pi-state-model.ts";
21
+ import type { ModelObservation } from "../hub/events.ts";
20
22
 
21
23
  export interface PiModelDescriptor { id: string; name?: string; contextWindow?: number; maxTokens?: number; reasoning?: boolean; }
22
24
  export interface PiToolSchema { name: string; description?: string; parameters: Record<string, unknown>; }
@@ -55,7 +57,11 @@ export interface PiOptions {
55
57
  /** Reported message usage as increments, before agent_settled releases the turn. */
56
58
  onTokens?: (added: number) => void;
57
59
  /** `ceiling` is the validated, session/turn-bound tool-step ceiling signal (#179), present only when the trusted extension emitted one for this turn. */
58
- onTurnFailure?: (envs: Envelope[], reason: string, ceiling?: PiToolStepCeiling) => Promise<void>;
60
+ onTurnFailure?: (envs: Envelope[], reason: string, ceiling?: PiToolStepCeiling, settledCeiling?: boolean) => Promise<void>;
61
+ /** Observation only: cancelled/stopped logical turns never request failure handoff. */
62
+ onTurnAborted?: (envs: Envelope[]) => void;
63
+ /** Observation only: a real successful turn resets the host's continuation count. */
64
+ onTurnSuccess?: (envs: Envelope[]) => void;
59
65
  watchdogMs?: number; log?: (line: string) => void;
60
66
  /** Once per owner, after it is offline; a TUI owner may have unknown OS exit status. */
61
67
  onExit?: (exit: PiExit) => void;
@@ -185,8 +191,11 @@ export class PiPeer extends BasePeer {
185
191
  private executionAbort?: AbortController;
186
192
  private readonly budgetStops = new Map<number, string>();
187
193
  private readonly ceilingStops = new Map<number, PiToolStepCeiling>();
194
+ private ceilingUnsafe = false;
195
+ private turnObserved = false;
188
196
  private readonly idleBashReservations = new Map<string, { generation: number; expiresAt: number; deadlineAt?: number }>();
189
197
  private budgetGeneration = 0;
198
+ private settledGeneration: number | undefined;
190
199
  private modelStep = 0;
191
200
  private readonly observationScope = randomUUID();
192
201
  private emptyResumeVerified = false;
@@ -206,9 +215,12 @@ export class PiPeer extends BasePeer {
206
215
  private approvalAbortSent = false;
207
216
  private approvalStopReason = "";
208
217
  private requestedStopReason: string | undefined;
218
+ private stopCause: "aborted" | "failure" | undefined;
209
219
  private owner = randomUUID();
210
220
  private _tuiLaunch?: PiTuiLaunch;
211
221
  private requestedModel = "";
222
+ /** #1402: what the turn that is running, or just ended, was on: the `get_state` model (`session`), else the model the hub set (`configured`). Read once at the turn end; never invented. */
223
+ private turnModel: ModelObservation | undefined;
212
224
  private baselineRequestedModel = "";
213
225
  private runtimeModelSelected = false;
214
226
  private starting?: Promise<void>;
@@ -246,6 +258,11 @@ export class PiPeer extends BasePeer {
246
258
  return { sessionId: this.opts.sessionId, sessionFile: this.opts.sessionFile };
247
259
  }
248
260
  get acceptingTools(): boolean { return !this.stopping && !this.rosterDetached && !this.rosterUnownedRun; }
261
+ /** Failure handoff may follow a verified internal teardown; it never grants tool execution. */
262
+ get failureHandoffAllowed(): boolean {
263
+ return !this.rosterDetached && !this.rosterUnownedRun && this.stopCause !== "aborted"
264
+ && (!this.stopping || this.state === "offline" && this.stopCause === "failure");
265
+ }
249
266
  /** Idle verified owners can be stopped; uncertain live owners and pending launches stay fenced. */
250
267
  get recoveryReady(): boolean {
251
268
  if (this.state === "busy" || this.starting || this.activeTools) return false;
@@ -492,6 +509,8 @@ export class PiPeer extends BasePeer {
492
509
  this.observedTitle = undefined; this.titleRevision = -1; this.nativeTitleEpoch = undefined; this.onDoing?.("reset");
493
510
  this.rosterDetached = false; this.rosterUnownedRun = false;
494
511
  this.requestedStopReason = undefined;
512
+ this.stopCause = undefined;
513
+ this.settledGeneration = undefined;
495
514
  this.approvalTurnAbort = false;
496
515
  this.fencedPrompt = false; this.hubPromptId = undefined; this.hubPromptGeneration = undefined; this.pendingPromptId = undefined;
497
516
  this.exitReported = false; this.started = false; this.lastToolName = undefined; this.shutdownExit = undefined;
@@ -625,9 +644,19 @@ export class PiPeer extends BasePeer {
625
644
  get mode(): "headless" | "tui" { return this.opts.mode; }
626
645
  get form(): StartForm { return this.opts.mode; }
627
646
 
647
+ private observeTurn(outcome: "aborted" | "success"): void {
648
+ if (this.turnObserved || !this.agentRunning && !this.activeEnvs.length) return;
649
+ this.turnObserved = true;
650
+ try {
651
+ if (outcome === "aborted") this.opts.onTurnAborted?.(this.activeEnvs.slice());
652
+ else this.opts.onTurnSuccess?.(this.activeEnvs.slice());
653
+ } catch { /* observation cannot change delivery settlement */ }
654
+ }
655
+
628
656
  /** Withdraw hub admission without shutting down a person's Pi TUI or its bridge. */
629
657
  async detachForRoster(): Promise<void> {
630
658
  if (this.opts.mode !== "tui") throw new Error("Pi roster detach requires a personal TUI");
659
+ this.observeTurn("aborted");
631
660
  this.terminalOwnerObservation = undefined;
632
661
  this.rosterDetached = true; this.rosterEpoch++;
633
662
  this.setState("offline");
@@ -669,7 +698,9 @@ export class PiPeer extends BasePeer {
669
698
  if (!snapshot.idle) this.clearWatchdog();
670
699
  }
671
700
 
672
- async stop(reason?: string, failureCause?: DeliveryFailureCause): Promise<void> {
701
+ async stop(reason?: string, failureCause?: DeliveryFailureCause, cause: "aborted" | "failure" = "aborted"): Promise<void> {
702
+ if (cause === "aborted" || this.stopCause === undefined) this.stopCause = cause;
703
+ if (cause === "aborted") this.observeTurn("aborted");
673
704
  if (reason !== undefined) this.requestedStopReason = reason;
674
705
  this.rosterEpoch++;
675
706
  this.terminalOwnerObservation = undefined;
@@ -755,6 +786,9 @@ export class PiPeer extends BasePeer {
755
786
  if (deliveryId) this.delivery({ id: deliveryId, state: "failed_safe", reason });
756
787
  throw new Error(reason);
757
788
  }
789
+ // ponytail: host turn starts at busy before async model preflight. Later workflow
790
+ // notices wait for the following turn; closing that window needs an ACK-safe prepare/commit port.
791
+ this.turnObserved = false;
758
792
  this.setState("busy"); this.activeEnvs = envs; this.currentReply = replyParent(envs); this.settledText = "";
759
793
  const rosterEpoch = this.rosterEpoch;
760
794
  let attempted = false;
@@ -772,6 +806,8 @@ export class PiPeer extends BasePeer {
772
806
  this.runtimeModelSelected = selection?.model !== undefined;
773
807
  }
774
808
  if (rosterEpoch !== this.rosterEpoch || !this.acceptingTools) throw new Error("Pi is off roster or stopped");
809
+ await this.captureTurnModel(requested);
810
+ if (rosterEpoch !== this.rosterEpoch || !this.acceptingTools) throw new Error("Pi is off roster or stopped");
775
811
  this.noteActivity();
776
812
  attempted = true;
777
813
  if (deliveryId) this.activeDeliveryIds.add(deliveryId);
@@ -847,6 +883,22 @@ export class PiPeer extends BasePeer {
847
883
  }
848
884
  }
849
885
 
886
+ /**
887
+ * #1402 T4: a headless Pi reports its current model in `get_state`; that is `session` evidence. The TUI snapshot (`get_session_state`) carries no model, and a failed or placeholder read leaves the model the hub
888
+ * itself set through `set_model` (Pi acknowledged it), which is only `configured`. A read that fails never fails the delivery.
889
+ */
890
+ private async captureTurnModel(requested: string | undefined): Promise<void> {
891
+ this.turnModel = undefined;
892
+ if (this.opts.mode !== "tui") {
893
+ try {
894
+ const state = await this.waitRpc("get_state", 5_000);
895
+ const id = state.success === true ? stateModelId(state.data) : undefined;
896
+ if (id) { this.turnModel = { model: id, evidence: "session" }; return; }
897
+ } catch { /* optional metadata: the turn goes on without it */ }
898
+ }
899
+ if (requested) this.turnModel = { model: requested, evidence: "configured" };
900
+ }
901
+ observedModel(): ModelObservation | undefined { const model = this.turnModel; this.turnModel = undefined; return model; }
850
902
  getRequestedModel(): string { return this.requestedModel; }
851
903
  getBaselineRequestedModel(): string { return this.baselineRequestedModel; }
852
904
  async setRequestedModel(model: string): Promise<void> {
@@ -874,6 +926,7 @@ export class PiPeer extends BasePeer {
874
926
  else {
875
927
  if (this.pendingPromptId || this.activeEnvs.length) {
876
928
  // Await the prompt's exact ACK before deciding whether its effect was absent or uncertain.
929
+ this.observeTurn("aborted");
877
930
  this.rosterDetached = true; this.rosterEpoch++; this.clearWatchdog();
878
931
  this.activeEnvs = []; this.currentReply = undefined; this.settledText = ""; this.settledError = "";
879
932
  this.abortTools();
@@ -907,6 +960,8 @@ export class PiPeer extends BasePeer {
907
960
  return;
908
961
  }
909
962
  if (this.stopping && ["agent_start", "agent_end", "agent_settled"].includes(event.type)) return;
963
+ // Settled generation replay cannot become a failure of the next delivered prompt.
964
+ if (["agent_end", "agent_settled"].includes(event.type) && Number.isSafeInteger(event.generation) && event.generation === this.settledGeneration) return;
910
965
  if (event.type === "session_start") {
911
966
  if (!this.ownerClaimed) { this.ownerClaimed = true; this.ownerToken = String(event.ownerToken ?? ""); }
912
967
  this.approvalTurnAbort = event.approvalTurnAbort === true;
@@ -923,6 +978,7 @@ export class PiPeer extends BasePeer {
923
978
  if ((event.type === "session_title" || event.type === "agent_start" && Object.hasOwn(event, "sessionName")) && event.sessionId === this.sessionId && this.verifiedOwner()) this.observeTitle(event.sessionName, event.titleRevision, event.titleEpoch);
924
979
  if (event.type === "session_shutdown") {
925
980
  this.observedTitle = undefined; this.titleRevision = -1; this.nativeTitleEpoch = undefined; this.onDoing?.("reset");
981
+ if (this.stopCause === undefined) this.stopCause = "failure";
926
982
  const exit = this.exitMetadata("session_shutdown");
927
983
  this.shutdownExit ??= exit; // headless waits for the OS exit, retaining the pre-cleanup turn and stop facts
928
984
  this.stopping = true; this.ownerClaimed = false; this.clearOwnerMonitor(); this.resolveTuiExit?.(); this.resolveTuiExit = undefined;
@@ -945,6 +1001,7 @@ export class PiPeer extends BasePeer {
945
1001
  const generation = Number.isSafeInteger(event.generation) ? event.generation : this.budgetGeneration + 1;
946
1002
  if (generation <= this.budgetGeneration) return;
947
1003
  this.modelStep = 0;
1004
+ this.ceilingUnsafe = false; this.turnObserved = false;
948
1005
  this.approvalExpiries = 0; this.approvalAnswerEpoch = undefined; this.approvalStopReason = ""; this.approvalAbortSent = false; this.abortedToolIds.clear(); this.abortIdsOverflow = false;
949
1006
  this.usageSeen.clear(); this.ceilingStops.clear(); this.abortTools(); this.executionAbort = new AbortController(); this.budgetGeneration = generation; this.noteActivity(); this.agentRunning = true; this.setState("busy");
950
1007
  }
@@ -955,6 +1012,8 @@ export class PiPeer extends BasePeer {
955
1012
  const ceiling = piToolStepCeiling(event);
956
1013
  if (ceiling && ceiling.sessionId === this.sessionId && ceiling.generation === this.budgetGeneration && this.agentRunning && this.state === "busy" && !this.ceilingStops.has(ceiling.generation)) {
957
1014
  this.ceilingStops.set(ceiling.generation, ceiling);
1015
+ // Tools may settle before agent_settled; that cannot erase uncertainty at the ceiling.
1016
+ this.ceilingUnsafe = this.activeTools > 0 || this.pendingToolGenerations.size > 0;
958
1017
  for (const old of this.ceilingStops.keys()) if (old < ceiling.generation - 8) this.ceilingStops.delete(old);
959
1018
  }
960
1019
  }
@@ -976,25 +1035,30 @@ export class PiPeer extends BasePeer {
976
1035
  }
977
1036
  if (event.type === "agent_settled") {
978
1037
  if (Number.isSafeInteger(event.generation) && event.generation !== this.budgetGeneration) return;
1038
+ this.settledGeneration = this.budgetGeneration;
979
1039
  clearTimeout(this.executionBudgetTimer); this.executionBudgetTimer = undefined;
980
1040
  this.agentRunning = false;
981
1041
  if (typeof event.text === "string" && event.text.trim()) this.settledText = event.text;
982
1042
  const generation = Number.isSafeInteger(event.generation) ? event.generation : this.budgetGeneration;
983
1043
  const approvalStopReason = this.approvalStopReason;
984
- const text = this.settledText.trim(); const error = approvalStopReason || this.budgetStops.get(generation) || this.settledError; const cancelled = !error && this.settledCancelled;
1044
+ const text = this.settledText.trim(); const error = approvalStopReason || this.budgetStops.get(generation) || this.settledError; const cancelled = this.settledCancelled;
985
1045
  const ceiling = this.ceilingStops.get(generation);
1046
+ const settledCeiling = !!ceiling && !!error && !cancelled && !approvalStopReason && !this.budgetStops.has(generation)
1047
+ && !this.ceilingUnsafe && !this.activeTools && !this.pendingToolGenerations.size && this.acceptingTools;
1048
+ const ceilingReason = settledCeiling && ceiling ? `ceiling steps ${ceiling.count}/${ceiling.limit}` : undefined;
986
1049
  this.budgetStops.delete(generation);
987
1050
  this.ceilingStops.delete(generation);
988
1051
  this.settledText = ""; this.settledError = ""; this.settledCancelled = false;
989
1052
  // Answer the peers this turn was for, not every peer on the bus (issue #29). activeEnvs still holds the
990
1053
  // whole delivery here, steered additions included.
991
1054
  const reply = { inReplyTo: this.currentReply, to: replyAudience(this.activeEnvs) };
992
- if (cancelled) this.onMessage?.("Pi turn cancelled; inspect any partial effects before continuing.", reply);
993
- else if (error?.startsWith("execution budget")) this.onMessage?.(`Pi stopped at the execution budget: ${error}. Inspect partial work before continuing.`, reply);
994
- else if (approvalStopReason) this.onMessage?.(approvalStopReason, reply);
995
- else if (error) void this.opts.onTurnFailure?.(this.activeEnvs, error, ceiling);
996
- else if (text) this.finalAnswer(text, reply);
997
- for (const id of this.activeDeliveryIds) this.delivery({ id, state: approvalStopReason ? "completed" : error || cancelled ? "needs_review" : "completed", ...(error || cancelled ? { reason: error || "Pi turn cancelled; partial effects are possible" } : {}) });
1055
+ if (cancelled) { this.observeTurn("aborted"); this.onMessage?.("Pi turn cancelled; inspect any partial effects before continuing.", reply); }
1056
+ else if (error?.startsWith("execution budget")) { this.observeTurn("aborted"); this.onMessage?.(`Pi stopped at the execution budget: ${error}. Inspect partial work before continuing.`, reply); }
1057
+ else if (approvalStopReason) { this.observeTurn("aborted"); this.onMessage?.(approvalStopReason, reply); }
1058
+ else if (error && !this.turnObserved) { this.turnObserved = true; void this.opts.onTurnFailure?.(this.activeEnvs, error, ceiling, settledCeiling); }
1059
+ else if (error) { /* This logical turn was already observed, including legacy unnumbered replays. */ }
1060
+ else { this.observeTurn("success"); if (text) this.finalAnswer(text, reply); }
1061
+ for (const id of this.activeDeliveryIds) this.delivery({ id, state: approvalStopReason || settledCeiling ? "completed" : error || cancelled ? "needs_review" : "completed", ...(ceilingReason ? { reason: ceilingReason } : error || cancelled ? { reason: error || "Pi turn cancelled; partial effects are possible" } : {}) });
998
1062
  this.activeDeliveryIds.clear();
999
1063
  this.currentReply = undefined; this.activeEnvs = [];
1000
1064
  this.hubPromptId = undefined; this.hubPromptGeneration = undefined;
@@ -1071,7 +1135,8 @@ export class PiPeer extends BasePeer {
1071
1135
  const envs = this.activeEnvs; this.activeEnvs = [];
1072
1136
  for (const id of this.activeDeliveryIds) this.delivery({ id, state: "needs_review", reason: error.message });
1073
1137
  this.activeDeliveryIds.clear();
1074
- if (envs.length && !this.requestedStopReason && !this.rosterDetached) {
1138
+ if (envs.length && !this.requestedStopReason && !this.rosterDetached && !this.turnObserved) {
1139
+ this.turnObserved = true;
1075
1140
  this.onMessage?.(approvalStopReason ? `${approvalStopReason} Pi is offline because its extension could not abort the turn; restart with ahub pi and settle the held delivery after inspecting prior work.` : "Pi turn failed; inspect its session and any partial effects before continuing.", { inReplyTo: this.currentReply });
1076
1141
  if (!approvalStopReason && !(error instanceof ApprovalWaitStop)) void this.opts.onTurnFailure?.(envs, error.message).catch(() => this.opts.log?.("Pi failure handoff could not be completed"));
1077
1142
  }
@@ -1115,7 +1180,7 @@ export class PiPeer extends BasePeer {
1115
1180
  const envs = this.activeEnvs.slice(), reply = this.currentReply;
1116
1181
  this.stopping = true;
1117
1182
  try {
1118
- await this.stop(undefined, failureCause);
1183
+ await this.stop(undefined, failureCause, "failure");
1119
1184
  // The process exit handler may already have reported this failure.
1120
1185
  if (this.activeEnvs.length) this.fail(error);
1121
1186
  } catch (stopError) {
@@ -0,0 +1,24 @@
1
+ import { safeModelLabel } from "../omniroute/usage.ts";
2
+
3
+ /**
4
+ * #1402 T2: the model a Claude print run served, from the `modelUsage` of its `result` row (keys are the model ids, values the per-model usage). One safe key is that model. Several (a main
5
+ * model plus a helper such as a summarizer) name the one that handled strictly more tokens than every other; a tie or a breakdown with no token counts names none, because guessing which model
6
+ * ran the turn would put a wrong id on the record. Only the usage counters weigh (input, output, cache read and creation); `maxOutputTokens` and `contextWindow` describe the model, not the turn. A key `safeModelLabel` refuses never counts, and nothing but the id is kept. Absent field: no observation.
7
+ */
8
+ export function resultModel(row: unknown): string | undefined {
9
+ if (!row || typeof row !== "object") return undefined;
10
+ const usage = (row as { modelUsage?: unknown }).modelUsage;
11
+ if (!usage || typeof usage !== "object" || Array.isArray(usage)) return undefined;
12
+ const seen: { model: string; weight: number }[] = [];
13
+ for (const key of Object.keys(usage)) {
14
+ const model = safeModelLabel(key);
15
+ if (model === undefined || model.toLowerCase() === "unknown") continue;
16
+ const value = (usage as Record<string, unknown>)[key];
17
+ let weight = 0;
18
+ if (value && typeof value === "object") for (const [name, count] of Object.entries(value)) if (/^(input|output|cacheRead|cacheCreation)[A-Za-z]*tokens$/i.test(name) && typeof count === "number" && Number.isFinite(count) && count > 0) weight += count;
19
+ seen.push({ model, weight });
20
+ }
21
+ if (seen.length === 1) return seen[0]!.model;
22
+ const ranked = seen.sort((a, b) => b.weight - a.weight);
23
+ return ranked.length > 1 && ranked[0]!.weight > ranked[1]!.weight ? ranked[0]!.model : undefined;
24
+ }
@@ -24,6 +24,7 @@ import type { CodexOptions } from "./codex-appserver.ts";
24
24
  import type { JcodeOptions } from "./jcode.ts";
25
25
  import type { LocalOptions } from "./local-worker.ts";
26
26
  import type { PiOptions } from "./pi.ts";
27
+ import type { CompatId } from "./compat.ts";
27
28
  import type { QwenDualOptions } from "./qwen-dual.ts";
28
29
  import type { ClaudePrintOptions } from "./claude-print.ts";
29
30
 
@@ -145,6 +146,8 @@ export interface NativeFactsInput {
145
146
  invocation?: number;
146
147
  fullyIdle?: boolean;
147
148
  terminationReason?: string;
149
+ /** #1402: the hook payload's `modelName` when it is a safe model id; the session's current model, never a per-response one. */
150
+ model?: string;
148
151
  }
149
152
  export interface NativeFactsReadOptions {
150
153
  completion?: boolean;
@@ -276,6 +279,8 @@ export interface AdapterDefinition {
276
279
  trackUnattended?: boolean;
277
280
  };
278
281
  session: {
282
+ /** Observational recovery preflight only; actual native startup repeats its own version admission. */
283
+ restoreVersionGate?: CompatId;
279
284
  nativeRevert?: boolean;
280
285
  crashPlan?(meta: Record<string, unknown>): { resume?: Record<string, string>; how: string; fresh?: Record<string, string>; tui?: true };
281
286
  unrecordedTerminal?: "always" | "tui";
@@ -332,13 +337,18 @@ export interface AdapterDefinition {
332
337
  /** Fixed factory support only; the host still checks the actual native surface and form. */
333
338
  modelOverride?: { readonly boundary: "turn"; readonly acp?: import("./acp-model-policy.ts").AcpModelPolicy };
334
339
  /** Stable host projection order and planner eligibility, independent of default task roles. */
335
- projection?: { roleRank?: number; startRank?: number; helpRank?: number; plannerEligible?: boolean };
340
+ projection?: { roleRank?: number; startRank?: number; helpRank?: number; plannerEligible?: boolean;
341
+ /** #1408 R1: true only for a kind with an interactive form that receives hub pushes and holds a writable tools connection. Absent means false: a kind not yet proven is not eligible. */
342
+ conductorEligible?: boolean;
343
+ /** #1408 R1: the kind can receive `hub_review`. Absent means false. */
344
+ reviewerEligible?: boolean };
336
345
  cli: {
337
346
  command: string;
338
347
  /** Fixed builtin CLI ports; project definitions cannot supply these callbacks. */
339
348
  entry?: Readonly<Omit<BuiltinCliEntry, "command">>;
340
349
  preview?: NativePreviewBuilder;
341
- usage?: readonly (readonly [usage: string, description: string])[];
350
+ /** `[usage, description, summary?]`: the optional third element is the one-line row of `ahub help` for this form (#1504; three or more words, at most 56 cells). It rides this field's fixed-builtin restriction. */
351
+ usage?: readonly (readonly [usage: string, description: string, summary?: string])[];
342
352
  /** Configuration leaves that select this peer's next native launch command or provider profile. */
343
353
  launchConfigKeys?: readonly string[];
344
354
  /** Restrictions only; core identity remains authoritative. */
@@ -174,6 +174,23 @@ export const CONDUCTOR_START_PEERS = [
174
174
  ...ADAPTERS.filter(adapter => !(CONDUCTOR_START_PRIORITY as readonly string[]).includes(adapter.kind)).map(adapter => adapter.kind),
175
175
  ];
176
176
 
177
+ /**
178
+ * The words a person reads about which kinds a conductor may start, derived from the definitions in registry order so a new kind is named without a text edit (#1408 R5).
179
+ * `refusal` keeps the sentence the conductor always got, with the kinds read from `conductorStartable` and `optional`.
180
+ */
181
+ export function conductorStartText(): { peers: string; refusal: string; tuiPeers: string } {
182
+ const startable = SUPPORTED_PEERS.filter(peer => definitionOf(peer)?.start.conductorStartable === true);
183
+ const list = (names: readonly string[], joiner: string) => names.length < 2 ? names.join("") : `${names.slice(0, names.length - 1).join(", ")} ${joiner} ${names[names.length - 1]}`;
184
+ const optional = (peer: string) => definitionOf(peer)?.optional === true;
185
+ // A kind opens in a terminal when its person-set start mode is tui, and a kind whose own default form is a terminal one starts that way.
186
+ const tui = startable.filter(peer => definitionOf(peer)!.start.defaultForm === "tui" && definitionOf(peer)!.start.forms.includes("tui"));
187
+ return {
188
+ peers: list(startable, "or"),
189
+ refusal: `only ${list(startable.filter(peer => !optional(peer)), "and")}, plus the opt-in ${list(startable.filter(optional), "and")}, may be started by the conductor`,
190
+ tuiPeers: list(tui, "and"),
191
+ };
192
+ }
193
+
177
194
  /** A missing definition retains external-id admission; Pi's legacy enabled switch controls its default only. */
178
195
  export function defaultRosterEnabled(peer: string, piEnabled: boolean): boolean {
179
196
  const definition = definitionOf(peer);
@@ -200,9 +217,9 @@ export function assertDefinitionCoherence(definition: AdapterDefinition): void {
200
217
  }
201
218
  const projection = definition.projection;
202
219
  if (projection !== undefined) {
203
- if (!projection || typeof projection !== "object" || Array.isArray(projection) || Object.keys(projection).some(key => !["roleRank", "startRank", "helpRank", "plannerEligible"].includes(key))) fail("projection", "invalid projection metadata");
220
+ if (!projection || typeof projection !== "object" || Array.isArray(projection) || Object.keys(projection).some(key => !["roleRank", "startRank", "helpRank", "plannerEligible", "conductorEligible", "reviewerEligible"].includes(key))) fail("projection", "invalid projection metadata");
204
221
  for (const field of ["roleRank", "startRank", "helpRank"] as const) if (projection[field] !== undefined && (typeof projection[field] !== "number" || !Number.isFinite(projection[field]))) fail(`projection.${field}`, "rank must be finite");
205
- if (projection.plannerEligible !== undefined && typeof projection.plannerEligible !== "boolean") fail("projection.plannerEligible", "boolean required");
222
+ for (const field of ["plannerEligible", "conductorEligible", "reviewerEligible"] as const) if (projection[field] !== undefined && typeof projection[field] !== "boolean") fail(`projection.${field}`, "boolean required");
206
223
  }
207
224
  const attach = definition.attach, pullOnly = attach?.pullOnlyForms;
208
225
  if (pullOnly !== undefined) {