@skrr-ai/cli 0.1.179 → 0.1.180

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/commands/code/index.js +5 -0
  2. package/dist/commands/diagnostics/inference-smoke.d.ts +13 -0
  3. package/dist/commands/diagnostics/inference-smoke.js +50 -0
  4. package/dist/commands/harnesses/evaluations/evidence.d.ts +2 -0
  5. package/dist/commands/harnesses/evaluations/evidence.js +20 -0
  6. package/dist/commands/harnesses/evaluations/fixed-tool.d.ts +10 -0
  7. package/dist/commands/harnesses/evaluations/fixed-tool.js +189 -0
  8. package/dist/commands/harnesses/evaluations/platform-h9-turn.d.ts +13 -0
  9. package/dist/commands/harnesses/evaluations/platform-h9-turn.js +322 -0
  10. package/dist/commands/machines/hosted/identity-evaluations/issue.d.ts +12 -0
  11. package/dist/commands/machines/hosted/identity-evaluations/issue.js +40 -0
  12. package/dist/commands/machines/hosted/identity-evaluations/revoke.d.ts +11 -0
  13. package/dist/commands/machines/hosted/identity-evaluations/revoke.js +21 -0
  14. package/dist/commands/machines/hosted/identity-evaluations/show.d.ts +8 -0
  15. package/dist/commands/machines/hosted/identity-evaluations/show.js +20 -0
  16. package/dist/commands/machines/hosted/start.d.ts +1 -0
  17. package/dist/commands/machines/hosted/start.js +6 -0
  18. package/dist/lib/agentic-stream.d.ts +3 -0
  19. package/dist/lib/agentic-stream.js +63 -1
  20. package/dist/lib/copilot-fixed-probe-runner.d.ts +72 -0
  21. package/dist/lib/copilot-fixed-probe-runner.js +213 -0
  22. package/dist/lib/copilot-fixed-probe.d.ts +61 -0
  23. package/dist/lib/copilot-fixed-probe.js +223 -0
  24. package/dist/lib/first-party-harness-broker.d.ts +5 -0
  25. package/dist/lib/first-party-harness-broker.js +99 -0
  26. package/dist/lib/h9-platform-stream.d.ts +63 -0
  27. package/dist/lib/h9-platform-stream.js +317 -0
  28. package/dist/lib/h9-prior-stream.d.ts +44 -0
  29. package/dist/lib/h9-prior-stream.js +217 -0
  30. package/dist/lib/harness-evaluations.d.ts +85 -0
  31. package/dist/lib/harness-evaluations.js +8 -0
  32. package/dist/lib/hosted-identity-evaluations.d.ts +26 -0
  33. package/dist/lib/hosted-identity-evaluations.js +18 -0
  34. package/dist/lib/hosted-machines.d.ts +1 -0
  35. package/dist/lib/inference-overload-smoke-contract.d.ts +53 -0
  36. package/dist/lib/inference-overload-smoke-contract.js +192 -0
  37. package/dist/lib/inference-overload-smoke.d.ts +78 -0
  38. package/dist/lib/inference-overload-smoke.js +350 -0
  39. package/dist/lib/operator-probe-files.d.ts +6 -0
  40. package/dist/lib/operator-probe-files.js +68 -0
  41. package/dist/lib/platform-h9-plan.d.ts +47 -0
  42. package/dist/lib/platform-h9-plan.js +78 -0
  43. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/codex-model-catalog.json +150 -0
  44. package/dist/node_modules/@skrr-ai/data-provider/index.js +6 -6
  45. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/index.d.ts +3 -1
  46. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/index.js +23 -1
  47. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/managed-haiku-none.d.ts +8 -0
  48. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/managed-haiku-none.js +40 -0
  49. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/managed-inference-broker.d.ts +2 -11
  50. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/managed-inference-broker.js +31 -5
  51. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/overload-smoke.d.ts +56 -0
  52. package/dist/node_modules/@skrr-ai/inference-broker/dist/cjs/overload-smoke.js +277 -0
  53. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/index.d.ts +3 -1
  54. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/index.js +3 -1
  55. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/managed-haiku-none.d.ts +8 -0
  56. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/managed-haiku-none.js +20 -0
  57. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/managed-inference-broker.d.ts +2 -11
  58. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/managed-inference-broker.js +28 -4
  59. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/overload-smoke.d.ts +56 -0
  60. package/dist/node_modules/@skrr-ai/inference-broker/dist/esm/overload-smoke.js +261 -0
  61. package/oclif.manifest.json +473 -1
  62. package/package.json +2 -2
@@ -87,6 +87,7 @@ const first_party_harness_1 = require("./first-party-harness");
87
87
  const first_party_harness_agent_1 = require("./first-party-harness-agent");
88
88
  const first_party_harness_managed_1 = require("./first-party-harness-managed");
89
89
  const task_execution_1 = require("./task-execution");
90
+ const inference_overload_smoke_contract_1 = require("./inference-overload-smoke-contract");
90
91
  const RELEASE_LEASE_RE = /\/+$/;
91
92
  /**
92
93
  * Harness selections the POLICY resolves, mirroring the server's own set.
@@ -334,6 +335,9 @@ async function acquireManagedSession(input = {}, deps = {}) {
334
335
  sessionId,
335
336
  sessionToken,
336
337
  model: input.model?.trim() || AUTOMATIC_MODEL,
338
+ ...(input.reasoningEffort !== undefined
339
+ ? { reasoningEffort: input.reasoningEffort }
340
+ : {}),
337
341
  localRuntimeId: (deps.localRuntimeId ?? localRuntimeId)(),
338
342
  // The hardware id every Daemon row is keyed on — the same function
339
343
  // the daemon calls — not the minted `~/.skrr/daemon.id` UUIDv7,
@@ -507,6 +511,55 @@ async function acquireManagedSession(input = {}, deps = {}) {
507
511
  await compensate(releaseModel, sessionToken);
508
512
  throw err;
509
513
  }
514
+ let stopping = false;
515
+ let smokeBeginClaimed = false, smokeFailed = false, smokeBatchPending = false, nextSmokeBatch = 0;
516
+ let smokeOperationId = null;
517
+ const smokePath = `${serverUrl.replace(RELEASE_LEASE_RE, '')}/api/agentic/sessions/${encodeURIComponent(sessionId)}/inference/diagnostics/overload-smoke`;
518
+ const smokeRequest = async (body, signal) => {
519
+ if (stopping && body.action !== 'receipt')
520
+ throw new inference_overload_smoke_contract_1.InferenceSmokeError('SMOKE_SESSION_STOPPED');
521
+ const controller = new AbortController();
522
+ const timeout = setTimeout(() => controller.abort(), body.action === 'receipt' ? RELEASE_TIMEOUT_MS : 180000);
523
+ const abort = () => controller.abort();
524
+ signal?.addEventListener('abort', abort, { once: true });
525
+ if (signal?.aborted)
526
+ abort();
527
+ try {
528
+ const raw = await fetchImpl(smokePath, {
529
+ method: 'POST',
530
+ headers: {
531
+ Accept: 'application/json',
532
+ 'Content-Type': 'application/json',
533
+ Authorization: `Bearer ${sessionToken}`,
534
+ },
535
+ body: JSON.stringify(body),
536
+ signal: controller.signal,
537
+ redirect: 'error',
538
+ });
539
+ const response = await (0, inference_broker_1.boundedOverloadSmokeResponse)(raw, controller.signal);
540
+ if (!response.ok) {
541
+ // Read a fixed code only. Server/transport bodies can carry requests and credentials.
542
+ const data = (await response.json().catch(() => null));
543
+ const code = data?.code ?? data?.error?.code;
544
+ throw new inference_overload_smoke_contract_1.InferenceSmokeError(typeof code === 'string' && /^[A-Za-z0-9_.:-]{1,96}$/.test(code)
545
+ ? code
546
+ : `SMOKE_HTTP_${response.status}`);
547
+ }
548
+ return await response.json();
549
+ }
550
+ catch (error) {
551
+ if (error instanceof inference_overload_smoke_contract_1.InferenceSmokeError)
552
+ throw error;
553
+ const code = error?.code;
554
+ if (typeof code === 'string' && /^SMOKE_[A-Z0-9_]{1,90}$/.test(code))
555
+ throw new inference_overload_smoke_contract_1.InferenceSmokeError(code);
556
+ throw new inference_overload_smoke_contract_1.InferenceSmokeError(controller.signal.aborted ? 'SMOKE_ABORTED' : 'SMOKE_OPERATION_UNKNOWN');
557
+ }
558
+ finally {
559
+ clearTimeout(timeout);
560
+ signal?.removeEventListener('abort', abort);
561
+ }
562
+ };
510
563
  return {
511
564
  env: session.env,
512
565
  socketPath: session.socketPath,
@@ -519,7 +572,52 @@ async function acquireManagedSession(input = {}, deps = {}) {
519
572
  leaseExpiresInMs: lease.leaseExpiresInMs,
520
573
  ...(lease.renewalWindowMs !== undefined ? { renewalWindowMs: lease.renewalWindowMs } : {}),
521
574
  ...(lease.ceilingAtMs !== undefined ? { ceilingAtMs: lease.ceilingAtMs } : {}),
575
+ overloadSmoke: {
576
+ begin: async (signal) => {
577
+ if (smokeBeginClaimed || stopping)
578
+ throw new inference_overload_smoke_contract_1.InferenceSmokeError('SMOKE_BEGIN_ALREADY_CLAIMED');
579
+ smokeBeginClaimed = true;
580
+ try {
581
+ const begun = (0, inference_overload_smoke_contract_1.projectSmokeBegin)(await smokeRequest({ action: 'begin' }, signal));
582
+ smokeOperationId = begun.operationId;
583
+ return begun;
584
+ }
585
+ catch (error) {
586
+ smokeFailed = true;
587
+ throw error;
588
+ }
589
+ },
590
+ batch: async (operationId, index, signal) => {
591
+ if (!Number.isSafeInteger(index) ||
592
+ index < 0 ||
593
+ index >= 64 ||
594
+ operationId !== smokeOperationId ||
595
+ index !== nextSmokeBatch ||
596
+ smokeBatchPending ||
597
+ smokeFailed ||
598
+ stopping)
599
+ throw new inference_overload_smoke_contract_1.InferenceSmokeError('SMOKE_BATCH_INDEX_INVALID');
600
+ smokeBatchPending = true;
601
+ nextSmokeBatch += 1;
602
+ try {
603
+ return (0, inference_overload_smoke_contract_1.projectSmokeBatch)(await smokeRequest({ action: 'batch', operationId, index }, signal), index);
604
+ }
605
+ catch (error) {
606
+ smokeFailed = true;
607
+ throw error;
608
+ }
609
+ finally {
610
+ smokeBatchPending = false;
611
+ }
612
+ },
613
+ receipt: async (operationId, signal) => {
614
+ if (operationId !== smokeOperationId)
615
+ throw new inference_overload_smoke_contract_1.InferenceSmokeError('SMOKE_OPERATION_MISMATCH');
616
+ return (0, inference_overload_smoke_contract_1.projectSmokeReceipt)(await smokeRequest({ action: 'receipt', operationId }, signal), operationId);
617
+ },
618
+ },
522
619
  stop: async (reason = 'cli_session_ended') => {
620
+ stopping = true;
523
621
  try {
524
622
  // The broker FIRST, because `stop()` stops the renewal loop: releasing
525
623
  // while a heartbeat is in flight risks the renewal re-extending the lease
@@ -822,6 +920,7 @@ signal) {
822
920
  },
823
921
  body: JSON.stringify({
824
922
  model: input.model,
923
+ ...(input.reasoningEffort !== undefined ? { reasoningEffort: input.reasoningEffort } : {}),
825
924
  localRuntimeId: input.localRuntimeId,
826
925
  machineUuid: input.machineUuid,
827
926
  }),
@@ -0,0 +1,63 @@
1
+ import { type AgenticStreamEvent, type EnvelopeReplayPage } from './agentic-stream';
2
+ export declare const H9_TURN_LABELS: readonly ["streaming", "toolCalls", "remember", "interrupt", "recall", "cancel"];
3
+ export type H9TurnLabel = (typeof H9_TURN_LABELS)[number];
4
+ export type H9Harness = 'pi' | 'copilot-sdk';
5
+ type Row = Record<string, any>;
6
+ /** Fixed prompts for the two reviewed platform qualification pairs. */
7
+ export declare function h9FixedPrompt(label: H9TurnLabel, nonce: string, harness?: H9Harness): string;
8
+ export type H9AcceptedScope = {
9
+ agentId: string;
10
+ harnessId: string;
11
+ harness: H9Harness;
12
+ workspaceId?: string;
13
+ daemonId: string;
14
+ conversationId?: string;
15
+ };
16
+ /** Actual normal HTTP acceptance, not a caller-provided session or permission context. */
17
+ export declare function validateH9Acceptance(accepted: Row, scope: H9AcceptedScope): import("./copilot-fixed-probe").InteractiveAdmission;
18
+ export interface H9StreamInput {
19
+ label: H9TurnLabel;
20
+ nonce: string;
21
+ accepted: Row;
22
+ scope: H9AcceptedScope;
23
+ deadline: number;
24
+ baseURL: string;
25
+ token: string;
26
+ replayEnvelopes: (from: number) => Promise<EnvelopeReplayPage>;
27
+ readResponseMessage?: () => Promise<unknown>;
28
+ onEvent: (event: AgenticStreamEvent) => void;
29
+ signal?: AbortSignal;
30
+ }
31
+ /**
32
+ * Internal transport seam only. The closed operator runner must establish owner, unused
33
+ * grant, exact image/runtime/model and per-turn financial barriers before calling this.
34
+ * The shared client is the ONLY permission responder. No generic approval/input option.
35
+ */
36
+ export declare function streamH9PlatformTurn(input: H9StreamInput): Promise<{
37
+ result: {
38
+ responseMessageId: string | undefined;
39
+ sessionId: string;
40
+ text: string;
41
+ status: "completed" | "aborted" | "failed";
42
+ repaired?: true;
43
+ permissionDenials?: string[];
44
+ lastEvent?: AgenticStreamEvent;
45
+ };
46
+ permission: {
47
+ permissionRecorded: boolean;
48
+ toolVerified: boolean;
49
+ failure: string | null;
50
+ toolUseId: string | null;
51
+ requestId: string | null;
52
+ interactiveAdmission: import("./copilot-fixed-probe").InteractiveAdmission;
53
+ autonomousRunClaimed: boolean;
54
+ autonomousAttemptClaimed: boolean;
55
+ approvalSource: string;
56
+ } | null;
57
+ cancelRequestedAtMs: null;
58
+ successful: boolean;
59
+ refusal: null;
60
+ providerAbsenceClaimed: boolean;
61
+ financialSettlementClaimed: boolean;
62
+ }>;
63
+ export {};
@@ -0,0 +1,317 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.H9_TURN_LABELS = void 0;
4
+ exports.h9FixedPrompt = h9FixedPrompt;
5
+ exports.validateH9Acceptance = validateH9Acceptance;
6
+ exports.streamH9PlatformTurn = streamH9PlatformTurn;
7
+ const node_stream_1 = require("node:stream");
8
+ const data_provider_1 = require("@skrr-ai/data-provider");
9
+ const agentic_stream_1 = require("./agentic-stream");
10
+ const copilot_fixed_probe_1 = require("./copilot-fixed-probe");
11
+ exports.H9_TURN_LABELS = [
12
+ 'streaming',
13
+ 'toolCalls',
14
+ 'remember',
15
+ 'interrupt',
16
+ 'recall',
17
+ 'cancel',
18
+ ];
19
+ const need = (value, code) => {
20
+ if (!value)
21
+ throw new Error(code);
22
+ };
23
+ const id = (value) => typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.:@-]{0,239}$/.test(value);
24
+ /** Fixed prompts for the two reviewed platform qualification pairs. */
25
+ function h9FixedPrompt(label, nonce, harness = 'pi') {
26
+ need(exports.H9_TURN_LABELS.includes(label), 'H9_LABEL_INVALID');
27
+ (0, copilot_fixed_probe_1.fixedCopilotCommand)(nonce); // Shared nonce validation and exact tool syntax.
28
+ switch (label) {
29
+ case 'streaming':
30
+ return 'Greet me in two short sentences. Do not use tools.';
31
+ case 'toolCalls':
32
+ if (harness === 'copilot-sdk')
33
+ return `Use Bash exactly once to run the exact command below, then reply with its printed value. Do not use any other tools.
34
+
35
+ ${(0, copilot_fixed_probe_1.copilotPlatformScratchCommand)(nonce)}`;
36
+ return `Use Bash exactly once to run exactly: ${(0, copilot_fixed_probe_1.fixedCopilotCommand)(nonce)}. Use no other tools. Then reply with the printed value.`;
37
+ case 'remember':
38
+ return `Remember this marker: H9-MARKER-${nonce}. Reply OK only. Do not use tools.`;
39
+ case 'recall':
40
+ return 'What was the marker I asked you to remember? Reply with the marker only. Do not use tools.';
41
+ case 'interrupt':
42
+ case 'cancel':
43
+ // A counting prompt can trigger a shell command before the first text delta.
44
+ return 'Write a 1000-word story about a lighthouse, without using tools.';
45
+ }
46
+ }
47
+ /** Actual normal HTTP acceptance, not a caller-provided session or permission context. */
48
+ function validateH9Acceptance(accepted, scope) {
49
+ need(accepted?.success === true &&
50
+ id(accepted.sessionId) &&
51
+ id(accepted.conversationId) &&
52
+ id(accepted.responseMessageId) &&
53
+ accepted.workspaceId === (scope.workspaceId ?? null) &&
54
+ (!scope.workspaceId || accepted.workspaceSource === 'request'), 'H9_EXACT_WORKSPACE_ACCEPTANCE_REQUIRED');
55
+ need(!scope.conversationId || accepted.conversationId === scope.conversationId, 'H9_CONVERSATION_CHANGED');
56
+ need(accepted.runtime?.mode === 'local' &&
57
+ accepted.runtime.provider === scope.harness &&
58
+ accepted.runtime.daemonId === scope.daemonId &&
59
+ accepted.runtime.agentRuntime === scope.harnessId &&
60
+ accepted.runtime.executionPlan?.selectedExecutionSelector === scope.harnessId &&
61
+ accepted.runtime.executionPlan?.fallbackUsed === false, 'H9_ACCEPTED_RUNTIME_MISMATCH');
62
+ const context = (0, copilot_fixed_probe_1.interactiveAdmission)(accepted.interactiveAdmission);
63
+ need(context.sessionId === accepted.sessionId &&
64
+ context.responseMessageId === accepted.responseMessageId, 'H9_ACCEPTED_CONTEXT_MISMATCH');
65
+ return context;
66
+ }
67
+ /** Pi 1.5.2 emits this structured Bash result and the daemon JSON-encodes it. */
68
+ function matchesPiBashOutput(actual, expected) {
69
+ if (typeof actual !== 'string' || actual.length > 1024)
70
+ return false;
71
+ try {
72
+ const result = JSON.parse(actual);
73
+ const content = result?.content;
74
+ const structured = result?.structuredContent;
75
+ return (Object.keys(result).sort().join(',') === 'content,structuredContent' &&
76
+ Array.isArray(content) &&
77
+ content.length === 1 &&
78
+ Object.keys(content[0]).sort().join(',') === 'text,type' &&
79
+ content[0].type === 'text' &&
80
+ content[0].text === expected &&
81
+ Object.keys(structured).sort().join(',') === 'exit_code,output,truncated,wall_time_seconds' &&
82
+ structured.output === expected &&
83
+ structured.truncated === false &&
84
+ structured.exit_code === 0 &&
85
+ Number.isFinite(structured.wall_time_seconds) &&
86
+ structured.wall_time_seconds >= 0);
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ }
92
+ /** Copilot 1.0.112 can append the runtime's shell completion trailer to stdout. */
93
+ function matchesCopilotBashOutput(actual, expected) {
94
+ if (actual === expected)
95
+ return true;
96
+ if (typeof actual !== 'string' || !actual.startsWith(expected))
97
+ return false;
98
+ const trailer = actual.slice(expected.length);
99
+ return (/^<shellId: (?:0|[1-9][0-9]{0,8}) completed with exit code 0>$/u.exec(trailer)?.[0] === trailer);
100
+ }
101
+ /** The normal, owner-scoped message route returns an array, even for one exact id. */
102
+ function recordedH9Response(rows, accepted, outcome) {
103
+ if (!Array.isArray(rows) || rows.length !== 1)
104
+ return null;
105
+ const only = rows[0];
106
+ if (only?.messageId !== accepted.responseMessageId ||
107
+ only.conversationId !== accepted.conversationId ||
108
+ only.isCreatedByUser !== false ||
109
+ only.metadata?.agentic?.sessionId !== accepted.sessionId ||
110
+ only.metadata.agentic.sessionOutcome?.status !== outcome ||
111
+ only.unfinished !== false ||
112
+ only.error !== false ||
113
+ typeof only.text !== 'string' ||
114
+ (0, data_provider_1.resolveMessageFailure)(only))
115
+ return null;
116
+ return { text: only.text, responseMessageId: only.messageId };
117
+ }
118
+ /**
119
+ * Internal transport seam only. The closed operator runner must establish owner, unused
120
+ * grant, exact image/runtime/model and per-turn financial barriers before calling this.
121
+ * The shared client is the ONLY permission responder. No generic approval/input option.
122
+ */
123
+ async function streamH9PlatformTurn(input) {
124
+ h9FixedPrompt(input.label, input.nonce, input.scope.harness);
125
+ const now = Date.now();
126
+ need(Number.isFinite(input.deadline) && input.deadline > now && input.deadline <= now + 60_000, 'H9_TURN_DEADLINE_INVALID');
127
+ const context = validateH9Acceptance(input.accepted, input.scope);
128
+ // Non-tool turns intentionally have no permission gate. Their first ask cancels the run.
129
+ const permission = input.label === 'toolCalls'
130
+ ? new copilot_fixed_probe_1.FixedCopilotPermission(context, input.nonce, input.deadline, Date.now, input.scope.harness === 'pi' ? matchesPiBashOutput : matchesCopilotBashOutput, input.scope.harness === 'copilot-sdk')
131
+ : undefined;
132
+ const sink = new node_stream_1.Writable({
133
+ write(_chunk, _encoding, done) {
134
+ done();
135
+ },
136
+ });
137
+ let deltas = 0, bytes = 0, cancelRequestedAtMs = null;
138
+ let refusal = null;
139
+ let durableResponseId;
140
+ let expectedStopObserved = false;
141
+ const stopReason = 'H9 fixed cancellation case';
142
+ const expectedCancel = input.label === 'interrupt' || input.label === 'cancel';
143
+ const canReconcile = () => cancelRequestedAtMs === null &&
144
+ !refusal &&
145
+ !input.signal?.aborted &&
146
+ Date.now() < input.deadline;
147
+ const readResponseMessage = input.readResponseMessage;
148
+ const reconcileTerminal = !expectedCancel && readResponseMessage
149
+ ? async () => {
150
+ if (!canReconcile())
151
+ return null;
152
+ const terminal = recordedH9Response(await readResponseMessage(), input.accepted, 'succeeded');
153
+ if (!terminal || !canReconcile())
154
+ return null;
155
+ durableResponseId = terminal.responseMessageId;
156
+ return { ...terminal, status: 'completed' };
157
+ }
158
+ : undefined;
159
+ const cancel = (reason) => {
160
+ permission?.stop(reason);
161
+ if (cancelRequestedAtMs !== null)
162
+ return;
163
+ cancelRequestedAtMs = Date.now();
164
+ client.cancel(reason); // Normal authenticated execution:interrupt, not a local detach.
165
+ };
166
+ const client = new agentic_stream_1.AgenticStreamClient({
167
+ baseURL: input.baseURL,
168
+ token: input.token,
169
+ sessionId: input.accepted.sessionId,
170
+ conversationId: input.accepted.conversationId,
171
+ // An empty selector is the legacy explicit Personal scope.
172
+ workspaceId: input.scope.workspaceId ?? '',
173
+ fixedCopilotProbe: permission,
174
+ quiet: true,
175
+ output: sink,
176
+ statusOutput: sink,
177
+ attachTimeoutMs: 10_000,
178
+ replayEnvelopes: input.replayEnvelopes,
179
+ reconcileTerminal,
180
+ idleTerminalProbeMs: 5_000,
181
+ onEvent: (event) => {
182
+ if (event.sessionId !== undefined && event.sessionId !== input.accepted.sessionId) {
183
+ refusal ??= 'H9_EVENT_SCOPE_MISMATCH';
184
+ cancel(refusal);
185
+ return;
186
+ }
187
+ bytes += Buffer.byteLength(JSON.stringify(event));
188
+ if (bytes > 1_048_576) {
189
+ refusal ??= 'H9_EVENT_LIMIT';
190
+ cancel(refusal);
191
+ return;
192
+ }
193
+ if ((!permission &&
194
+ ['permission.requested', 'tool.started', 'tool.completed'].includes(event.type)) ||
195
+ [
196
+ 'question.requested',
197
+ 'permission.browser_required',
198
+ 'run.handed_over',
199
+ 'stream.gap',
200
+ 'transport.error',
201
+ 'text.reset',
202
+ ].includes(event.type)) {
203
+ refusal ??= 'H9_UNEXPECTED_INTERACTION_OR_CONTEXT_LOSS';
204
+ cancel(refusal);
205
+ }
206
+ if (expectedCancel &&
207
+ event.type === 'run.cancel_requested' &&
208
+ event.sessionId === input.accepted.sessionId &&
209
+ event.reason === stopReason)
210
+ expectedStopObserved = true;
211
+ input.onEvent(event); // Actual canonical client event; never manufacture a tool witness.
212
+ if (expectedCancel &&
213
+ event.type === 'text.delta' &&
214
+ typeof event.text === 'string' &&
215
+ event.text.length > 0 &&
216
+ ++deltas >= 3)
217
+ cancel(stopReason);
218
+ },
219
+ });
220
+ const abort = () => cancel('H9 operator interruption');
221
+ input.signal?.addEventListener('abort', abort, { once: true });
222
+ let hard;
223
+ const timer = setTimeout(() => cancel('H9 turn deadline'), Math.max(1, input.deadline - Date.now()));
224
+ try {
225
+ if (input.signal?.aborted)
226
+ throw new Error('H9_ABORTED_BEFORE_ATTACH');
227
+ const streamed = await Promise.race([
228
+ client.run(),
229
+ new Promise((_resolve, reject) => {
230
+ hard = setTimeout(() => {
231
+ cancel('H9 terminal unconfirmed');
232
+ reject(new Error('H9_TERMINAL_UNCONFIRMED'));
233
+ }, Math.max(1, input.deadline - Date.now()) + 15_000);
234
+ }),
235
+ ]);
236
+ // The normal result gets its response id from legacy message:stream frames. Canonical
237
+ // replay can leave it unset, even when execution:complete carries a responseMessageId.
238
+ // A contradictory id on either surface is never repaired with a durable read.
239
+ const expectedResponseId = input.accepted.responseMessageId;
240
+ need(streamed.sessionId === input.accepted.sessionId &&
241
+ (streamed.lastEvent?.sessionId === undefined ||
242
+ streamed.lastEvent.sessionId === input.accepted.sessionId) &&
243
+ (streamed.lastEvent?.conversationId === undefined ||
244
+ streamed.lastEvent.conversationId === input.accepted.conversationId) &&
245
+ [
246
+ streamed.responseMessageId,
247
+ streamed.lastEvent?.responseMessageId,
248
+ streamed.lastEvent?.messageId,
249
+ ].every((id) => id === undefined || id === expectedResponseId), 'H9_TERMINAL_SCOPE_MISMATCH');
250
+ let responseMessageId = streamed.responseMessageId;
251
+ const terminalEvent = streamed.lastEvent;
252
+ const observedAbort = streamed.status === 'aborted' &&
253
+ terminalEvent !== undefined &&
254
+ terminalEvent.sessionId === input.accepted.sessionId &&
255
+ terminalEvent.cancelled !== false;
256
+ const canBindCancellation = () => expectedStopObserved && !refusal && !input.signal?.aborted && Date.now() < input.deadline;
257
+ if (responseMessageId === undefined && streamed.status === 'completed' && reconcileTerminal) {
258
+ if (streamed.lastEvent?.type === 'run.reconciled' &&
259
+ streamed.lastEvent.reconciledFrom === 'durable_record') {
260
+ responseMessageId = durableResponseId;
261
+ }
262
+ else {
263
+ // The worker can emit completion before the message outcome is visible.
264
+ for (let attempt = 0; attempt < 3 && canReconcile(); attempt++) {
265
+ const recorded = await reconcileTerminal().catch(() => null);
266
+ if (recorded) {
267
+ responseMessageId = recorded.responseMessageId;
268
+ break;
269
+ }
270
+ if (attempt < 2 && canReconcile())
271
+ await new Promise((resolve) => setTimeout(resolve, 500));
272
+ }
273
+ }
274
+ }
275
+ if (responseMessageId === undefined && observedAbort && readResponseMessage) {
276
+ // Daemon cancellation ACKs name the session but omit the response ID. Require the
277
+ // fixed Stop and an independently persisted cancellation of this exact response.
278
+ for (let attempt = 0; attempt < 3 && canBindCancellation(); attempt++) {
279
+ const rows = await readResponseMessage().catch(() => null);
280
+ if (!canBindCancellation())
281
+ break;
282
+ const recorded = recordedH9Response(rows, input.accepted, 'cancelled');
283
+ if (recorded) {
284
+ responseMessageId = recorded.responseMessageId;
285
+ break;
286
+ }
287
+ if (attempt < 2)
288
+ await new Promise((resolve) => setTimeout(resolve, 500));
289
+ }
290
+ }
291
+ need(responseMessageId === expectedResponseId, 'H9_TERMINAL_SCOPE_MISMATCH');
292
+ const result = { ...streamed, responseMessageId };
293
+ input.onEvent({ type: 'run.result', ...result });
294
+ const permissionFacts = permission?.result() ?? null;
295
+ const successful = !refusal &&
296
+ (expectedCancel
297
+ ? expectedStopObserved && observedAbort && !input.signal?.aborted
298
+ : cancelRequestedAtMs === null && result.status === 'completed') &&
299
+ (!permission || permissionFacts?.toolVerified === true);
300
+ return {
301
+ result,
302
+ permission: permissionFacts,
303
+ cancelRequestedAtMs,
304
+ successful,
305
+ refusal,
306
+ providerAbsenceClaimed: false,
307
+ financialSettlementClaimed: false,
308
+ };
309
+ }
310
+ finally {
311
+ clearTimeout(timer);
312
+ clearTimeout(hard);
313
+ input.signal?.removeEventListener('abort', abort);
314
+ permission?.close();
315
+ client.close(); // Local close is never proof of provider stop or settlement.
316
+ }
317
+ }
@@ -0,0 +1,44 @@
1
+ import { type H9Harness } from './h9-platform-stream';
2
+ import type { HarnessEvaluationEvidence, HarnessEvaluationFinancialEvidence } from './harness-evaluations';
3
+ import type { PlatformH9Plan } from './platform-h9-plan';
4
+ /**
5
+ * The reviewer seals the historical owner reads before the former lease and
6
+ * conversation are cleaned up. Revalidate their exact scope and stream here.
7
+ */
8
+ export declare function capturedH9Stream(plan: PlatformH9Plan, harness: H9Harness, machineProduct: string | null): {
9
+ grantId: string;
10
+ machine: {
11
+ daemonId: string;
12
+ machineUuid: string;
13
+ machineProduct: string;
14
+ image: string;
15
+ };
16
+ harness: H9Harness;
17
+ version: "1.0.112" | "1.5.2";
18
+ model: "claude-sonnet-5";
19
+ sessionId: string;
20
+ conversationId: string;
21
+ responseMessageId: string;
22
+ requestId: string;
23
+ firstByteMs: number;
24
+ chunks: number;
25
+ };
26
+ export declare function bindH9PriorStreamSettlement(plan: PlatformH9Plan, stream: ReturnType<typeof capturedH9Stream>, readback: HarnessEvaluationFinancialEvidence, evidence: HarnessEvaluationEvidence, currentBinding: HarnessEvaluationEvidence['grant']['modelBindings'][number]): {
27
+ reservationId: string;
28
+ grantId: string;
29
+ machine: {
30
+ daemonId: string;
31
+ machineUuid: string;
32
+ machineProduct: string;
33
+ image: string;
34
+ };
35
+ harness: H9Harness;
36
+ version: "1.0.112" | "1.5.2";
37
+ model: "claude-sonnet-5";
38
+ sessionId: string;
39
+ conversationId: string;
40
+ responseMessageId: string;
41
+ requestId: string;
42
+ firstByteMs: number;
43
+ chunks: number;
44
+ };