@staix/agent-hub 0.47.0 → 0.48.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/src/hub/tasks.ts CHANGED
@@ -13,7 +13,7 @@ import { buildDecomposePrompt, parseDecomposition, planPartPublish, DECOMPOSE_IT
13
13
  import { pathCandidates } from "@staix/agent-mem";
14
14
  import { renderGuidanceVariantV1 } from "./guidance-variants.ts";
15
15
  import { GuidanceProbeFixtureHost, type GuidanceProbeStore } from "./guidance-probe-store.ts";
16
- import { GuidanceProbeError, GUIDANCE_PROBE_STOP_TIMEOUT_MS, GUIDANCE_PROBE_FENCE_INTERVAL_MS, guidanceProbeCanonical, guidanceProbeManifestKey,
16
+ import { GuidanceProbeError, GUIDANCE_PROBE_STOP_TIMEOUT_MS, GUIDANCE_PROBE_FENCE_INTERVAL_MS, GUIDANCE_PROBE_LIVE_LIMITS, isLiveGuidanceProbeManifest, guidanceProbeCanonical, guidanceProbeManifestKey,
17
17
  parseGuidanceProbeRegistration, parseGuidanceProbeReceiptExport, probeHash, probeSha256, probeInteger, probeSessionGeneration,
18
18
  type ProbeChildBinding, type ProbeStoredState, type ProbePublicReceipt, type ProbePublicStatus, type ProbeHostBinding,
19
19
  type ProbeReceiptExport, type ProbeExportSlot, type ProbeReceiptV1, type ProbeRetentionState,
@@ -184,10 +184,11 @@ export interface TasksDeps {
184
184
  taskTokens?: () => Readonly<Record<number, number | null>>;
185
185
  /** Timing-only owner question evidence for the idle-owner ladder. */
186
186
  ownerQuestionWait?: (task: number, peer: PeerId) => { open: boolean; settled?: number } | undefined;
187
- /** Private host-owned probe ledger and fixture ports. No configuration, wire or model-selected runner. */
187
+ /** Private probe ledger and host-selected runner. Wire input selects only an already registered content ID. */
188
188
  guidanceProbes?: {
189
189
  store: GuidanceProbeStore;
190
190
  fakePorts?: GuidanceProbeFakePorts;
191
+ live?: { id: string; adapter: Pick<import("../local/probe-types.ts").ProbeLocalAdapter, "ports" | "prepareWorkerFrame"> };
191
192
  prepareWorkerFrame?: ProbeWorkerFramePreparer;
192
193
  prepareEditorFrame?: (state: ProbeStoredState, slot: ProbeSlot) => string | Promise<string>;
193
194
  session?: (by: PeerId) => { generation: string | number; nativeSession: string | null; requestConnectionId: string; current: () => void } | undefined;
@@ -642,6 +643,7 @@ function hasReviewAnchorInput(raw: unknown): boolean {
642
643
  interface GuidanceProbeRuntime {
643
644
  id: string; by: PeerId; controller: AbortController; current: () => ProbeAdmissionRecheck;
644
645
  requestedRevision: number; variantId?: string;
646
+ ports: GuidanceProbeFakePorts;
645
647
  reservation?: ProbeReservation; promise?: Promise<ProbePublicReceipt>; stopPromise?: Promise<void>;
646
648
  launched: boolean; launchSettled: boolean; stopSettled: boolean; stopKnown: boolean; stopRequested: boolean;
647
649
  watch?: { handle: unknown }; failure?: Error;
@@ -6515,7 +6517,7 @@ export class Tasks {
6515
6517
  entry.controller.abort();
6516
6518
  if (!entry.launched || !entry.reservation) { this.guidanceProbeRetire(entry); return; }
6517
6519
  if (entry.stopRequested && (!entry.stopSettled || entry.stopKnown || !explicitStop)) return;
6518
- const reservation = entry.reservation, ports = this.d.guidanceProbes!.fakePorts!;
6520
+ const reservation = entry.reservation, ports = entry.ports;
6519
6521
  entry.stopRequested = true; entry.stopSettled = false; entry.stopKnown = false;
6520
6522
  entry.stopPromise = (async () => {
6521
6523
  try {
@@ -6534,7 +6536,9 @@ export class Tasks {
6534
6536
  if (!state || !entry.reservation || state.firstReservedAt === null) throw new Error("owned probe clock is unavailable");
6535
6537
  const now = this.d.now?.() ?? Date.now(), elapsed = now - state.firstReservedAt;
6536
6538
  if (!probeInteger(elapsed) || elapsed < state.counters.elapsedHighWaterMs || state.admissionHold !== "none") { this.guidanceProbeAbort(entry, "elapsed"); return; }
6537
- const remaining = state.registration.manifest.limits.elapsedMs - elapsed;
6539
+ const live = state.sessions.find(session => session.slotId === entry.reservation!.slotId)?.live;
6540
+ const remaining = Math.min(state.registration.manifest.limits.elapsedMs - elapsed,
6541
+ live === undefined ? Infinity : GUIDANCE_PROBE_LIVE_LIMITS.elapsedMs - (now - live.reservedAt));
6538
6542
  if (remaining <= 0) { this.guidanceProbeAbort(entry, "elapsed"); return; }
6539
6543
  entry.watch = { handle: this.guidanceProbeTimer().set(() => {
6540
6544
  if (this.guidanceProbeActive.get(entry.id) !== entry || entry.controller.signal.aborted) return;
@@ -6551,7 +6555,7 @@ export class Tasks {
6551
6555
  && state.sessions.filter(item => item.state === "closed_fixture").every(item => item.coverage.coverageVerified)
6552
6556
  && state.sessions.every(item => item.state !== "failed_known" || item.coverage.preLaunchFailure || item.coverage.coverageVerified);
6553
6557
  const evidence: ProbePublicReceipt["evidence"] = state.counters.workerAttempts + state.counters.editorAttempts === 0 ? "declaration"
6554
- : holds || !verifiedCoverage || state.sessions.some(item => ["reserved", "running", "unknown_held"].includes(item.state)) ? "unknown" : "fixture";
6558
+ : holds || !verifiedCoverage || state.sessions.some(item => ["reserved", "running", "unknown_held"].includes(item.state)) ? "unknown" : launchedSessions.every(item => item.live !== undefined) ? "live" : "fixture";
6555
6559
  return { ...state.receipt, already, taskId: state.registration.manifest.task.id,
6556
6560
  experimentId: this.guidancePublicField(state.registration.manifest.experimentId), evidence,
6557
6561
  counters: { ...state.counters }, cancelRequested: state.cancelRequested, notNeeded: state.notNeeded, authoring,
@@ -6670,8 +6674,17 @@ export class Tasks {
6670
6674
  if (!probeInteger(revision) || variantId !== undefined && !probeSha256(variantId))
6671
6675
  throw new PreEffectToolRefusal("guidance probe start selector is invalid; use its current CAS revision and exact G1 id");
6672
6676
  const dependency = this.d.guidanceProbes!;
6673
- // No production runner: refuse before original-child selection, G1 raw read, binding, reservation or timer.
6674
- if (!dependency.fakePorts) throw new PreEffectToolRefusal("guidance probe runner is unavailable in production T1; use fake-only fixtures, not a live launch");
6677
+ // Match a host-configured content ID, never a mode requested by the caller or carried by imported evidence.
6678
+ const live = dependency.live?.id === id ? dependency.live.adapter : undefined;
6679
+ if (live && (by === USER || request.nativeSession === null))
6680
+ // refusal:by-design human-authority: live starts require an authenticated conductor session
6681
+ throw new PreEffectToolRefusal("live guidance probes require the current authenticated conductor native session");
6682
+ if (live && !isLiveGuidanceProbeManifest(state.registration.manifest))
6683
+ // refusal:by-design operator-knowledge: the operator must supply the preregistered bounded declaration
6684
+ throw new PreEffectToolRefusal("live guidance probe requires a bounded baseline and candidate declaration");
6685
+ const selectedPorts = live?.ports ?? dependency.fakePorts;
6686
+ // refusal:by-design human-authority: only the host operator can select a live registration
6687
+ if (!selectedPorts) throw new PreEffectToolRefusal("guidance probe runner is unavailable in production T1 for this registration");
6675
6688
  const key = { projectKey: host.projectKey, id }, original = dependency.store.startSelector(key, revision);
6676
6689
  if (original && (original.actor !== by || original.sessionGeneration !== host.sessionGeneration || original.nativeSession !== host.nativeSession
6677
6690
  || original.requestConnectionId !== host.requestConnectionId)) throw new PreEffectToolRefusal("guidance probe original start belongs to another request session; inspect its retained id without replaying it");
@@ -6697,11 +6710,11 @@ export class Tasks {
6697
6710
  throw new PreEffectToolRefusal("guidance probe active start belongs to another request session; inspect its retained id without replaying it");
6698
6711
  // Frame preparation has not granted a reservation. A duplicate is only a read of truthful current metadata.
6699
6712
  if (!active.reservation) return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), true);
6700
- const replay = dependency.store.reserveSession({ key, expectedRevision: revision, ...prepared, now: this.d.now?.() ?? Date.now() }, current);
6713
+ const replay = dependency.store.reserveSession({ key, expectedRevision: revision, ...prepared, ...(live ? { mode: "live" as const } : {}), now: this.d.now?.() ?? Date.now() }, current);
6701
6714
  if (replay.kind !== "existing") throw new Error("guidance probe start is unconfirmed; inspect retained state before any further work");
6702
6715
  return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), true);
6703
6716
  }
6704
- const entry: GuidanceProbeRuntime = { id, by, requestedRevision: revision, ...(variantId === undefined ? {} : { variantId }), controller: new AbortController(), current, launched: false, launchSettled: false,
6717
+ const entry: GuidanceProbeRuntime = { id, by, requestedRevision: revision, ...(variantId === undefined ? {} : { variantId }), controller: new AbortController(), current, ports: selectedPorts, launched: false, launchSettled: false,
6705
6718
  stopRequested: false, stopSettled: false, stopKnown: false };
6706
6719
  this.guidanceProbeActive.set(id, entry);
6707
6720
  const ports: GuidanceProbeFakePorts = {
@@ -6710,17 +6723,17 @@ export class Tasks {
6710
6723
  this.guidanceProbeWatch(entry);
6711
6724
  if (signal.aborted) throw new Error("owned probe was aborted before launch");
6712
6725
  entry.launched = true;
6713
- return dependency.fakePorts!.launch(input, effects, signal);
6726
+ return selectedPorts.launch(input, effects, signal);
6714
6727
  },
6715
- stop: (input, signal) => dependency.fakePorts!.stop(input, signal),
6716
- ...(dependency.fakePorts.discardRetained ? { discardRetained: record => dependency.fakePorts!.discardRetained!(record) } : {}),
6728
+ stop: (input, signal) => selectedPorts.stop(input, signal),
6729
+ ...(selectedPorts.discardRetained ? { discardRetained: record => selectedPorts.discardRetained!(record) } : {}),
6717
6730
  };
6718
6731
  let reserved = false, returned = false;
6719
- const runner = new GuidanceProbeFixtureHost(dependency.store, { ports, revalidate: current, now: () => this.d.now?.() ?? Date.now(),
6720
- prepareWorkerFrame: dependency.prepareWorkerFrame, prepareEditorFrame: dependency.prepareEditorFrame, onReserved: () => { reserved = true; } });
6732
+ const runner = new GuidanceProbeFixtureHost(dependency.store, { ports, ...(live ? { mode: "live" as const } : {}), revalidate: current, now: () => this.d.now?.() ?? Date.now(),
6733
+ prepareWorkerFrame: live?.prepareWorkerFrame ?? dependency.prepareWorkerFrame, prepareEditorFrame: dependency.prepareEditorFrame, onReserved: () => { reserved = true; } });
6721
6734
  entry.promise = (async () => {
6722
6735
  try {
6723
- const saved = await runner.start({ key, expectedRevision: revision, ...prepared, now: this.d.now?.() ?? Date.now() }, entry.controller.signal);
6736
+ const saved = await runner.start({ key, expectedRevision: revision, ...prepared, ...(live ? { mode: "live" as const } : {}), now: this.d.now?.() ?? Date.now() }, entry.controller.signal);
6724
6737
  returned = true;
6725
6738
  if (saved.state === "unknown_held" && entry.launched) {
6726
6739
  this.guidanceProbeAbort(entry, "observation", true);
@@ -50,6 +50,7 @@ export interface ProbeLocalSession {
50
50
  config: Readonly<ProbeLocalModelConfig>;
51
51
  accounting: ProbeLocalEffectScope;
52
52
  reserve(charges: ProbeResourceCharges, descriptor: string): Promise<void>;
53
+ pinnedChat?: Awaited<ReturnType<OmniRoute["pinCampusChat"]>>;
53
54
  }
54
55
  export interface ProbeLocalResult {
55
56
  answer: string;
@@ -224,6 +224,55 @@ export function probeWorkspaceCurrent(workspace: ProbeWorkspace): void {
224
224
  }
225
225
  export function probeWorkspacePrivateRoot(workspace: ProbeWorkspace): string { probeWorkspaceCurrent(workspace); return workspaces.get(workspace)!.parent; }
226
226
  export function probeWorkspaceTemporaryRoot(workspace: ProbeWorkspace): string { probeWorkspaceCurrent(workspace); return workspaces.get(workspace)!.temporaryRoot; }
227
+
228
+ /** Release an empty-source live workspace after its owner joined the stop and collected output. */
229
+ export function releaseEmptyProbeWorkspace(workspace: ProbeWorkspace): void {
230
+ probeWorkspacePhysical(workspace);
231
+ const state = workspaces.get(workspace)!;
232
+ if (state.identities.length || workspace.files.length) refused();
233
+ const directories = new Map(state.directories.map(entry => [entry.file, entry])), allowedDirectories = new Set(directories.keys());
234
+ const writable = new Set(workspace.allowedWrites);
235
+ for (const file of writable) {
236
+ for (let directory = dirname(file); !allowedDirectories.has(directory); directory = dirname(directory)) {
237
+ if (directory === dirname(directory)) refused();
238
+ allowedDirectories.add(directory);
239
+ }
240
+ }
241
+ const files: { file: string; dev: number; ino: number }[] = [];
242
+ const find = (directory: string): void => {
243
+ const handle = opendirSync(directory);
244
+ try {
245
+ for (let entry = handle.readSync(); entry; entry = handle.readSync()) {
246
+ const file = join(directory, entry.name);
247
+ if (allowedDirectories.has(file)) {
248
+ const existing = directories.get(file);
249
+ if (existing) requireDirectory(existing);
250
+ else directories.set(file, directoryIdentity(file));
251
+ find(file);
252
+ } else if (writable.has(file)) {
253
+ const stat = lstatSync(file);
254
+ if (!stat.isFile() || stat.nlink !== 1) refused();
255
+ files.push({ file, dev: stat.dev, ino: stat.ino });
256
+ } else refused();
257
+ }
258
+ } finally { handle.closeSync(); }
259
+ };
260
+ find(state.parent);
261
+ const requireParents = (file: string): void => {
262
+ for (let directory = dirname(file); directories.has(directory); directory = dirname(directory))
263
+ requireDirectory(directories.get(directory)!);
264
+ };
265
+ for (const entry of files) {
266
+ requireParents(entry.file);
267
+ const stat = lstatSync(entry.file);
268
+ if (!stat.isFile() || stat.nlink !== 1 || stat.dev !== entry.dev || stat.ino !== entry.ino) refused();
269
+ unlinkSync(entry.file);
270
+ }
271
+ for (const entry of [...directories.values()].sort((a, b) => b.file.length - a.file.length)) {
272
+ requireParents(entry.file); requireDirectory(entry); rmdirSync(entry.file);
273
+ }
274
+ workspaces.delete(workspace);
275
+ }
227
276
  /** Local conservative ceiling, called before the owner ledger's compound admission; never performs a second ledger effect. */
228
277
  export function reserveProbeWorkspaceBytes(workspace: ProbeWorkspace, bytes: number): void {
229
278
  probeWorkspaceCurrent(workspace); const state = workspaces.get(workspace)!;
@@ -45,6 +45,7 @@ export interface ChatOptions {
45
45
  onCampusOnly?: boolean;
46
46
  signal?: AbortSignal;
47
47
  }
48
+ type ChatRequest = { model: string; messages: ChatMessage[]; tools?: unknown[]; max_tokens?: number; temperature?: number; reasoning_effort?: string };
48
49
 
49
50
  const readSecret = (file?: string) => {
50
51
  try {
@@ -155,10 +156,24 @@ export class OmniRoute {
155
156
  }
156
157
  }
157
158
 
158
- async chat(body: { model: string; messages: ChatMessage[]; tools?: unknown[]; max_tokens?: number; temperature?: number; reasoning_effort?: string }, opts: ChatOptions = {}): Promise<ChatResult> {
159
+ async chat(body: ChatRequest, opts: ChatOptions = {}): Promise<ChatResult> {
159
160
  const base = await this.base();
160
161
  if (!base) throw new Error("no model gateway is configured or reachable (omniroute.urls in .agenthub/config.json; see ahub doctor)");
161
162
  if (opts.onCampusOnly && this.isAccessHost(base)) throw new Error("PII model calls require the confirmed campus gateway");
163
+ return this.chatAt(base, body, opts);
164
+ }
165
+
166
+ /** A single endpoint and model for a confined experiment, with no route selection after admission. */
167
+ async pinCampusChat(model: string): Promise<(body: Omit<ChatRequest, "model">, signal: AbortSignal) => Promise<ChatResult>> {
168
+ const onCampus = await this.onCampus();
169
+ const base = this.live;
170
+ if (!base) throw new Error("campus gateway unavailable (no healthy endpoint); run ahub doctor");
171
+ if (this.isAccessHost(base)) throw new Error("campus gateway unavailable (Access endpoint selected); run ahub doctor on campus");
172
+ if (!onCampus) throw new Error("campus gateway unavailable (campus connection unconfirmed); run ahub doctor");
173
+ return (body, signal) => this.chatAt(base, { ...body, model }, { signal }, true);
174
+ }
175
+
176
+ private async chatAt(base: string, body: ChatRequest, opts: ChatOptions, pinned = false): Promise<ChatResult> {
162
177
  const headers: Record<string, string> = { "content-type": "application/json" };
163
178
  const key = this.apiKey();
164
179
  if (!key) throw new Error("no OmniRoute API key (set OMNIROUTE_API_KEY or omniroute.api_key_file)");
@@ -167,15 +182,16 @@ export class OmniRoute {
167
182
  try {
168
183
  res = await fetch(`${base}/chat/completions`, {
169
184
  method: "POST",
185
+ ...(pinned ? { redirect: "error" as const } : {}),
170
186
  headers,
171
187
  body: JSON.stringify({ ...body, messages: body.messages.map(({ is_error: _internalError, ...message }) => message), stream: false }),
172
188
  ...(opts.signal ? { signal: opts.signal } : {}),
173
189
  });
174
190
  } catch (e) {
175
- this.live = undefined; // probe again next time: the VPN may have dropped
191
+ if (!pinned) this.live = undefined; // probe again next time: the VPN may have dropped
176
192
  throw e;
177
193
  }
178
- if (!res.ok) throw new Error(`model call failed: HTTP ${res.status} ${(await res.text()).slice(0, 300)}`);
194
+ if (!res.ok) throw new Error(`model call failed: HTTP ${res.status}${pinned ? "" : ` ${(await res.text()).slice(0, 300)}`}`);
179
195
  const json = (await res.json()) as { choices?: { message?: ChatMessage }[]; usage?: unknown; model?: unknown };
180
196
  const message = json.choices?.[0]?.message;
181
197
  if (!message) throw new Error("model call returned no message");
@@ -20,7 +20,7 @@ export default (host) => {
20
20
  const probeLabel = node('label'); probeLabel.append(node('span', 'Probe ID (64 hex)'), probeId);
21
21
  const probeButton = node('button', 'Read probe status'); probeButton.type = 'submit';
22
22
  probeForm.append(probeLabel, probeButton);
23
- const probeNote = node('p', 'Probe status is fixture evidence only: it reads the sealed receipts and the outcome denominator and claims no live model or worker trial.');
23
+ const probeNote = node('p', 'Probe status reads sealed receipts and the outcome denominator. A run with fixture evidence only claims no live model or worker trial.');
24
24
  const probeOutput = node('pre', undefined, 'ahub-guidance-output');
25
25
  probeOutput.tabIndex = 0; probeOutput.setAttribute('aria-label', 'Guidance probe status');
26
26
  const scopeForm = node('form', undefined, 'ahub-guidance-scope');
@@ -145,7 +145,7 @@ export default (host) => {
145
145
  state(typeof result?.error === 'string' && result.ok === false ? result.error : 'Probe status unavailable. Refresh the probe id or check access and guidance_probe_receipts support.'); return;
146
146
  }
147
147
  probeOutput.textContent = result.lines.join('\n');
148
- state('Probe status read. Fixture evidence only; every unknown stays unknown.');
148
+ state(result.probe.slots?.some(slot => slot.receipt?.mode === 'live') ? 'Probe status read. Live attempt evidence.' : 'Probe status read. Fixture evidence only; every unknown stays unknown.');
149
149
  } catch { if (active(token)) state('Probe status unavailable. Refresh the probe id or check access and guidance_probe_receipts support.'); }
150
150
  finally { if (active(token)) { busy = false; update(); } }
151
151
  }
@@ -49,7 +49,7 @@ const known = (value: number | null): string => value === null ? "unknown" : Str
49
49
  /**
50
50
  * T4 (#1226): the producer's probe status, one text for the plugin panel and the CLI. It states what the host observed and nothing more: a fixture run says
51
51
  * `fixture`, a missing measurement says `unknown` and never zero, and every state that is not a success stays visible, so a failed, cancelled or unavailable
52
- * arm cannot disappear from the denominator. A live trial is never claimed here: no production runner exists, and evidence is at most `fixture`.
52
+ * arm cannot disappear from the denominator. Only a host-sealed live record is rendered as a live attempt.
53
53
  */
54
54
  export function guidanceProbeStatusLines(exported: ProbeReceiptExport): string[] {
55
55
  const status = exported.status, counts = exported.counts;
@@ -60,7 +60,9 @@ export function guidanceProbeStatusLines(exported: ProbeReceiptExport): string[]
60
60
  `Attempts: ${status.counters.workerAttempts} worker, ${status.counters.editorAttempts} editor; model calls ${status.counters.modelCalls}; tool calls ${status.counters.toolCalls}.`,
61
61
  `Token usage: ${status.counters.usageUnknown || status.counters.modelCalls === 0 ? "unknown" : status.counters.tokensObservedKnown}.`,
62
62
  `Cancel requested: ${status.cancelRequested ? "yes" : "no"}.`,
63
- "Fixture evidence only: no live model or worker trial, sampling control, provider behaviour or model quality is claimed."];
63
+ exported.slots.some(slot => slot.receipt?.mode === "live")
64
+ ? "Live attempt evidence. Upstream fallback policy and sampling control remain unknown."
65
+ : "Fixture evidence only: no live model or worker trial, sampling control, provider behaviour or model quality is claimed."];
64
66
  for (const slot of exported.slots) {
65
67
  const receipt = slot.receipt;
66
68
  lines.push(`Slot ${plain(slot.slotId)}: ${slot.stage}/${slot.role}/${slot.arm}; session ${slot.state}; retained output ${slot.retention}.`);