@akagilnc/pi-workflow-roles 0.1.2521 → 0.1.2653-next.71811ca

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 (109) hide show
  1. package/README.md +129 -39
  2. package/README.zh-CN.md +128 -39
  3. package/dist/activation-ledger-topology.js +1 -1
  4. package/dist/archivist-record-entry.js +47 -26
  5. package/dist/auditor-dossier-tool.js +3 -1
  6. package/dist/compliance-transport.js +17 -26
  7. package/dist/doctor-contracts.js +1 -2
  8. package/dist/dossier-resolution.js +4 -8
  9. package/dist/engine-detour-tool.js +33 -8
  10. package/dist/engine-detour.js +1 -0
  11. package/dist/evidence-child-executor.js +277 -424
  12. package/dist/host-contracts.js +22 -0
  13. package/dist/institutional-resolution.js +88 -0
  14. package/dist/merger-contracts.js +1 -2
  15. package/dist/navigator-attendance.js +16 -0
  16. package/dist/notary-contracts.js +2 -3
  17. package/dist/package-contracts/fixer-output.js +1 -2
  18. package/dist/packaged-role-registry.js +102 -9
  19. package/dist/pi/in-process-session.js +671 -0
  20. package/dist/public-cli/config.js +7 -5
  21. package/dist/public-cli/main.js +3767 -4113
  22. package/dist/reviewer-child-executor.js +6 -1
  23. package/dist/session-opening-materials.js +10 -38
  24. package/dist/sitian-appender.js +146 -0
  25. package/dist/sitian-contracts.js +21 -0
  26. package/dist/sitian-facade.js +15 -0
  27. package/dist/sitian-reader.js +52 -0
  28. package/extensions/role-runtime.ts +9 -7
  29. package/package.json +5 -5
  30. package/resources/engines/cursor.md +12 -26
  31. package/resources/engines/hermes.md +2 -23
  32. package/resources/engines/opus.md +1 -16
  33. package/resources/navigator-route-playbook.md +2 -2
  34. package/scripts/build-package.mjs +0 -1
  35. package/souls/quality-law.md +1 -1
  36. package/src/activation-ledger-topology.ts +1 -1
  37. package/src/archivist-record-entry.ts +57 -45
  38. package/src/auditor-dossier-tool.ts +4 -2
  39. package/src/canonical-skill-binding.ts +37 -27
  40. package/src/collector-role.ts +11 -20
  41. package/src/collector-tool-schemas.ts +1 -4
  42. package/src/compliance-transport.ts +19 -44
  43. package/src/doctor-auditor.ts +1 -5
  44. package/src/doctor-contracts.ts +1 -4
  45. package/src/doctor-role.ts +31 -8
  46. package/src/dossier-resolution.ts +8 -8
  47. package/src/engine-detour-tool.ts +48 -19
  48. package/src/engine-detour.ts +3 -0
  49. package/src/evidence-child-executor.ts +277 -485
  50. package/src/factory-board.ts +3 -3
  51. package/src/gatekeeper-role.ts +21 -10
  52. package/src/host-contracts.ts +386 -0
  53. package/src/in-process-session.ts +1 -115
  54. package/src/institutional-resolution.ts +135 -0
  55. package/src/judge-auditor.ts +1 -5
  56. package/src/judge-role.ts +37 -51
  57. package/src/merger-contracts.ts +1 -4
  58. package/src/merger-role.ts +7 -11
  59. package/src/navigator-attendance.ts +20 -1
  60. package/src/notary-contracts.ts +8 -11
  61. package/src/notary-role.ts +7 -23
  62. package/src/notary-source-run.ts +4 -3
  63. package/src/package-contracts/fixer-output.ts +1 -4
  64. package/src/package-resources/method-skill-binding.ts +10 -34
  65. package/src/packaged-role-registry.ts +122 -12
  66. package/src/pi/adapter.ts +192 -0
  67. package/src/pi/durable-principal.ts +98 -0
  68. package/src/pi/in-process-session.ts +819 -0
  69. package/src/pi/known-failure.ts +77 -0
  70. package/src/pi/pi-normalization.ts +284 -0
  71. package/src/pi/role-turn-host.ts +459 -0
  72. package/src/public-cli/auto-resume.ts +42 -44
  73. package/src/public-cli/cli.ts +171 -257
  74. package/src/public-cli/coder-run.ts +115 -433
  75. package/src/public-cli/collector-run.ts +62 -314
  76. package/src/public-cli/config.ts +7 -5
  77. package/src/public-cli/doctor-run.ts +41 -52
  78. package/src/public-cli/fixer-run.ts +122 -427
  79. package/src/public-cli/invocation.ts +287 -96
  80. package/src/public-cli/judge-run.ts +92 -422
  81. package/src/public-cli/merger-run.ts +167 -429
  82. package/src/public-cli/notary-run.ts +41 -47
  83. package/src/public-cli/option-definitions.ts +136 -3
  84. package/src/public-cli/post-admission.ts +497 -0
  85. package/src/public-cli/public-run-credentials.ts +4 -4
  86. package/src/public-cli/reviewer-dispatch-rejection.ts +106 -0
  87. package/src/public-cli/reviewer-run.ts +132 -449
  88. package/src/public-cli/run-lifecycle.ts +339 -327
  89. package/src/public-cli/settlement.ts +251 -134
  90. package/src/public-cli/terminal.ts +3 -9
  91. package/src/public-cli/turn-request.ts +87 -0
  92. package/src/reviewer-child-executor.ts +9 -1
  93. package/src/reviewer-role.ts +11 -20
  94. package/src/role-runtime.ts +129 -78
  95. package/src/session-opening-materials.ts +25 -39
  96. package/src/sitian-appender.ts +171 -0
  97. package/src/sitian-contracts.ts +106 -0
  98. package/src/sitian-facade.ts +18 -0
  99. package/src/sitian-reader.ts +62 -0
  100. package/src/worker-role.ts +42 -40
  101. package/src/worker-submission-gates.ts +33 -0
  102. package/dist/archivist-role-run-coordinates.js +0 -28
  103. package/dist/package-contracts/terminating-infrastructure.js +0 -90
  104. package/resources/engines/sonnet.md +0 -27
  105. package/resources/engines/zcode.md +0 -63
  106. package/src/archivist-role-run-coordinates.ts +0 -45
  107. package/src/package-contracts/terminating-infrastructure.ts +0 -132
  108. package/src/public-cli/explicit-internal.ts +0 -427
  109. package/src/public-cli/one-shot-dispatch.ts +0 -300
@@ -0,0 +1,819 @@
1
+ /**
2
+ * Pi Institutional Sub-Session Open Seam (#518 / #233).
3
+ * Adapts Pi AgentSession / ModelRuntime / ModelRegistry into the host-neutral
4
+ * HostInstitutionalSessionHandle contract.
5
+ * Zero Pi type leakage out of this module.
6
+ */
7
+ import { mkdtemp, rm } from "node:fs/promises";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+
11
+ import {
12
+ createAgentSession,
13
+ DefaultResourceLoader,
14
+ ModelRegistry,
15
+ ModelRuntime,
16
+ SettingsManager,
17
+ type AgentToolResult,
18
+ type SessionManager,
19
+ type ToolDefinition,
20
+ } from "@earendil-works/pi-coding-agent";
21
+ import {
22
+ createAssistantMessageEventStream,
23
+ InMemoryCredentialStore,
24
+ type Api,
25
+ type AssistantMessage,
26
+ type Context,
27
+ type Model,
28
+ type Provider,
29
+ type ProviderStreamOptions,
30
+ type Usage,
31
+ } from "@earendil-works/pi-ai";
32
+
33
+ import { createRecordSession } from "../archivist-record-entry.ts";
34
+ import type {
35
+ HostAssistantTurnResult,
36
+ HostInstitutionalModelSelection,
37
+ HostInstitutionalSessionEvent,
38
+ HostInstitutionalSessionHandle,
39
+ HostInstitutionalSessionOptions,
40
+ HostSessionUsage,
41
+ } from "../host-contracts.ts";
42
+ import {
43
+ createStreamIdleGuard,
44
+ isStreamIdleTimeoutError,
45
+ StreamIdleTimeoutError,
46
+ } from "../stream-idle-guard.ts";
47
+ import {
48
+ hasUpstreamErrorTestimony,
49
+ isNonSuccessHttpStatus,
50
+ projectConfirmedRemotePayload,
51
+ } from "../upstream-error-testimony.ts";
52
+
53
+ export const DEFAULT_COMPLIANCE_IDLE_MAX_RETRIES = 2;
54
+
55
+ /** Recover a typed idle timeout from a thrown error or an error-stop message. */
56
+ function streamIdleTimeoutFromUnknown(value: unknown): StreamIdleTimeoutError | undefined {
57
+ if (isStreamIdleTimeoutError(value)) return value;
58
+ const message = value instanceof Error ? value.message : typeof value === "string" ? value : undefined;
59
+ if (message === undefined) return undefined;
60
+ const match = /stream idle timeout after (\d+)ms/i.exec(message);
61
+ return match !== null && match[1] !== undefined
62
+ ? new StreamIdleTimeoutError(Number(match[1]))
63
+ : undefined;
64
+ }
65
+
66
+ // ── Legacy openInProcessAgentSession (preserved for Navigator B) ───────────
67
+
68
+ type OpenInProcessAgentSessionBase = {
69
+ readonly cwd: string;
70
+ readonly agentDir?: string;
71
+ readonly model: Model<Api>;
72
+ readonly modelRuntime: ModelRuntime;
73
+ readonly thinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
74
+ readonly systemPrompt?: string;
75
+ readonly customTools?: ToolDefinition[];
76
+ readonly noTools?: "all" | "builtin";
77
+ readonly tools?: string[];
78
+ };
79
+
80
+ export type OpenInProcessAgentSessionOptions =
81
+ | (OpenInProcessAgentSessionBase & {
82
+ readonly sessionManager: SessionManager;
83
+ readonly kind?: never;
84
+ readonly subject?: never;
85
+ readonly parent?: never;
86
+ })
87
+ | (OpenInProcessAgentSessionBase & {
88
+ readonly sessionManager?: undefined;
89
+ readonly kind: string;
90
+ readonly subject?: string;
91
+ readonly parent?: { getSessionFile(): string | undefined };
92
+ });
93
+
94
+ function resolveSessionManager(options: OpenInProcessAgentSessionOptions): SessionManager {
95
+ if (options.sessionManager !== undefined) return options.sessionManager;
96
+ return createRecordSession({
97
+ cwd: options.cwd,
98
+ kind: options.kind,
99
+ ...(options.subject === undefined ? {} : { subject: options.subject }),
100
+ ...(options.parent === undefined ? {} : { parent: options.parent }),
101
+ });
102
+ }
103
+
104
+ export async function openInProcessAgentSession(
105
+ options: OpenInProcessAgentSessionOptions,
106
+ ): Promise<{ session: Awaited<ReturnType<typeof createAgentSession>>["session"]; dispose(): void }> {
107
+ const settings = SettingsManager.inMemory({ compaction: { enabled: false }, retry: { enabled: false } });
108
+ const sessionManager = resolveSessionManager(options);
109
+
110
+ const createArgs: Parameters<typeof createAgentSession>[0] = {
111
+ cwd: options.cwd,
112
+ model: options.model,
113
+ thinkingLevel: options.thinkingLevel ?? "off",
114
+ modelRuntime: options.modelRuntime,
115
+ sessionManager,
116
+ settingsManager: settings,
117
+ ...(options.noTools === undefined ? {} : { noTools: options.noTools }),
118
+ ...(options.tools === undefined ? {} : { tools: options.tools }),
119
+ ...(options.customTools === undefined ? {} : { customTools: options.customTools }),
120
+ };
121
+
122
+ if (options.agentDir !== undefined) {
123
+ const loader = new DefaultResourceLoader({
124
+ cwd: options.cwd,
125
+ agentDir: options.agentDir,
126
+ settingsManager: settings,
127
+ noExtensions: true,
128
+ noSkills: true,
129
+ noPromptTemplates: true,
130
+ noThemes: true,
131
+ noContextFiles: true,
132
+ ...(options.systemPrompt === undefined ? {} : { systemPrompt: options.systemPrompt }),
133
+ });
134
+ await loader.reload();
135
+ createArgs.agentDir = options.agentDir;
136
+ createArgs.resourceLoader = loader;
137
+ } else if (options.systemPrompt !== undefined) {
138
+ throw new Error("openInProcessAgentSession requires agentDir when systemPrompt is set");
139
+ }
140
+
141
+ const { session } = await createAgentSession(createArgs);
142
+ return {
143
+ session,
144
+ dispose() {
145
+ session.dispose();
146
+ },
147
+ };
148
+ }
149
+
150
+ // ── Stream / remote error projection helpers ───────────────────────────────
151
+
152
+ function emptyUsage(): Usage {
153
+ return {
154
+ input: 0,
155
+ output: 0,
156
+ cacheRead: 0,
157
+ cacheWrite: 0,
158
+ totalTokens: 0,
159
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
160
+ };
161
+ }
162
+
163
+ function addUsage(total: Usage, next?: Usage): void {
164
+ if (!next) return;
165
+ total.input += next.input;
166
+ total.output += next.output;
167
+ total.cacheRead += next.cacheRead;
168
+ total.cacheWrite += next.cacheWrite;
169
+ total.totalTokens += next.totalTokens;
170
+ total.cost.input += next.cost?.input ?? 0;
171
+ total.cost.output += next.cost?.output ?? 0;
172
+ total.cost.cacheRead += next.cost?.cacheRead ?? 0;
173
+ total.cost.cacheWrite += next.cost?.cacheWrite ?? 0;
174
+ total.cost.total += next.cost?.total ?? 0;
175
+ }
176
+
177
+ function numericHttpStatus(value: unknown): number | undefined {
178
+ return isNonSuccessHttpStatus(value) ? value : undefined;
179
+ }
180
+
181
+ type StructuredRemoteProjection = {
182
+ readonly hasTestimony: boolean;
183
+ readonly httpStatus?: number;
184
+ readonly diagnostics?: unknown;
185
+ readonly body?: unknown;
186
+ readonly code?: unknown;
187
+ readonly errno?: unknown;
188
+ };
189
+
190
+ function projectStructuredRemote(error: unknown): StructuredRemoteProjection {
191
+ let httpStatus: number | undefined;
192
+ let diagnostics: unknown;
193
+ let body: unknown;
194
+ let code: unknown;
195
+ let errno: unknown;
196
+ let cursor: unknown = error;
197
+ const seen = new Set<unknown>();
198
+ while (typeof cursor === "object" && cursor !== null && !seen.has(cursor)) {
199
+ seen.add(cursor);
200
+ const record = cursor as Record<string, unknown>;
201
+ const nodeStatus = numericHttpStatus(record.statusCode)
202
+ ?? numericHttpStatus(record.status)
203
+ ?? numericHttpStatus(record.httpStatus);
204
+ const nodeDiagnostics = Array.isArray(record.diagnostics) && record.diagnostics.length > 0
205
+ ? record.diagnostics
206
+ : undefined;
207
+ const nodeHasTestimony = hasUpstreamErrorTestimony({
208
+ ...(nodeStatus === undefined ? {} : { httpStatus: nodeStatus }),
209
+ ...(nodeDiagnostics === undefined ? {} : { diagnostics: nodeDiagnostics }),
210
+ });
211
+ if (httpStatus === undefined && nodeStatus !== undefined) httpStatus = nodeStatus;
212
+ if (diagnostics === undefined && nodeDiagnostics !== undefined) diagnostics = nodeDiagnostics;
213
+ if (nodeHasTestimony) {
214
+ const payload = projectConfirmedRemotePayload(record);
215
+ if (body === undefined && payload.body !== undefined) body = payload.body;
216
+ if (code === undefined && payload.code !== undefined) code = payload.code;
217
+ if (errno === undefined && payload.errno !== undefined) errno = payload.errno;
218
+ }
219
+ cursor = record.cause;
220
+ }
221
+ return {
222
+ hasTestimony: hasUpstreamErrorTestimony({
223
+ ...(httpStatus === undefined ? {} : { httpStatus }),
224
+ ...(diagnostics === undefined ? {} : { diagnostics }),
225
+ }),
226
+ ...(httpStatus === undefined ? {} : { httpStatus }),
227
+ ...(diagnostics === undefined ? {} : { diagnostics }),
228
+ ...(body === undefined ? {} : { body }),
229
+ ...(code === undefined ? {} : { code }),
230
+ ...(errno === undefined ? {} : { errno }),
231
+ };
232
+ }
233
+
234
+ function attachObservedHttpStatus<T extends AssistantMessage>(
235
+ message: T,
236
+ observedHttpStatus: number | undefined,
237
+ ): T {
238
+ if (observedHttpStatus === undefined) return message;
239
+ if (message.stopReason !== "error" && message.stopReason !== "aborted") return message;
240
+ if (numericHttpStatus(observedHttpStatus) === undefined) return message;
241
+ if (projectStructuredRemote(message).httpStatus !== undefined) return message;
242
+ return Object.assign(message, {
243
+ status: observedHttpStatus,
244
+ statusCode: observedHttpStatus,
245
+ });
246
+ }
247
+
248
+ function enrichStreamEvent(event: unknown, observedHttpStatus: number | undefined): unknown {
249
+ if (observedHttpStatus === undefined || event === null || typeof event !== "object") return event;
250
+ const record = event as Record<string, unknown>;
251
+ if (record.type === "error" && record.error !== null && typeof record.error === "object") {
252
+ return {
253
+ ...record,
254
+ error: attachObservedHttpStatus(record.error as AssistantMessage, observedHttpStatus),
255
+ };
256
+ }
257
+ if (record.type === "done" && record.message !== null && typeof record.message === "object") {
258
+ return {
259
+ ...record,
260
+ message: attachObservedHttpStatus(record.message as AssistantMessage, observedHttpStatus),
261
+ };
262
+ }
263
+ if (record.partial !== null && typeof record.partial === "object") {
264
+ return {
265
+ ...record,
266
+ partial: attachObservedHttpStatus(record.partial as AssistantMessage, observedHttpStatus),
267
+ };
268
+ }
269
+ return event;
270
+ }
271
+
272
+ // ── S3 Institutional Session Open Seam ─────────────────────────────────────
273
+
274
+ export type OpenPiInstitutionalSessionOptions = HostInstitutionalSessionOptions & {
275
+ readonly label?: string;
276
+ };
277
+
278
+ /**
279
+ * Result of the Pi institutional open seam (#518 §1②).
280
+ * The host-neutral handle is the open-turn-close surface and does not leak
281
+ * AgentSession, ModelRuntime, or Provider objects out of the adapter.
282
+ */
283
+ export type OpenPiInstitutionalSessionResult = {
284
+ readonly handle: HostInstitutionalSessionHandle;
285
+ /**
286
+ * Primary provider-stream failure held at the adapter boundary when a
287
+ * provider stream errors after idle-only retries are exhausted. Consumers
288
+ * that need to distinguish a step machine "error" response from a real
289
+ * transport failure read this to preserve primary-cause fidelity
290
+ * (ADR 0018 / 失败诚实宪法). Undefined while the session stays healthy.
291
+ */
292
+ readonly streamFailure: unknown;
293
+ };
294
+
295
+ export async function openPiInstitutionalSession(
296
+ options: OpenPiInstitutionalSessionOptions,
297
+ ): Promise<OpenPiInstitutionalSessionResult> {
298
+ const label = options.label ?? "Institutional sub-session";
299
+ const selection = options.selection;
300
+
301
+ // 1. Scratch management
302
+ let scratchDir: string | undefined;
303
+ let resolvedAgentDir = options.agentDir;
304
+ if (resolvedAgentDir === undefined) {
305
+ scratchDir = await mkdtemp(join(options.credentialScratchParent ?? tmpdir(), "ak-institutional-"));
306
+ resolvedAgentDir = scratchDir;
307
+ }
308
+
309
+ try {
310
+ // 2. Auth resolution in Pi layer via explicit selection (Hop 3)
311
+ // spec-2: adapter creates its OWN child-local ModelRuntime and ModelRegistry.
312
+ // Auth is resolved strictly by explicit selection on the child registry — never
313
+ // ambiently inherited from the parent ExtensionContext/modelRegistry.
314
+ const childRuntime = await ModelRuntime.create();
315
+ const childRegistry = new ModelRegistry(childRuntime);
316
+
317
+ const childProvider: Provider | undefined = typeof childRegistry.getProvider === "function"
318
+ ? childRegistry.getProvider(selection.provider)
319
+ : undefined;
320
+
321
+ const foundModel = typeof childRegistry.find === "function"
322
+ ? childRegistry.find(selection.provider, selection.model)
323
+ : undefined;
324
+ const providerDefaultModel = childProvider?.getModels?.()[0];
325
+ const fallbackApi = providerDefaultModel?.api
326
+ ?? (childProvider as any)?.api
327
+ ?? (selection.provider === "openai-codex" ? "openai-codex-responses" : "openai-completions");
328
+ const modelToUse = foundModel ?? {
329
+ id: selection.model,
330
+ name: selection.model,
331
+ api: fallbackApi as any,
332
+ provider: selection.provider,
333
+ baseUrl: providerDefaultModel?.baseUrl ?? "",
334
+ reasoning: selection.thinking !== undefined && selection.thinking !== "off",
335
+ input: ["text"],
336
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
337
+ contextWindow: 128000,
338
+ maxTokens: 16384,
339
+ };
340
+
341
+ let resolution: { auth: { baseUrl?: string; apiKey?: string; headers?: Record<string, string | null> }; env?: Record<string, string> } | undefined;
342
+ if (typeof childRegistry.getProviderAuth === "function") {
343
+ resolution = await childRegistry.getProviderAuth(selection.provider).catch((error: unknown) => {
344
+ throw new Error(`${label} authentication failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
345
+ });
346
+ if (resolution === undefined) {
347
+ throw new Error(`${label} authentication failed: provider is not configured: ${selection.provider}`);
348
+ }
349
+ }
350
+
351
+ let authResult: { ok: boolean; error?: string; apiKey?: string; headers?: Record<string, string | null>; env?: Record<string, string> } | undefined;
352
+ if (typeof childRegistry.getApiKeyAndHeaders === "function") {
353
+ authResult = await childRegistry.getApiKeyAndHeaders(modelToUse as any);
354
+ if (authResult && !authResult.ok) {
355
+ throw new Error(`${label} authentication failed: ${authResult.error}`);
356
+ }
357
+ }
358
+
359
+ const resolvedApiKey = authResult?.apiKey ?? resolution?.auth?.apiKey;
360
+ const resolvedHeaders = authResult?.headers ?? resolution?.auth?.headers;
361
+ const resolvedEnv = authResult?.env ?? resolution?.env;
362
+ const effectiveBaseUrl = resolution?.auth?.baseUrl ?? modelToUse.baseUrl;
363
+
364
+ const effectiveModel: Model<Api> = {
365
+ ...modelToUse,
366
+ baseUrl: effectiveBaseUrl,
367
+ };
368
+
369
+ // 3. Standalone ModelRuntime + Provider with idle-only retry.
370
+ // spec-2: the adapter constructs its OWN runtime/provider registration.
371
+ // Auth is resolved only by explicit selection above and seeded into the
372
+ // child runtime's own credential store — never inherited ambiently from
373
+ // the parent ExtensionContext/Provider.
374
+ const credentials = new InMemoryCredentialStore();
375
+ const runtime = await ModelRuntime.create({
376
+ credentials,
377
+ modelsPath: null,
378
+ });
379
+
380
+ // Seed the child runtime's own credential store with the explicitly
381
+ // resolved auth so stream auth resolution is self-contained. No ambient
382
+ // fallback: absence of a resolved apiKey is not silently supplied.
383
+ if (resolvedApiKey !== undefined) {
384
+ await credentials.modify(selection.provider, async () => ({
385
+ type: "api_key",
386
+ key: resolvedApiKey,
387
+ ...(resolvedEnv === undefined ? {} : { env: resolvedEnv }),
388
+ }));
389
+ }
390
+
391
+ const abortReason = (signal: AbortSignal): unknown =>
392
+ signal.reason ?? new Error(`${label} provider stream aborted`);
393
+
394
+ let streamFailureValue: unknown;
395
+
396
+ async function waitForStream<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
397
+ if (signal.aborted) throw abortReason(signal);
398
+ let onAbort: (() => void) | undefined;
399
+ try {
400
+ return await Promise.race([
401
+ promise,
402
+ new Promise<never>((_resolve, reject) => {
403
+ onAbort = () => reject(abortReason(signal));
404
+ signal.addEventListener("abort", onAbort, { once: true });
405
+ }),
406
+ ]);
407
+ } finally {
408
+ if (onAbort !== undefined) signal.removeEventListener("abort", onAbort);
409
+ }
410
+ }
411
+
412
+ const createRetriedStream = (
413
+ simple: boolean,
414
+ model: Model<Api>,
415
+ context: Context,
416
+ request?: ProviderStreamOptions,
417
+ ): ReturnType<Provider["stream"]> => {
418
+ const wrapped = createAssistantMessageEventStream();
419
+ void (async () => {
420
+ for (let attempt = 0; ; attempt += 1) {
421
+ const idle = createStreamIdleGuard(
422
+ options.signal === undefined ? {} : { parentSignal: options.signal },
423
+ );
424
+ let observedHttpStatus: number | undefined;
425
+ try {
426
+ const requestSignal = request?.signal;
427
+ const streamSignal = requestSignal === undefined
428
+ ? idle.signal
429
+ : AbortSignal.any([idle.signal, requestSignal]);
430
+ const priorOnResponse = request?.onResponse;
431
+ const retriedRequest: ProviderStreamOptions = {
432
+ ...(request ?? {}),
433
+ ...(resolvedEnv === undefined ? {} : { env: resolvedEnv }),
434
+ signal: streamSignal,
435
+ maxRetries: 0,
436
+ onResponse: async (
437
+ response: { status: number; headers: Record<string, string> },
438
+ resModel: Model<Api>,
439
+ ) => {
440
+ if (typeof response?.status === "number") observedHttpStatus = response.status;
441
+ await priorOnResponse?.(response, resModel);
442
+ },
443
+ };
444
+
445
+ if (childProvider === undefined) {
446
+ throw new Error(`${label} provider not found: ${model.provider}`);
447
+ }
448
+
449
+ const source = simple
450
+ ? childProvider.streamSimple(model, context, retriedRequest as any)
451
+ : childProvider.stream(model, context, retriedRequest as any);
452
+ let sawEvent = false;
453
+ const attemptEvents: any[] = [];
454
+ const iterator = source[Symbol.asyncIterator]();
455
+ while (true) {
456
+ const next = await waitForStream(iterator.next(), idle.signal);
457
+ if (next.done) break;
458
+ sawEvent = true;
459
+ idle.poke();
460
+ attemptEvents.push(enrichStreamEvent(next.value, observedHttpStatus));
461
+ }
462
+ const response = attachObservedHttpStatus(
463
+ await waitForStream(source.result(), idle.signal),
464
+ observedHttpStatus,
465
+ );
466
+ // Some stream APIs (e.g. OpenAI-completions over an HTTP error)
467
+ // surface the failure as an error-stop message rather than throwing.
468
+ // Hold that primary provider failure at the adapter boundary so
469
+ // consumers surface a real transport failure, never a projected
470
+ // step-machine "error" response (ADR 0018 / #518 §3).
471
+ if (response.stopReason === "error") {
472
+ const errorMessage = response.errorMessage ?? `${label} provider stream failed`;
473
+ const idleFailure = streamIdleTimeoutFromUnknown(errorMessage);
474
+ if (
475
+ options.idleRetry !== false
476
+ && idleFailure !== undefined
477
+ && attempt < DEFAULT_COMPLIANCE_IDLE_MAX_RETRIES
478
+ && options.signal?.aborted !== true
479
+ ) {
480
+ continue;
481
+ }
482
+ streamFailureValue = idleFailure ?? new Error(errorMessage, { cause: response });
483
+ }
484
+ for (const ev of attemptEvents) {
485
+ wrapped.push(ev as any);
486
+ }
487
+ wrapped.end(response);
488
+ return;
489
+ } catch (error) {
490
+ if (request?.signal?.aborted) {
491
+ const response: AssistantMessage = {
492
+ role: "assistant",
493
+ content: [],
494
+ api: model.api,
495
+ provider: model.provider,
496
+ model: model.id,
497
+ usage: emptyUsage(),
498
+ stopReason: "aborted",
499
+ errorMessage: `${label} session aborted`,
500
+ timestamp: Date.now(),
501
+ };
502
+ wrapped.push({ type: "error", reason: "aborted", error: response });
503
+ wrapped.end(response);
504
+ return;
505
+ }
506
+ const failure = isStreamIdleTimeoutError(idle.signal.reason) ? idle.signal.reason : error;
507
+ const idleFailure = streamIdleTimeoutFromUnknown(failure);
508
+ if (
509
+ options.idleRetry !== false
510
+ && idleFailure !== undefined
511
+ && attempt < DEFAULT_COMPLIANCE_IDLE_MAX_RETRIES
512
+ && options.signal?.aborted !== true
513
+ ) {
514
+ continue;
515
+ }
516
+ const typedFailure = idleFailure ?? failure;
517
+ // Hold the primary provider failure at the adapter boundary (ADR
518
+ // 0018 / 失败诚实宪法). Consumers that surface transport failures
519
+ // read this so the real cause is never masked by a projected
520
+ // step-machine "error" response.
521
+ streamFailureValue = typedFailure;
522
+ const projected = projectStructuredRemote(failure);
523
+ const httpStatus = projected.httpStatus ?? numericHttpStatus(observedHttpStatus);
524
+ const response = {
525
+ role: "assistant" as const,
526
+ content: [] as [],
527
+ api: model.api,
528
+ provider: model.provider,
529
+ model: model.id,
530
+ usage: emptyUsage(),
531
+ stopReason: "error" as const,
532
+ errorMessage: failure instanceof Error ? failure.message : String(failure),
533
+ timestamp: Date.now(),
534
+ ...(projected.diagnostics === undefined ? {} : { diagnostics: projected.diagnostics }),
535
+ ...(httpStatus === undefined ? {} : { status: httpStatus, statusCode: httpStatus }),
536
+ ...(projected.body === undefined ? {} : { body: projected.body }),
537
+ ...(projected.code === undefined ? {} : { code: projected.code }),
538
+ ...(projected.errno === undefined ? {} : { errno: projected.errno }),
539
+ } as unknown as AssistantMessage;
540
+ wrapped.push({ type: "error", reason: "error", error: response });
541
+ wrapped.end(response);
542
+ return;
543
+ } finally {
544
+ idle.dispose();
545
+ }
546
+ }
547
+ })();
548
+ return wrapped as ReturnType<Provider["stream"]>;
549
+ };
550
+
551
+ const provider: Provider = {
552
+ id: selection.provider,
553
+ name: childProvider?.name ?? label,
554
+ ...(effectiveBaseUrl ? { baseUrl: effectiveBaseUrl } : {}),
555
+ ...(resolvedHeaders ? { headers: resolvedHeaders as any } : {}),
556
+ auth: {
557
+ apiKey: {
558
+ name: `${label} authentication`,
559
+ async resolve() {
560
+ return {
561
+ auth: {
562
+ ...(resolvedApiKey === undefined ? {} : { apiKey: resolvedApiKey }),
563
+ ...(resolvedHeaders === undefined ? {} : { headers: resolvedHeaders }),
564
+ ...(effectiveBaseUrl === undefined ? {} : { baseUrl: effectiveBaseUrl }),
565
+ },
566
+ ...(resolvedEnv === undefined ? {} : { env: resolvedEnv }),
567
+ };
568
+ },
569
+ },
570
+ },
571
+ getModels() { return [effectiveModel]; },
572
+ stream(model, childContext, request) {
573
+ return createRetriedStream(false, model, childContext, request as ProviderStreamOptions | undefined);
574
+ },
575
+ streamSimple(model, childContext, request) {
576
+ return createRetriedStream(true, model, childContext, request as ProviderStreamOptions | undefined);
577
+ },
578
+ };
579
+
580
+ runtime.registerNativeProvider(provider);
581
+ await runtime.refresh({ allowNetwork: false });
582
+
583
+ // 4. Settings and ResourceLoader (fixed adapter policies: no extensions/skills/themes/templates/context-files)
584
+ const settings = SettingsManager.inMemory({ compaction: { enabled: false }, retry: { enabled: false } });
585
+ const loader = new DefaultResourceLoader({
586
+ cwd: options.cwd,
587
+ agentDir: resolvedAgentDir,
588
+ settingsManager: settings,
589
+ noExtensions: true,
590
+ noSkills: true,
591
+ noPromptTemplates: true,
592
+ noThemes: true,
593
+ noContextFiles: true,
594
+ systemPrompt: options.systemPrompt,
595
+ });
596
+ await loader.reload();
597
+
598
+ // 5. SessionManager resolution
599
+ let sessionManager: SessionManager;
600
+ if (options.sessionManager !== undefined) {
601
+ sessionManager = options.sessionManager as SessionManager;
602
+ } else if (options.sessionIdentity !== undefined) {
603
+ sessionManager = createRecordSession({
604
+ cwd: options.cwd,
605
+ kind: options.sessionIdentity.kind,
606
+ ...(options.sessionIdentity.subject === undefined ? {} : { subject: options.sessionIdentity.subject }),
607
+ ...(options.sessionIdentity.parent === undefined ? {} : { parent: options.sessionIdentity.parent }),
608
+ });
609
+ } else {
610
+ sessionManager = createRecordSession({
611
+ cwd: options.cwd,
612
+ kind: "institutional",
613
+ });
614
+ }
615
+
616
+ // 6. Tools mapping
617
+ const customTools: ToolDefinition[] = [];
618
+ if (options.customTools !== undefined) {
619
+ customTools.push(...(options.customTools as ToolDefinition[]));
620
+ }
621
+ if (options.tools !== undefined) {
622
+ for (const hostTool of options.tools) {
623
+ customTools.push({
624
+ name: hostTool.name,
625
+ label: hostTool.label,
626
+ description: hostTool.description,
627
+ parameters: hostTool.parameters,
628
+ execute: async (toolCallId, params, signal, update, _ctx) => {
629
+ const res = await hostTool.execute(
630
+ toolCallId,
631
+ params as any,
632
+ signal,
633
+ update === undefined ? undefined : (u) => update(u as AgentToolResult<unknown>),
634
+ undefined as any,
635
+ );
636
+ return res as AgentToolResult<unknown>;
637
+ },
638
+ });
639
+ }
640
+ }
641
+
642
+ // 7. Create AgentSession
643
+ const { session } = await createAgentSession({
644
+ cwd: options.cwd,
645
+ model: effectiveModel,
646
+ thinkingLevel: (options.selection.thinking ?? "off") as any,
647
+ modelRuntime: runtime,
648
+ sessionManager,
649
+ settingsManager: settings,
650
+ agentDir: resolvedAgentDir,
651
+ resourceLoader: loader,
652
+ ...(options.noTools === undefined ? {} : { noTools: options.noTools }),
653
+ ...(options.toolsAllowlist === undefined ? {} : { tools: options.toolsAllowlist as string[] }),
654
+ ...(customTools.length === 0 ? {} : { customTools }),
655
+ });
656
+
657
+ // 8. Event subscriptions
658
+ const listeners = new Set<(event: HostInstitutionalSessionEvent) => void>();
659
+ const accumulatedUsage = emptyUsage();
660
+
661
+ let lastEmittedAssistant: AssistantMessage | undefined;
662
+ const unsubscribeSession = session.subscribe((event) => {
663
+ if (event.type === "message_end") {
664
+ const msg = event.message as AssistantMessage;
665
+ if (msg.role === "assistant") {
666
+ lastEmittedAssistant = msg;
667
+ if (msg.usage) {
668
+ addUsage(accumulatedUsage, msg.usage);
669
+ }
670
+ }
671
+ for (const listener of listeners) {
672
+ listener({
673
+ type: "message_end",
674
+ role: msg.role,
675
+ message: msg,
676
+ ...(msg.usage === undefined ? {} : { usage: msg.usage as HostSessionUsage }),
677
+ });
678
+ }
679
+ } else if (event.type === "turn_end") {
680
+ const msg = event.message as AssistantMessage;
681
+ for (const listener of listeners) {
682
+ listener({
683
+ type: "turn_end",
684
+ ...(msg.stopReason === undefined ? {} : { stopReason: msg.stopReason }),
685
+ });
686
+ }
687
+ } else if (event.type === "tool_execution_start") {
688
+ for (const listener of listeners) {
689
+ listener({
690
+ type: "tool_call",
691
+ toolCallId: event.toolCallId,
692
+ toolName: event.toolName,
693
+ args: (event as any).args ?? (event as any).input,
694
+ });
695
+ }
696
+ } else if (event.type === "tool_execution_end") {
697
+ for (const listener of listeners) {
698
+ listener({
699
+ type: "tool_result",
700
+ toolCallId: event.toolCallId,
701
+ toolName: event.toolName,
702
+ isError: event.isError,
703
+ details: (event as any).result ?? (event as any).details,
704
+ });
705
+ }
706
+ }
707
+ });
708
+
709
+ let closed = false;
710
+ const sessionFile = sessionManager.getSessionFile();
711
+ const sessionId = (sessionManager as any).getHeader?.()?.id;
712
+
713
+ const handle: HostInstitutionalSessionHandle = {
714
+ ...(sessionFile === undefined ? {} : { sessionFile }),
715
+ ...(sessionId === undefined ? {} : { sessionId }),
716
+
717
+ async prompt(text: string): Promise<HostAssistantTurnResult> {
718
+ const abortSession = () => { void session.abort(); };
719
+ if (options.signal?.aborted) abortSession();
720
+ else options.signal?.addEventListener("abort", abortSession, { once: true });
721
+
722
+ let promptError: unknown;
723
+ try {
724
+ await session.prompt(text);
725
+ } catch (error) {
726
+ promptError = error;
727
+ } finally {
728
+ options.signal?.removeEventListener("abort", abortSession);
729
+ }
730
+
731
+ const lastAssistant = [...session.messages]
732
+ .reverse()
733
+ .find((message) => message.role === "assistant") as AssistantMessage | undefined;
734
+
735
+ if (lastAssistant !== undefined && lastAssistant !== lastEmittedAssistant) {
736
+ lastEmittedAssistant = lastAssistant;
737
+ for (const listener of listeners) {
738
+ listener({
739
+ type: "message_end",
740
+ role: lastAssistant.role,
741
+ message: lastAssistant,
742
+ ...(lastAssistant.usage === undefined ? {} : { usage: lastAssistant.usage as HostSessionUsage }),
743
+ });
744
+ }
745
+ }
746
+
747
+ if (promptError !== undefined && lastAssistant === undefined) {
748
+ throw promptError;
749
+ }
750
+
751
+ return {
752
+ text: session.getLastAssistantText() ?? "",
753
+ ...(lastAssistant?.stopReason === undefined ? {} : { stopReason: lastAssistant.stopReason }),
754
+ ...(lastAssistant?.errorMessage === undefined ? {} : { errorMessage: lastAssistant.errorMessage }),
755
+ usage: accumulatedUsage as HostSessionUsage,
756
+ messages: session.messages,
757
+ };
758
+ },
759
+
760
+ subscribe(listener: (event: HostInstitutionalSessionEvent) => void): () => void {
761
+ listeners.add(listener);
762
+ return () => {
763
+ listeners.delete(listener);
764
+ };
765
+ },
766
+
767
+ abort(): void {
768
+ void session.abort();
769
+ },
770
+
771
+ async close(): Promise<void> {
772
+ if (closed) return;
773
+ closed = true;
774
+ listeners.clear();
775
+ try {
776
+ unsubscribeSession();
777
+ } finally {
778
+ // spec-3: handle.close must always dispose the child session even when
779
+ // unsubscribing throws (the throwing unsubscribe is a cleanup failure the
780
+ // caller aggregates, never a reason to skip session teardown).
781
+ session.dispose();
782
+ }
783
+
784
+ if (scratchDir !== undefined) {
785
+ try {
786
+ await rm(scratchDir, { recursive: true, force: true });
787
+ } catch (error) {
788
+ throw error;
789
+ }
790
+ }
791
+ },
792
+ };
793
+
794
+ return {
795
+ handle,
796
+ // Read lazily: the provider stream runs during session.prompt, so the
797
+ // primary failure is only known after that turn completes. A getter keeps
798
+ // this reflecting the latest value instead of freezing it at open time.
799
+ get streamFailure() {
800
+ return streamFailureValue;
801
+ },
802
+ };
803
+ } catch (openError) {
804
+ if (scratchDir !== undefined) {
805
+ try {
806
+ await rm(scratchDir, { recursive: true, force: true });
807
+ } catch (cleanupFailure) {
808
+ // ADR 0018 / #518 §1④: primary failure and cleanup failure stay
809
+ // separated — cleanup must not mask the original open cause.
810
+ throw new AggregateError(
811
+ [openError, cleanupFailure],
812
+ `${label} open failed and its scratch cleanup also failed`,
813
+ { cause: openError },
814
+ );
815
+ }
816
+ }
817
+ throw openError;
818
+ }
819
+ }