@staix/agent-hub 0.38.0 → 0.39.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 (144) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +17 -7
  3. package/docs/adding-an-ai-tool.md +6 -4
  4. package/docs/agent-notes/README.md +16 -0
  5. package/docs/agent-notes/adapters.md +4 -2
  6. package/docs/agent-notes/budget.md +8 -0
  7. package/docs/agent-notes/daemon.md +15 -8
  8. package/docs/agent-notes/local-worker.md +1 -1
  9. package/docs/agent-notes/security-review.md +55 -0
  10. package/docs/agent-notes/tasks.md +15 -4
  11. package/docs/agent-notes/tests.md +3 -2
  12. package/docs/design/adapters.md +51 -0
  13. package/docs/design/agent-hub-architecture.md +29 -1
  14. package/docs/design/task-board.md +151 -5
  15. package/docs/dogfood.md +20 -6
  16. package/docs/events.md +3 -3
  17. package/docs/memory.md +5 -5
  18. package/docs/operations.md +177 -28
  19. package/docs/profiles.md +100 -8
  20. package/docs/quickstart.md +32 -4
  21. package/docs/research.md +6 -3
  22. package/docs/roles.md +52 -0
  23. package/docs/sdlc.md +187 -1
  24. package/docs/security.md +50 -11
  25. package/docs/text-projection.md +1 -0
  26. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  27. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  28. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  29. package/docs/verified.json +48 -25
  30. package/package.json +3 -3
  31. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  32. package/plugins/agent-hub/kimi-hook.js +1953 -460
  33. package/plugins/agent-hub/server.js +2019 -498
  34. package/src/adapters/acp-model-policy.ts +1 -1
  35. package/src/adapters/acp-session-model.ts +35 -0
  36. package/src/adapters/acp.ts +14 -0
  37. package/src/adapters/agy/definition.ts +1 -1
  38. package/src/adapters/agy/hooks.ts +7 -0
  39. package/src/adapters/claude-channel.ts +1 -1
  40. package/src/adapters/claude-implementer.ts +8 -0
  41. package/src/adapters/claude-print-child.ts +26 -2
  42. package/src/adapters/claude-print.ts +4 -0
  43. package/src/adapters/codex-appserver.ts +90 -16
  44. package/src/adapters/codex-review-isolation.ts +2 -0
  45. package/src/adapters/compat.ts +4 -4
  46. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  47. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  48. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  49. package/src/adapters/definitions/builtin-metadata.ts +6 -6
  50. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  51. package/src/adapters/definitions/native-quota.ts +122 -0
  52. package/src/adapters/definitions/native-recovery.ts +3 -0
  53. package/src/adapters/definitions/qwen.ts +1 -1
  54. package/src/adapters/kimi-review.ts +23 -0
  55. package/src/adapters/kimi-wire-usage.ts +39 -16
  56. package/src/adapters/local-worker.ts +6 -3
  57. package/src/adapters/pi-state-model.ts +12 -0
  58. package/src/adapters/pi.ts +22 -0
  59. package/src/adapters/print-result-model.ts +24 -0
  60. package/src/adapters/registry-types.ts +10 -1
  61. package/src/adapters/registry.ts +19 -2
  62. package/src/adapters/reviewer-print.ts +130 -15
  63. package/src/adapters/role-eligibility.ts +99 -0
  64. package/src/adapters/same-directory.ts +16 -0
  65. package/src/cli/agy-mcp.ts +18 -7
  66. package/src/cli/console-state.ts +3 -1
  67. package/src/cli/free-text.ts +20 -0
  68. package/src/cli/handoff-args.ts +1 -1
  69. package/src/cli/help.ts +61 -6
  70. package/src/cli/identity.ts +10 -4
  71. package/src/cli/init-prompt.ts +31 -2
  72. package/src/cli/init-roles.ts +156 -0
  73. package/src/cli/init-settings.ts +24 -2
  74. package/src/cli/init.ts +139 -17
  75. package/src/cli/main.ts +194 -49
  76. package/src/cli/model.ts +1 -1
  77. package/src/cli/output.ts +56 -1
  78. package/src/cli/preview.ts +1 -1
  79. package/src/cli/recovery-launch.ts +114 -0
  80. package/src/cli/recovery-package.ts +14 -7
  81. package/src/cli/recovery-version-preflight.ts +104 -0
  82. package/src/cli/role-doctor.ts +39 -0
  83. package/src/cli/sdlc-output.ts +66 -1
  84. package/src/cli/study-output.ts +54 -0
  85. package/src/cli/study.ts +14 -1
  86. package/src/cli/terminal-recovery.ts +14 -0
  87. package/src/cli/upgrade-presentation.ts +4 -0
  88. package/src/cli/upgrade-restore-state.ts +12 -3
  89. package/src/cli/upgrade-runtime.ts +40 -2
  90. package/src/cli/upgrade.ts +8 -4
  91. package/src/hub/advisor-survey.ts +139 -0
  92. package/src/hub/audit-source.ts +66 -0
  93. package/src/hub/board.ts +479 -14
  94. package/src/hub/budget.ts +54 -4
  95. package/src/hub/conductor.ts +14 -8
  96. package/src/hub/config-apply.ts +2 -1
  97. package/src/hub/config-edit-host.ts +77 -5
  98. package/src/hub/considered-findings.ts +47 -0
  99. package/src/hub/control-client.ts +1 -1
  100. package/src/hub/daemon.ts +343 -58
  101. package/src/hub/deliverable-files.ts +17 -1
  102. package/src/hub/dogfood-profile.ts +3 -2
  103. package/src/hub/events.ts +23 -2
  104. package/src/hub/folder-trigger.ts +11 -4
  105. package/src/hub/hub-tools.ts +88 -16
  106. package/src/hub/kimi-usage.ts +34 -2
  107. package/src/hub/lifecycle-schema.ts +3 -3
  108. package/src/hub/memory-profile.ts +9 -1
  109. package/src/hub/memory-sync-state.ts +1 -0
  110. package/src/hub/model-overrides.ts +2 -1
  111. package/src/hub/no-writes.ts +2 -0
  112. package/src/hub/operational-authority.ts +6 -1
  113. package/src/hub/operational-view.ts +5 -1
  114. package/src/hub/peers.ts +2 -0
  115. package/src/hub/plan-conformance.ts +20 -2
  116. package/src/hub/quota-account.ts +34 -0
  117. package/src/hub/recovery-policy.ts +18 -4
  118. package/src/hub/research-evidence.ts +51 -3
  119. package/src/hub/research.ts +77 -13
  120. package/src/hub/restart.ts +14 -0
  121. package/src/hub/review-budget.ts +88 -0
  122. package/src/hub/review-findings.ts +93 -12
  123. package/src/hub/reviewer-pool-config.ts +6 -2
  124. package/src/hub/reviewer-pool.ts +39 -6
  125. package/src/hub/routing.ts +7 -3
  126. package/src/hub/sdlc-merge.ts +1 -1
  127. package/src/hub/sdlc-queue.ts +14 -4
  128. package/src/hub/sdlc-release.ts +1 -1
  129. package/src/hub/sdlc.ts +10 -6
  130. package/src/hub/security-audit.ts +178 -0
  131. package/src/hub/security-pass.ts +115 -0
  132. package/src/hub/settings.ts +11 -5
  133. package/src/hub/source-read.ts +80 -2
  134. package/src/hub/sources.ts +57 -9
  135. package/src/hub/startup-event-seeds.ts +5 -3
  136. package/src/hub/startup-timing.ts +1 -0
  137. package/src/hub/synthesis-readiness.ts +279 -0
  138. package/src/hub/tasks.ts +1083 -69
  139. package/src/hub/text-projection.ts +11 -1
  140. package/src/memory/capture.ts +2 -1
  141. package/src/ui/index.html +3 -0
  142. package/src/ui/office-model.ts +11 -3
  143. package/src/ui/office-space.ts +50 -30
  144. package/src/ui/plugin.ts +21 -11
@@ -75,7 +75,7 @@ const CLAUDE_IMPLEMENTER_VARIANT: AdapterDefinition = {
75
75
  // daemon.ts runtime mappings/stop policy, budget.ts exemptions, and ui/peer-palette.ts CSS foregrounds.
76
76
  export const NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN: readonly AdapterDefinition[] = Object.freeze([
77
77
  {
78
- projection: { roleRank: 0, helpRank: 0, plannerEligible: true },
78
+ projection: { roleRank: 0, helpRank: 0, plannerEligible: true, conductorEligible: true, reviewerEligible: true },
79
79
  api: 1, kind: "claude", questionWaitMs: 45000, displayName: "Claude Code", family: "claude", transport: "claude-channel",
80
80
  roles: Object.freeze(["planner", "reviewer"]), defaultOnRoster: true, trust: { onPrem: false, hubSandboxed: false },
81
81
  start: { forms: Object.freeze(["tui"] as const), defaultForm: "tui", launch: claudeNativeLaunch, version: claudeObservedVersion, ...CLAUDE_LAUNCH_POLICY, conductorStartable: true, upStart: { allowed: true, default: true },
@@ -92,7 +92,7 @@ export const NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN: readonly AdapterDefinition
92
92
  },
93
93
  {
94
94
  reviewerVariant: CODEX_REVIEWER_VARIANT,
95
- projection: { roleRank: 1, startRank: 1, helpRank: 1, plannerEligible: true },
95
+ projection: { roleRank: 1, startRank: 1, helpRank: 1, plannerEligible: true, conductorEligible: true, reviewerEligible: true },
96
96
  api: 1, kind: "codex", questionWaitMs: 45000, displayName: "Codex", family: "codex", transport: "codex-appserver",
97
97
  modelOverride: { boundary: "turn" },
98
98
  roles: Object.freeze(["implementer"]), defaultOnRoster: true, trust: { onPrem: false, hubSandboxed: false },
@@ -106,7 +106,7 @@ export const NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN: readonly AdapterDefinition
106
106
  },
107
107
  {
108
108
  reviewerVariant: KIMI_REVIEWER_VARIANT,
109
- projection: { roleRank: 2, startRank: 2, helpRank: 2, plannerEligible: true },
109
+ projection: { roleRank: 2, startRank: 2, helpRank: 2, plannerEligible: true, conductorEligible: false, reviewerEligible: true },
110
110
  api: 1, kind: "kimi", questionWaitMs: 45000, displayName: "Kimi Code", family: "kimi", transport: "acp",
111
111
  modelOverride: { boundary: "turn", acp: { admission: { nativeIdentity: true }, agentName: "Kimi Code CLI", version: "2.5.2",
112
112
  setter: "set_config_option", modelUpdate: "config_option_update", receipt: "docs/verification/2026-11-08-kimi-252-model-setter-1317.md" } },
@@ -123,7 +123,7 @@ export const NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN: readonly AdapterDefinition
123
123
  cli: { command: "kimi", entry: { lifecycleAdmission: true, execute: runKimiEntry }, preview: previewKimi, usage: [["ahub kimi [--print-command] [--mode tui|headless] [--model <alias>]", "default: Kimi's own TUI, pull-only via hub_inbox; no push, steer, watchdog, console approvals or automatic quota handoff. Select headless for ACP"]], launchConfigKeys: ["kimi_cmd", "peers.kimi.start_mode"], stopNotice: form => form === "tui" ? "Kimi belongs to its own TUI terminal; end it in that terminal" : "", startWords: form => ["kimi", "--mode", form] }, display: KIMI_DISPLAY,
124
124
  },
125
125
  {
126
- projection: { roleRank: 4, startRank: 0, helpRank: 6, plannerEligible: false },
126
+ projection: { roleRank: 4, startRank: 0, helpRank: 6, plannerEligible: false, conductorEligible: true, reviewerEligible: true },
127
127
  api: 1, kind: "pi", questionWaitMs: 300000, title: "hub", titlePersistence: "native", enabledSwitchStartOnly: true, displayName: "Pi", family: "pi", transport: "hub-native",
128
128
  modelOverride: { boundary: "turn" },
129
129
  roles: implementerRoles, defaultOnRoster: false, trust: { onPrem: false, hubSandboxed: true },
@@ -137,7 +137,7 @@ export const NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN: readonly AdapterDefinition
137
137
  cli: { command: "pi", entry: { lifecycleAdmission: false, execute: runPiEntry }, preview: previewPi, usage: [["ahub pi [--print-command] [--mode headless|tui | --headless] [--backend auto|dgx|mlx] [--model <alias>] [--session-id <id>] [--session-file <path>] [--replace-session]", "start Pi: its TUI in this terminal unless --headless or the start mode setting (peers.pi.start_mode) says headless; without a terminal the hub opens one or says how"]], launchConfigKeys: ["pi.cmd", "pi.backend", "pi.dgx_coding", "pi.dgx_fast", "pi.max_steps", "routing.pi", "peers.pi.start_mode"], previewArgs: ["--mode", "tui"], retainedTerminalNotice: piRetainedTerminalNotice, personOnlyFlags: ["--replace-session"], startWords: form => ["pi", "--mode", form] }, display: PI_DISPLAY,
138
138
  },
139
139
  {
140
- projection: { roleRank: 3, helpRank: 7, plannerEligible: false },
140
+ projection: { roleRank: 3, helpRank: 7, plannerEligible: false, conductorEligible: false, reviewerEligible: true },
141
141
  api: 1, kind: "local", questionWaitMs: 300000, title: "hub", displayName: "Local worker", family: "local", transport: "hub-native",
142
142
  modelOverride: { boundary: "turn" },
143
143
  roles: implementerRoles, defaultOnRoster: true, trust: { onPrem: true, hubSandboxed: true },
@@ -151,7 +151,7 @@ export const NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN: readonly AdapterDefinition
151
151
  cli: { command: "local", entry: { lifecycleAdmission: false, execute: runLocalEntry }, usage: [["ahub local [--route <id> | --model <id>]", "start the hub-native worker on the self-hosted models (routing.toml)"]], launchConfigKeys: ["local.deny", "local.bash_network", "local.network_allow", "local.max_steps", "local.read_allow", "routing.local"], startWords: () => ["local"] }, display: LOCAL_DISPLAY,
152
152
  },
153
153
  {
154
- projection: { roleRank: 6, startRank: 3, helpRank: 3, plannerEligible: true },
154
+ projection: { roleRank: 6, startRank: 3, helpRank: 3, plannerEligible: true, conductorEligible: true, reviewerEligible: true },
155
155
  api: 1, kind: "jcode", questionWaitMs: 45000, displayName: "Jcode", family: "jcode", transport: "acp",
156
156
  roles: implementerRoles, optional: true, defaultOnRoster: false, trust: { onPrem: false, hubSandboxed: false },
157
157
  start: { create: createJcode, preflight: jcodeStartPreflight, daemonPort: "owned-acp", forms: dualForms, defaultForm: "tui", explicitHeadlessMode: true, conductorStartable: true, upStart: { allowed: true }, hubSwitches: [], ownedFlags: [] },
@@ -2,6 +2,7 @@ import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, open
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { join } from "node:path";
4
4
  import { hubGitSync } from "../../hub/git.ts";
5
+ import { sameDirectory, shownValue } from "../same-directory.ts";
5
6
 
6
7
  export const JCODE_MCP_FILE = ".jcode/mcp.json", JCODE_MCP_NAME = "agent-hub-jcode";
7
8
  type Document = Record<string, unknown>;
@@ -24,8 +25,21 @@ const map = (doc: Document): Document => (doc.mcpServers ?? doc.servers ?? {}) a
24
25
  * hub tools act as the base peer. Each owned launch path supplies its own id instead (peerChildEnv for serve and ACP, the TUI launch env).
25
26
  * An entry written before this still hardcodes the id: `jcodeMcpReady` is false for it, and the launcher rewrites it.
26
27
  */
27
- const owned = (entry: unknown, cwd: string): entry is Document => object(entry) && object(entry.env) && entry.env.AGENTHUB_MODE === "tools"
28
- && (entry.env.AGENTHUB_PEER_ID === undefined || entry.env.AGENTHUB_PEER_ID === "jcode") && entry.env.AGENTHUB_PROJECT_DIR === cwd;
28
+ /**
29
+ * The first field that makes an existing entry not the hub's, or undefined when it is. The project dir is compared by real path (#1423): a project directory that was renamed, with the old
30
+ * path left as a symlink, still names this directory, so the hub's own entry from before the move is rewritten rather than refused as foreign.
31
+ */
32
+ function foreignField(entry: unknown, cwd: string): string | undefined {
33
+ if (!object(entry)) return "the entry is not an object";
34
+ if (!object(entry.env)) return "env is missing";
35
+ if (entry.env.AGENTHUB_MODE !== "tools") return "AGENTHUB_MODE is not tools";
36
+ if (entry.env.AGENTHUB_PEER_ID !== undefined && entry.env.AGENTHUB_PEER_ID !== "jcode") return "AGENTHUB_PEER_ID names another peer";
37
+ if (!sameDirectory(entry.env.AGENTHUB_PROJECT_DIR, cwd)) {
38
+ const named = shownValue(entry.env.AGENTHUB_PROJECT_DIR);
39
+ return `AGENTHUB_PROJECT_DIR ${named ? `${named} ` : ""}is not this project (${cwd})`;
40
+ }
41
+ return undefined;
42
+ }
29
43
 
30
44
  export function jcodeMcpEntry(cwd: string, stateDir: string, bundle: string) {
31
45
  return { command: "bun", args: ["run", bundle], shared: false, env: { AGENTHUB_MODE: "tools", AGENTHUB_DELIVERY_ONLY: "true", AGENTHUB_STATE_DIR: stateDir, AGENTHUB_PROJECT_DIR: cwd } };
@@ -48,7 +62,8 @@ export function jcodeMcpReady(cwd: string, stateDir: string, bundle: string): bo
48
62
  /** Only the console launcher calls this; daemon starts use jcodeMcpReady read-only. */
49
63
  export function configureJcodeMcp(cwd: string, stateDir: string, bundle: string, remove = false): { changed: boolean; tracked: boolean } {
50
64
  const current = inspect(cwd), servers = { ...map(current) }, existing = servers[JCODE_MCP_NAME];
51
- if (existing !== undefined && !owned(existing, cwd)) throw new Error("agent-hub-jcode is a foreign MCP entry; it was not changed");
65
+ const why = existing === undefined ? undefined : foreignField(existing, cwd);
66
+ if (why !== undefined) throw new Error(`agent-hub-jcode is a foreign MCP entry (${why}); it was not changed. If it is the hub's own entry from before the project moved, remove the ${JCODE_MCP_NAME} key from ${JCODE_MCP_FILE} and run ahub jcode again.`);
52
67
  if (remove) delete servers[JCODE_MCP_NAME]; else servers[JCODE_MCP_NAME] = jcodeMcpEntry(cwd, stateDir, bundle);
53
68
  const key = current.servers !== undefined ? "servers" : "mcpServers";
54
69
  const next = { ...current, ...(current[key] !== undefined || !remove ? { [key]: servers } : {}) };
@@ -1,3 +1,5 @@
1
+ import { quotaAccountUsage, type QuotaAccountUsage } from "../../hub/quota-account.ts";
2
+ import { types } from "node:util";
1
3
  import type { UsageWindow } from "../../hub/budget.ts";
2
4
 
3
5
  /** Codex `rateLimits` snapshot (account/rateLimits/read, account/rateLimits/updated) -> windows. */
@@ -27,3 +29,123 @@ export function claudeWindows(rateLimits: any): UsageWindow[] {
27
29
  }
28
30
  return out;
29
31
  }
32
+
33
+
34
+ /** Bounds inspection of native detail rows; the native availableCount remains authoritative. */
35
+ const MAX_RESET_CREDIT_DETAILS = 128;
36
+ const record = (value: unknown): Record<string, unknown> => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
37
+ const epochMillis = (value: unknown): number | undefined => {
38
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) return undefined;
39
+ const ms = value * 1000;
40
+ return Number.isSafeInteger(ms) && Number.isFinite(new Date(ms).getTime()) ? ms : undefined;
41
+ };
42
+
43
+ /** Codex 0.167.2 GetAccountRateLimitsResponse: no balance, account/credit id, title or description escapes. */
44
+ export function codexAccountUsage(snapshot: unknown): QuotaAccountUsage {
45
+ const value = record(snapshot), limits = record(value.rateLimits), credits = record(limits.credits), reset = record(value.rateLimitResetCredits);
46
+ const out: QuotaAccountUsage = {};
47
+ if (typeof value.ordinaryUsageAllowed === "boolean") out.ordinaryUsageAllowed = value.ordinaryUsageAllowed;
48
+ if (typeof credits.hasCredits === "boolean") out.hasCredits = credits.hasCredits;
49
+ if (typeof credits.unlimited === "boolean") out.unlimited = credits.unlimited;
50
+ const count = reset.availableCount;
51
+ if (typeof count === "number" && Number.isSafeInteger(count) && count >= 0) {
52
+ out.resetCreditsAvailable = count;
53
+ out.resetCreditsExpiryKnown = count === 0;
54
+ const rows = reset.credits;
55
+ // Native lists may be capped: a partial list cannot prove the earliest expiry across the full count.
56
+ if (count > 0 && Array.isArray(rows) && rows.length === count && rows.length <= MAX_RESET_CREDIT_DETAILS) {
57
+ let complete = true, earliest: number | undefined;
58
+ for (const item of rows) {
59
+ const row = record(item);
60
+ if (row.status !== "available" || row.resetType !== "codexRateLimits") { complete = false; break; }
61
+ if (row.expiresAt === null) continue; // explicitly non-expiring; absence instead means unknown
62
+ const expires = epochMillis(row.expiresAt);
63
+ if (expires === undefined) { complete = false; break; }
64
+ earliest = earliest === undefined ? expires : Math.min(earliest, expires);
65
+ }
66
+ out.resetCreditsExpiryKnown = complete;
67
+ if (complete && earliest !== undefined) out.resetCreditsExpireAt = earliest;
68
+ }
69
+ }
70
+ return quotaAccountUsage(out);
71
+ }
72
+
73
+ /** Preserve the existing window callback shape without forwarding raw account/credit data. */
74
+ export function codexQuotaWindowInput(value: unknown): unknown {
75
+ const raw = record(value);
76
+ const window = (value: unknown) => {
77
+ const row = record(value);
78
+ if (typeof row.usedPercent !== "number" || !Number.isFinite(row.usedPercent)) return null;
79
+ return { usedPercent: row.usedPercent,
80
+ ...(typeof row.windowDurationMins === "number" && Number.isFinite(row.windowDurationMins) ? { windowDurationMins: row.windowDurationMins } : {}),
81
+ ...(typeof row.resetsAt === "number" && Number.isFinite(row.resetsAt) ? { resetsAt: row.resetsAt } : {}) };
82
+ };
83
+ const reached = raw.rateLimitReachedType;
84
+ const known = ["usageLimitExceeded", "rate_limit_reached", "workspace_owner_credits_depleted", "workspace_member_credits_depleted", "workspace_owner_usage_limit_reached", "workspace_member_usage_limit_reached"];
85
+ return { primary: window(raw.primary), secondary: window(raw.secondary),
86
+ ...(reached ? { rateLimitReachedType: typeof reached === "string" && known.includes(reached) ? reached : "usageLimitExceeded" } : {}) };
87
+ }
88
+
89
+ /** Closed native failure metadata. No vendor message, account data or credit information leaves the decoder. */
90
+ export interface NativeReviewerQuota {
91
+ id: "5h" | "week";
92
+ used: 1;
93
+ windowMins: number;
94
+ source: "Claude reviewer quota" | "Codex reviewer quota" | "Kimi reviewer quota";
95
+ resetsAt?: number;
96
+ }
97
+ function nativeQuotaObject(value: unknown): Record<string, unknown> {
98
+ if (!value || typeof value !== "object" || Array.isArray(value) || types.isProxy(value)
99
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || Object.getOwnPropertySymbols(value).length) return {};
100
+ const fields = Object.getOwnPropertyDescriptors(value);
101
+ if (Object.values(fields).some(field => !Object.hasOwn(field, "value") || !field.enumerable)) return {};
102
+ return Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, field.value]));
103
+ }
104
+ /** Revalidate even a backend's typed result before a host callback receives it. */
105
+ export function nativeReviewerQuota(value: unknown): NativeReviewerQuota | undefined {
106
+ const row = nativeQuotaObject(value);
107
+ if (row.used !== 1 || row.id !== "5h" && row.id !== "week" || !["Claude reviewer quota", "Codex reviewer quota", "Kimi reviewer quota"].includes(row.source as string)) return;
108
+ const expected = row.id === "week" ? 10_080 : 300;
109
+ if (row.windowMins !== expected) return;
110
+ const resetsAt = typeof row.resetsAt === "number" && Number.isSafeInteger(row.resetsAt) && row.resetsAt > 0 && Number.isFinite(new Date(row.resetsAt).getTime()) ? row.resetsAt : undefined;
111
+ return { id: row.id, used: 1, windowMins: expected, source: row.source as NativeReviewerQuota["source"], ...(resetsAt === undefined ? {} : { resetsAt }) };
112
+ }
113
+ /** Claude Agent SDK native rate_limit_event uses camelCase inside rate_limit_info, not the SDK's snake_case projection. */
114
+ export function claudeReviewerQuota(value: unknown): NativeReviewerQuota | undefined {
115
+ const row = nativeQuotaObject(value), base = { id: "5h" as const, used: 1 as const, windowMins: 300, source: "Claude reviewer quota" as const };
116
+ if (row.type === "assistant" && row.error === "rate_limit") return base;
117
+ if (row.type !== "rate_limit_event") return;
118
+ const info = nativeQuotaObject(row.rate_limit_info);
119
+ if (info.status !== "rejected") return;
120
+ const kind = info.rateLimitType;
121
+ const known = kind === "five_hour" || kind === "seven_day" || kind === "seven_day_opus" || kind === "seven_day_sonnet";
122
+ const id = kind === "five_hour" ? "5h" as const : "week" as const;
123
+ const resetsAt = known ? epochMillis(info.resetsAt) : undefined;
124
+ return known ? { ...base, id, windowMins: id === "week" ? 10_080 : 300, ...(resetsAt === undefined ? {} : { resetsAt }) } : base;
125
+ }
126
+ /** Codex 0.166.0 exec ThreadErrorEvent is message-only. Never read assistant/item/tool prose or app-server-shaped invented fields. */
127
+ export const CODEX_EXEC_QUOTA_PREFIX = "You’ve hit your usage limit.";
128
+ const CODEX_EXEC_QUOTA_MESSAGES = [
129
+ "Your workspace is out of credits. Add credits to continue.",
130
+ "Your workspace is out of credits. Ask your workspace owner to refill in order to continue.",
131
+ "You hit your spend cap set in your workspace. Increase your spend cap to continue.",
132
+ "You hit your spend cap set by the owner of your workspace. Ask an owner to increase your spend cap to continue.",
133
+ ];
134
+ export function codexReviewerQuota(value: unknown): NativeReviewerQuota | undefined {
135
+ const row = nativeQuotaObject(value);
136
+ const message = row.type === "error" ? row.message : row.type === "turn.failed" ? nativeQuotaObject(row.error).message : undefined;
137
+ if (typeof message !== "string" || !(message.startsWith(CODEX_EXEC_QUOTA_PREFIX) || message.startsWith("You’ve hit your usage limit for ") || CODEX_EXEC_QUOTA_MESSAGES.includes(message))) return;
138
+ return { id: "5h", used: 1, windowMins: 300, source: "Codex reviewer quota" };
139
+ }
140
+
141
+ /**
142
+ * ponytail: only the owned nonzero-exit stderr line observed on Kimi 2.2.0 is classified (2026-10-19 receipt).
143
+ * 2.5.2 remains unverified for this diagnostic. Replace with a version-pinned typed native frame when one exists.
144
+ */
145
+ export function kimiReviewerQuotaOnExit(value: { exitCode: number | null; stderr: { status: "complete"; text: string } | { status: "unknown" } }): NativeReviewerQuota | undefined {
146
+ if (typeof value.exitCode !== "number" || value.exitCode === 0 || value.stderr.status !== "complete" || !value.stderr.text.endsWith("\n")) return;
147
+ const hit = value.stderr.text.split(/\r?\n/).some(line => line.startsWith("error: failed to run prompt: provider.") && line.includes("usage limit"));
148
+ if (!hit) return;
149
+ // The receipt supplied no exact reset. Its displayed weekly wording supplies no guessed timestamp.
150
+ return { id: "5h", used: 1, windowMins: 300, source: "Kimi reviewer quota" };
151
+ }
@@ -48,6 +48,7 @@ export const CLAUDE_RECOVERY_SESSION: SessionPolicy = {
48
48
  personFresh: true, missingEvidence: "transcript",
49
49
  };
50
50
  export const PI_RECOVERY_SESSION: SessionPolicy = {
51
+ restoreVersionGate: "pi",
51
52
  resumeArgv: binding => ["pi", "--mode", "tui", ...(binding.backend ? ["--backend", binding.backend] : []), ...(binding.model ? ["--model", binding.model] : []),
52
53
  ...(binding.sessionFile ? ["--session-file", binding.sessionFile] : ["--session-id", binding.sessionId])],
53
54
  personFresh: false,
@@ -75,11 +76,13 @@ export const KIMI_RECOVERY_SESSION: SessionPolicy = {
75
76
  };
76
77
  export const LOCAL_RECOVERY_SESSION: SessionPolicy = { restoreArgs: startupArgs };
77
78
  export const JCODE_RECOVERY_SESSION: SessionPolicy = {
79
+ restoreVersionGate: "jcode",
78
80
  legacyTargetSupport: { file: "src/hub/peer-catalog.ts", exportName: "OPTIONAL_PEERS", refusal: "target does not support Jcode; end it and make a new plan, or choose a supporting target; runtimes unchanged" },
79
81
  recoveryRefusal: (_peer, phase = "plan") => phase === "restore" ? undefined : "jcode: source-pinned native load cannot prove conversation identity; end the peer and make a new recovery plan before effects",
80
82
  restoreArgs: peer => ({ ...startupArgs(peer), ...(peer.sessionId ? { "session-id": peer.sessionId } : {}), ...(peer.args?.providerProfile ? { "provider-profile": peer.args.providerProfile } : {}) }),
81
83
  };
82
84
  export const QWEN_RECOVERY_SESSION: SessionPolicy = {
85
+ restoreVersionGate: "qwen",
83
86
  legacyTargetSupport: { file: "src/hub/peer-catalog.ts", exportName: "OPTIONAL_PEERS", refusal: "target does not support Qwen; end Qwen and make a new plan, or choose a supporting target; runtimes unchanged" },
84
87
  restoreArgs: peer => ({ ...startupArgs(peer), ...(peer.sessionId ? { "session-id": peer.sessionId } : {}) }),
85
88
  // #286 Part 3: the Qwen TUI belongs to the person's terminal. It is never restored as a headless worker; `ahub qwen --mode tui` resumes it (qwen -r <session>) from its saved offset.
@@ -13,7 +13,7 @@ import { createQwenDual } from "./native-factories.ts";
13
13
  export const QWEN_DEFINITION: AdapterDefinition = {
14
14
  api: 1,
15
15
  kind: "qwen",
16
- projection: { roleRank: 5, helpRank: 5, plannerEligible: true },
16
+ projection: { roleRank: 5, helpRank: 5, plannerEligible: true, conductorEligible: false, reviewerEligible: true },
17
17
  displayName: "Qwen Code",
18
18
  family: "qwen",
19
19
  transport: "acp",
@@ -5,6 +5,9 @@ import { homedir, tmpdir } from "node:os";
5
5
  import { basename, join, resolve } from "node:path";
6
6
  import { stopOwnedProcess, trackGroup } from "../hub/child-process.ts";
7
7
  import { realPath } from "../hub/project.ts";
8
+ import { kimiReviewerQuotaOnExit } from "./definitions/native-quota.ts";
9
+ import { ownedKimiSession, type KimiWireRow } from "./kimi-wire-usage.ts";
10
+ import { KimiUsage } from "../hub/kimi-usage.ts";
8
11
  import type { ReviewerBackend, ReviewerLaunch, ReviewerPrepareContext } from "./reviewer-print.ts";
9
12
  import { assertCleanCwdAncestors, checkKimiReviewPolicy, kimiReviewFingerprint as hash, projectKimiReviewPolicyBinding, readKimiReviewFile as read } from "./kimi-review-policy.ts";
10
13
  import { startKimiReviewPolicyWatch, type KimiReviewPolicyFactory } from "./kimi-review-policy-worker.ts";
@@ -86,6 +89,19 @@ export async function stopKimiReview(child: ChildProcess, locks: readonly string
86
89
  await stopOwnedProcess(child, { group: true });
87
90
  }
88
91
 
92
+ /** Usage only: the error diagnostic exception never reads wire or log error content. */
93
+ export function readKimiReviewerUsage(home: string, startedAt: number): readonly KimiWireRow[] | undefined {
94
+ const session = ownedKimiSession(home);
95
+ if (!session) return;
96
+ const rows: KimiWireRow[] = []; let now = startedAt;
97
+ const usage = new KimiUsage({ home, now: () => now, ceiling: () => 0, session: () => session,
98
+ record: (_peer, row) => { rows.push(row); }, report: () => {}, forget: () => {}, notice: () => {} });
99
+ try {
100
+ usage.turnStarted("owned-review"); now = Date.now(); usage.collect("owned-review", false, true);
101
+ return usage.complete("owned-review") && rows.length ? rows : undefined;
102
+ } finally { usage.stop(); }
103
+ }
104
+
89
105
  export async function prepareKimiReviewer(context: ReviewerPrepareContext, policyFactory: KimiReviewPolicyFactory = startKimiReviewPolicyWatch): Promise<ReviewerLaunch | { unavailable: string }> {
90
106
  let own: string | undefined;
91
107
  try {
@@ -131,6 +147,12 @@ export async function prepareKimiReviewer(context: ReviewerPrepareContext, polic
131
147
  };
132
148
  return { command, args: ["-p", "Review the supplied task facts and record the evidence-based verdict with hub_review.", "--output-format", "stream-json", "--agent-file", agentFile, "--skills-dir", skills],
133
149
  cwd, env, envMode: "replace", cleanup, watchCurrent: true,
150
+ readUsage: (startedAt, receive) => {
151
+ const rows = readKimiReviewerUsage(tool, startedAt);
152
+ if (!rows) return false;
153
+ for (const row of rows) receive({ input_tokens: row.inputOther, output_tokens: row.output, cache_creation_input_tokens: row.inputCacheCreation, cache_read_input_tokens: row.inputCacheRead }, { id: row.id, at: row.at, ...(row.model ? { model: row.model } : {}) });
154
+ return true;
155
+ },
134
156
  stop: child => stopKimiReview(child, [join(sources[1]!, "kimi-code.lock"), join(sources[1]!, `${selected.lock}.lock`)]),
135
157
  current: () => !cleaned && !context.signal.aborted && checkKimiReviewPolicy(binding),
136
158
  startPolicyWatch: () => {
@@ -161,4 +183,5 @@ export async function prepareKimiReviewer(context: ReviewerPrepareContext, polic
161
183
 
162
184
  export const kimiReviewerBackend: ReviewerBackend = {
163
185
  id: "kimi", taskMcp: true, nativePolicy: true, prepare: context => prepareKimiReviewer(context),
186
+ failureOnExit: kimiReviewerQuotaOnExit,
164
187
  };
@@ -1,4 +1,4 @@
1
- import { closeSync, fstatSync, lstatSync, openSync, readSync as fsReadSync, readdirSync, statSync } from "node:fs";
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync as fsReadSync, readdirSync, statSync } from "node:fs";
2
2
  import { createHash } from "node:crypto";
3
3
  import { join, sep } from "node:path";
4
4
  import { realPath } from "../hub/project.ts";
@@ -85,6 +85,43 @@ class Unknown extends Error { constructor(readonly reason: KimiWireReason) { sup
85
85
  const count = (value: unknown): number | undefined => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
86
86
  const inside = (root: string, path: string): boolean => path.startsWith(root + sep);
87
87
 
88
+ type IndexRead = (fd: number, buffer: Buffer, offset: number, length: number, position: number) => number;
89
+ function readIndex(home: string, read: IndexRead = fsReadSync, owned = false): string {
90
+ let fd: number;
91
+ try { fd = openSync(join(home, "session_index.jsonl"), owned ? constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK : "r"); } catch { throw new Unknown("no-index"); }
92
+ try {
93
+ const stat = fstatSync(fd);
94
+ if (!stat.isFile() || stat.size > INDEX_CAP) throw new Unknown("io-error");
95
+ const buffer = Buffer.allocUnsafe(stat.size); let got = 0;
96
+ while (got < stat.size) { const n = read(fd, buffer, got, stat.size - got, got); if (n <= 0) break; got += n; }
97
+ if (owned && (got !== stat.size || fstatSync(fd).size !== stat.size)) throw new Unknown("partial-line");
98
+ return buffer.toString("utf8", 0, got);
99
+ } catch (error) { throw error instanceof Unknown ? error : new Unknown("io-error"); }
100
+ finally { closeSync(fd); }
101
+ }
102
+
103
+ /** The fresh owned reviewer profile may contain exactly one native session. This is not a hub observer UUID. */
104
+ export function ownedKimiSession(home: string): string | undefined {
105
+ try {
106
+ const root = realPath(home), sessions = realPath(join(home, "sessions"));
107
+ if (!inside(root, sessions)) return;
108
+ const text = readIndex(home, fsReadSync, true);
109
+ if (!text.endsWith("\n")) return;
110
+ const entries = new Map<string, string>();
111
+ for (const line of text.split("\n")) {
112
+ if (!line.trim()) continue;
113
+ if (Buffer.byteLength(line) > LINE_CAP) return;
114
+ const row = JSON.parse(line) as { sessionId?: unknown; sessionDir?: unknown };
115
+ if (typeof row.sessionId !== "string" || !SESSION_ID.test(row.sessionId) || typeof row.sessionDir !== "string") return;
116
+ const directory = realPath(row.sessionDir);
117
+ if (!inside(sessions, directory) || entries.has(row.sessionId) && entries.get(row.sessionId) !== directory) return;
118
+ entries.set(row.sessionId, directory);
119
+ if (entries.size > 1) return;
120
+ }
121
+ return entries.size === 1 ? [...entries.keys()][0] : undefined;
122
+ } catch { return; }
123
+ }
124
+
88
125
  export class KimiWireReader {
89
126
  private readonly home: string;
90
127
  private readonly sessionId: string;
@@ -178,21 +215,7 @@ export class KimiWireReader {
178
215
 
179
216
  /** The index, opened once and sized from that descriptor, so a link swapped in between a check and the read cannot lift the bound. */
180
217
  private index(): string {
181
- let fd: number;
182
- try { fd = openSync(join(this.home, "session_index.jsonl"), "r"); } catch { throw new Unknown("no-index"); }
183
- try {
184
- const stat = fstatSync(fd);
185
- if (!stat.isFile() || stat.size > INDEX_CAP) throw new Unknown("io-error");
186
- const buffer = Buffer.allocUnsafe(stat.size);
187
- let got = 0;
188
- while (got < stat.size) {
189
- const n = this.readBytes(fd, buffer, got, stat.size - got, got);
190
- if (n <= 0) break;
191
- got += n;
192
- }
193
- return buffer.toString("utf8", 0, got);
194
- } catch (error) { throw error instanceof Unknown ? error : new Unknown("io-error"); }
195
- finally { closeSync(fd); }
218
+ return readIndex(this.home, (fd, buffer, offset, length, position) => this.readBytes(fd, buffer, offset, length, position));
196
219
  }
197
220
 
198
221
  /** `agents/<name>/wire.jsonl` of every agent that has one: the main agent and its sub-agents. */
@@ -38,6 +38,9 @@ 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;
41
44
  /** Host-owned conditional instruction, sampled once per delivered turn. */
42
45
  titlePreface?: () => string | undefined;
43
46
  cwd: string;
@@ -243,7 +246,7 @@ export class LocalPeer extends BasePeer {
243
246
  await this.requireBudget(envs, "model_calls");
244
247
  if (generation !== this.turn) throw new Error("route belongs to an ended turn");
245
248
  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) : [])];
249
+ 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).filter(tool => tool.name !== "hub_delivery_retry"), ...CONDUCTOR_TOOLS].concat(SESSION_TITLE_TOOL).map(asFunction) : [])];
247
250
  this.releaseObserverInput(this.currentObserverInputContext, envs);
248
251
  const result = await this.opts.omni.chat({ model, messages, ...(tools ? { tools } : {}), ...(judge ? { max_tokens: maxTokens ?? 2048 } : {}) }, { signal, ...(pii ? { onCampusOnly: true } : {}) });
249
252
  this.recordUsage(result, model, task);
@@ -496,7 +499,7 @@ export class LocalPeer extends BasePeer {
496
499
  progress.answerComplete = concluded.complete;
497
500
  return concluded.answer;
498
501
  }
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;
502
+ 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
503
  const results: ChatMessage[] = [];
501
504
  try {
502
505
  for (const call of res.message.tool_calls) {
@@ -667,7 +670,7 @@ export class LocalPeer extends BasePeer {
667
670
  }
668
671
  const fixedModel = selection?.model ?? policy?.fixedModel ?? this.opts.fixedModel;
669
672
  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) : [])];
673
+ const tools = [...this.toolSchemas(), ...(this.opts.taskTool ? [...profileTaskTools(this.opts.profile, this.opts.sdlcStages, this.opts.sdlcCriteria, this.opts.sdlcAudit, this.opts.sdlcSurvey).filter(tool => tool.name !== "hub_delivery_retry"), ...CONDUCTOR_TOOLS].concat(SESSION_TITLE_TOOL).map(asFunction) : [])];
671
674
  const signal = this.abort!.signal;
672
675
  const messages: ChatMessage[] = [{ role: "system", content: fixedPrompt }, ...this.history, ...turnMsgs];
673
676
  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>; }
@@ -209,6 +211,8 @@ export class PiPeer extends BasePeer {
209
211
  private owner = randomUUID();
210
212
  private _tuiLaunch?: PiTuiLaunch;
211
213
  private requestedModel = "";
214
+ /** #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. */
215
+ private turnModel: ModelObservation | undefined;
212
216
  private baselineRequestedModel = "";
213
217
  private runtimeModelSelected = false;
214
218
  private starting?: Promise<void>;
@@ -772,6 +776,8 @@ export class PiPeer extends BasePeer {
772
776
  this.runtimeModelSelected = selection?.model !== undefined;
773
777
  }
774
778
  if (rosterEpoch !== this.rosterEpoch || !this.acceptingTools) throw new Error("Pi is off roster or stopped");
779
+ await this.captureTurnModel(requested);
780
+ if (rosterEpoch !== this.rosterEpoch || !this.acceptingTools) throw new Error("Pi is off roster or stopped");
775
781
  this.noteActivity();
776
782
  attempted = true;
777
783
  if (deliveryId) this.activeDeliveryIds.add(deliveryId);
@@ -847,6 +853,22 @@ export class PiPeer extends BasePeer {
847
853
  }
848
854
  }
849
855
 
856
+ /**
857
+ * #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
858
+ * itself set through `set_model` (Pi acknowledged it), which is only `configured`. A read that fails never fails the delivery.
859
+ */
860
+ private async captureTurnModel(requested: string | undefined): Promise<void> {
861
+ this.turnModel = undefined;
862
+ if (this.opts.mode !== "tui") {
863
+ try {
864
+ const state = await this.waitRpc("get_state", 5_000);
865
+ const id = state.success === true ? stateModelId(state.data) : undefined;
866
+ if (id) { this.turnModel = { model: id, evidence: "session" }; return; }
867
+ } catch { /* optional metadata: the turn goes on without it */ }
868
+ }
869
+ if (requested) this.turnModel = { model: requested, evidence: "configured" };
870
+ }
871
+ observedModel(): ModelObservation | undefined { const model = this.turnModel; this.turnModel = undefined; return model; }
850
872
  getRequestedModel(): string { return this.requestedModel; }
851
873
  getBaselineRequestedModel(): string { return this.baselineRequestedModel; }
852
874
  async setRequestedModel(model: string): Promise<void> {
@@ -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,7 +337,11 @@ 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. */
@@ -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) {