@staix/agent-hub 0.37.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.
- package/CHANGELOG.md +55 -0
- package/README.md +17 -7
- package/docs/adding-an-ai-tool.md +6 -4
- package/docs/agent-notes/README.md +16 -0
- package/docs/agent-notes/adapters.md +4 -2
- package/docs/agent-notes/budget.md +8 -0
- package/docs/agent-notes/daemon.md +15 -8
- package/docs/agent-notes/local-worker.md +1 -1
- package/docs/agent-notes/security-review.md +55 -0
- package/docs/agent-notes/tasks.md +15 -4
- package/docs/agent-notes/tests.md +3 -2
- package/docs/design/adapters.md +51 -0
- package/docs/design/agent-hub-architecture.md +29 -1
- package/docs/design/guidance-probes.md +365 -0
- package/docs/design/task-board.md +151 -5
- package/docs/dogfood.md +22 -7
- package/docs/events.md +3 -3
- package/docs/memory.md +5 -5
- package/docs/operations.md +189 -32
- package/docs/profiles.md +101 -9
- package/docs/quickstart.md +38 -4
- package/docs/research.md +6 -3
- package/docs/roles.md +52 -0
- package/docs/sdlc.md +187 -1
- package/docs/security.md +56 -13
- package/docs/text-projection.md +1 -0
- package/docs/verification/2026-11-11-0.38.0.md +41 -0
- package/docs/verification/2026-11-11-guidance-probe-t3-1226.md +85 -0
- package/docs/verification/2026-11-11-guidance-probe-t4-1226.md +65 -0
- package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
- package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
- package/docs/verification/2026-11-14-0.39.0.md +51 -0
- package/docs/verified.json +48 -25
- package/package.json +3 -3
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +1989 -474
- package/plugins/agent-hub/server.js +2056 -512
- package/src/adapters/acp-model-policy.ts +1 -1
- package/src/adapters/acp-session-model.ts +35 -0
- package/src/adapters/acp.ts +14 -0
- package/src/adapters/agy/definition.ts +1 -1
- package/src/adapters/agy/hooks.ts +7 -0
- package/src/adapters/claude-channel.ts +3 -2
- package/src/adapters/claude-implementer.ts +8 -0
- package/src/adapters/claude-print-child.ts +26 -2
- package/src/adapters/claude-print.ts +4 -0
- package/src/adapters/codex-appserver.ts +90 -16
- package/src/adapters/codex-review-isolation.ts +2 -0
- package/src/adapters/compat.ts +4 -4
- package/src/adapters/conformance/fakes/acp-server.ts +11 -2
- package/src/adapters/conformance/fakes/app-server.ts +5 -1
- package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
- package/src/adapters/definitions/builtin-metadata.ts +6 -6
- package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
- package/src/adapters/definitions/native-quota.ts +122 -0
- package/src/adapters/definitions/native-recovery.ts +3 -0
- package/src/adapters/definitions/qwen.ts +1 -1
- package/src/adapters/kimi-review.ts +23 -0
- package/src/adapters/kimi-wire-usage.ts +39 -16
- package/src/adapters/local-probe.ts +65 -6
- package/src/adapters/local-worker.ts +6 -3
- package/src/adapters/pi-state-model.ts +12 -0
- package/src/adapters/pi.ts +22 -0
- package/src/adapters/print-result-model.ts +24 -0
- package/src/adapters/registry-types.ts +10 -1
- package/src/adapters/registry.ts +19 -2
- package/src/adapters/reviewer-print.ts +130 -15
- package/src/adapters/role-eligibility.ts +99 -0
- package/src/adapters/same-directory.ts +16 -0
- package/src/cli/agy-mcp.ts +18 -7
- package/src/cli/console-state.ts +3 -1
- package/src/cli/free-text.ts +20 -0
- package/src/cli/handoff-args.ts +1 -1
- package/src/cli/help.ts +61 -6
- package/src/cli/identity.ts +10 -4
- package/src/cli/init-prompt.ts +31 -2
- package/src/cli/init-roles.ts +156 -0
- package/src/cli/init-settings.ts +24 -2
- package/src/cli/init.ts +141 -17
- package/src/cli/main.ts +216 -56
- package/src/cli/model.ts +1 -1
- package/src/cli/output.ts +64 -5
- package/src/cli/preview.ts +1 -1
- package/src/cli/recovery-launch.ts +114 -0
- package/src/cli/recovery-package.ts +14 -7
- package/src/cli/recovery-version-preflight.ts +104 -0
- package/src/cli/role-doctor.ts +39 -0
- package/src/cli/sdlc-output.ts +66 -1
- package/src/cli/study-output.ts +54 -0
- package/src/cli/study.ts +14 -1
- package/src/cli/terminal-recovery.ts +14 -0
- package/src/cli/upgrade-presentation.ts +4 -0
- package/src/cli/upgrade-restore-state.ts +12 -3
- package/src/cli/upgrade-runtime.ts +41 -3
- package/src/cli/upgrade.ts +8 -4
- package/src/hub/advisor-survey.ts +139 -0
- package/src/hub/audit-source.ts +66 -0
- package/src/hub/board.ts +479 -14
- package/src/hub/budget.ts +54 -4
- package/src/hub/bus.ts +2 -2
- package/src/hub/conductor.ts +14 -8
- package/src/hub/config-apply.ts +2 -1
- package/src/hub/config-edit-host.ts +77 -5
- package/src/hub/considered-findings.ts +47 -0
- package/src/hub/control-client.ts +1 -1
- package/src/hub/daemon.ts +373 -66
- package/src/hub/deliverable-files.ts +17 -1
- package/src/hub/dogfood-profile.ts +3 -2
- package/src/hub/envelope.ts +6 -1
- package/src/hub/events.ts +23 -2
- package/src/hub/folder-trigger.ts +11 -4
- package/src/hub/guidance-probe-store.ts +345 -14
- package/src/hub/guidance-probes.ts +338 -4
- package/src/hub/hub-tools.ts +88 -16
- package/src/hub/kimi-usage.ts +34 -2
- package/src/hub/lifecycle-schema.ts +3 -3
- package/src/hub/manager.ts +24 -1
- package/src/hub/memory-profile.ts +9 -1
- package/src/hub/memory-sync-state.ts +1 -0
- package/src/hub/model-overrides.ts +2 -1
- package/src/hub/no-writes.ts +2 -0
- package/src/hub/operational-authority.ts +8 -2
- package/src/hub/operational-view.ts +5 -1
- package/src/hub/peers.ts +2 -0
- package/src/hub/person-command.ts +25 -0
- package/src/hub/plan-conformance.ts +20 -2
- package/src/hub/quota-account.ts +34 -0
- package/src/hub/recovery-policy.ts +18 -4
- package/src/hub/research-evidence.ts +51 -3
- package/src/hub/research.ts +77 -13
- package/src/hub/restart.ts +14 -0
- package/src/hub/review-budget.ts +88 -0
- package/src/hub/review-findings.ts +93 -12
- package/src/hub/reviewer-pool-config.ts +6 -2
- package/src/hub/reviewer-pool.ts +39 -6
- package/src/hub/routing.ts +7 -3
- package/src/hub/sdlc-merge.ts +1 -1
- package/src/hub/sdlc-queue.ts +14 -4
- package/src/hub/sdlc-release.ts +1 -1
- package/src/hub/sdlc.ts +10 -6
- package/src/hub/security-audit.ts +178 -0
- package/src/hub/security-pass.ts +115 -0
- package/src/hub/settings.ts +11 -5
- package/src/hub/source-read.ts +80 -2
- package/src/hub/sources.ts +57 -9
- package/src/hub/startup-event-seeds.ts +5 -3
- package/src/hub/startup-timing.ts +1 -0
- package/src/hub/supervision.ts +3 -2
- package/src/hub/synthesis-readiness.ts +279 -0
- package/src/hub/tasks.ts +1131 -72
- package/src/hub/text-projection.ts +11 -1
- package/src/local/probe-types.ts +2 -0
- package/src/local/probe-workspace.ts +191 -2
- package/src/memory/capture.ts +2 -1
- package/src/ui/guidance-panel.ts +34 -2
- package/src/ui/guidance-view.ts +33 -0
- package/src/ui/index.html +3 -0
- package/src/ui/office-model.ts +11 -3
- package/src/ui/office-space.ts +50 -30
- package/src/ui/plugin.ts +31 -14
- package/templates/AGENTS.block.md +14 -14
- package/templates/profiles/general.json +1 -1
- package/templates/profiles/research.json +1 -1
- package/templates/profiles/writing.json +1 -1
|
@@ -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
|
-
|
|
28
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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. */
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { LocalPeer, localProbeFingerprints, prepareLocalProbeInput } from "./local-worker.ts";
|
|
3
3
|
import { GUIDANCE_PROBE_LIMITS, GUIDANCE_PROBE_MODEL, guidanceProbeCanonical, guidanceProbeManifestKey, probeHash,
|
|
4
|
-
type ProbeFakeLaunch, type ProbeFakeObservation, type ProbeReservation, type ProbeResourceCharges, type ProbeSlot, type ProbeStoredState } from "../hub/guidance-probes.ts";
|
|
5
|
-
import { materializeProbeWorkspace, probeWorkspaceCurrent, PROBE_WORKSPACE_LIMITS,
|
|
4
|
+
type ProbeFakeLaunch, type ProbeFakeObservation, type ProbeMeasuredSession, type ProbeReceiptLimit, type ProbeReservation, type ProbeRetainedRecord, type ProbeResourceCharges, type ProbeSlot, type ProbeStoredState } from "../hub/guidance-probes.ts";
|
|
5
|
+
import { collectProbeOutput, materializeProbeWorkspace, probeWorkspaceCurrent, PROBE_WORKSPACE_LIMITS, removeRetained, retainProbeOutput,
|
|
6
6
|
type ProbeWorkspace } from "../local/probe-workspace.ts";
|
|
7
7
|
import { ProbeConfinementError, requireProbeConfinement, verifyProbeConfinement, type ProbeConfinement } from "../local/probe-sandbox.ts";
|
|
8
8
|
import { ProbeLocalError, probeLocalEffect, type ProbeLocalAdapter, type ProbeLocalAdapterOptions, type ProbeLocalEffectScope,
|
|
@@ -25,6 +25,8 @@ interface Owned {
|
|
|
25
25
|
closeUnknown?: () => Promise<void>;
|
|
26
26
|
closed: boolean;
|
|
27
27
|
closeFailed?: boolean;
|
|
28
|
+
/** Output collected and retained once, after the stop reported quiescence and before the host releases the workspace. */
|
|
29
|
+
harvest?: { output: ProbeMeasuredSession["output"]; scratchBytes: number; limits: ProbeReceiptLimit[]; retained?: ProbeMeasuredSession["retained"] };
|
|
28
30
|
}
|
|
29
31
|
const bytesHash = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
|
|
30
32
|
const reservationKey = (reservation: ProbeReservation) => probeHash(guidanceProbeCanonical(reservation));
|
|
@@ -39,10 +41,14 @@ export function createGuidanceProbeLocalAdapter(options: ProbeLocalAdapterOption
|
|
|
39
41
|
if (options.fixture && options.fixture.evidence !== "fixture_only") throw new ProbeLocalError("invalid");
|
|
40
42
|
const current = options.current.bind(options), resolveInput = options.resolveInput.bind(options), permit = options.permit.bind(options), omni = options.omni;
|
|
41
43
|
const workspaceOwned = options.workspaceOwned?.bind(options);
|
|
44
|
+
const retentionRoot = options.retentionRoot;
|
|
42
45
|
const fixture = options.fixture && Object.freeze({ materialize: options.fixture.materialize.bind(options.fixture), confine: options.fixture.confine.bind(options.fixture) });
|
|
43
46
|
const config = Object.freeze({ maxSteps: options.config.maxSteps, maxOutputTokens: options.config.maxOutputTokens,
|
|
44
47
|
...(options.config.tokenUpperBound === undefined ? {} : { tokenUpperBound: options.config.tokenUpperBound }) });
|
|
45
48
|
const prepared = new Map<string, Prepared>(), owned = new Map<string, Owned>(), completed = new WeakSet<ProbeReservation>();
|
|
49
|
+
// Every retention directory this adapter created, by canonical record. `discardRetained` removes only a record that is still exactly one of these: the host
|
|
50
|
+
// can hand back nothing else, so a forged or altered record never reaches a delete. Removal is by the identity captured at creation (`removeRetained`).
|
|
51
|
+
const retainedHere = new Map<string, ProbeRetainedRecord>();
|
|
46
52
|
const prepare = async (state: ProbeStoredState, slot: ProbeSlot, guidance: string): Promise<Prepared> => {
|
|
47
53
|
current();
|
|
48
54
|
state = freeze(JSON.parse(JSON.stringify(state)) as ProbeStoredState);
|
|
@@ -86,11 +92,54 @@ export function createGuidanceProbeLocalAdapter(options: ProbeLocalAdapterOption
|
|
|
86
92
|
entry.closed = true;
|
|
87
93
|
} catch { entry.closeFailed = true; throw new ProbeLocalError("interrupted"); }
|
|
88
94
|
};
|
|
89
|
-
|
|
95
|
+
/**
|
|
96
|
+
* Collect, then retain, the declared output. This runs only AFTER `close` returned: the peer and the confinement have then reported quiescence, so no
|
|
97
|
+
* child can still be writing (the contract's Sealing order), and before the host releases the workspace it owns. When the stop failed or is uncertain
|
|
98
|
+
* nothing is read at all: the output of a process tree that may still be running is not evidence. It never throws: a failure is recorded as a limit,
|
|
99
|
+
* which can only keep the receipt from being a success. The declared caps hold here too: past either, nothing is retained and the receipt carries
|
|
100
|
+
* `storage_over_cap`.
|
|
101
|
+
*/
|
|
102
|
+
const harvestOutput = (entry: Owned, ready: Prepared): void => {
|
|
103
|
+
if (entry.harvest || !entry.workspace) return;
|
|
104
|
+
if (!entry.closed || entry.closeFailed) { entry.harvest = { output: { v: 1, entries: [], excluded: [], totalBytes: 0 }, scratchBytes: 0, limits: ["output_truncated"] }; return; }
|
|
105
|
+
const limits = ready.state.registration.manifest.limits;
|
|
106
|
+
try {
|
|
107
|
+
const collected = collectProbeOutput(entry.workspace, limits.outputBytes);
|
|
108
|
+
const harvest: NonNullable<Owned["harvest"]> = { output: collected.manifest, scratchBytes: collected.scratchBytes, limits: [] };
|
|
109
|
+
// Scratch deeper than the walk limit was not fully measured: treat its size as unknown, which is over the cap.
|
|
110
|
+
const over = collected.scratchUnmeasured || collected.scratchBytes > limits.scratchBytes || collected.manifest.totalBytes > limits.outputBytes;
|
|
111
|
+
if (over) harvest.limits.push("storage_over_cap");
|
|
112
|
+
else if (retentionRoot && collected.manifest.entries.length > 0) {
|
|
113
|
+
try {
|
|
114
|
+
harvest.retained = retainProbeOutput(entry.workspace, collected, retentionRoot);
|
|
115
|
+
retainedHere.set(guidanceProbeCanonical(harvest.retained), harvest.retained);
|
|
116
|
+
// The host discards right after the launch returns, so only recent records matter; a sealed one is never asked for again. Bounded, oldest first.
|
|
117
|
+
while (retainedHere.size > GUIDANCE_PROBE_LIMITS.slots) retainedHere.delete(retainedHere.keys().next().value!);
|
|
118
|
+
} catch { harvest.limits.push("output_truncated"); }
|
|
119
|
+
}
|
|
120
|
+
entry.harvest = harvest;
|
|
121
|
+
} catch { entry.harvest = { output: { v: 1, entries: [], excluded: [], totalBytes: 0 }, scratchBytes: 0, limits: ["output_truncated"] }; }
|
|
122
|
+
};
|
|
123
|
+
/** The host's own fingerprints at seal time, never the declaration's. Null when they cannot be read, which the Store treats as unverified coverage. */
|
|
124
|
+
const hostRuntime = (): ProbeMeasuredSession["runtime"] => {
|
|
125
|
+
try { const actual = localProbeFingerprints(config); return { runtimeSha256: actual.runtimeSha256, toolsetSha256: actual.toolsetSha256, modelConfigSha256: actual.modelConfigSha256 }; }
|
|
126
|
+
catch { return null; }
|
|
127
|
+
};
|
|
128
|
+
const measuredSession = (entry: Owned, servedModel: string | null, flags: { unavailable: boolean }): Omit<ProbeMeasuredSession, "startedAt"> => ({
|
|
129
|
+
servedModel, workerEffectiveInputSha256: null, nonGuidanceInputSha256: null, runtime: hostRuntime(),
|
|
130
|
+
teardownVerified: entry.closed && !entry.closeFailed, cancelled: entry.controller.signal.aborted, timedOut: false, unavailable: flags.unavailable,
|
|
131
|
+
limits: entry.harvest?.limits ?? [], scratchBytes: entry.harvest?.scratchBytes ?? 0,
|
|
132
|
+
output: entry.harvest?.output ?? { v: 1, entries: [], excluded: [], totalBytes: 0 }, ...(entry.harvest?.retained ? { retained: entry.harvest.retained } : {}),
|
|
133
|
+
});
|
|
134
|
+
const observation = (input: ProbeFakeLaunch, ready: Prepared, servedModel: string | null, outcome: ProbeFakeObservation["outcome"], usage: ProbeFakeObservation["usage"],
|
|
135
|
+
entry?: Owned, unavailable = false): ProbeFakeObservation => ({
|
|
90
136
|
reservation: input.reservation, outcome, servedModel, inputFrameHash: ready.input.inputSha256,
|
|
91
137
|
workerEffectiveInputHash: input.slot.role === "worker" ? ready.input.inputSha256 : null,
|
|
92
138
|
nonGuidanceInputSha256: input.slot.role === "worker" ? ready.input.nonGuidanceInputSha256 : null,
|
|
93
139
|
candidateArtifactSha256: null, usage,
|
|
140
|
+
...(entry ? { measured: { ...measuredSession(entry, servedModel, { unavailable }),
|
|
141
|
+
workerEffectiveInputSha256: input.slot.role === "worker" ? ready.input.inputSha256 : null,
|
|
142
|
+
nonGuidanceInputSha256: input.slot.role === "worker" ? ready.input.nonGuidanceInputSha256 : null } } : {}),
|
|
94
143
|
});
|
|
95
144
|
return {
|
|
96
145
|
prepareWorkerFrame: async (state, slot, guidance) => {
|
|
@@ -146,20 +195,30 @@ export function createGuidanceProbeLocalAdapter(options: ProbeLocalAdapterOption
|
|
|
146
195
|
maxSteps: config.maxSteps, tools: { deny: [], permit } }, entry.confinement, fixture ? "fixture_only" : undefined);
|
|
147
196
|
const result = await entry.peer.runProbe({ purpose: "guidance_probe", prepared: ready.input, workspace: entry.workspace,
|
|
148
197
|
confinement: entry.confinement, config, accounting, reserve }, entry.controller.signal);
|
|
149
|
-
accounting.current(); await close(entry);
|
|
198
|
+
accounting.current(); await close(entry); harvestOutput(entry, ready);
|
|
150
199
|
effects.current(); current();
|
|
151
|
-
return observation(input, ready, result.servedModel, result.complete ? "closed_fixture" : "failed_known", result.usageKnown ? "known_fixture" : "unknown");
|
|
200
|
+
return observation(input, ready, result.servedModel, result.complete ? "closed_fixture" : "failed_known", result.usageKnown ? "known_fixture" : "unknown", entry);
|
|
152
201
|
}).catch(async error => {
|
|
153
202
|
if (error instanceof ProbeConfinementError) entry.closeUnknown = error.stop;
|
|
154
203
|
try { await close(entry); }
|
|
155
204
|
catch { throw new ProbeLocalError("interrupted"); }
|
|
156
|
-
|
|
205
|
+
// Only after the stop confirmed quiescence, and only while the workspace is still ours: a drifted workspace is read by identity or not at all.
|
|
206
|
+
harvestOutput(entry, ready);
|
|
207
|
+
// `unavailable` means the session could not start: a confinement error before any peer existed. Once a peer ran, the Store treats it as unknown or failed.
|
|
208
|
+
return observation(input, ready, entry.peer?.probeObservation().servedModel ?? null, "unknown", "unknown", entry, error instanceof ProbeConfinementError && !entry.peer);
|
|
157
209
|
}).finally(() => {
|
|
158
210
|
signal.removeEventListener("abort", abort);
|
|
159
211
|
if (entry.closed) { completed.add(entry.reservation); owned.delete(id); }
|
|
160
212
|
});
|
|
161
213
|
return entry.promise;
|
|
162
214
|
},
|
|
215
|
+
discardRetained(record) {
|
|
216
|
+
// Only what this adapter retained and has not yet handed to a receipt. A record that is not exactly one of ours is ignored, never deleted.
|
|
217
|
+
const key = guidanceProbeCanonical(record), ours = retainedHere.get(key);
|
|
218
|
+
if (!ours) return;
|
|
219
|
+
retainedHere.delete(key);
|
|
220
|
+
try { removeRetained(ours, true); } catch { /* the identity checks inside leave a replaced name alone; a failure leaves the directory for the person's prune preview */ }
|
|
221
|
+
},
|
|
163
222
|
async stop(input) {
|
|
164
223
|
const entry = owned.get(reservationKey(input.reservation));
|
|
165
224
|
if (!entry) return { reservation: input.reservation, stopped: completed.has(input.reservation) ? "known_fixture" : "unknown" };
|
|
@@ -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
|
+
}
|
package/src/adapters/pi.ts
CHANGED
|
@@ -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> {
|