@staix/agent-hub 0.52.0 → 0.54.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 +37 -0
- package/README.md +4 -3
- package/docs/addons/open-code-review.md +3 -6
- package/docs/agent-notes/README.md +1 -1
- package/docs/agent-notes/adapters.md +5 -4
- package/docs/agent-notes/budget.md +2 -2
- package/docs/agent-notes/bus.md +1 -0
- package/docs/agent-notes/daemon.md +6 -5
- package/docs/agent-notes/models.md +1 -1
- package/docs/agent-notes/tasks.md +3 -3
- package/docs/agent-notes/tests.md +4 -4
- package/docs/contracts/companion-cli-v2.json +90 -0
- package/docs/contracts/companion-cli-v3.json +348 -0
- package/docs/design/adapters.md +1 -1
- package/docs/design/agent-hub-architecture.md +8 -5
- package/docs/design/bus.md +1 -1
- package/docs/design/cli-output-inventory.md +4 -2
- package/docs/design/execution-reference.md +1 -1
- package/docs/design/guidance-experiments.md +1 -0
- package/docs/design/guidance-probes.md +1 -0
- package/docs/design/model-routes.md +20 -5
- package/docs/design/roadmap.md +6 -4
- package/docs/design/task-board.md +21 -2
- package/docs/dogfood.md +13 -6
- package/docs/events.md +1 -1
- package/docs/memory.md +2 -2
- package/docs/operations.md +158 -50
- package/docs/quickstart.md +14 -2
- package/docs/security.md +17 -9
- package/docs/specs/2026-09-19-agent-hub-design.md +5 -3
- package/docs/specs/2026-09-19-multi-project-design.md +1 -1
- package/docs/specs/2026-09-20-upgrade-recovery-design.md +24 -0
- package/docs/specs/2026-12-04-arev-adoption-design.md +84 -0
- package/docs/specs/mcp-endpoint.md +15 -4
- package/docs/specs/relay-contract.md +38 -0
- package/docs/verification/2026-12-04-host-shared-receipts.md +43 -0
- package/docs/verification/2026-12-05-0.53.0.md +101 -0
- package/docs/verification/2026-12-05-agy-1.5.24.md +55 -0
- package/docs/verification/2026-12-05-claude-implementer-2.1.337.md +43 -0
- package/docs/verification/2026-12-06-0.54.0.md +76 -0
- package/docs/verification/2026-12-06-codex-0174-reviewer-isolation.md +43 -0
- package/docs/verification/2026-12-06-codex-0174-reviewer-tool-call.md +34 -0
- package/docs/verification/2026-12-06-compat-codex-capabilities-0.174.0.md +25 -0
- package/docs/verification/2026-12-06-compat-pi-1.8.0.md +23 -0
- package/docs/verified.json +38 -29
- package/package.json +9 -3
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/.mcp.json +1 -1
- package/plugins/agent-hub/compat.json +9 -5
- package/plugins/agent-hub/kimi-hook.js +892 -874
- package/plugins/agent-hub/relay-launcher.js +24 -0
- package/plugins/agent-hub/server.js +27271 -25146
- package/src/adapters/acp-session-model.ts +1 -1
- package/src/adapters/acp.ts +5 -4
- package/src/adapters/agy/definition.ts +1 -1
- package/src/adapters/agy/hooks.ts +1 -1
- package/src/adapters/channel-peer.ts +3 -1
- package/src/adapters/claude-channel-evidence.ts +26 -1
- package/src/adapters/claude-channel.ts +27 -30
- package/src/adapters/claude-connection-policy.ts +62 -0
- package/src/adapters/claude-relay.ts +255 -0
- package/src/adapters/codex-review-isolation.ts +1 -2
- package/src/adapters/compat.ts +28 -18
- package/src/adapters/definitions/native-cli-preview-pi.ts +2 -1
- package/src/adapters/definitions/native-config-defaults.ts +1 -1
- package/src/adapters/definitions/native-context.ts +1 -2
- package/src/adapters/definitions/native-factories.ts +4 -1
- package/src/adapters/definitions/native-quota.ts +1 -1
- package/src/adapters/definitions/native-recovery.ts +3 -1
- package/src/adapters/external-modules.ts +2 -2
- package/src/adapters/kimi-review.ts +1 -1
- package/src/adapters/kimi-tui-facts.ts +1 -1
- package/src/adapters/local-worker.ts +3 -3
- package/src/adapters/native-capabilities.ts +1 -1
- package/src/adapters/pi.ts +26 -7
- package/src/adapters/registry-types.ts +2 -0
- package/src/adapters/relay-launcher.ts +27 -0
- package/src/adapters/reviewer-mcp.ts +1 -1
- package/src/cli/agents.ts +20 -8
- package/src/cli/agy-mcp.ts +1 -1
- package/src/cli/claude-profile-hook.ts +1 -1
- package/src/cli/command-table.ts +1 -0
- package/src/cli/commands/agents.ts +18 -1
- package/src/cli/commands/doctor.ts +18 -4
- package/src/cli/commands/launch-line.ts +32 -0
- package/src/cli/commands/status.ts +14 -3
- package/src/cli/help.ts +7 -4
- package/src/cli/identity.ts +1 -1
- package/src/cli/init-roles.ts +1 -1
- package/src/cli/init-settings.ts +1 -1
- package/src/cli/launch-line-plan.ts +82 -0
- package/src/cli/launch-line-project.ts +13 -0
- package/src/cli/main.ts +10 -9
- package/src/cli/pi-steps-warning.ts +14 -0
- package/src/cli/recovery-package.ts +60 -6
- package/src/cli/reset.ts +1 -1
- package/src/cli/shell-quote.ts +1 -3
- package/src/cli/upgrade-interactive.ts +7 -2
- package/src/cli/upgrade-keep-plan.ts +47 -0
- package/src/cli/upgrade-restore-state.ts +1 -1
- package/src/cli/upgrade-runtime.ts +119 -18
- package/src/cli/upgrade.ts +17 -2
- package/src/hub/accounts.ts +8 -4
- package/src/hub/action-class.ts +1 -3
- package/src/hub/adec-triage.ts +105 -0
- package/src/hub/autonomy.ts +1 -1
- package/src/hub/board.ts +3 -27
- package/src/hub/bus.ts +39 -6
- package/src/hub/capabilities.ts +1 -1
- package/src/hub/channel-project-base.ts +46 -0
- package/src/hub/channel-project.ts +21 -46
- package/src/hub/config-apply.ts +1 -1
- package/src/hub/config-edit.ts +1 -1
- package/src/hub/config-tier.ts +1 -1
- package/src/hub/config.ts +2 -2
- package/src/hub/confirmation-matrix.ts +1 -1
- package/src/hub/control/board-messages.ts +415 -0
- package/src/hub/control/dashboard-messages.ts +221 -0
- package/src/hub/control/delivery-messages.ts +356 -0
- package/src/hub/control/dispatch.ts +114 -0
- package/src/hub/control/hub-tool-helpers.ts +243 -0
- package/src/hub/control/hub-tools.ts +147 -0
- package/src/hub/control/native-messages.ts +665 -0
- package/src/hub/control/operations-messages.ts +269 -0
- package/src/hub/control/peer-messages.ts +126 -0
- package/src/hub/control/recovery-messages.ts +391 -0
- package/src/hub/control/recovery-operation.ts +480 -0
- package/src/hub/control/scope.ts +460 -0
- package/src/hub/control/sdlc-messages.ts +373 -0
- package/src/hub/control/task-ops-more.ts +245 -0
- package/src/hub/control/task-ops.ts +553 -0
- package/src/hub/control/ui-actions.ts +241 -0
- package/src/hub/control-write-trace.ts +1 -4
- package/src/hub/daemon.ts +485 -4324
- package/src/hub/delivery-hints.ts +2 -0
- package/src/hub/delivery-journal.ts +17 -6
- package/src/hub/events.ts +2 -1
- package/src/hub/execution-reference.ts +1 -1
- package/src/hub/host.ts +41 -9
- package/src/hub/hub-tools.ts +3 -4
- package/src/hub/invocations.ts +1 -1
- package/src/hub/lifecycle.ts +4 -3
- package/src/hub/mcp-endpoint-serve.ts +4 -3
- package/src/hub/mcp-endpoint.ts +15 -6
- package/src/hub/memory-profile-check.ts +1 -1
- package/src/hub/no-writes.ts +1 -1
- package/src/hub/peers.ts +2 -0
- package/src/hub/pi-exit-policy.ts +27 -0
- package/src/hub/progress.ts +1 -1
- package/src/hub/project-runtime-state.ts +17 -4
- package/src/hub/project-runtime.ts +3 -1
- package/src/hub/protocol-window.ts +1 -1
- package/src/hub/recovery-continuity.ts +3 -3
- package/src/hub/recovery-kept-roster.ts +50 -0
- package/src/hub/review-anchor.ts +13 -181
- package/src/hub/review-brief.ts +78 -28
- package/src/hub/review-findings.ts +15 -193
- package/src/hub/review-ledger.ts +162 -0
- package/src/hub/review-material.ts +3 -3
- package/src/hub/reviewer-pool.ts +4 -2
- package/src/hub/roadmap-issue-states.ts +65 -14
- package/src/hub/roadmap-sync.ts +39 -14
- package/src/hub/routing.ts +9 -0
- package/src/hub/runtime-capture-prune.ts +8 -2
- package/src/hub/runtime-package-assets.ts +3 -0
- package/src/hub/sdlc-release-policy.ts +1 -2
- package/src/hub/settings.ts +1 -1
- package/src/hub/spec-ack-tool.ts +4 -0
- package/src/hub/spec-report-history.ts +36 -0
- package/src/hub/specs.ts +1 -4
- package/src/hub/supervision.ts +33 -6
- package/src/hub/tasks-audit.ts +390 -0
- package/src/hub/tasks-backlog.ts +522 -0
- package/src/hub/tasks-handoff.ts +208 -0
- package/src/hub/tasks-release.ts +257 -0
- package/src/hub/tasks-roadmap.ts +17 -3
- package/src/hub/tasks-specs.ts +672 -0
- package/src/hub/tasks-types.ts +334 -0
- package/src/hub/tasks.ts +286 -1961
- package/src/hub/upgrade-session-contract.ts +11 -0
- package/src/local/probe-sandbox.ts +1 -2
- package/src/local/probe-workspace.ts +1 -1
- package/src/models/route/config.ts +4 -4
- package/src/models/route/decision.ts +18 -10
- package/src/models/route/observation-signals.ts +1 -2
- package/src/models/route/runtime.ts +8 -5
- package/src/npm-artifact.ts +76 -0
- package/src/omniroute/client.ts +6 -0
- package/src/pi/extension.ts +5 -2
- package/src/pi/install.ts +77 -0
- package/src/pi/pin.ts +49 -0
- package/src/primitives.ts +14 -0
- package/src/version.ts +2 -0
- package/templates/adec/README.md +10 -6
- package/templates/config.json +1 -1
- package/templates/specs.block.md +1 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
import { parseSessionContract, type SessionContract } from "./project-runtime-state.ts";
|
|
5
|
+
|
|
6
|
+
export { parseSessionContract, type SessionContract } from "./project-runtime-state.ts";
|
|
7
|
+
|
|
8
|
+
/** Read release metadata as data. The caller verifies the package identity and digest. */
|
|
9
|
+
export function readSessionContract(root: string): SessionContract | undefined {
|
|
10
|
+
return parseSessionContract(JSON.parse(readFileSync(join(root, "package.json"), "utf8")).sessionContract);
|
|
11
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { sha256Hex as digest } from "../primitives.ts";
|
|
2
2
|
import { closeSync, constants, fstatSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { realPath } from "../hub/project.ts";
|
|
@@ -25,7 +25,6 @@ interface ProofState { workspace: ProbeWorkspace; profile: string; digest: strin
|
|
|
25
25
|
interface OwnedProofPath { file: string; dev: number; ino: number; directory: boolean; optional?: boolean; removed?: boolean }
|
|
26
26
|
const proofs = new WeakMap<ProbeConfinement, ProofState>();
|
|
27
27
|
let proofOwner: { workspace: ProbeWorkspace; stop(): Promise<void> } | undefined;
|
|
28
|
-
const digest = (value: string): string => createHash("sha256").update(value).digest("hex");
|
|
29
28
|
const q = sbplString;
|
|
30
29
|
const literal = (value: string) => `(literal ${q(value)})`;
|
|
31
30
|
const subpath = (value: string) => `(subpath ${q(value)})`;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { sha256Hex as digest } from "../primitives.ts";
|
|
1
2
|
import { createHash } from "node:crypto";
|
|
2
3
|
import { chmodSync, constants, closeSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, opendirSync, readSync, rmSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
4
|
import { tmpdir } from "node:os";
|
|
@@ -40,7 +41,6 @@ export interface ProbeWorkspace {
|
|
|
40
41
|
interface DirectoryIdentity { file: string; dev: number; ino: number }
|
|
41
42
|
interface WorkspaceState { parent: string; temporaryRoot: string; current(): void; reserveStorage(bytes: number): void | Promise<void>; maximum: number; charged: number; directories: readonly DirectoryIdentity[]; identities: readonly { file: string; dev: number; ino: number; size: number; mtimeMs: number; ctimeMs: number }[] }
|
|
42
43
|
const workspaces = new WeakMap<ProbeWorkspace, WorkspaceState>();
|
|
43
|
-
const digest = (bytes: Uint8Array | string): string => createHash("sha256").update(bytes).digest("hex");
|
|
44
44
|
function refused(): never { throw new Error("probe workspace source, role, path or resource proof is unavailable"); }
|
|
45
45
|
const integer = (value: number): boolean => Number.isSafeInteger(value) && value >= 0;
|
|
46
46
|
const sha = (value: string): boolean => /^[a-f0-9]{64}$/.test(value);
|
|
@@ -5,7 +5,7 @@ import { AMBIGUOUS_BAND_DEFAULT, AMBIGUOUS_BAND_MAX } from "./stage-fallback.ts"
|
|
|
5
5
|
export interface HubRoute {
|
|
6
6
|
type: "stage" | "plan_execute" | "advisor" | "escalation" | "decision";
|
|
7
7
|
decision_backend?: "adec";
|
|
8
|
-
decision_mode?: "off" | "shadow";
|
|
8
|
+
decision_mode?: "off" | "shadow" | "enforce";
|
|
9
9
|
adec_endpoint?: string;
|
|
10
10
|
policy_id?: string;
|
|
11
11
|
candidates?: { alias: string; efforts: string[] }[];
|
|
@@ -96,11 +96,11 @@ const SERVICE_FIELDS = ["decision_backend", "decision_mode", "policy_id", "adec_
|
|
|
96
96
|
function parseServiceConfig(id: string, r: Record<string, unknown>): Pick<HubRoute, "decision_backend" | "decision_mode" | "adec_endpoint"> {
|
|
97
97
|
const problem = (field: string, step: string): never => { throw new Error(`routing.toml: invalid ${id}.${field}; ${step}`); };
|
|
98
98
|
if (r.decision_backend !== "adec") problem("decision_backend", 'set decision_backend = "adec" for a loopback policy service');
|
|
99
|
-
if (r.decision_mode === "enforce") throw new Error("decision_mode enforce is not available yet; use shadow; tracked in #554");
|
|
100
|
-
if (r.decision_mode !== undefined && !["off", "shadow"].includes(
|
|
99
|
+
if (r.decision_mode === "enforce" && r.type !== "decision") throw new Error("decision_mode enforce is not available yet; use shadow; tracked in #554");
|
|
100
|
+
if (r.decision_mode !== undefined && (typeof r.decision_mode !== "string" || !["off", "shadow", "enforce"].includes(r.decision_mode))) problem("decision_mode", 'use "off", "shadow", or "enforce" on a decision route');
|
|
101
101
|
if (typeof r.policy_id !== "string" || !/^[a-z0-9][a-z0-9._-]{0,49}$/.test(r.policy_id)) problem("policy_id", "name a configured adec policy with 1 to 50 lowercase identifier characters");
|
|
102
102
|
const endpoint = r.adec_endpoint ?? "http://127.0.0.1:8740/v1/route";
|
|
103
103
|
if (!isAdecRouteEndpoint(endpoint)) return problem("adec_endpoint", "use an HTTP numeric loopback /v1/route URL without credentials, query or fragment");
|
|
104
104
|
if (r.decision_timeout_ms !== undefined && (!Number.isSafeInteger(r.decision_timeout_ms) || Number(r.decision_timeout_ms) < 1 || Number(r.decision_timeout_ms) > 30_000)) problem("decision_timeout_ms", "use 1 to 30000 milliseconds");
|
|
105
|
-
return { decision_backend: "adec", decision_mode: (r.decision_mode ?? "off") as "
|
|
105
|
+
return { decision_backend: "adec", decision_mode: (r.decision_mode ?? "off") as HubRoute["decision_mode"], adec_endpoint: endpoint };
|
|
106
106
|
}
|
|
@@ -19,7 +19,7 @@ export interface DecisionHost {
|
|
|
19
19
|
onDecisionIssue?: (reason: AdecFailure | AdecReason) => void;
|
|
20
20
|
}
|
|
21
21
|
export interface DecisionTrace {
|
|
22
|
-
decisionMode: "
|
|
22
|
+
decisionMode: NonNullable<HubRoute["decision_mode"]>;
|
|
23
23
|
chosenAlias: string | null; chosenEffort: string | null; margin?: number; decisionLatencyMs?: number;
|
|
24
24
|
decisionReason?: string; fallbackApplied?: boolean;
|
|
25
25
|
decider?: { provider: string; model: string; version?: string; latencyMs: number } | null;
|
|
@@ -31,6 +31,8 @@ interface Context {
|
|
|
31
31
|
hostChoice?: { purpose: HostChoicePurpose; phase?: HostPhase };
|
|
32
32
|
deadline?: number;
|
|
33
33
|
closed?(): boolean;
|
|
34
|
+
/** #1936: the alias the heuristic picked for this call, sent as adec's `current`. */
|
|
35
|
+
heuristic?: string;
|
|
34
36
|
}
|
|
35
37
|
/** What one stage classification needs: bounded evidence instead of a conversation projection. */
|
|
36
38
|
export interface StageClassifyContext {
|
|
@@ -42,11 +44,11 @@ export type DecisionPurpose = "stage" | "decision" | "phase" | "judge";
|
|
|
42
44
|
export interface HostChoiceContext {
|
|
43
45
|
route: string; scope: string; turn: ReturnType<RouteLabelTracker["captureTurn"]>;
|
|
44
46
|
current(): boolean; messages: ChatMessage[]; evidence: StageEvidence; pii: boolean; signal: AbortSignal;
|
|
45
|
-
purpose: HostChoicePurpose; phase?: HostPhase; deadline?: number;
|
|
47
|
+
purpose: HostChoicePurpose; phase?: HostPhase; deadline?: number; heuristic?: string;
|
|
46
48
|
}
|
|
47
49
|
interface Options { pairs: AdecPair[]; candidates: string[]; current?: AdecPair }
|
|
48
50
|
interface Privacy { pii: boolean; private: boolean; excluded: boolean }
|
|
49
|
-
export interface DecisionSelection { trace?: DecisionTrace; check?(): void }
|
|
51
|
+
export interface DecisionSelection { trace?: DecisionTrace; apply?: AdecPair; check?(): void }
|
|
50
52
|
type Selection = DecisionSelection;
|
|
51
53
|
type Attempt = { result: AdecResult; privacy: Privacy } | { skipped: string };
|
|
52
54
|
type PreparedRequest = { privacy: Privacy; input: AdecRouteRequest; options: Options; timeoutMs: number } | { skipped: string };
|
|
@@ -79,11 +81,13 @@ export class DecisionRouteController {
|
|
|
79
81
|
if (config.type !== "decision" || (config.decision_mode ?? "off") === "off") { this.issues.delete(context.route); return {}; }
|
|
80
82
|
if (context.signal.aborted || context.turn?.closed) throw ended();
|
|
81
83
|
const privacy = this.privacy(context.pii);
|
|
84
|
+
const options = this.decisionOptions(config, context.heuristic);
|
|
82
85
|
const checked = (selection: Selection): Selection => {
|
|
83
86
|
this.fence(context, privacy);
|
|
84
|
-
|
|
87
|
+
const apply = config.decision_mode === "enforce" ? selection.apply ?? options.current : undefined;
|
|
88
|
+
return { ...selection, ...(apply ? { apply } : {}), check: () => { this.fence(context, privacy); selection.check?.(); } };
|
|
85
89
|
};
|
|
86
|
-
try { return checked(await this.select(config, context, "decision",
|
|
90
|
+
try { return checked(await this.select(config, context, "decision", options)); }
|
|
87
91
|
catch (error) {
|
|
88
92
|
if (context.signal.aborted || context.turn?.closed) throw ended();
|
|
89
93
|
this.fence(context, privacy); // a rejected await is still an authority boundary
|
|
@@ -132,9 +136,11 @@ export class DecisionRouteController {
|
|
|
132
136
|
private turnKey(purpose: DecisionPurpose, context: Context): string {
|
|
133
137
|
return createHash("sha256").update(JSON.stringify([purpose, context.route, context.scope, context.turn?.context.turn])).digest("hex");
|
|
134
138
|
}
|
|
135
|
-
private decisionOptions(config: HubRoute): Options {
|
|
139
|
+
private decisionOptions(config: HubRoute, heuristic?: string): Options {
|
|
136
140
|
const pairs = config.candidates?.flatMap(candidate => candidate.efforts.map(effort => ({ alias: candidate.alias, effort }))) ?? [];
|
|
137
|
-
|
|
141
|
+
// #1936: the pair the route would use without adec (the alias the heuristic picked, else the efficient alias, else the first offered), so the shadow rows carry what adec is compared with.
|
|
142
|
+
const current = pairs.find(pair => pair.alias === (heuristic ?? config.efficient)) ?? pairs.find(pair => pair.alias === config.efficient) ?? pairs[0];
|
|
143
|
+
return { pairs, candidates: [...new Set(pairs.map(pair => pair.alias))], ...(current ? { current } : {}) };
|
|
138
144
|
}
|
|
139
145
|
/** A tier carries no effort, so both offerings use "none" and the answer maps back by alias equality. */
|
|
140
146
|
private stageOptions(config: HubRoute, tier: StageTier): Options | undefined {
|
|
@@ -161,11 +167,11 @@ export class DecisionRouteController {
|
|
|
161
167
|
const purpose: DecisionPurpose = context.purpose === "plan_execute_model" ? "phase" : "judge";
|
|
162
168
|
const inner: Context = { route: context.route, scope: context.scope, turn: context.turn, current: context.current,
|
|
163
169
|
messages: context.messages, dimensions: context.evidence.dimensions, stageEvidence: context.evidence,
|
|
164
|
-
hostChoice: { purpose: context.purpose, ...(context.phase ? { phase: context.phase } : {}) },
|
|
170
|
+
hostChoice: { purpose: context.purpose, ...(context.phase ? { phase: context.phase } : {}) }, ...(context.heuristic ? { heuristic: context.heuristic } : {}),
|
|
165
171
|
pii: context.pii, signal: context.signal, ...(context.deadline === undefined ? {} : { deadline: context.deadline }) };
|
|
166
172
|
const initial = this.privacy(context.pii);
|
|
167
173
|
let state: State | undefined, key: string | undefined;
|
|
168
|
-
const began = performance.now(), options = this.decisionOptions(config);
|
|
174
|
+
const began = performance.now(), options = this.decisionOptions(config, context.heuristic);
|
|
169
175
|
type Prepared = PreparedRequest | { cached: AdecResult; privacy: Privacy };
|
|
170
176
|
return startChoiceWindow<Prepared, Selection>({
|
|
171
177
|
signal: context.signal,
|
|
@@ -264,7 +270,9 @@ export class DecisionRouteController {
|
|
|
264
270
|
if (d.decider === null) decider = null;
|
|
265
271
|
else if (this.host.publicDecisionText?.(JSON.stringify(d.decider)) === true) decider = { provider: d.decider.provider, model: d.decider.model, latencyMs: d.decider.latencyMs, ...(d.decider.version === undefined ? {} : { version: d.decider.version }) };
|
|
266
272
|
this.fence(context, attempt.privacy);
|
|
267
|
-
|
|
273
|
+
const apply = config.type === "decision" && config.decision_mode === "enforce" && !d.abstain && d.alias !== null && d.effort !== null
|
|
274
|
+
? { alias: d.alias, effort: d.effort } : undefined;
|
|
275
|
+
return { ...(apply ? { apply } : {}), check: () => this.publicationFence(context, attempt.privacy),
|
|
268
276
|
trace: { decisionMode: config.decision_mode ?? "off", chosenAlias: d.alias, chosenEffort: d.effort, margin: d.margin,
|
|
269
277
|
decisionLatencyMs: Math.max(0, performance.now() - began), decisionReason: d.reason, fallbackApplied: d.fallbackApplied,
|
|
270
278
|
...(decider === undefined ? {} : { decider }) } };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { sha256Hex as digest } from "../../primitives.ts";
|
|
2
2
|
import { types } from "node:util";
|
|
3
3
|
import { captureJudgeConversation, type JudgeMessage } from "./conversation-view.ts";
|
|
4
4
|
import { captureStageInput, estimateStageInputTokens } from "./stage-input.ts";
|
|
@@ -33,7 +33,6 @@ interface ResultFacts {
|
|
|
33
33
|
const WIRE_BYTES = 2_000_000;
|
|
34
34
|
const OPERATION_BYTES = 256;
|
|
35
35
|
const unavailable = Symbol("observation unavailable");
|
|
36
|
-
const digest = (value: string): string => createHash("sha256").update(value).digest("hex");
|
|
37
36
|
const testName = /\b(?:test|tests|spec|specs|pytest|vitest|jest|cargo test|go test)\b|^(?:run_tests|run_test|unittest)$/iu;
|
|
38
37
|
// Local lexical evidence only, never an executable/exit-status attestation.
|
|
39
38
|
const testCommand = /\b(?:bun test|pytest|vitest|jest|cargo test|go test|npm test|pnpm test|yarn test)\b|(?:^|[\s;&|])(?:(?:bun|npm|pnpm|yarn)\s+(?:run\s+)?test(?:$|[\s:])|python(?:3(?:\.\d+)?)?\s+-m\s+(?:pytest|unittest)\b|(?:make|just)\s+test\b)/iu;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { DecisionRouteController, type DecisionHost, type DecisionTrace, type DecisionSelection, DecisionPolicyChangedError } from "./decision.ts";
|
|
2
|
-
import type { ChatMessage, ChatResult } from "../../omniroute/client.ts";
|
|
2
|
+
import type { ChatMessage, ChatResult, ChatOptions } from "../../omniroute/client.ts";
|
|
3
3
|
import { AdvisorTrigger } from "./advisor-trigger.ts";
|
|
4
4
|
import { buildAdvisorRequest, buildEscalationRequest, planningInstruction, redoFeedback } from "./hub-prompts.ts";
|
|
5
5
|
import { captureJudgeConversation, captureRouteView } from "./conversation-view.ts";
|
|
@@ -22,7 +22,7 @@ export interface RouteEvent extends Partial<SwitchTrace>, Partial<DecisionTrace>
|
|
|
22
22
|
export interface AdvisorEvent { route: string; trigger: string; verdict: "approve" | "redo" | "failed"; discardedChars: number }
|
|
23
23
|
interface RouteState { fingerprint: string; stage: FallbackStageState; pin?: Tier; plan: PlanPhase; escalation: EscalationControl; advisor: AdvisorTrigger }
|
|
24
24
|
export interface RouteHost extends DecisionHost {
|
|
25
|
-
execute: (model: string, messages: ChatMessage[], judge: boolean, signal: AbortSignal, maxTokens?: number) => Promise<ChatResult>;
|
|
25
|
+
execute: (model: string, messages: ChatMessage[], judge: boolean, signal: AbortSignal, maxTokens?: number, decisionChoice?: ChatOptions["decisionChoice"]) => Promise<ChatResult>;
|
|
26
26
|
/** Read on every stage call (#197); absent is the shadow default. */
|
|
27
27
|
staySwitch?: () => StaySwitchPolicy | undefined;
|
|
28
28
|
onRoute?: (event: RouteEvent) => void;
|
|
@@ -97,12 +97,12 @@ export class HubRouteRuntime {
|
|
|
97
97
|
const current = () => !signal.aborted && !labelTurn?.closed && this.labels.captureTurn() === labelTurn;
|
|
98
98
|
let phaseGuard: ReturnType<DecisionRouteController["captureGuard"]> | undefined;
|
|
99
99
|
let proposed: DecisionSelection = {};
|
|
100
|
-
if (config.type === "decision") proposed = await this.decisions.pick(config, { route, scope, turn: labelTurn, messages, dimensions, pii, signal, current });
|
|
100
|
+
if (config.type === "decision") proposed = await this.decisions.pick(config, { route, scope, turn: labelTurn, messages, dimensions, pii, signal, current, heuristic: model });
|
|
101
101
|
else if (config.type === "plan_execute" && config.decision_backend === "adec" && (config.decision_mode ?? "off") === "shadow") {
|
|
102
102
|
phaseGuard = this.decisions.captureGuard(pii, current);
|
|
103
103
|
const timeout = config.decision_timeout_ms ?? this.judgeTimeoutMs;
|
|
104
104
|
const window = this.decisions.openHostChoice(config, { route, scope, turn: labelTurn, messages, evidence, pii, signal, current,
|
|
105
|
-
purpose: "plan_execute_model", phase, deadline: performance.now() + timeout });
|
|
105
|
+
purpose: "plan_execute_model", phase, heuristic: model, deadline: performance.now() + timeout });
|
|
106
106
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
107
107
|
try {
|
|
108
108
|
if (window) {
|
|
@@ -114,8 +114,11 @@ export class HubRouteRuntime {
|
|
|
114
114
|
}
|
|
115
115
|
const picked = this.decisions.confirm(proposed);
|
|
116
116
|
source = picked.trace ? "decision" : source;
|
|
117
|
+
if (picked.apply) model = picked.apply.alias;
|
|
117
118
|
let decisionId = this.emitRoute({ route, tier: model, source, score, ms: performance.now() - started, ...trace, ...picked?.trace }, labelTurn, dimensions, pii, messages);
|
|
118
|
-
const result =
|
|
119
|
+
const result = picked.apply
|
|
120
|
+
? await this.host.execute(model, sent, false, signal, undefined, { effort: picked.apply.effort, assertCurrent: () => { this.decisions.confirm(picked); } })
|
|
121
|
+
: await this.host.execute(model, sent, false, signal);
|
|
119
122
|
phaseGuard?.("executor reply");
|
|
120
123
|
if (config.type !== "escalation" || state.escalation.snapshot().latched) return this.withDecision(result, decisionId);
|
|
121
124
|
const conversation = captureJudgeConversation([...messages, result.message]);
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
export type ArtifactFetch = (...args: Parameters<typeof fetch>) => ReturnType<typeof fetch>;
|
|
4
|
+
|
|
5
|
+
export class PublicArtifactError extends Error {
|
|
6
|
+
constructor(readonly causeCode: "input" | "integrity" | "install-unavailable") { super(causeCode); }
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function publicURL(value: unknown, hosts: readonly string[], base?: string): string {
|
|
10
|
+
if (typeof value !== "string") throw new PublicArtifactError("integrity");
|
|
11
|
+
let url: URL;
|
|
12
|
+
try { url = new URL(value, base); }
|
|
13
|
+
catch { throw new PublicArtifactError("integrity"); }
|
|
14
|
+
if (url.protocol !== "https:" || url.username || url.password || url.port || !hosts.includes(url.hostname)) throw new PublicArtifactError("integrity");
|
|
15
|
+
return url.href;
|
|
16
|
+
}
|
|
17
|
+
export async function publicArtifactBytes(fetcher: ArtifactFetch, url: string, signal: AbortSignal, cap: number, accept: "application/json" | "application/octet-stream" = "application/octet-stream"): Promise<Buffer> {
|
|
18
|
+
// Public requests never consult account credentials or forward authentication on redirects.
|
|
19
|
+
let response: Response | undefined;
|
|
20
|
+
for (let redirects = 0; redirects <= 4; redirects++) {
|
|
21
|
+
response = await fetcher(url, { signal, credentials: "omit", redirect: "manual", headers: { Accept: accept } });
|
|
22
|
+
if (![301, 302, 303, 307, 308].includes(response.status)) break;
|
|
23
|
+
const location = response.headers.get("location");
|
|
24
|
+
await response.body?.cancel();
|
|
25
|
+
if (!location || redirects === 4) throw new PublicArtifactError("integrity");
|
|
26
|
+
url = publicURL(location, ["registry.npmjs.org", "api.github.com", "github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com"], url);
|
|
27
|
+
}
|
|
28
|
+
if (!response) throw new PublicArtifactError("install-unavailable");
|
|
29
|
+
if (!response.ok || !response.body) throw new PublicArtifactError("install-unavailable");
|
|
30
|
+
const size = response.headers.get("content-length");
|
|
31
|
+
if (size !== null && (!/^\d+$/.test(size) || Number(size) > cap)) throw new PublicArtifactError("integrity");
|
|
32
|
+
const reader = response.body.getReader();
|
|
33
|
+
const chunks: Uint8Array[] = [];
|
|
34
|
+
let count = 0;
|
|
35
|
+
try {
|
|
36
|
+
while (true) {
|
|
37
|
+
const next = await reader.read();
|
|
38
|
+
if (next.done) break;
|
|
39
|
+
count += next.value.byteLength;
|
|
40
|
+
if (count > cap) throw new PublicArtifactError("integrity");
|
|
41
|
+
chunks.push(next.value);
|
|
42
|
+
}
|
|
43
|
+
} finally { await reader.cancel().catch(() => {}); }
|
|
44
|
+
return Buffer.concat(chunks);
|
|
45
|
+
}
|
|
46
|
+
interface NpmMetadata { name: string; version: string; dist?: { tarball?: string; integrity?: string } }
|
|
47
|
+
export function parseArtifactMetadata<T>(text: string): T {
|
|
48
|
+
try {
|
|
49
|
+
const value: unknown = JSON.parse(text);
|
|
50
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new PublicArtifactError("integrity");
|
|
51
|
+
return value as T;
|
|
52
|
+
} catch { throw new PublicArtifactError("integrity"); }
|
|
53
|
+
}
|
|
54
|
+
// These are public JSON documents; critical identity/URL/digest fields are checked before effects.
|
|
55
|
+
export async function publicArtifactJson<T>(fetcher: ArtifactFetch, url: string, signal: AbortSignal, cap: number): Promise<T> {
|
|
56
|
+
try { return parseArtifactMetadata<T>((await publicArtifactBytes(fetcher, url, signal, cap, "application/json")).toString("utf8")); }
|
|
57
|
+
catch (error) { if (error instanceof PublicArtifactError) throw error; throw new PublicArtifactError("integrity"); }
|
|
58
|
+
}
|
|
59
|
+
function verifySRI(data: Buffer, integrity: unknown): string {
|
|
60
|
+
// Require one strong digest rather than letting a weaker alternate mask a mismatch.
|
|
61
|
+
if (typeof integrity !== "string" || !/^sha(256|384|512)-[A-Za-z0-9+/]+={0,2}$/.test(integrity)) throw new PublicArtifactError("integrity");
|
|
62
|
+
const [algorithm, encoded] = integrity.split("-");
|
|
63
|
+
const expected = Buffer.from(encoded!, "base64");
|
|
64
|
+
const actual = createHash(algorithm!).update(data).digest();
|
|
65
|
+
if (expected.length !== actual.length || !timingSafeEqual(actual, expected)) throw new PublicArtifactError("integrity");
|
|
66
|
+
return integrity;
|
|
67
|
+
}
|
|
68
|
+
export async function fetchExactNpmArtifact(name: string, version: string, fetcher: ArtifactFetch, signal: AbortSignal,
|
|
69
|
+
limits: { metadataBytes: number; artifactBytes: number }): Promise<{ data: Buffer; integrity: string }> {
|
|
70
|
+
if (!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(name) || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(version)) throw new PublicArtifactError("input");
|
|
71
|
+
const metadata = await publicArtifactJson<NpmMetadata>(fetcher, `https://registry.npmjs.org/${name}/${version}`, signal, limits.metadataBytes);
|
|
72
|
+
if (metadata.name !== name || metadata.version !== version) throw new PublicArtifactError("integrity");
|
|
73
|
+
const tarball = publicURL(metadata.dist?.tarball, ["registry.npmjs.org"]);
|
|
74
|
+
const data = await publicArtifactBytes(fetcher, tarball, signal, limits.artifactBytes);
|
|
75
|
+
return { data, integrity: verifySRI(data, metadata.dist?.integrity) };
|
|
76
|
+
}
|
package/src/omniroute/client.ts
CHANGED
|
@@ -44,6 +44,8 @@ export interface ChatOptions {
|
|
|
44
44
|
/** Refuse a changed/off-campus gateway immediately before transport. */
|
|
45
45
|
onCampusOnly?: boolean;
|
|
46
46
|
signal?: AbortSignal;
|
|
47
|
+
/** Host-screened route effort, checked again after gateway discovery. */
|
|
48
|
+
decisionChoice?: { effort: string; assertCurrent(): void };
|
|
47
49
|
}
|
|
48
50
|
type ChatRequest = { model: string; messages: ChatMessage[]; tools?: unknown[]; max_tokens?: number; temperature?: number; reasoning_effort?: string };
|
|
49
51
|
|
|
@@ -160,6 +162,10 @@ export class OmniRoute {
|
|
|
160
162
|
const base = await this.base();
|
|
161
163
|
if (!base) throw new Error("no model gateway is configured or reachable (omniroute.urls in .agenthub/config.json; see ahub doctor)");
|
|
162
164
|
if (opts.onCampusOnly && this.isAccessHost(base)) throw new Error("PII model calls require the confirmed campus gateway");
|
|
165
|
+
if (opts.decisionChoice) {
|
|
166
|
+
opts.decisionChoice.assertCurrent();
|
|
167
|
+
body = { ...body, reasoning_effort: opts.decisionChoice.effort };
|
|
168
|
+
}
|
|
163
169
|
return this.chatAt(base, body, opts);
|
|
164
170
|
}
|
|
165
171
|
|
package/src/pi/extension.ts
CHANGED
|
@@ -17,6 +17,8 @@ const models = (() => {
|
|
|
17
17
|
let pollStarted = false;
|
|
18
18
|
let pollStopped = false;
|
|
19
19
|
let toolSteps = 0;
|
|
20
|
+
// #1967 T2: steps are counted from the logical turn's first agent_start to its agent_settled; a native retry's agent_start inside it does not reset them.
|
|
21
|
+
let logicalTurnOpen = false;
|
|
20
22
|
let lastActivity = 0;
|
|
21
23
|
let usageSeq = 0;
|
|
22
24
|
let shellSeq = 0;
|
|
@@ -221,8 +223,8 @@ export default function(pi: ExtensionAPI): void {
|
|
|
221
223
|
catch { /* title observation must not disrupt the native session */ }
|
|
222
224
|
});
|
|
223
225
|
// Native retries/continuations emit more starts before the one logical agent_settled.
|
|
224
|
-
pi.on("agent_start", async () => { toolSteps = 0; forcedFailure = ""; turnGeneration++; activePromptId = pendingPromptId ?? activePromptId; pendingPromptId = undefined; await post("/event", { type: "agent_start", sessionId, ...(typeof pi.getSessionName === "function" ? { sessionName: pi.getSessionName() ?? "", titleEpoch, titleRevision } : {}), generation: turnGeneration, ...(activePromptId ? { promptId: activePromptId } : {}) }); });
|
|
225
|
-
pi.on("model_select", async (_event: any, ctx: any) => { runtimeCtx = ctx; if (ctx.model?.provider && ctx.model.provider !== "agent-hub-local") ctx.shutdown?.(); else try { await post("/event", { type: "pi_model", sessionId, model: ctx.model ? { id: ctx.model.id } : undefined }); } catch { /* optional telemetry */ } });
|
|
226
|
+
pi.on("agent_start", async () => { if (!logicalTurnOpen || forcedFailure) toolSteps = 0; logicalTurnOpen = true; forcedFailure = ""; turnGeneration++; activePromptId = pendingPromptId ?? activePromptId; pendingPromptId = undefined; await post("/event", { type: "agent_start", sessionId, ...(typeof pi.getSessionName === "function" ? { sessionName: pi.getSessionName() ?? "", titleEpoch, titleRevision } : {}), generation: turnGeneration, ...(activePromptId ? { promptId: activePromptId } : {}) }); });
|
|
227
|
+
pi.on("model_select", async (_event: any, ctx: any) => { runtimeCtx = ctx; if (ctx.model?.provider && ctx.model.provider !== "agent-hub-local") { try { await post("/event", { type: "model_select_foreign", sessionId, provider: String(ctx.model.provider).slice(0, 64) }); } catch { /* the shutdown below stays authoritative */ } ctx.shutdown?.(); } else try { await post("/event", { type: "pi_model", sessionId, model: ctx.model ? { id: ctx.model.id } : undefined }); } catch { /* optional telemetry */ } });
|
|
226
228
|
pi.on("before_agent_start", async (event: any, ctx: any) => {
|
|
227
229
|
if (ctx.model?.provider && ctx.model.provider !== "agent-hub-local") { ctx.abort?.(); return { systemPrompt: event.systemPrompt }; }
|
|
228
230
|
return undefined;
|
|
@@ -236,6 +238,7 @@ export default function(pi: ExtensionAPI): void {
|
|
|
236
238
|
return undefined;
|
|
237
239
|
});
|
|
238
240
|
pi.on("agent_settled", async (_event: any, ctx: any) => {
|
|
241
|
+
logicalTurnOpen = false;
|
|
239
242
|
let release!: () => void;
|
|
240
243
|
const current = new Promise<void>(resolve => { release = resolve; });
|
|
241
244
|
settlement = current;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, join, relative, sep } from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { COMPAT } from "../adapters/compat.ts";
|
|
5
|
+
import { fetchExactNpmArtifact, PublicArtifactError, type ArtifactFetch } from "../npm-artifact.ts";
|
|
6
|
+
import { hubHome, realPath } from "../hub/project.ts";
|
|
7
|
+
import { PI_PACKAGE, ownedPiDirectory, piInstalledCommand, piInstallRoot } from "./pin.ts";
|
|
8
|
+
|
|
9
|
+
const FETCH_MS = 30_000, INSTALL_MS = 180_000;
|
|
10
|
+
const LIMITS = { metadataBytes: 1024 * 1024, artifactBytes: 64 * 1024 * 1024 };
|
|
11
|
+
|
|
12
|
+
async function installArchive(prefix: string, archive: string, scratch: string): Promise<void> {
|
|
13
|
+
const userConfig = join(scratch, "user.npmrc"), globalConfig = join(scratch, "global.npmrc");
|
|
14
|
+
const home = join(scratch, "home"), cache = join(scratch, "cache");
|
|
15
|
+
mkdirSync(home, { mode: 0o700 });
|
|
16
|
+
for (const config of [userConfig, globalConfig]) writeFileSync(config, "", { flag: "wx", mode: 0o600 });
|
|
17
|
+
const npm = Bun.which("npm");
|
|
18
|
+
if (!npm) throw new PublicArtifactError("install-unavailable");
|
|
19
|
+
const child = Bun.spawn([npm, "install", "--prefix", prefix, "--ignore-scripts", "--no-audit", "--no-fund", "--save-exact", archive], {
|
|
20
|
+
cwd: scratch,
|
|
21
|
+
env: { HOME: home, PATH: process.env.PATH, TMPDIR: scratch, LANG: "C", npm_config_userconfig: userConfig,
|
|
22
|
+
npm_config_globalconfig: globalConfig, npm_config_cache: cache, npm_config_registry: "https://registry.npmjs.org/", npm_config_update_notifier: "false" },
|
|
23
|
+
stdin: "ignore", stdout: "ignore", stderr: "ignore", timeout: INSTALL_MS, killSignal: "SIGKILL",
|
|
24
|
+
});
|
|
25
|
+
if (await child.exited !== 0) throw new PublicArtifactError("install-unavailable");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function matchingInstall(prefix: string, version: string, data: Buffer): Promise<string> {
|
|
29
|
+
const command = piInstalledCommand(prefix, version);
|
|
30
|
+
if (!command) throw new PublicArtifactError("integrity");
|
|
31
|
+
const packageRoot = realPath(join(prefix, "node_modules", PI_PACKAGE));
|
|
32
|
+
const files = await new Bun.Archive(data).files();
|
|
33
|
+
if (!files.has("package/package.json")) throw new PublicArtifactError("integrity");
|
|
34
|
+
for (const [name, file] of files) {
|
|
35
|
+
if (!name.startsWith("package/")) throw new PublicArtifactError("integrity");
|
|
36
|
+
const candidate = join(packageRoot, name.slice("package/".length)), actual = realPath(candidate);
|
|
37
|
+
const rel = relative(packageRoot, actual);
|
|
38
|
+
if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel) || actual !== candidate) throw new PublicArtifactError("integrity");
|
|
39
|
+
const stat = lstatSync(actual);
|
|
40
|
+
if (!stat.isFile() || stat.size !== file.size || !readFileSync(actual).equals(Buffer.from(await file.arrayBuffer()))) throw new PublicArtifactError("integrity");
|
|
41
|
+
}
|
|
42
|
+
return command;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function installPinnedPi(version: string, ports: {
|
|
46
|
+
home?: string; fetch?: ArtifactFetch; install?: typeof installArchive;
|
|
47
|
+
} = {}): Promise<{ version: string; command: string }> {
|
|
48
|
+
if (!(COMPAT.pi.verified as readonly string[]).includes(version)) throw new PublicArtifactError("input");
|
|
49
|
+
const { data, integrity } = await fetchExactNpmArtifact(PI_PACKAGE, version, ports.fetch ?? fetch, AbortSignal.timeout(FETCH_MS), LIMITS);
|
|
50
|
+
const home = ports.home ?? hubHome();
|
|
51
|
+
mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
52
|
+
const root = piInstallRoot(realPath(home));
|
|
53
|
+
for (const dir of [join(realPath(home), "agents"), root]) {
|
|
54
|
+
try { mkdirSync(dir, { mode: 0o700 }); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
|
|
55
|
+
if (!ownedPiDirectory(dir)) throw new PublicArtifactError("integrity");
|
|
56
|
+
}
|
|
57
|
+
const prefix = join(root, version);
|
|
58
|
+
let scratch: string | undefined;
|
|
59
|
+
try {
|
|
60
|
+
if (!existsSync(prefix)) {
|
|
61
|
+
scratch = mkdtempSync(join(root, ".install-"));
|
|
62
|
+
const staging = join(scratch, "prefix"), archive = join(scratch, "pi.tgz");
|
|
63
|
+
mkdirSync(staging, { mode: 0o700 });
|
|
64
|
+
writeFileSync(archive, data, { flag: "wx", mode: 0o600 });
|
|
65
|
+
await (ports.install ?? installArchive)(staging, archive, scratch);
|
|
66
|
+
await matchingInstall(staging, version, data);
|
|
67
|
+
try { renameSync(staging, prefix); } catch (error) { if (!existsSync(prefix)) throw error; }
|
|
68
|
+
}
|
|
69
|
+
const command = await matchingInstall(prefix, version, data);
|
|
70
|
+
const pending = join(root, `.current-${randomUUID()}`);
|
|
71
|
+
try {
|
|
72
|
+
writeFileSync(pending, JSON.stringify({ version, integrity }) + "\n", { flag: "wx", mode: 0o600 });
|
|
73
|
+
renameSync(pending, join(root, "current.json"));
|
|
74
|
+
} finally { rmSync(pending, { force: true }); }
|
|
75
|
+
return { version, command };
|
|
76
|
+
} finally { if (scratch) rmSync(scratch, { recursive: true, force: true }); }
|
|
77
|
+
}
|
package/src/pi/pin.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { existsSync, lstatSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
3
|
+
import { hubHome, realPath } from "../hub/project.ts";
|
|
4
|
+
|
|
5
|
+
export const PI_PACKAGE = "@earendil-works/pi-coding-agent";
|
|
6
|
+
const MAX_PIN_BYTES = 4096;
|
|
7
|
+
export const piInstallRoot = (home = hubHome()): string => join(home, "agents", "pi");
|
|
8
|
+
|
|
9
|
+
function inside(root: string, path: string): boolean {
|
|
10
|
+
const suffix = relative(root, path);
|
|
11
|
+
return suffix !== ".." && !suffix.startsWith(`..${sep}`) && !isAbsolute(suffix);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** The launcher and installer accept pins only from the same user-owned directories. */
|
|
15
|
+
export function ownedPiDirectory(path: string): boolean {
|
|
16
|
+
const stat = lstatSync(path);
|
|
17
|
+
return stat.isDirectory() && (stat.mode & 0o022) === 0 && (!process.getuid || stat.uid === process.getuid());
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function piInstalledCommand(prefix: string, version: string): string | undefined {
|
|
21
|
+
try {
|
|
22
|
+
if (!ownedPiDirectory(prefix)) return;
|
|
23
|
+
const packageRoot = realPath(join(prefix, "node_modules", PI_PACKAGE));
|
|
24
|
+
if (!inside(realPath(prefix), packageRoot)) return;
|
|
25
|
+
const manifest = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
|
|
26
|
+
const bin: unknown = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.pi;
|
|
27
|
+
if (manifest.name !== PI_PACKAGE || manifest.version !== version || typeof bin !== "string") return;
|
|
28
|
+
const command = join(prefix, "node_modules", ".bin", "pi");
|
|
29
|
+
const actual = realPath(command);
|
|
30
|
+
if (!inside(packageRoot, actual) || actual !== realPath(resolve(packageRoot, bin))) return;
|
|
31
|
+
const file = statSync(actual);
|
|
32
|
+
if (file.isFile() && file.mode & 0o111) return command;
|
|
33
|
+
} catch { /* a missing or incomplete install is not launch authority */ }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function readPiPin(verified: readonly string[], home = hubHome()): { version: string; command: string } | undefined {
|
|
37
|
+
try {
|
|
38
|
+
const root = piInstallRoot(home), file = join(root, "current.json");
|
|
39
|
+
if (!existsSync(file) || !ownedPiDirectory(join(home, "agents")) || !ownedPiDirectory(root)) return;
|
|
40
|
+
const stat = lstatSync(file);
|
|
41
|
+
if (!stat.isFile() || stat.size > MAX_PIN_BYTES || (stat.mode & 0o077) !== 0
|
|
42
|
+
|| (process.getuid && stat.uid !== process.getuid())) return;
|
|
43
|
+
const { version, integrity } = JSON.parse(readFileSync(file, "utf8"));
|
|
44
|
+
if (typeof version !== "string" || !verified.includes(version)
|
|
45
|
+
|| typeof integrity !== "string" || !/^sha(256|384|512)-[A-Za-z0-9+/]+={0,2}$/.test(integrity)) return;
|
|
46
|
+
const command = piInstalledCommand(join(root, version), version);
|
|
47
|
+
if (command) return { version, command };
|
|
48
|
+
} catch { /* invalid records do not select an executable */ }
|
|
49
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Leaf of the import graph (#1830 S1): no import from this repository, so every light entry (#1778) may import it.
|
|
5
|
+
* Share primitives here only when the local implementations have identical behavior.
|
|
6
|
+
*/
|
|
7
|
+
export const isRecord = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
|
|
8
|
+
|
|
9
|
+
export const sha256Hex = (value: string | Uint8Array): string => createHash("sha256").update(value).digest("hex");
|
|
10
|
+
export const shellQuote = (value: string): string => `'${value.replace(/'/g, `'\\''`)}'`;
|
|
11
|
+
|
|
12
|
+
export const asRecord = (value: unknown): Record<string, unknown> | undefined => isRecord(value) ? value : undefined;
|
|
13
|
+
|
|
14
|
+
export const recordOrEmpty = (value: unknown): Record<string, unknown> => isRecord(value) ? value : {};
|
package/src/version.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import pkg from "../package.json";
|
|
2
|
+
import type { SessionContract } from "./hub/upgrade-session-contract.ts";
|
|
2
3
|
|
|
3
4
|
/** The one version. `scripts/build.mjs` stamps it into the plugin manifest and the bundle, and `--check` fails when they differ. */
|
|
4
5
|
export const VERSION: string = pkg.version;
|
|
6
|
+
export const SESSION_CONTRACT: SessionContract = pkg.sessionContract;
|
|
5
7
|
|
|
6
8
|
const SEMVER = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?(?:\+[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/;
|
|
7
9
|
/** A version another process reported, kept only when it is a plain semver of at most 64 characters; anything else is unknown, never shown. Display only (#1385). */
|
package/templates/adec/README.md
CHANGED
|
@@ -20,12 +20,16 @@ The `contextLimit` value `20000` and `minMargin` value `0.05` are example
|
|
|
20
20
|
settings, not measured or calibrated defaults. ADEc's `minMargin` is independent
|
|
21
21
|
of the hub's `ambiguous_band`.
|
|
22
22
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
23
|
+
Decision mode defaults to off. The stage and plan/execute examples here use
|
|
24
|
+
shadow when enabled. Stage, phase and judge routes support shadow observation
|
|
25
|
+
only, so the host keeps its model, effort, phase transitions and review or
|
|
26
|
+
escalation rules.
|
|
27
|
+
|
|
28
|
+
On a separate `type = "decision"` route, a person can enable
|
|
29
|
+
`decision_mode = "enforce"` in `.agenthub/routing.toml`. The hub applies a
|
|
30
|
+
validated, non-abstaining pair and sends its `reasoning_effort` to the gateway.
|
|
31
|
+
An abstention, timeout, failure or ineligible pair uses `constraints.current`.
|
|
32
|
+
The person owns local ADEc policy placement and service configuration.
|
|
29
33
|
|
|
30
34
|
No provider, alias, effort, latency gain, live model behavior, or production
|
|
31
35
|
readiness is established by these examples. The manual model-routing receipt
|
package/templates/config.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"qwen_cmd": ["qwen", "--acp"],
|
|
5
5
|
"jcode_cmd": ["jcode"],
|
|
6
6
|
"codex_bin": "codex",
|
|
7
|
-
"pi": { "enabled": false, "auto_start": false, "
|
|
7
|
+
"pi": { "enabled": false, "auto_start": false, "backend": "auto", "dgx_coding": "coding", "dgx_fast": "fast", "max_steps": 100 },
|
|
8
8
|
"batch_max": 3,
|
|
9
9
|
"batch_ms": 15000,
|
|
10
10
|
"queue_cap": 200,
|
package/templates/specs.block.md
CHANGED
|
@@ -3,3 +3,4 @@
|
|
|
3
3
|
- Design specs are Markdown files with `id` and `type` frontmatter whose `paths` name the files they govern. The hub names the specs covering a task when you propose or accept it, and `hub_specs` answers on request.
|
|
4
4
|
- Read a covering spec when your change touches a boundary, contract, invariant or decision it states. Follow it, or reconcile the contradiction; never silently diverge.
|
|
5
5
|
- When your change alters one of those, update the owning spec in the same change. Never edit `verified-against`; a person stamps it.
|
|
6
|
+
- For a move, rename or refactor that preserves those rules, leave the spec as written. For public work with specs review enabled, pass `spec_ack: [{id, reason}]` to `hub_task_done` for each unchanged covering spec at the submitted head, with its id and a public reason such as "moves only, with the same boundaries and contracts", to avoid a roadmap drift report. After filing, add a missed acknowledgement with `hub_spec_ack {id, head, spec_ack}` at the filed head.
|