@staix/agent-hub 0.35.0 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +43 -0
- package/README.md +25 -4
- package/THIRD_PARTY_NOTICES.md +0 -18
- package/docs/agent-notes/README.md +71 -1
- package/docs/agent-notes/adapters.md +5 -2
- package/docs/agent-notes/bus.md +1 -0
- package/docs/agent-notes/daemon.md +7 -6
- package/docs/agent-notes/local-worker.md +1 -0
- package/docs/agent-notes/models.md +5 -3
- package/docs/agent-notes/tasks.md +9 -2
- package/docs/agent-notes/tests.md +1 -1
- package/docs/contracts/companion-cli-v1.json +70 -0
- package/docs/design/adapters.md +115 -2
- package/docs/design/agent-hub-architecture.md +10 -2
- package/docs/design/bus.md +8 -0
- package/docs/design/execution-reference.md +171 -11
- package/docs/design/guidance-experiments.md +438 -0
- package/docs/design/guidance-probes.md +802 -0
- package/docs/design/model-routes.md +1053 -0
- package/docs/design/supervision.md +121 -0
- package/docs/design/task-board.md +111 -0
- package/docs/dogfood.md +24 -15
- package/docs/events.md +20 -1
- package/docs/memory.md +3 -3
- package/docs/operations.md +366 -133
- package/docs/profiles.md +2 -2
- package/docs/quickstart.md +114 -3
- package/docs/research.md +5 -3
- package/docs/sdlc.md +113 -7
- package/docs/security.md +88 -6
- package/docs/specs/2026-09-19-agent-hub-design.md +14 -11
- package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
- package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
- package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
- package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
- package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +61 -0
- package/docs/verification/2026-11-10-0.36.0.md +59 -0
- package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
- package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
- package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
- package/docs/verification/2026-11-11-0.37.0.md +40 -0
- package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
- package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
- package/docs/verification/claude-shell-wrapper-native.py +1 -1
- package/docs/verified.json +27 -27
- package/package.json +3 -4
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +3570 -1800
- package/plugins/agent-hub/server.js +4112 -1913
- package/src/adapters/channel-peer.ts +7 -1
- package/src/adapters/claude-channel.ts +7 -4
- package/src/adapters/compat.ts +10 -10
- package/src/adapters/local-probe.ts +174 -0
- package/src/adapters/local-worker.ts +233 -22
- package/src/adapters/qwen-dual.ts +324 -44
- package/src/cli/console-state.ts +25 -6
- package/src/cli/console-versions.ts +99 -0
- package/src/cli/console.ts +13 -1
- package/src/cli/guidance.ts +67 -0
- package/src/cli/help.ts +12 -4
- package/src/cli/identity.ts +10 -3
- package/src/cli/init-prompt.ts +15 -2
- package/src/cli/init-required-checks.ts +122 -0
- package/src/cli/init-settings.ts +10 -4
- package/src/cli/init.ts +39 -3
- package/src/cli/install-paths.ts +7 -2
- package/src/cli/lineage.ts +78 -0
- package/src/cli/main.ts +171 -14
- package/src/cli/runtime-version-warning.ts +2 -2
- package/src/cli/sdlc-output.ts +9 -5
- package/src/cli/setup-research.ts +10 -0
- package/src/hub/autonomy-defaults.ts +20 -9
- package/src/hub/board.ts +346 -4
- package/src/hub/build-entry.ts +11 -0
- package/src/hub/bus.ts +12 -0
- package/src/hub/ci-watch.ts +4 -4
- package/src/hub/config-apply.ts +6 -3
- package/src/hub/config-trust.ts +7 -1
- package/src/hub/control-client.ts +5 -2
- package/src/hub/daemon.ts +508 -26
- package/src/hub/delivery-hints.ts +4 -2
- package/src/hub/delivery-journal.ts +50 -2
- package/src/hub/delivery-public.ts +51 -0
- package/src/hub/dogfood-profile.ts +8 -4
- package/src/hub/events.ts +3 -2
- package/src/hub/execution-lineage-owner.ts +272 -0
- package/src/hub/execution-lineage.ts +52 -8
- package/src/hub/execution-links.ts +85 -0
- package/src/hub/guidance-probe-store.ts +713 -0
- package/src/hub/guidance-probes.ts +358 -0
- package/src/hub/guidance-variants.ts +398 -0
- package/src/hub/handoff.ts +1 -0
- package/src/hub/hub-tools.ts +43 -2
- package/src/hub/inference.ts +18 -5
- package/src/hub/manager.ts +44 -2
- package/src/hub/memory-policy.ts +2 -2
- package/src/hub/operational-authority.ts +13 -1
- package/src/hub/peers.ts +6 -1
- package/src/hub/planning.ts +1 -1
- package/src/hub/ports.ts +1 -1
- package/src/hub/progress.ts +47 -23
- package/src/hub/report.ts +2 -0
- package/src/hub/research.ts +1 -0
- package/src/hub/restart.ts +20 -0
- package/src/hub/roles.ts +26 -0
- package/src/hub/routing.ts +4 -1
- package/src/hub/sdlc-merge.ts +39 -1
- package/src/hub/sdlc-release-authorization.ts +139 -17
- package/src/hub/sdlc-release-policy.ts +100 -0
- package/src/hub/sdlc-release.ts +60 -8
- package/src/hub/sdlc.ts +62 -11
- package/src/hub/settings.ts +2 -0
- package/src/hub/supervision-proposals.ts +405 -0
- package/src/hub/supervision-rules.ts +388 -0
- package/src/hub/supervision.ts +2 -0
- package/src/hub/task-approval.ts +2 -2
- package/src/hub/task-repository.ts +5 -0
- package/src/hub/tasks.ts +917 -53
- package/src/local/probe-errors.ts +28 -0
- package/src/local/probe-sandbox.ts +224 -0
- package/src/local/probe-types.ts +108 -0
- package/src/local/probe-workspace.ts +237 -0
- package/src/local/sandbox.ts +71 -2
- package/src/local/tools.ts +135 -9
- package/src/memory/capture.ts +2 -2
- package/src/models/relay.ts +9 -2
- package/src/models/route/advisor-trigger.ts +88 -0
- package/src/models/route/config.ts +39 -8
- package/src/models/route/conversation-view.ts +179 -0
- package/src/models/route/decision-evidence.ts +1 -1
- package/src/models/route/decision.ts +193 -26
- package/src/models/route/escalation-control.ts +30 -0
- package/src/models/route/hub-prompts.ts +97 -0
- package/src/models/route/judge-choice.ts +155 -0
- package/src/models/route/judge-replies.ts +102 -0
- package/src/models/route/labels.ts +14 -70
- package/src/models/route/observation-signals.ts +250 -0
- package/src/models/route/plan-execute-choice.ts +27 -0
- package/src/models/route/relay-selector.ts +10 -9
- package/src/models/route/runtime.ts +129 -60
- package/src/models/route/stage-diagnostics.ts +22 -0
- package/src/models/route/stage-evidence.ts +55 -0
- package/src/models/route/stage-fallback.ts +58 -0
- package/src/models/route/stage-input.ts +155 -0
- package/src/models/route/stage.ts +5 -147
- package/src/models/route/turn-state.ts +77 -0
- package/src/omniroute/client.ts +3 -0
- package/src/ui/guidance-panel.ts +156 -0
- package/src/ui/guidance-view.ts +43 -0
- package/src/ui/lineage-view.ts +34 -0
- package/src/ui/plugin.ts +141 -27
- package/src/version.ts +4 -0
- package/templates/adec/README.md +32 -0
- package/templates/adec/ahub.plan-execute.json +23 -0
- package/templates/adec/ahub.stage.json +23 -0
- package/LICENSES/Apache-2.0.txt +0 -204
- package/src/models/route/advisor.ts +0 -102
- package/src/models/route/escalation.ts +0 -82
- package/src/models/route/judge.ts +0 -23
- package/src/models/route/normalize.ts +0 -103
- package/src/models/route/plan-execute.ts +0 -52
- package/src/models/route/prompts.ts +0 -8
- package/src/models/route/signals.ts +0 -247
- package/src/models/route/state.ts +0 -54
- package/src/models/route/text.ts +0 -61
|
@@ -5,9 +5,9 @@ import { DecisionPolicyChangedError, type DecisionHost } from "../models/route/d
|
|
|
5
5
|
import { HubRouteRuntime, type RouteEvent, type AdvisorEvent } from "../models/route/runtime.ts";
|
|
6
6
|
import type { HubRoute } from "../models/route/config.ts";
|
|
7
7
|
import type { RouteLabelEvent, RouteTurnOutcome } from "../models/route/labels.ts";
|
|
8
|
-
import type { StaySwitchPolicy } from "../models/route/stage.ts";
|
|
9
|
-
import type { ToolObservation } from "../
|
|
10
|
-
import { randomUUID } from "node:crypto";
|
|
8
|
+
import type { StaySwitchPolicy } from "../models/route/stage-fallback.ts";
|
|
9
|
+
import type { NativeToolObservation as ToolObservation } from "../hub/progress.ts";
|
|
10
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
11
11
|
import { MAX_HOP, remoteEnvelope, renderDigest, replyAudience, replyParent, STANDING_INSTRUCTION, USER, type Envelope, type EnvelopeOpts, type PeerId } from "../hub/envelope.ts";
|
|
12
12
|
import { CONDUCTOR_TOOL_NAMES, CONDUCTOR_TOOLS, TASK_TOOL_NAMES, TASK_TOOLS, profileTaskTools, SESSION_TITLE_TOOL } from "../hub/hub-tools.ts";
|
|
13
13
|
import { BasePeer, type SessionTitleResult } from "../hub/peers.ts";
|
|
@@ -15,13 +15,22 @@ import type { PublishResult } from "../hub/bus.ts";
|
|
|
15
15
|
import { profile, proxyEnv, type SandboxNetwork } from "../local/sandbox.ts";
|
|
16
16
|
import type { DocReadPort } from "../local/doc-read.ts";
|
|
17
17
|
import type { WebFetchPort } from "../local/web-fetch.ts";
|
|
18
|
-
import { DOC_READ_SCHEMA, WEB_FETCH_SCHEMA, runTool, toolResultFailed, TOOL_SCHEMAS, touchedPaths, ApprovalWaitStop,
|
|
18
|
+
import { DOC_READ_SCHEMA, WEB_FETCH_SCHEMA, runTool, toolResultFailed, TOOL_SCHEMAS, touchedPaths, ApprovalWaitStop, planProbeTool, requireProbeToolWrite,
|
|
19
|
+
type ProbeToolResourcePlan, type ToolApproval, type ApprovalProvenance, type ToolContext } from "../local/tools.ts";
|
|
19
20
|
import type { Capture } from "../memory/capture.ts";
|
|
20
21
|
import type { ChatMessage, ChatResult, OmniRoute, ToolCall } from "../omniroute/client.ts";
|
|
21
22
|
import { safeModelLabel } from "../omniroute/usage.ts";
|
|
22
23
|
import { effectiveLocalRoute } from "../hub/routing.ts";
|
|
23
24
|
import type { ExecutionBudgetDecision } from "../hub/execution-budget.ts";
|
|
24
25
|
import type { OwnedInputContext, OwnedInputObserver } from "./claude-print-child.ts";
|
|
26
|
+
import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
|
|
27
|
+
import { GUIDANCE_PROBE_MODEL, GUIDANCE_PROBE_SESSION_BYTES, guidanceProbeCanonical, probeHash, probeInteger,
|
|
28
|
+
type ProbeResourceCharges, type ProbeSlot, type ProbeStoredState } from "../hub/guidance-probes.ts";
|
|
29
|
+
import { ProbeLocalError, probeLocalEffect, probeObservedTokens, type ProbeLocalModelConfig, type ProbeLocalRequest,
|
|
30
|
+
type ProbeLocalResult, type ProbeLocalSession, type ProbePreparedLocalInput } from "../local/probe-types.ts";
|
|
31
|
+
import { requireProbeConfinement, type ProbeConfinement } from "../local/probe-sandbox.ts";
|
|
32
|
+
import { probeRelativePath, reserveProbeWorkspaceBytes } from "../local/probe-workspace.ts";
|
|
33
|
+
import { ProbeToolRefusal, formatProbeToolRefusal } from "../local/probe-errors.ts";
|
|
25
34
|
|
|
26
35
|
export interface LocalOptions {
|
|
27
36
|
/** Host-only choice sampled once at the next turn/review boundary. */
|
|
@@ -97,6 +106,75 @@ const system = (cwd: string, preamble = "") =>
|
|
|
97
106
|
preamble,
|
|
98
107
|
].filter(Boolean).join("\n");
|
|
99
108
|
|
|
109
|
+
const probeSchemas = () => TOOL_SCHEMAS.filter(tool => ["read", "write", "edit"].includes(tool.function.name));
|
|
110
|
+
const probePolicy = () => `${system("/workspace")}\nThis is a private guidance probe. Only read, write and edit are available. Do not send messages, change sessions or invoke hub, package, shell or network operations.`;
|
|
111
|
+
const probeRoleInstruction = (role: Exclude<ProbeSlot["role"], "worker">): string => ({
|
|
112
|
+
proposal: "Propose one guidance revision using only this task and its admitted evidence. Return the proposed text for private host inspection.",
|
|
113
|
+
compose: "Compose one guidance revision from the admitted proposals and evidence. Return the proposed text for private host inspection.",
|
|
114
|
+
select: "Compare only the anonymous deliverables and admitted task sources. Return a reasoned private selection using their anonymous names.",
|
|
115
|
+
reflect: "Review only the admitted evidence from the closed round. Return bounded observations and unresolved questions for private host inspection.",
|
|
116
|
+
})[role];
|
|
117
|
+
|
|
118
|
+
function probeRuntimeHash(): string {
|
|
119
|
+
const sources = [import.meta.url, new URL("../local/probe-types.ts", import.meta.url), new URL("./local-probe.ts", import.meta.url),
|
|
120
|
+
new URL("../local/probe-workspace.ts", import.meta.url), new URL("../local/probe-sandbox.ts", import.meta.url),
|
|
121
|
+
new URL("../local/tools.ts", import.meta.url), new URL("../local/probe-errors.ts", import.meta.url),
|
|
122
|
+
new URL("../local/sandbox.ts", import.meta.url), new URL("../omniroute/client.ts", import.meta.url)].map(value => {
|
|
123
|
+
const file = openSync(new URL(value), constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
124
|
+
try {
|
|
125
|
+
const before = fstatSync(file);
|
|
126
|
+
if (!before.isFile() || before.size > GUIDANCE_PROBE_SESSION_BYTES) throw new ProbeLocalError("invalid");
|
|
127
|
+
const buffer = Buffer.alloc(GUIDANCE_PROBE_SESSION_BYTES + 1), bytes = readSync(file, buffer, 0, buffer.length, 0), after = fstatSync(file);
|
|
128
|
+
if (bytes !== before.size || before.size !== after.size || before.ino !== after.ino || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs)
|
|
129
|
+
throw new ProbeLocalError("drift");
|
|
130
|
+
return createHash("sha256").update(buffer.subarray(0, bytes)).digest("hex");
|
|
131
|
+
} finally { closeSync(file); }
|
|
132
|
+
});
|
|
133
|
+
return probeHash(guidanceProbeCanonical({ engine: process.versions.bun ?? null, platform: process.platform, arch: process.arch, sources }));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Host preregistration helper; fingerprints actual trusted policy, code, tool schemas and frozen generation configuration. */
|
|
137
|
+
export function localProbeFingerprints(config: Readonly<ProbeLocalModelConfig>): {
|
|
138
|
+
systemPolicy: string; runtimeSha256: string; toolsetSha256: string; modelConfigSha256: string;
|
|
139
|
+
} {
|
|
140
|
+
if (!probeInteger(config.maxSteps) || !config.maxSteps || !probeInteger(config.maxOutputTokens) || !config.maxOutputTokens
|
|
141
|
+
|| config.tokenUpperBound !== undefined && (!probeInteger(config.tokenUpperBound) || !config.tokenUpperBound)) throw new ProbeLocalError("invalid");
|
|
142
|
+
const modelConfig = { maxSteps: config.maxSteps, maxOutputTokens: config.maxOutputTokens,
|
|
143
|
+
...(config.tokenUpperBound === undefined ? {} : { tokenUpperBound: config.tokenUpperBound }) };
|
|
144
|
+
return { systemPolicy: probePolicy(), runtimeSha256: probeRuntimeHash(), toolsetSha256: probeHash(guidanceProbeCanonical(probeSchemas())),
|
|
145
|
+
modelConfigSha256: probeHash(guidanceProbeCanonical(modelConfig)) };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Exact initial wire request, before any worker or materialization effect. Guidance is one explicit host slot. */
|
|
149
|
+
export function prepareLocalProbeInput(state: ProbeStoredState, slot: ProbeSlot, guidance: string,
|
|
150
|
+
files: ProbePreparedLocalInput["files"], config: Readonly<ProbeLocalModelConfig>): ProbePreparedLocalInput {
|
|
151
|
+
const actual = localProbeFingerprints(config), manifest = state.registration.manifest, snapshots = state.registration.snapshots;
|
|
152
|
+
if (manifest.limits.tokens !== undefined && config.tokenUpperBound === undefined) throw new ProbeToolRefusal("token_bound_unavailable");
|
|
153
|
+
if (manifest.runtime.runtimeSha256 !== actual.runtimeSha256 || manifest.runtime.toolsetSha256 !== actual.toolsetSha256
|
|
154
|
+
|| manifest.runtime.modelConfigSha256 !== actual.modelConfigSha256 || snapshots.systemPolicy !== actual.systemPolicy
|
|
155
|
+
|| manifest.model.requested !== GUIDANCE_PROBE_MODEL || manifest.model.expectedServed !== GUIDANCE_PROBE_MODEL) throw new ProbeLocalError("drift");
|
|
156
|
+
const rolePolicy = snapshots.dataPolicy.roles[slot.role];
|
|
157
|
+
if (!rolePolicy || files.length !== rolePolicy.dataIds.length || files.some(file => !rolePolicy.dataIds.includes(file.dataId))) throw new ProbeLocalError("invalid");
|
|
158
|
+
const visibleFiles = files.map(({ relative, sha256, bytes }) => ({ relative, sha256, bytes }));
|
|
159
|
+
const writes = snapshots.dataPolicy.allowedWrites.map(({ root, relative }) => {
|
|
160
|
+
if (!["scratch", "output"].includes(root) || !probeRelativePath(relative)) throw new ProbeLocalError("invalid");
|
|
161
|
+
return `/workspace/${root}/${relative}`;
|
|
162
|
+
});
|
|
163
|
+
const writeInstruction = writes.length ? `Admitted logical write targets: ${writes.join(", ")}. No other target is writable.`
|
|
164
|
+
: "No write target is admitted. Use only declared read inputs.";
|
|
165
|
+
const context = slot.role === "reflect" ? { role: slot.role, files: visibleFiles }
|
|
166
|
+
: slot.role === "select" ? { role: slot.role, task: snapshots.task, files: visibleFiles }
|
|
167
|
+
: { role: slot.role, task: snapshots.task, baselineContext: snapshots.baselineContext, files: visibleFiles,
|
|
168
|
+
...((slot.role === "proposal" || slot.role === "compose") && snapshots.dataPolicy.roles[slot.role].improverContext
|
|
169
|
+
? { improverContext: snapshots.improverContext ?? (() => { throw new ProbeLocalError("invalid"); })() } : {}) };
|
|
170
|
+
const requestFor = (slotGuidance: string): ProbeLocalRequest => ({ model: GUIDANCE_PROBE_MODEL,
|
|
171
|
+
messages: [{ role: "system", content: `${actual.systemPolicy}\n${writeInstruction}` }, { role: "system", content: slot.role === "worker" ? slotGuidance : probeRoleInstruction(slot.role) }, { role: "user", content: JSON.stringify(context) }],
|
|
172
|
+
tools: probeSchemas(), max_tokens: config.maxOutputTokens, stream: false });
|
|
173
|
+
const request = requestFor(guidance), inputFrame = JSON.stringify(request);
|
|
174
|
+
return { inputFrame, inputSha256: probeHash(inputFrame), nonGuidanceInputSha256: probeHash(JSON.stringify(requestFor(""))),
|
|
175
|
+
request: JSON.parse(inputFrame) as ProbeLocalRequest, role: slot.role, files };
|
|
176
|
+
}
|
|
177
|
+
|
|
100
178
|
/** Hub-native agent loop: the hub owns every model call, so it can choose the model per call (L2) and the gateway (L3). */
|
|
101
179
|
export class LocalPeer extends BasePeer {
|
|
102
180
|
readonly hubNative = true;
|
|
@@ -138,12 +216,24 @@ export class LocalPeer extends BasePeer {
|
|
|
138
216
|
private currentObserverInputContext: OwnedInputContext | undefined;
|
|
139
217
|
private observerInputReleasedId: string | undefined;
|
|
140
218
|
private readonly sandboxProfile: string; // built once: profile() spawns git and must stay off the per-call path
|
|
219
|
+
private probeSession: ProbeLocalSession | undefined;
|
|
220
|
+
private probePromise: Promise<ProbeLocalResult> | undefined;
|
|
221
|
+
private probeStarted = false;
|
|
222
|
+
private probeStopping = false;
|
|
223
|
+
private probeCalls = 0;
|
|
224
|
+
private probeServedModel: string | null = null;
|
|
225
|
+
private probeServedExact = false;
|
|
226
|
+
private probeUsageKnown = true;
|
|
227
|
+
private probeToolPlan: ProbeToolResourcePlan | undefined;
|
|
228
|
+
private readonly probePermits = new Set<Promise<unknown>>();
|
|
141
229
|
/** What served the last call, for `ahub status`. */
|
|
142
230
|
lastServedBy = "";
|
|
143
231
|
|
|
144
232
|
constructor(
|
|
145
233
|
id: PeerId,
|
|
146
234
|
private readonly opts: LocalOptions,
|
|
235
|
+
private readonly probeConfinement?: ProbeConfinement,
|
|
236
|
+
private readonly probeFixture?: "fixture_only",
|
|
147
237
|
) {
|
|
148
238
|
super(id, opts.watchdogMs);
|
|
149
239
|
this.routes = new HubRouteRuntime({
|
|
@@ -171,7 +261,7 @@ export class LocalPeer extends BasePeer {
|
|
|
171
261
|
onAdvisor: event => this.opts.onAdvisor?.(event),
|
|
172
262
|
onRouteOutcome: event => this.opts.onRouteOutcome?.(event),
|
|
173
263
|
});
|
|
174
|
-
this.sandboxProfile = profile(opts.cwd, opts.tools.bashNetwork ?? false, opts.tools.readAllow, opts.tools.deny, opts.tools.readOnly);
|
|
264
|
+
this.sandboxProfile = probeConfinement?.profile ?? profile(opts.cwd, opts.tools.bashNetwork ?? false, opts.tools.readAllow, opts.tools.deny, opts.tools.readOnly);
|
|
175
265
|
}
|
|
176
266
|
|
|
177
267
|
private decisionContext(): { pii: boolean; private: boolean; excluded: boolean } {
|
|
@@ -186,11 +276,13 @@ export class LocalPeer extends BasePeer {
|
|
|
186
276
|
}
|
|
187
277
|
|
|
188
278
|
async start(): Promise<void> {
|
|
279
|
+
if (this.probeConfinement) throw new ProbeLocalError("invalid");
|
|
189
280
|
this.opts.capture?.init(this.sessionId, "agent-hub local worker session");
|
|
190
281
|
this.setState("idle");
|
|
191
282
|
}
|
|
192
283
|
|
|
193
284
|
async stop(reason?: string): Promise<void> {
|
|
285
|
+
if (this.probeConfinement) return this.stopProbe();
|
|
194
286
|
this.endRouteTurn(this.labelTurnId, "failed");
|
|
195
287
|
if (this.activeDeliveryId) this.delivery({ id: this.activeDeliveryId, state: "needs_review", reason: reason ?? "turn stopped before settlement" });
|
|
196
288
|
this.activeDeliveryId = undefined;
|
|
@@ -201,8 +293,59 @@ export class LocalPeer extends BasePeer {
|
|
|
201
293
|
await this.opts.capture?.end();
|
|
202
294
|
}
|
|
203
295
|
|
|
296
|
+
/** A host-owned private instance shares this loop, never ordinary delivery or observer settlement. */
|
|
297
|
+
async runProbe(session: ProbeLocalSession, signal: AbortSignal): Promise<ProbeLocalResult> {
|
|
298
|
+
if (!this.probeConfinement || this.probeStarted || this.probePromise || this.state !== "offline" || this.history.length || this.title || this.activeDeliveryId || signal.aborted
|
|
299
|
+
|| session.purpose !== "guidance_probe" || session.confinement !== this.probeConfinement || session.workspace !== this.probeConfinement.workspace
|
|
300
|
+
|| session.workspace.root !== this.opts.cwd || this.opts.fixedModel !== GUIDANCE_PROBE_MODEL || this.opts.maxSteps !== session.config.maxSteps
|
|
301
|
+
|| session.prepared.inputSha256 !== probeHash(session.prepared.inputFrame) || JSON.stringify(session.prepared.request) !== session.prepared.inputFrame)
|
|
302
|
+
return Promise.reject(new ProbeLocalError("invalid"));
|
|
303
|
+
if (!this.probeFixture) requireProbeConfinement(this.probeConfinement, session.workspace);
|
|
304
|
+
session.accounting.current();
|
|
305
|
+
this.probeStarted = true; this.probeSession = session;
|
|
306
|
+
const turn = ++this.turn, controller = new AbortController(); this.abort = controller;
|
|
307
|
+
const cancel = () => controller.abort(); signal.addEventListener("abort", cancel, { once: true });
|
|
308
|
+
const msgs: ChatMessage[] = JSON.parse(JSON.stringify(session.prepared.request.messages.slice(1))) as ChatMessage[];
|
|
309
|
+
const progress = { sideEffects: 0, last: "", answerComplete: false };
|
|
310
|
+
this.probePromise = Promise.resolve().then(async () => {
|
|
311
|
+
session.accounting.current();
|
|
312
|
+
const answer = await this.run([], turn, msgs, progress, { pii: false }, {}, { excluded: false });
|
|
313
|
+
if (signal.aborted || controller.signal.aborted || this.probeStopping || turn !== this.turn) throw new ProbeLocalError("interrupted");
|
|
314
|
+
await session.reserve({ outputBytes: Buffer.byteLength(answer, "utf8") }, "probe-final-output");
|
|
315
|
+
return { answer, complete: progress.answerComplete, servedModel: this.probeServedModel,
|
|
316
|
+
servedModelExact: this.probeServedExact, usageKnown: this.probeUsageKnown };
|
|
317
|
+
}).catch(error => {
|
|
318
|
+
if (error instanceof ProbeToolRefusal && error.code === "token_ceiling") {
|
|
319
|
+
if (signal.aborted || controller.signal.aborted || this.probeStopping || turn !== this.turn) throw new ProbeLocalError("interrupted");
|
|
320
|
+
try { session.accounting.current(); } catch { throw new ProbeLocalError("interrupted"); }
|
|
321
|
+
return { answer: "", complete: false, servedModel: this.probeServedModel, servedModelExact: this.probeServedExact,
|
|
322
|
+
usageKnown: this.probeCalls > 0 && this.probeUsageKnown, refusal: "token_ceiling" as const, reason: formatProbeToolRefusal(error) };
|
|
323
|
+
}
|
|
324
|
+
throw error instanceof ProbeLocalError ? error : new ProbeLocalError("interrupted");
|
|
325
|
+
})
|
|
326
|
+
.finally(async () => {
|
|
327
|
+
signal.removeEventListener("abort", cancel); this.clearWatchdog();
|
|
328
|
+
await Promise.allSettled([...this.probePermits]);
|
|
329
|
+
this.probeSession = undefined;
|
|
330
|
+
});
|
|
331
|
+
return this.probePromise;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** No timeout is success: the outer owner may bound this join and retain its handle on uncertainty. */
|
|
335
|
+
async stopProbe(): Promise<void> {
|
|
336
|
+
this.probeStopping = true; this.turn++; this.abort?.abort(); this.clearWatchdog();
|
|
337
|
+
if (this.probePromise) await this.probePromise.catch(() => {});
|
|
338
|
+
await this.probeConfinement?.stop();
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Private adapter bookkeeping, not an ordinary usage/status observer. */
|
|
342
|
+
probeObservation(): Pick<ProbeLocalResult, "servedModel" | "servedModelExact" | "usageKnown"> {
|
|
343
|
+
return { servedModel: this.probeServedModel, servedModelExact: this.probeServedExact, usageKnown: this.probeUsageKnown };
|
|
344
|
+
}
|
|
345
|
+
|
|
204
346
|
/** Resolves once the turn is claimed; a turn that cannot reach any model hands the envelopes back through onFailed. */
|
|
205
347
|
async deliver(envs: Envelope[], deliveryId?: string): Promise<void> {
|
|
348
|
+
if (this.probeConfinement) throw new ProbeLocalError("invalid");
|
|
206
349
|
if (this.state !== "idle") {
|
|
207
350
|
if (deliveryId) this.delivery({ id: deliveryId, state: "failed_safe", reason: `${this.id} is ${this.state}` });
|
|
208
351
|
throw new Error(`${this.id} is ${this.state}`);
|
|
@@ -296,6 +439,7 @@ export class LocalPeer extends BasePeer {
|
|
|
296
439
|
}
|
|
297
440
|
|
|
298
441
|
protected override onWatchdog(): void {
|
|
442
|
+
if (this.probeConfinement) { this.probeStopping = true; this.turn++; this.abort?.abort(); this.clearWatchdog(); return; }
|
|
299
443
|
this.endRouteTurn(this.labelTurnId, "failed");
|
|
300
444
|
if (this.activeDeliveryId) this.delivery({ id: this.activeDeliveryId, state: "needs_review", reason: "turn watchdog timeout", failureCause: "timeout" });
|
|
301
445
|
this.activeDeliveryId = undefined;
|
|
@@ -322,6 +466,7 @@ export class LocalPeer extends BasePeer {
|
|
|
322
466
|
// Remote text/tool output is never memory evidence, even beside ordinary local work in the same turn.
|
|
323
467
|
const remoteTurn = envs.some(remoteEnvelope);
|
|
324
468
|
const capture = policy?.pii || remoteTurn ? undefined : this.opts.capture;
|
|
469
|
+
const activeCapture = this.probeConfinement ? undefined : capture;
|
|
325
470
|
// Unknown gateway state is never permission to send PII.
|
|
326
471
|
if (policy?.pii && !(await this.opts.omni.onCampus())) {
|
|
327
472
|
return "Refused: this is a PII task and the only reachable gateway is off campus (Cloudflare Access). Connect the VPN and assign it again.";
|
|
@@ -330,7 +475,9 @@ export class LocalPeer extends BasePeer {
|
|
|
330
475
|
this.routePii = !!policy?.pii;
|
|
331
476
|
this.routeReviewScope = reviewScope;
|
|
332
477
|
if (turn !== this.turn || turnSignal.aborted) return "";
|
|
333
|
-
const fixedPrompt = this.
|
|
478
|
+
const fixedPrompt = this.probeConfinement
|
|
479
|
+
? this.probeSession?.prepared.request.messages[0]?.content ?? (() => { throw new ProbeLocalError("invalid"); })()
|
|
480
|
+
: this.turnRecordPrompt(system(this.opts.cwd, this.opts.preamble));
|
|
334
481
|
const ctx = this.toolContext(envs, turnSignal, !!policy?.pii, reply);
|
|
335
482
|
let usedTools = false;
|
|
336
483
|
let captureInvocation = 0;
|
|
@@ -338,23 +485,23 @@ export class LocalPeer extends BasePeer {
|
|
|
338
485
|
this.elide(msgs);
|
|
339
486
|
const res = await this.call(msgs, policy, envs, selection, fixedPrompt);
|
|
340
487
|
if (turn !== this.turn) return "";
|
|
341
|
-
this.touch();
|
|
488
|
+
if (!this.probeConfinement) this.touch();
|
|
342
489
|
msgs.push(res.message);
|
|
343
490
|
progress.last = res.message.content?.trim() || progress.last;
|
|
344
491
|
if (!res.message.tool_calls?.length) {
|
|
345
492
|
const concluded = await this.conclude(msgs, policy, turn, step, maxSteps, progress.last, turnSignal, res.routeDecision, selection, fixedPrompt);
|
|
346
493
|
if (turn !== this.turn) return "";
|
|
347
494
|
if (concluded === undefined) continue;
|
|
348
|
-
if (usedTools && !reviewScope.excluded)
|
|
495
|
+
if (usedTools && !reviewScope.excluded) activeCapture?.summarize(concluded.answer);
|
|
349
496
|
progress.answerComplete = concluded.complete;
|
|
350
497
|
return concluded.answer;
|
|
351
498
|
}
|
|
352
|
-
if (res.message.tool_calls.some(call => call.function.name.replace(/^mcp__[^ ]+__/, "") === "hub_review" && reviewCaptureExcluded(call.function.name, call.function.arguments))) reviewScope.excluded = true;
|
|
499
|
+
if (!this.probeConfinement && res.message.tool_calls.some(call => call.function.name.replace(/^mcp__[^ ]+__/, "") === "hub_review" && reviewCaptureExcluded(call.function.name, call.function.arguments))) reviewScope.excluded = true;
|
|
353
500
|
const results: ChatMessage[] = [];
|
|
354
501
|
try {
|
|
355
502
|
for (const call of res.message.tool_calls) {
|
|
356
503
|
// A tool has its own timeout (bash up to 600 s) and an approval can take 120 s: neither is the model going silent.
|
|
357
|
-
const alive = setInterval(() => this.state === "busy" && turn === this.turn && this.touch(), 30_000);
|
|
504
|
+
const alive = this.probeConfinement ? undefined : setInterval(() => this.state === "busy" && turn === this.turn && this.touch(), 30_000);
|
|
358
505
|
const name = call.function.name;
|
|
359
506
|
try {
|
|
360
507
|
await this.requireBudget(envs, "tool_calls");
|
|
@@ -362,14 +509,27 @@ export class LocalPeer extends BasePeer {
|
|
|
362
509
|
} catch (error) { clearInterval(alive); throw error; }
|
|
363
510
|
const taskToolName = name.replace(/^mcp__[^ ]+__/, "");
|
|
364
511
|
const reviewNoteWrite = taskToolName === "hub_remember" || taskToolName === "hub_task_propose";
|
|
365
|
-
const
|
|
512
|
+
const toolRun = () => this.probeConfinement && !["read", "write", "edit"].includes(name)
|
|
513
|
+
? Promise.resolve(formatProbeToolRefusal(new ProbeToolRefusal("tool_unavailable")))
|
|
514
|
+
: reviewScope.excluded && reviewNoteWrite
|
|
366
515
|
? Promise.resolve("error: anchored review in this batch; save notes in a later turn")
|
|
367
516
|
: (TASK_TOOL_NAMES.has(name) || CONDUCTOR_TOOL_NAMES.has(name)) && this.opts.taskTool
|
|
368
517
|
? this.opts.taskTool(name, safeParse(call.function.arguments), { pii: !!policy?.pii, signal: turnSignal }).catch((e: Error) => `error: ${e.message}`)
|
|
369
518
|
: runTool(name, call.function.arguments, ctx);
|
|
370
|
-
const
|
|
519
|
+
const probe = this.probeSession;
|
|
520
|
+
const running = probe ? (async () => {
|
|
521
|
+
try {
|
|
522
|
+
const plan = planProbeTool(name, call.function.arguments, ctx);
|
|
523
|
+
if (!this.probeFixture) reserveProbeWorkspaceBytes(probe.workspace, plan.scratchBytes + plan.outputBytes);
|
|
524
|
+
this.probeToolPlan = plan;
|
|
525
|
+
const charges: ProbeResourceCharges = { scratchBytes: plan.scratchBytes, outputBytes: plan.outputBytes };
|
|
526
|
+
return await probeLocalEffect(probe.accounting, "tool_calls", JSON.stringify({ name, arguments: call.function.arguments }), charges, undefined,
|
|
527
|
+
async () => ({ value: await toolRun(), usage: 1 }));
|
|
528
|
+
} catch (error) { if (error instanceof ProbeToolRefusal) return formatProbeToolRefusal(error); throw error; }
|
|
529
|
+
})() : toolRun();
|
|
530
|
+
const output = await running.finally(() => { clearInterval(alive); if (probe) this.probeToolPlan = undefined; });
|
|
371
531
|
if (turn !== this.turn) return "";
|
|
372
|
-
this.touch();
|
|
532
|
+
if (!this.probeConfinement) this.touch();
|
|
373
533
|
usedTools = true;
|
|
374
534
|
if (SIDE_EFFECTS.has(call.function.name) && !output.startsWith("error:")) progress.sideEffects++;
|
|
375
535
|
const result: ChatMessage = { role: "tool", tool_call_id: call.id, content: output, is_error: toolResultFailed(name, output) };
|
|
@@ -379,26 +539,36 @@ export class LocalPeer extends BasePeer {
|
|
|
379
539
|
// Hub tool arguments/results are not capture evidence; Tasks owns its screened memory writes.
|
|
380
540
|
// doc_read text is converted document content (a converter can surface hidden text), never memory evidence: not captured, whatever the turn.
|
|
381
541
|
// web_fetch text is a third party's page and its URL is the model's own request: neither is memory evidence either (#515b).
|
|
382
|
-
if (!reviewScope.excluded && name !== "hub_send" && name !== "doc_read" && name !== "web_fetch" && !TASK_TOOL_NAMES.has(name) && !CONDUCTOR_TOOL_NAMES.has(name))
|
|
542
|
+
if (!reviewScope.excluded && name !== "hub_send" && name !== "doc_read" && name !== "web_fetch" && !TASK_TOOL_NAMES.has(name) && !CONDUCTOR_TOOL_NAMES.has(name)) activeCapture?.observe({ tool: call.function.name, args: call.function.arguments, output, id: call.id, sourceId: `${this.sessionId}.${turn}.${step}.${captureInvocation++}`, paths: touchedPaths(call.function.name, safeParse(call.function.arguments)) });
|
|
383
543
|
}
|
|
384
|
-
} finally { if (results.length) this.routes.observeResults(res.routeDecision, res.message, results); }
|
|
544
|
+
} finally { if (results.length && !this.probeConfinement) this.routes.observeResults(res.routeDecision, res.message, results); }
|
|
385
545
|
}
|
|
386
|
-
if (usedTools && !reviewScope.excluded)
|
|
387
|
-
this.opts.onLimit?.("steps");
|
|
546
|
+
if (usedTools && !reviewScope.excluded) activeCapture?.summarize(progress.last);
|
|
547
|
+
if (!this.probeConfinement) this.opts.onLimit?.("steps");
|
|
388
548
|
return `(stopped after ${maxSteps} steps) ${progress.last}`.trim();
|
|
389
549
|
}
|
|
390
550
|
|
|
391
551
|
/** The base tools, plus `doc_read` and `web_fetch` only when the project opted in (`local.doc_read`, `local.web_fetch.allow`; both off by default). */
|
|
392
|
-
private toolSchemas() { const extra = [...(this.opts.tools.docRead ? [DOC_READ_SCHEMA] : []), ...(this.opts.tools.webFetch ? [WEB_FETCH_SCHEMA] : [])]; return extra.length ? [...TOOL_SCHEMAS, ...extra] : TOOL_SCHEMAS; }
|
|
552
|
+
private toolSchemas() { if (this.probeConfinement) return probeSchemas(); const extra = [...(this.opts.tools.docRead ? [DOC_READ_SCHEMA] : []), ...(this.opts.tools.webFetch ? [WEB_FETCH_SCHEMA] : [])]; return extra.length ? [...TOOL_SCHEMAS, ...extra] : TOOL_SCHEMAS; }
|
|
393
553
|
|
|
394
554
|
private toolContext(envs: Envelope[], turnSignal: AbortSignal, pii: boolean, reply: EnvelopeOpts): ToolContext {
|
|
395
555
|
const executionGeneration=this.turn;
|
|
396
|
-
|
|
556
|
+
const probe = this.probeSession;
|
|
557
|
+
const context: ToolContext = {
|
|
397
558
|
...(this.opts.tools.docRead ? { docRead: { ...this.opts.tools.docRead, pii } } : {}),
|
|
398
559
|
...(this.opts.tools.webFetch ? { webFetch: { ...this.opts.tools.webFetch, pii } } : {}),
|
|
399
560
|
cwd: this.opts.cwd,
|
|
400
561
|
deny: this.opts.tools.deny,
|
|
401
562
|
readOnly: this.opts.tools.readOnly,
|
|
563
|
+
...(probe ? { probe: { root: probe.workspace.root, writableRoots: probe.workspace.allowedWrites,
|
|
564
|
+
current: () => {
|
|
565
|
+
if (turnSignal.aborted || this.probeStopping) throw new ProbeToolRefusal("authority_stopped");
|
|
566
|
+
probe.accounting.current(); if (!this.probeFixture) requireProbeConfinement(probe.confinement, probe.workspace);
|
|
567
|
+
},
|
|
568
|
+
reserveWrite: async (bytes: number, canonicalPath: string) => {
|
|
569
|
+
if (!this.probeToolPlan) throw new ProbeLocalError("invalid");
|
|
570
|
+
requireProbeToolWrite(this.probeToolPlan, bytes, canonicalPath, context);
|
|
571
|
+
} } } : {}),
|
|
402
572
|
permit: async (title, tool, _signal, canonicalTarget, _observe, originalPath, input, policy) => {
|
|
403
573
|
if (turnSignal.aborted) return "aborted";
|
|
404
574
|
const generation = this.turn;
|
|
@@ -412,14 +582,17 @@ export class LocalPeer extends BasePeer {
|
|
|
412
582
|
if (provenance.source === "person") this.approvalExpiries = 0;
|
|
413
583
|
if (provenance.source === "expired" && provenance.eligibleExpiry !== false && ++this.approvalExpiries >= 2) {
|
|
414
584
|
this.approvalStopReason = "Local turn stopped after two unanswered approvals; no person answered. Do not retry the calls; inspect prior work before handoff or stopping.";
|
|
415
|
-
try { this.opts.onApprovalStop?.(this.approvalStopReason); } catch { /* stop remains authoritative */ }
|
|
585
|
+
try { if (!this.probeConfinement) this.opts.onApprovalStop?.(this.approvalStopReason); } catch { /* stop remains authoritative */ }
|
|
416
586
|
}
|
|
417
587
|
};
|
|
418
588
|
const picked = await new Promise<ToolApproval>((resolve, reject) => {
|
|
419
589
|
const finish = (decision: ToolApproval) => { turnSignal.removeEventListener("abort", onAbort); resolve(decision); };
|
|
420
590
|
const onAbort = () => finish("aborted");
|
|
421
591
|
turnSignal.addEventListener("abort", onAbort, { once: true });
|
|
422
|
-
this.opts.tools.permit(title, tool, turnSignal, canonicalTarget, observe, originalPath, input, policy)
|
|
592
|
+
const asking = this.opts.tools.permit(title, tool, turnSignal, canonicalTarget, observe, originalPath, input, policy);
|
|
593
|
+
if (this.probeConfinement) this.probePermits.add(asking);
|
|
594
|
+
void asking.then(finish, (error) => { turnSignal.removeEventListener("abort", onAbort); reject(error); })
|
|
595
|
+
.finally(() => { this.probePermits.delete(asking); });
|
|
423
596
|
});
|
|
424
597
|
if (generation !== this.turn || (turnSignal.aborted && picked !== "expired")) return "aborted";
|
|
425
598
|
// Legacy permit callbacks can represent a person's denial without provenance. A true
|
|
@@ -430,15 +603,17 @@ export class LocalPeer extends BasePeer {
|
|
|
430
603
|
},
|
|
431
604
|
shellExecutionCheck: input=>turnSignal.aborted||executionGeneration!==this.turn?"aborted":this.opts.tools.shellExecutionCheck?.(input)??"valid",
|
|
432
605
|
sandboxProfile: this.sandboxProfile,
|
|
433
|
-
sandboxEnv: { ...proxyEnv(this.opts.tools.bashNetwork ?? false), AGENTHUB_PEER_ID: this.id },
|
|
606
|
+
sandboxEnv: this.probeConfinement ? { ...this.probeConfinement.env } : { ...proxyEnv(this.opts.tools.bashNetwork ?? false), AGENTHUB_PEER_ID: this.id },
|
|
434
607
|
signal: turnSignal,
|
|
435
608
|
send: (text, to) => {
|
|
609
|
+
if (this.probeConfinement) return "error: messaging unavailable in guidance probe";
|
|
436
610
|
const result = this.onMessage?.(text, pii ? reply : { inReplyTo: replyParent(envs), to: to?.length ? to : replyAudience(envs) }) as PublishResult | string | undefined;
|
|
437
611
|
if (typeof result === "string") return `not sent: ${result}`;
|
|
438
612
|
if (result?.dropped === "hop") return `not delivered: reply chain reached the hop cap (${MAX_HOP}); send a new message without reply_to`;
|
|
439
613
|
return pii ? "sent to the console user only (PII task)" : "sent";
|
|
440
614
|
},
|
|
441
615
|
};
|
|
616
|
+
return context;
|
|
442
617
|
}
|
|
443
618
|
|
|
444
619
|
private reportBudgetStop(e: Error, msgs: ChatMessage[], progress: { sideEffects: number; last: string }, reply: EnvelopeOpts, privateHistory: boolean, deliveryId?: string, remoteTurn = false, reviewTurn = false): void {
|
|
@@ -455,6 +630,7 @@ export class LocalPeer extends BasePeer {
|
|
|
455
630
|
}
|
|
456
631
|
|
|
457
632
|
private async requireBudget(envs: Envelope[], unit: "model_calls" | "tool_calls"): Promise<void> {
|
|
633
|
+
if (this.probeConfinement) return;
|
|
458
634
|
if (!this.opts.admitBudget) return;
|
|
459
635
|
const decisions = await this.opts.admitBudget(envs, unit);
|
|
460
636
|
const denied = decisions.find((decision) => !decision.allowed);
|
|
@@ -482,6 +658,7 @@ export class LocalPeer extends BasePeer {
|
|
|
482
658
|
|
|
483
659
|
/** Hub-owned in-process policy, with a fixed OmniRoute alias as fallback. */
|
|
484
660
|
private async call(turnMsgs: ChatMessage[], policy: { route?: string; fixedModel?: string; pii?: boolean; task?: string } | undefined, envs: Envelope[], selection?: ModelOverrideSelection, fixedPrompt = system(this.opts.cwd, this.opts.preamble)): Promise<ChatResult> {
|
|
661
|
+
if (this.probeConfinement) return this.callProbe(turnMsgs, fixedPrompt);
|
|
485
662
|
const { omni } = this.opts;
|
|
486
663
|
const route = selection?.model === undefined ? effectiveLocalRoute(this.opts.route, policy?.route, policy?.fixedModel) : undefined;
|
|
487
664
|
if (route && !route.startsWith("hub/") && !this.warnedLegacyRoutes.has(route)) {
|
|
@@ -504,7 +681,38 @@ export class LocalPeer extends BasePeer {
|
|
|
504
681
|
return res;
|
|
505
682
|
}
|
|
506
683
|
|
|
684
|
+
private async callProbe(turnMsgs: ChatMessage[], fixedPrompt: string): Promise<ChatResult> {
|
|
685
|
+
const probe = this.probeSession;
|
|
686
|
+
if (!probe || this.probeStopping || this.abort?.signal.aborted) throw new ProbeToolRefusal("authority_stopped");
|
|
687
|
+
probe.accounting.current();
|
|
688
|
+
if (!this.probeFixture) requireProbeConfinement(probe.confinement, probe.workspace);
|
|
689
|
+
const body = JSON.parse(JSON.stringify({ model: GUIDANCE_PROBE_MODEL,
|
|
690
|
+
messages: [{ role: "system", content: fixedPrompt }, ...turnMsgs.map(({ is_error: _internal, ...message }) => message)], tools: probe.prepared.request.tools,
|
|
691
|
+
max_tokens: probe.config.maxOutputTokens, stream: false })) as ProbeLocalRequest;
|
|
692
|
+
const frame = JSON.stringify(body), first = this.probeCalls === 0;
|
|
693
|
+
if (first && frame !== probe.prepared.inputFrame) throw new ProbeLocalError("drift");
|
|
694
|
+
// ponytail: byte-level BPE input tokens are bounded by exact framed UTF-8 bytes; add the output-token cap.
|
|
695
|
+
// Recheck every request; upgrade to a pinned tokenizer-measured whole-call bound when available.
|
|
696
|
+
const upper = probe.config.tokenUpperBound, inputBytes = Buffer.byteLength(frame, "utf8");
|
|
697
|
+
if (upper !== undefined && (probe.config.maxOutputTokens > upper || inputBytes > upper - probe.config.maxOutputTokens))
|
|
698
|
+
throw new ProbeToolRefusal("token_ceiling");
|
|
699
|
+
const result = await probeLocalEffect(probe.accounting, "model_calls", frame, first ? undefined : { inputBytes },
|
|
700
|
+
probe.config.tokenUpperBound, async signal => {
|
|
701
|
+
if (signal.aborted || this.abort?.signal.aborted) throw new ProbeLocalError("interrupted");
|
|
702
|
+
const value = await this.opts.omni.chat(body, { signal: this.abort!.signal });
|
|
703
|
+
return { value, usage: probeObservedTokens(value) };
|
|
704
|
+
});
|
|
705
|
+
this.probeCalls++;
|
|
706
|
+
this.probeServedModel = result.servedModel ?? null;
|
|
707
|
+
this.probeServedExact = result.servedModelExact === true;
|
|
708
|
+
this.probeUsageKnown = this.probeUsageKnown && probeObservedTokens(result) !== null;
|
|
709
|
+
if (!this.probeUsageKnown) throw new ProbeLocalError("usage");
|
|
710
|
+
if (result.servedModel !== GUIDANCE_PROBE_MODEL || result.servedModelExact !== true) throw new ProbeLocalError("model");
|
|
711
|
+
return result;
|
|
712
|
+
}
|
|
713
|
+
|
|
507
714
|
private releaseObserverInput(context: OwnedInputContext | undefined, envs: Envelope[]): void {
|
|
715
|
+
if (this.probeConfinement) return;
|
|
508
716
|
if (!context || this.currentObserverInputContext !== context || this.observerInputReleasedId === context.inputId) return;
|
|
509
717
|
this.observerInputReleasedId = context.inputId;
|
|
510
718
|
try { this.opts.inputReleased?.(context, envs); } catch { /* observer metadata never changes the local model result */ }
|
|
@@ -548,6 +756,7 @@ export class LocalPeer extends BasePeer {
|
|
|
548
756
|
}
|
|
549
757
|
|
|
550
758
|
private async conclude(msgs: ChatMessage[], policy: { route?: string; fixedModel?: string; pii: boolean } | undefined, turn: number, step: number, maxSteps: number, answer: string, signal: AbortSignal, decisionId?: string, selection?: ModelOverrideSelection, fixedPrompt = system(this.opts.cwd, this.opts.preamble)): Promise<{ answer: string; complete: boolean } | undefined> {
|
|
759
|
+
if (this.probeConfinement) return { answer, complete: true };
|
|
551
760
|
const route = selection?.model === undefined ? effectiveLocalRoute(this.opts.route, policy?.route, policy?.fixedModel) : undefined, config = this.hubConfig(route);
|
|
552
761
|
if (!route || !config) return { answer, complete: true };
|
|
553
762
|
const messages: ChatMessage[] = [{ role: "system", content: fixedPrompt }, ...this.history, ...msgs];
|
|
@@ -559,6 +768,7 @@ export class LocalPeer extends BasePeer {
|
|
|
559
768
|
}
|
|
560
769
|
|
|
561
770
|
private observeTool(call: ToolCall, output: string, policy: { pii: boolean; task?: string } | undefined, nativeTurn: string): void {
|
|
771
|
+
if (this.probeConfinement) return;
|
|
562
772
|
if (policy?.pii || call.function.name === "doc_read" || call.function.name === "web_fetch") return; // document and web text: no research observation carries it
|
|
563
773
|
try {
|
|
564
774
|
const command = safeParse(call.function.arguments).command;
|
|
@@ -567,6 +777,7 @@ export class LocalPeer extends BasePeer {
|
|
|
567
777
|
}
|
|
568
778
|
|
|
569
779
|
private recordUsage(res: ChatResult, requestedModel: string, task?: number): void {
|
|
780
|
+
if (this.probeConfinement) return;
|
|
570
781
|
try {
|
|
571
782
|
this.opts.onUsage?.({
|
|
572
783
|
id: randomUUID(),
|