@akagilnc/pi-workflow-roles 0.1.3572 → 0.1.3621

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 (129) hide show
  1. package/dist/acp-host/production-host.js +20239 -10556
  2. package/dist/analyst-gate-cycles-read.js +387 -0
  3. package/dist/archivist-record-entry.js +22 -1
  4. package/dist/audit-escalation.js +6 -0
  5. package/dist/auditor-soul.js +74 -0
  6. package/dist/collector-config.js +86 -0
  7. package/dist/collector-evidence.js +316 -0
  8. package/dist/collector-github.js +527 -0
  9. package/dist/collector-ledger.js +853 -0
  10. package/dist/collector-tool-schemas.js +33 -0
  11. package/dist/compliance-transport.js +104 -52
  12. package/dist/diarist-mechanical.js +411 -0
  13. package/dist/diarist-ticket-resolution.js +177 -0
  14. package/dist/diarist.js +311 -0
  15. package/dist/doctor-auditor.js +25 -0
  16. package/dist/doctor-contracts.js +2 -0
  17. package/dist/doctor-evidence.js +142 -0
  18. package/dist/gatekeeper-role.js +104 -81
  19. package/dist/host-transition-prior-native.js +78 -0
  20. package/dist/institutional-resolution.js +1 -95
  21. package/dist/judge-auditor.js +26 -0
  22. package/dist/ledger-session-read.js +227 -0
  23. package/dist/merger-git-state.js +78 -0
  24. package/dist/navigator-attendance.js +15 -7
  25. package/dist/navigator-public-session.js +170 -0
  26. package/dist/navigator-session-contracts.js +36 -40
  27. package/dist/notary-source-run.js +122 -0
  28. package/dist/package-contracts/auditor-output.js +66 -0
  29. package/dist/package-contracts/evidence-child-output.js +34 -0
  30. package/dist/package-contracts/judge-output.js +2 -0
  31. package/dist/package-contracts/terminating-tools.js +25 -2
  32. package/dist/package-resources/method-skill.js +254 -0
  33. package/dist/packaged-role-registry.js +36 -0
  34. package/dist/pi/durable-principal.js +61 -0
  35. package/dist/pi/in-process-session.js +25 -6
  36. package/dist/pi/known-failure.js +52 -0
  37. package/dist/pi/role-turn-host.js +430 -0
  38. package/dist/public-cli/auto-resume.js +414 -0
  39. package/dist/public-cli/cli-errors.js +8 -0
  40. package/dist/public-cli/cli-io.js +1 -0
  41. package/dist/public-cli/command-renderer.js +5 -0
  42. package/dist/public-cli/doctor-run.js +84 -0
  43. package/dist/public-cli/inspector-run.js +136 -0
  44. package/dist/public-cli/instruction-seat-run.js +256 -0
  45. package/dist/public-cli/invocation.js +2225 -0
  46. package/dist/public-cli/judge-run.js +118 -0
  47. package/dist/public-cli/load-production-acp-host.js +40 -0
  48. package/dist/public-cli/main.js +1140 -652
  49. package/dist/public-cli/notary-run.js +161 -0
  50. package/dist/public-cli/option-definitions.js +1192 -0
  51. package/dist/public-cli/post-admission.js +667 -0
  52. package/dist/public-cli/public-run-credentials.js +49 -0
  53. package/dist/public-cli/registry.js +4 -1
  54. package/dist/public-cli/reviewer-dispatch-rejection.js +77 -0
  55. package/dist/public-cli/run-lifecycle.js +1344 -0
  56. package/dist/public-cli/seat-ticket-binding.js +113 -0
  57. package/dist/public-cli/settlement.js +3441 -0
  58. package/dist/public-cli/terminal.js +135 -0
  59. package/dist/public-cli/turn-request.js +25 -0
  60. package/dist/public-role-summons.js +301 -0
  61. package/dist/receipt-delivery-policy.js +10 -0
  62. package/dist/reviewer-child-executor.js +80 -8
  63. package/dist/reviewer-execution-ledger.js +2 -1
  64. package/dist/run-terminal-artifacts.js +195 -0
  65. package/dist/run-ticket-number.js +40 -0
  66. package/dist/session-assistant-usage.js +107 -0
  67. package/dist/shape-unreadable-failure.js +34 -0
  68. package/dist/submission-errors.js +3 -0
  69. package/dist/submission-ledger.js +388 -0
  70. package/dist/ticket-provenance-contracts.js +115 -0
  71. package/dist/ticket-provenance.js +340 -0
  72. package/extensions/role-runtime.ts +7 -0
  73. package/package.json +1 -1
  74. package/scripts/build-package.mjs +2 -1
  75. package/souls/doctor-auditor.md +1 -0
  76. package/souls/evidence-child.md +1 -0
  77. package/src/acp-host/production-host.ts +3 -0
  78. package/src/acp-host/role-envelope.ts +2 -2
  79. package/src/acp-host/role-turn-host.ts +9 -1
  80. package/src/analyst-gate-cycles-read.ts +37 -2
  81. package/src/archivist-record-entry.ts +45 -1
  82. package/src/audit-escalation.ts +17 -0
  83. package/src/auditor-role.ts +22 -0
  84. package/src/auditor-soul.ts +42 -0
  85. package/src/compliance-transport.ts +177 -66
  86. package/src/doctor-auditor.ts +10 -14
  87. package/src/doctor-contracts.ts +1 -0
  88. package/src/doctor-role.ts +2 -2
  89. package/src/evidence-child-role.ts +22 -0
  90. package/src/gatekeeper-pass-envelope.ts +109 -0
  91. package/src/gatekeeper-role.ts +145 -104
  92. package/src/host-contracts.ts +9 -1
  93. package/src/institutional-resolution.ts +8 -163
  94. package/src/judge-auditor.ts +10 -15
  95. package/src/judge-role.ts +8 -0
  96. package/src/navigator-attendance.ts +25 -9
  97. package/src/navigator-public-session.ts +217 -0
  98. package/src/navigator-session-contracts.ts +61 -54
  99. package/src/notary-source-run.ts +3 -1
  100. package/src/package-contracts/auditor-output.ts +82 -0
  101. package/src/package-contracts/evidence-child-output.ts +51 -0
  102. package/src/package-contracts/judge-output.ts +1 -0
  103. package/src/package-contracts/reviewer-output.ts +2 -2
  104. package/src/package-contracts/terminating-tools.ts +31 -1
  105. package/src/packaged-role-registry.ts +43 -0
  106. package/src/pi/adapter.ts +2 -1
  107. package/src/pi/in-process-session.ts +38 -12
  108. package/src/pi/role-turn-host.ts +34 -0
  109. package/src/public-cli/cli.ts +14 -6
  110. package/src/public-cli/instruction-seat-run.ts +289 -50
  111. package/src/public-cli/invocation.ts +66 -25
  112. package/src/public-cli/option-definitions.ts +61 -0
  113. package/src/public-cli/post-admission.ts +7 -1
  114. package/src/public-cli/registry.ts +4 -1
  115. package/src/public-cli/run-lifecycle.ts +22 -3
  116. package/src/public-cli/settlement.ts +120 -5
  117. package/src/public-cli/terminal.ts +2 -0
  118. package/src/public-role-summons.ts +431 -0
  119. package/src/receipt-delivery-policy.ts +10 -0
  120. package/src/reviewer-agent.ts +1 -1
  121. package/src/reviewer-child-executor.ts +114 -12
  122. package/src/reviewer-execution-ledger.ts +3 -2
  123. package/src/role-runtime.ts +158 -17
  124. package/src/session-assistant-usage.ts +119 -0
  125. package/src/session-opening-materials.ts +1 -1
  126. package/src/shape-unreadable-failure.ts +49 -0
  127. package/src/submission-errors.ts +3 -0
  128. package/dist/evidence-child-executor.js +0 -829
  129. package/src/evidence-child-executor.ts +0 -1140
@@ -1,829 +0,0 @@
1
- import { mkdtemp, rm } from "node:fs/promises";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
- import {
5
- } from "@earendil-works/pi-ai";
6
- import {
7
- AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE,
8
- AUDITOR_PARENT_ATTEMPT_BINDING_ENTRY_TYPE
9
- } from "./compliance-transport.js";
10
- import { auditorRunDirectory } from "./auditor-dossier-tool.js";
11
- import { sitianReport } from "./sitian-facade.js";
12
- import { createEngineDetourToolDefinition } from "./engine-detour-tool.js";
13
- import { engineNameFromEnv } from "./engine-detour.js";
14
- import {
15
- appendEngineSessionMaterial,
16
- engineSessionMaterialFromOptions
17
- } from "./package-resources/engine-material.js";
18
- import { readPackageMaterial } from "./session-opening-materials.js";
19
- import {
20
- } from "./public-cli/config.js";
21
- import { readInstitutionalSeatSelection } from "./institutional-resolution.js";
22
- import {
23
- NAVIGATOR_PREPARE_TOOL_NAME,
24
- NavigatorUnavailableError,
25
- navigatorModelSettingPath,
26
- navigatorProviderFailureFromDiagnostics,
27
- navigatorProviderFailureFromError,
28
- navigatorProviderFailureFromStatus,
29
- navigatorUnavailableError,
30
- parseNavigatorModelSetting,
31
- resolveNavigatorSeatSelection
32
- } from "./navigator-session-contracts.js";
33
- import { createReceiptDeliveryPolicy, NO_RECEIPT_LIFECYCLE_ENTRY_TYPE, RECEIPT_DELIVERY_PROMPT } from "./receipt-delivery-policy.js";
34
- import { recordTypedProviderHttpStatus } from "./typed-provider-http.js";
35
- import {
36
- hasUpstreamErrorTestimony,
37
- isNonSuccessHttpStatus,
38
- projectConfirmedRemotePayload
39
- } from "./upstream-error-testimony.js";
40
- const EVIDENCE_CHILD_SESSION_MATERIALS = [
41
- "souls/quality-law.md"
42
- ];
43
- async function buildEvidenceChildSystemPrompt(engineMaterial) {
44
- const materials = [];
45
- for (const relativePath of EVIDENCE_CHILD_SESSION_MATERIALS) {
46
- materials.push(await readPackageMaterial(relativePath));
47
- }
48
- return appendEngineSessionMaterial(materials, engineMaterial).join("\n");
49
- }
50
- const DEFAULT_COMPLIANCE_IDLE_MAX_RETRIES = 2;
51
- async function withInProcessScratch(options, run) {
52
- const scratch = await mkdtemp(join(options.parentDirectory ?? tmpdir(), options.prefix));
53
- let failure;
54
- try {
55
- return await run(scratch);
56
- } catch (error) {
57
- failure = error;
58
- throw error;
59
- } finally {
60
- try {
61
- await rm(scratch, { recursive: true, force: true });
62
- } catch (cleanupFailure) {
63
- if (failure !== void 0) {
64
- throw new AggregateError([failure, cleanupFailure], "in-process child scratch cleanup failed", { cause: failure });
65
- }
66
- throw cleanupFailure;
67
- }
68
- }
69
- }
70
- async function runChildCleanup(cleanups, primaryFailure, label) {
71
- let cleanupFailure;
72
- for (const cleanup of cleanups) {
73
- try {
74
- await cleanup();
75
- } catch (failure) {
76
- cleanupFailure = cleanupFailure === void 0 ? failure : new AggregateError([cleanupFailure, failure], `${label} cleanup failed`, {
77
- cause: cleanupFailure
78
- });
79
- }
80
- }
81
- if (cleanupFailure === void 0) return;
82
- if (primaryFailure !== void 0) {
83
- throw new AggregateError(
84
- [primaryFailure, cleanupFailure],
85
- `${label} execution and cleanup failed`,
86
- { cause: primaryFailure }
87
- );
88
- }
89
- throw new AggregateError([cleanupFailure], `${label} cleanup failed`, {
90
- cause: cleanupFailure
91
- });
92
- }
93
- function numericHttpStatus(value) {
94
- return isNonSuccessHttpStatus(value) ? value : void 0;
95
- }
96
- function projectStructuredRemote(error) {
97
- let httpStatus;
98
- let diagnostics;
99
- let body;
100
- let code;
101
- let errno;
102
- let cursor = error;
103
- const seen = /* @__PURE__ */ new Set();
104
- while (typeof cursor === "object" && cursor !== null && !seen.has(cursor)) {
105
- seen.add(cursor);
106
- const record = cursor;
107
- const nodeStatus = numericHttpStatus(record.statusCode) ?? numericHttpStatus(record.status) ?? numericHttpStatus(record.httpStatus);
108
- const nodeDiagnostics = Array.isArray(record.diagnostics) && record.diagnostics.length > 0 ? record.diagnostics : void 0;
109
- const nodeHasTestimony = hasUpstreamErrorTestimony({
110
- ...nodeStatus === void 0 ? {} : { httpStatus: nodeStatus },
111
- ...nodeDiagnostics === void 0 ? {} : { diagnostics: nodeDiagnostics }
112
- });
113
- if (httpStatus === void 0 && nodeStatus !== void 0) httpStatus = nodeStatus;
114
- if (diagnostics === void 0 && nodeDiagnostics !== void 0) diagnostics = nodeDiagnostics;
115
- if (nodeHasTestimony) {
116
- const payload = projectConfirmedRemotePayload(record);
117
- if (body === void 0 && payload.body !== void 0) body = payload.body;
118
- if (code === void 0 && payload.code !== void 0) code = payload.code;
119
- if (errno === void 0 && payload.errno !== void 0) errno = payload.errno;
120
- }
121
- cursor = record.cause;
122
- }
123
- return {
124
- hasTestimony: hasUpstreamErrorTestimony({
125
- ...httpStatus === void 0 ? {} : { httpStatus },
126
- ...diagnostics === void 0 ? {} : { diagnostics }
127
- }),
128
- ...httpStatus === void 0 ? {} : { httpStatus },
129
- ...diagnostics === void 0 ? {} : { diagnostics },
130
- ...body === void 0 ? {} : { body },
131
- ...code === void 0 ? {} : { code },
132
- ...errno === void 0 ? {} : { errno }
133
- };
134
- }
135
- function attachObservedHttpStatus(message, observedHttpStatus) {
136
- if (observedHttpStatus === void 0) return message;
137
- if (message.stopReason !== "error" && message.stopReason !== "aborted") return message;
138
- if (numericHttpStatus(observedHttpStatus) === void 0) return message;
139
- if (projectStructuredRemote(message).httpStatus !== void 0) return message;
140
- return Object.assign(message, {
141
- status: observedHttpStatus,
142
- statusCode: observedHttpStatus
143
- });
144
- }
145
- function enrichStreamEvent(event, observedHttpStatus) {
146
- if (observedHttpStatus === void 0 || event === null || typeof event !== "object") return event;
147
- const record = event;
148
- if (record.type === "error" && record.error !== null && typeof record.error === "object") {
149
- return {
150
- ...record,
151
- error: attachObservedHttpStatus(record.error, observedHttpStatus)
152
- };
153
- }
154
- if (record.type === "done" && record.message !== null && typeof record.message === "object") {
155
- return {
156
- ...record,
157
- message: attachObservedHttpStatus(record.message, observedHttpStatus)
158
- };
159
- }
160
- if (record.partial !== null && typeof record.partial === "object") {
161
- return {
162
- ...record,
163
- partial: attachObservedHttpStatus(record.partial, observedHttpStatus)
164
- };
165
- }
166
- return event;
167
- }
168
- function classifiedError(error, evidenceChildFailure) {
169
- const diagnostic = typeof error === "object" && error !== null && typeof error.errorMessage === "string" ? error.errorMessage : error === void 0 ? "" : String(error);
170
- const wrapped = error instanceof Error ? error : Object.assign(new Error(diagnostic, { cause: error }), { evidenceChildOriginal: error });
171
- const classification = "evidenceChildFailure" in wrapped ? wrapped.evidenceChildFailure : evidenceChildFailure === "provider" && !projectStructuredRemote(error).hasTestimony ? "unknown" : evidenceChildFailure;
172
- return Object.assign(wrapped, { evidenceChildFailure: classification });
173
- }
174
- function extractToolResultText(details) {
175
- if (typeof details !== "object" || details === null) return void 0;
176
- const record = details;
177
- const content = record.content;
178
- if (Array.isArray(content)) {
179
- for (const part of content) {
180
- if (typeof part === "object" && part !== null) {
181
- const text = part.text;
182
- if (typeof text === "string" && text.trim() !== "") return text;
183
- }
184
- }
185
- }
186
- return void 0;
187
- }
188
- function emptyUsage() {
189
- return {
190
- input: 0,
191
- output: 0,
192
- cacheRead: 0,
193
- cacheWrite: 0,
194
- totalTokens: 0,
195
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
196
- };
197
- }
198
- function addUsage(total, next) {
199
- total.input += next.input;
200
- total.output += next.output;
201
- total.cacheRead += next.cacheRead;
202
- total.cacheWrite += next.cacheWrite;
203
- total.totalTokens += next.totalTokens;
204
- total.cost.input += next.cost.input;
205
- total.cost.output += next.cost.output;
206
- total.cost.cacheRead += next.cost.cacheRead;
207
- total.cost.cacheWrite += next.cost.cacheWrite;
208
- total.cost.total += next.cost.total;
209
- }
210
- async function executeEvidenceChild(workspace, prompt, context, options = {}) {
211
- const signal = options.signal;
212
- const runDirectory = options.runDirectory ?? auditorRunDirectory(context);
213
- if (runDirectory === void 0) {
214
- throw new Error("Evidence child requires a run directory carrying the institutional resolution page");
215
- }
216
- const selection = await readInstitutionalSeatSelection(runDirectory, "evidenceChild");
217
- return withInProcessScratch(
218
- {
219
- prefix: "ak-evidence-child-",
220
- ...options.credentialScratchParent === void 0 ? {} : { parentDirectory: options.credentialScratchParent }
221
- },
222
- async (childConfigDir) => {
223
- const { openPiInstitutionalSession } = await import("./pi/in-process-session.js");
224
- const { createRecordSession } = await import("./archivist-record-entry.js");
225
- const engineName = engineNameFromEnv();
226
- const engineMaterial = engineName === void 0 ? void 0 : options.packageRoot === void 0 || options.packageRoot.trim() === "" ? Object.freeze({ name: engineName }) : engineSessionMaterialFromOptions({
227
- engine: engineName,
228
- packageRoot: options.packageRoot
229
- });
230
- let engineDetourFailure;
231
- const engineDetourTool = engineName === void 0 ? void 0 : createEngineDetourToolDefinition({
232
- engineName,
233
- fail(error) {
234
- engineDetourFailure ??= error instanceof Error ? error : new Error(String(error));
235
- throw engineDetourFailure;
236
- }
237
- });
238
- let opened;
239
- try {
240
- opened = await openPiInstitutionalSession({
241
- cwd: workspace,
242
- agentDir: childConfigDir,
243
- selection,
244
- systemPrompt: await buildEvidenceChildSystemPrompt(engineMaterial),
245
- ...engineDetourTool === void 0 ? {} : { customTools: [engineDetourTool] },
246
- sessionManager: createRecordSession({
247
- cwd: workspace,
248
- kind: "evidence-children",
249
- ...context.sessionManager === void 0 ? {} : { parent: context.sessionManager }
250
- }),
251
- ...signal === void 0 ? {} : { signal },
252
- label: "Evidence child"
253
- });
254
- } catch (error) {
255
- throw classifiedError(error, "provider");
256
- }
257
- const { handle } = opened;
258
- const usage = emptyUsage();
259
- const unsubscribe = handle.subscribe((event) => {
260
- if (event.type === "message_end" && event.role === "assistant") {
261
- if (event.usage) addUsage(usage, event.usage);
262
- }
263
- });
264
- const abortChild = () => {
265
- handle.abort();
266
- };
267
- if (signal?.aborted) abortChild();
268
- else signal?.addEventListener("abort", abortChild, { once: true });
269
- let primaryFailure;
270
- try {
271
- const delivered = prompt;
272
- let turnResult;
273
- try {
274
- turnResult = await handle.prompt(delivered);
275
- } catch (error) {
276
- if (engineDetourFailure !== void 0) {
277
- throw classifiedError(engineDetourFailure, "child");
278
- }
279
- throw classifiedError(error, "provider");
280
- }
281
- if (engineDetourFailure !== void 0) {
282
- throw classifiedError(engineDetourFailure, "child");
283
- }
284
- if (signal?.aborted) throw new Error("Evidence child was cancelled");
285
- const lastAssistant = turnResult.messages !== void 0 ? [...turnResult.messages].reverse().find((message) => message?.role === "assistant") : void 0;
286
- if (turnResult.stopReason === "error" || turnResult.stopReason === "aborted" || lastAssistant?.role === "assistant" && (lastAssistant.stopReason === "error" || lastAssistant.stopReason === "aborted")) {
287
- const errMsg = turnResult.errorMessage ?? lastAssistant?.errorMessage ?? "";
288
- throw classifiedError(
289
- new Error(errMsg, { cause: lastAssistant }),
290
- lastAssistant && projectStructuredRemote(lastAssistant).hasTestimony ? "provider" : "unknown"
291
- );
292
- }
293
- if (lastAssistant !== void 0 && lastAssistant.role !== "assistant") {
294
- throw classifiedError(
295
- new Error("Evidence child child terminated without a report", {
296
- cause: lastAssistant ?? turnResult.messages
297
- }),
298
- "child"
299
- );
300
- }
301
- const report = turnResult.text;
302
- if (report.trim().length === 0) {
303
- throw new Error("Evidence child returned a blank child report");
304
- }
305
- return { report, usage, prompt: delivered };
306
- } catch (error) {
307
- primaryFailure = classifiedError(error, "child");
308
- throw primaryFailure;
309
- } finally {
310
- signal?.removeEventListener("abort", abortChild);
311
- await runChildCleanup([() => unsubscribe(), () => handle.close()], primaryFailure, "Reviewer child");
312
- }
313
- }
314
- );
315
- }
316
- function auditorSeatKey(gateSeat) {
317
- return gateSeat ?? "auditor";
318
- }
319
- async function executeAuditorChild(options) {
320
- const runDirectory = options.runDirectory ?? auditorRunDirectory(options.context);
321
- if (runDirectory === void 0) {
322
- throw new Error(`${options.roleLabel} requires a run directory carrying the institutional resolution page`);
323
- }
324
- const seat = auditorSeatKey(options.gateSeat);
325
- const selection = await readInstitutionalSeatSelection(runDirectory, seat);
326
- return withInProcessScratch({ prefix: "ak-auditor-role-" }, async (scratch) => {
327
- const cwd = options.context.cwd ?? process.cwd();
328
- let decision;
329
- let noReceiptLifecycle;
330
- let decisionSubmitted = false;
331
- let decisionCallId;
332
- let decisionToolFailure;
333
- const decisionToolFailures = /* @__PURE__ */ new Map();
334
- const delivery = createReceiptDeliveryPolicy();
335
- const tool = {
336
- ...options.tool,
337
- label: options.roleLabel,
338
- async execute(...args) {
339
- if (decisionSubmitted && decisionCallId !== args[0]) {
340
- throw new Error("Auditor decision was submitted more than once");
341
- }
342
- try {
343
- const result = await options.tool.execute(...args);
344
- delivery.recordAccepted();
345
- const rawDecision = args[1];
346
- const isMissingArgs = rawDecision === void 0 || typeof rawDecision === "object" && rawDecision !== null && !Array.isArray(rawDecision) && Object.keys(rawDecision).length === 0;
347
- decision = isMissingArgs ? void 0 : rawDecision;
348
- decisionCallId = args[0];
349
- decisionToolFailure = void 0;
350
- decisionToolFailures.delete(args[0]);
351
- decisionSubmitted = true;
352
- return { ...result, terminate: true };
353
- } catch (error) {
354
- decisionToolFailure = error;
355
- decisionToolFailures.set(args[0], error);
356
- throw error;
357
- }
358
- }
359
- };
360
- const parentSessionManager = options.context.sessionManager;
361
- const parentHeader = parentSessionManager?.getHeader?.();
362
- const parentSessionFile = parentSessionManager?.getSessionFile?.();
363
- const parentAttemptEntryId = parentSessionManager?.getLeafId?.();
364
- const { createRecordSession } = await import("./archivist-record-entry.js");
365
- const auditorSessionManager = createRecordSession({
366
- cwd,
367
- kind: "auditor-roles",
368
- ...parentSessionManager === void 0 ? {} : { parent: parentSessionManager }
369
- });
370
- const { openPiInstitutionalSession } = await import("./pi/in-process-session.js");
371
- const evidenceToolFailures = /* @__PURE__ */ new Map();
372
- const wrappedDossierTool = {
373
- ...options.dossierTool,
374
- label: options.roleLabel,
375
- async execute(...args) {
376
- try {
377
- return await options.dossierTool.execute(...args);
378
- } catch (error) {
379
- evidenceToolFailures.set(args[0], error);
380
- throw error;
381
- }
382
- }
383
- };
384
- const opened = await openPiInstitutionalSession({
385
- cwd,
386
- agentDir: scratch,
387
- selection,
388
- systemPrompt: options.systemPrompt,
389
- customTools: [wrappedDossierTool, tool],
390
- sessionManager: auditorSessionManager,
391
- ...options.signal === void 0 ? {} : { signal: options.signal },
392
- idleRetry: true,
393
- label: options.roleLabel
394
- });
395
- const { handle } = opened;
396
- const binding = {
397
- version: 1,
398
- parent: {
399
- ...parentHeader?.id === void 0 ? {} : { sessionId: parentHeader.id },
400
- ...parentSessionFile === void 0 ? {} : { sessionFile: parentSessionFile },
401
- ...parentAttemptEntryId === null || parentAttemptEntryId === void 0 ? {} : { attemptEntryId: parentAttemptEntryId }
402
- }
403
- };
404
- auditorSessionManager.appendCustomEntry(AUDITOR_PARENT_ATTEMPT_BINDING_ENTRY_TYPE, binding);
405
- try {
406
- sitianReport({
407
- level: "event",
408
- kind: "auditor",
409
- cwd,
410
- sessionParent: parentSessionFile,
411
- payload: { type: AUDITOR_PARENT_ATTEMPT_BINDING_ENTRY_TYPE, ...binding },
412
- source: "evidence-child-executor"
413
- });
414
- } catch {
415
- }
416
- const sessionUsage = emptyUsage();
417
- let boundaryResponse;
418
- let retentionFailure;
419
- let retainedResponse;
420
- let rejectedDecisionResponse;
421
- let promptNeighboringFailure;
422
- let promptDecisionFailures = [];
423
- const findToolFailure = (response) => {
424
- const callIds = response.content.flatMap((part) => part.type === "toolCall" && part.name !== tool.name ? [part.id] : []);
425
- for (const callId of callIds) {
426
- if (evidenceToolFailures.has(callId)) return evidenceToolFailures.get(callId);
427
- }
428
- return void 0;
429
- };
430
- const drainRejectedDecisionFailures = (response) => {
431
- for (const part of response.content) {
432
- if (part.type !== "toolCall" || part.name !== tool.name || !decisionToolFailures.has(part.id)) continue;
433
- decisionToolFailure = decisionToolFailures.get(part.id);
434
- promptDecisionFailures.push(decisionToolFailure);
435
- decisionToolFailures.delete(part.id);
436
- }
437
- };
438
- const retainedAssistants = [];
439
- const unsubscribe = handle.subscribe((event) => {
440
- if (event.type === "tool_result" && event.isError === true && event.toolName !== tool.name) {
441
- const detailText = extractToolResultText(event.details);
442
- if (detailText !== void 0 && /^Tool\s+.+ not found$/.test(detailText.trim())) return;
443
- const failure = detailText === void 0 ? new Error(event.toolName ?? "evidence tool failed") : new Error(detailText);
444
- const errno = /^([A-Z_]+):/.exec(detailText ?? "");
445
- if (errno !== null && errno[1] !== void 0) failure.code = errno[1];
446
- evidenceToolFailures.set(event.toolCallId, failure);
447
- }
448
- if (event.type === "message_end" && event.role === "assistant" && boundaryResponse === void 0) {
449
- if (event.usage) addUsage(sessionUsage, event.usage);
450
- const msg = event.message;
451
- retainedResponse = msg;
452
- if (msg) {
453
- retainedAssistants.push(msg);
454
- try {
455
- options.retainResponse?.(msg);
456
- } catch (error) {
457
- retentionFailure = error;
458
- }
459
- for (const part of msg.content) {
460
- if (part.type === "toolCall" && part.name === tool.name) {
461
- rejectedDecisionResponse = msg;
462
- if (decision === void 0) {
463
- decision = part.arguments === void 0 || typeof part.arguments === "object" && part.arguments !== null && !Array.isArray(part.arguments) && Object.keys(part.arguments).length === 0 ? void 0 : part.arguments;
464
- decisionCallId = part.id;
465
- if (part.arguments === void 0 || typeof part.arguments === "object" && part.arguments !== null && !Array.isArray(part.arguments) && Object.keys(part.arguments).length === 0) {
466
- decisionSubmitted = true;
467
- }
468
- }
469
- }
470
- }
471
- if (msg.stopReason === "error") boundaryResponse = msg;
472
- }
473
- }
474
- if (event.type === "turn_end") {
475
- if (rejectedDecisionResponse !== void 0) {
476
- promptNeighboringFailure = findToolFailure(rejectedDecisionResponse);
477
- drainRejectedDecisionFailures(rejectedDecisionResponse);
478
- }
479
- if (decisionSubmitted || promptNeighboringFailure !== void 0 || boundaryResponse !== void 0 && rejectedDecisionResponse === void 0 || retentionFailure !== void 0) {
480
- handle.abort();
481
- }
482
- }
483
- });
484
- const abort = () => {
485
- handle.abort();
486
- };
487
- if (options.signal?.aborted) abort();
488
- else options.signal?.addEventListener("abort", abort, { once: true });
489
- let auditorFailure;
490
- try {
491
- try {
492
- const promptAllowingRejectedDecision = async (prompt) => {
493
- rejectedDecisionResponse = void 0;
494
- promptNeighboringFailure = void 0;
495
- decisionToolFailure = void 0;
496
- promptDecisionFailures = [];
497
- let promptFailure;
498
- try {
499
- await handle.prompt(prompt);
500
- } catch (error) {
501
- promptFailure = error;
502
- }
503
- const correlatedResponse = rejectedDecisionResponse;
504
- if (correlatedResponse !== void 0) {
505
- promptNeighboringFailure ??= findToolFailure(correlatedResponse);
506
- drainRejectedDecisionFailures(correlatedResponse);
507
- }
508
- if (promptNeighboringFailure !== void 0) throw promptNeighboringFailure;
509
- if (decisionSubmitted) {
510
- decisionToolFailure = void 0;
511
- return;
512
- }
513
- if (decisionToolFailure !== void 0) return;
514
- if (retentionFailure !== void 0) return;
515
- if (opened.streamFailure !== void 0) throw opened.streamFailure;
516
- if (promptFailure !== void 0) throw promptFailure;
517
- };
518
- const chargeAndClearRejectedDecisionFailures = (failures) => {
519
- for (const failure of failures) {
520
- delivery.recordRejected(failure instanceof Error ? failure.message : String(failure));
521
- }
522
- decisionToolFailure = void 0;
523
- promptDecisionFailures = [];
524
- };
525
- await promptAllowingRejectedDecision(options.prompt);
526
- while (!decisionSubmitted && retentionFailure === void 0 && (boundaryResponse === void 0 || decisionToolFailure !== void 0) && opened.streamFailure === void 0 && delivery.nextAction() === "request-delivery") {
527
- if (decisionToolFailure !== void 0) {
528
- const failures = promptDecisionFailures.length === 0 ? [decisionToolFailure] : promptDecisionFailures;
529
- chargeAndClearRejectedDecisionFailures(failures);
530
- if (delivery.nextAction() === "no-receipt") boundaryResponse = void 0;
531
- if (delivery.nextAction() === "request-delivery") {
532
- if (retainedResponse === rejectedDecisionResponse) {
533
- await promptAllowingRejectedDecision(RECEIPT_DELIVERY_PROMPT);
534
- chargeAndClearRejectedDecisionFailures(promptDecisionFailures);
535
- }
536
- }
537
- } else {
538
- delivery.recordDeliveryRequest();
539
- await promptAllowingRejectedDecision(RECEIPT_DELIVERY_PROMPT);
540
- }
541
- }
542
- if (!decisionSubmitted && retentionFailure === void 0 && opened.streamFailure === void 0 && delivery.nextAction() === "no-receipt") {
543
- const runPointer = options.context.sessionManager.getSessionFile() ?? options.context.cwd ?? process.cwd();
544
- const attemptPointer = binding.parent.attemptEntryId ?? binding.parent.sessionId ?? `current:${runPointer}`;
545
- const facts = delivery.facts({ runPointer, attemptPointer });
546
- decision = facts;
547
- decisionToolFailure = void 0;
548
- auditorSessionManager.appendCustomEntry(NO_RECEIPT_LIFECYCLE_ENTRY_TYPE, facts);
549
- try {
550
- sitianReport({
551
- level: "event",
552
- kind: "auditor",
553
- cwd,
554
- sessionParent: parentSessionFile,
555
- payload: { type: NO_RECEIPT_LIFECYCLE_ENTRY_TYPE, ...facts },
556
- source: "evidence-child-executor"
557
- });
558
- } catch {
559
- }
560
- noReceiptLifecycle = facts;
561
- }
562
- } catch (error) {
563
- if (options.signal?.aborted) throw options.signal.reason;
564
- if (retentionFailure === void 0 && opened.streamFailure !== void 0) throw opened.streamFailure;
565
- if (retentionFailure === void 0) throw error;
566
- }
567
- if (options.signal?.aborted) throw options.signal.reason;
568
- if (retentionFailure === void 0 && opened.streamFailure !== void 0) throw opened.streamFailure;
569
- if (!decisionSubmitted && decisionToolFailure !== void 0) throw decisionToolFailure;
570
- const relevantResponse = !decisionSubmitted ? boundaryResponse : retainedResponse && retainedResponse.role === "assistant" && retainedResponse.content.some((part) => part.type === "toolCall" && part.name === tool.name) ? retainedResponse : void 0;
571
- if (relevantResponse !== void 0) {
572
- const toolFailure = findToolFailure(relevantResponse);
573
- if (toolFailure !== void 0) throw toolFailure;
574
- }
575
- const assistants = [...retainedAssistants].reverse();
576
- const response = !decisionSubmitted ? assistants[0] : assistants.find((message) => message.content.some((part) => part.type === "toolCall" && part.name === tool.name));
577
- if (response !== void 0) {
578
- try {
579
- if (retentionFailure !== void 0) throw retentionFailure;
580
- if (retainedResponse === void 0) options.retainResponse?.(response);
581
- } catch (retentionFailure2) {
582
- if (response.stopReason !== "error") throw retentionFailure2;
583
- const diagnostic = typeof response.errorMessage === "string" && response.errorMessage.trim() !== "" ? response.errorMessage : void 0;
584
- const projected = projectStructuredRemote(response);
585
- const failure = new Error(
586
- diagnostic ?? "",
587
- { cause: retentionFailure2 }
588
- );
589
- if (projected.hasTestimony && (response.model || response.provider)) {
590
- failure.name = response.model || response.provider || "Error";
591
- failure.failureCode = response.provider || response.model;
592
- }
593
- failure.knownCause = projected.hasTestimony ? "provider" : "unrecognized";
594
- const retentionError = retentionFailure2 instanceof Error ? retentionFailure2 : void 0;
595
- const retentionCause = retentionError?.cause;
596
- failure.details = {
597
- ...diagnostic === void 0 ? {} : { errorMessage: diagnostic },
598
- ...projected.hasTestimony && response.provider ? { provider: response.provider } : {},
599
- ...projected.hasTestimony && response.model ? { model: response.model } : {},
600
- ...response.api ? { api: response.api } : {},
601
- ...response.rawStopReason ? { rawStopReason: response.rawStopReason } : {},
602
- ...projected.httpStatus === void 0 ? {} : { httpStatus: projected.httpStatus },
603
- ...projected.diagnostics === void 0 ? {} : { diagnostics: projected.diagnostics },
604
- ...projected.body === void 0 ? {} : { body: projected.body },
605
- ...projected.code === void 0 ? {} : { code: projected.code },
606
- ...projected.errno === void 0 ? {} : { errno: projected.errno },
607
- retentionFailure: {
608
- name: retentionError?.name ?? typeof retentionFailure2,
609
- message: retentionError?.message ?? String(retentionFailure2),
610
- ...retentionError?.code !== void 0 ? { code: retentionError.code } : {},
611
- ...retentionCause === void 0 ? {} : {
612
- cause: retentionCause instanceof Error ? {
613
- name: retentionCause.name,
614
- message: retentionCause.message,
615
- ...retentionCause.code === void 0 ? {} : { code: retentionCause.code }
616
- } : retentionCause
617
- }
618
- }
619
- };
620
- const failureData = {
621
- version: 1,
622
- parent: binding.parent,
623
- failure: {
624
- cause: failure.knownCause,
625
- ...failure.failureCode === void 0 ? {} : { identity: { name: failure.name, code: failure.failureCode } },
626
- ...failure.message === "" ? {} : { diagnostic: failure.message },
627
- details: failure.details
628
- }
629
- };
630
- auditorSessionManager.appendCustomEntry(AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE, failureData);
631
- try {
632
- sitianReport({
633
- level: "event",
634
- kind: "auditor",
635
- cwd,
636
- sessionParent: parentSessionFile,
637
- payload: { type: AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE, ...failureData },
638
- source: "evidence-child-executor"
639
- });
640
- } catch {
641
- }
642
- throw failure;
643
- }
644
- }
645
- if (response === void 0 || response.stopReason === "error" || !decisionSubmitted && (response.stopReason === "aborted" || decision === void 0)) {
646
- throw new Error(response?.errorMessage ?? `${options.roleLabel} exited without a readable decision receipt`);
647
- }
648
- return {
649
- decision,
650
- response: { ...response, usage: sessionUsage },
651
- ...noReceiptLifecycle === void 0 ? {} : { noReceiptLifecycle }
652
- };
653
- } catch (error) {
654
- auditorFailure = error;
655
- throw error;
656
- } finally {
657
- options.signal?.removeEventListener("abort", abort);
658
- await runChildCleanup([() => unsubscribe(), () => handle.close()], auditorFailure, options.roleLabel);
659
- }
660
- });
661
- }
662
- function exactRecord(value) {
663
- return typeof value === "object" && value !== null && !Array.isArray(value);
664
- }
665
- function createNativeNavigatorSessionFactory(defaultModelSettingPath = navigatorModelSettingPath()) {
666
- return async ({ context, subject, modelSettingPath, tool }) => {
667
- const resolved = await resolveNavigatorSeatSelection(context, modelSettingPath, defaultModelSettingPath);
668
- let selection = resolved.selection;
669
- let thinkingLevel = resolved.thinkingLevel;
670
- let configuredLabel = resolved.configuredLabel;
671
- const { createRecordSession } = await import("./archivist-record-entry.js");
672
- const sessionManager = createRecordSession({
673
- cwd: context.cwd,
674
- kind: "navigator",
675
- subject,
676
- parent: context.sessionManager
677
- });
678
- let providerFailure;
679
- let observationWrite = Promise.resolve();
680
- const assignProviderFailure = (fact) => {
681
- if (fact !== void 0) providerFailure = fact;
682
- };
683
- const classifyTerminalMessage = (message) => {
684
- if (!exactRecord(message)) {
685
- assignProviderFailure(navigatorProviderFailureFromError(message));
686
- return;
687
- }
688
- assignProviderFailure(navigatorProviderFailureFromDiagnostics(message.diagnostics));
689
- if (providerFailure !== void 0) return;
690
- if (message.role !== "assistant") assignProviderFailure(navigatorProviderFailureFromError(message));
691
- if (providerFailure !== void 0) return;
692
- const status = typeof message.statusCode === "number" ? message.statusCode : typeof message.status === "number" ? message.status : typeof message.httpStatus === "number" ? message.httpStatus : void 0;
693
- if (typeof status === "number") {
694
- assignProviderFailure(navigatorProviderFailureFromStatus(status));
695
- if (providerFailure === void 0 && status >= 400 && status < 600) {
696
- assignProviderFailure({ source: "transport", cause: "transport" });
697
- }
698
- const runDir = process.env.AK_ROLE_RUN_DIR;
699
- const provider = typeof message.provider === "string" && message.provider.trim() !== "" ? message.provider : selection.provider;
700
- if (typeof runDir === "string" && runDir.trim() !== "" && provider.trim() !== "") {
701
- observationWrite = observationWrite.then(
702
- () => recordTypedProviderHttpStatus(runDir, { httpStatus: status, provider })
703
- );
704
- }
705
- }
706
- };
707
- const { openPiInstitutionalSession } = await import("./pi/in-process-session.js");
708
- let opened;
709
- try {
710
- opened = await openPiInstitutionalSession({
711
- cwd: context.cwd,
712
- selection,
713
- systemPrompt: "",
714
- noTools: "all",
715
- toolsAllowlist: [NAVIGATOR_PREPARE_TOOL_NAME],
716
- customTools: [tool],
717
- sessionManager,
718
- label: "Navigator"
719
- });
720
- } catch (error) {
721
- const fact = navigatorProviderFailureFromError(error);
722
- throw navigatorUnavailableError(fact?.source ?? "session", error, fact?.cause ?? "session");
723
- }
724
- const unsubscribe = opened.handle.subscribe((event) => {
725
- if (event.type === "message_end" && event.message !== void 0) {
726
- const message = event.message;
727
- if (exactRecord(message) && (message.stopReason === "error" || message.stopReason === "aborted")) {
728
- classifyTerminalMessage(message);
729
- }
730
- }
731
- });
732
- let disposal;
733
- const dispose = () => {
734
- if (disposal === void 0) {
735
- disposal = runChildCleanup(
736
- [() => unsubscribe(), () => opened.handle.close()],
737
- void 0,
738
- "Navigator"
739
- );
740
- }
741
- return disposal;
742
- };
743
- return {
744
- prompt: async (text) => {
745
- providerFailure = void 0;
746
- observationWrite = Promise.resolve();
747
- const failFrom = (error) => {
748
- if (providerFailure === void 0) {
749
- assignProviderFailure({ source: "transport", cause: "transport" });
750
- }
751
- const fact = providerFailure;
752
- throw navigatorUnavailableError(fact.source, error, fact.cause);
753
- };
754
- let terminal;
755
- try {
756
- const turn = await opened.handle.prompt(text);
757
- if (turn.stopReason === "error" || turn.stopReason === "aborted") {
758
- const cause = turn.errorMessage ?? opened.streamFailure ?? "Navigator provider failure";
759
- if (providerFailure === void 0 && opened.streamFailure !== void 0) {
760
- classifyTerminalMessage(opened.streamFailure);
761
- }
762
- if (providerFailure === void 0) {
763
- assignProviderFailure(navigatorProviderFailureFromError(
764
- typeof cause === "object" && cause !== null ? cause : new Error(String(cause))
765
- ));
766
- }
767
- terminal = cause;
768
- } else if (opened.streamFailure !== void 0) {
769
- if (providerFailure === void 0) classifyTerminalMessage(opened.streamFailure);
770
- terminal = opened.streamFailure;
771
- }
772
- } catch (error) {
773
- if (error instanceof NavigatorUnavailableError) throw error;
774
- if (providerFailure === void 0) classifyTerminalMessage(error);
775
- terminal = error;
776
- }
777
- await observationWrite;
778
- if (terminal !== void 0) failFrom(terminal);
779
- },
780
- providerFailure: () => providerFailure,
781
- appendEntry: (customType, data) => {
782
- sessionManager.appendCustomEntry(customType, data);
783
- try {
784
- sitianReport({
785
- level: "event",
786
- kind: "attendance",
787
- cwd: context.cwd,
788
- sessionParent: sessionManager.getSessionFile(),
789
- payload: { customType, data },
790
- source: "evidence-child-executor"
791
- });
792
- } catch {
793
- }
794
- },
795
- entries: () => sessionManager.getEntries(),
796
- setModel: async (next) => {
797
- let nextParsed;
798
- try {
799
- nextParsed = parseNavigatorModelSetting(next);
800
- } catch (error) {
801
- throw navigatorUnavailableError("model", error);
802
- }
803
- if (nextParsed.provider !== selection.provider || nextParsed.model !== selection.model) {
804
- throw new NavigatorUnavailableError(
805
- "model",
806
- `Navigator model switch requires a new session: ${configuredLabel} \u2192 ${next}`
807
- );
808
- }
809
- selection = {
810
- provider: nextParsed.provider,
811
- model: nextParsed.model,
812
- ...nextParsed.thinkingLevel === void 0 ? {} : { thinking: nextParsed.thinkingLevel }
813
- };
814
- thinkingLevel = nextParsed.thinkingLevel;
815
- configuredLabel = next;
816
- },
817
- getThinkingLevel: () => thinkingLevel,
818
- recordPointer: () => sessionManager.getSessionDir(),
819
- dispose
820
- };
821
- };
822
- }
823
- export {
824
- DEFAULT_COMPLIANCE_IDLE_MAX_RETRIES,
825
- createNativeNavigatorSessionFactory,
826
- executeAuditorChild,
827
- executeEvidenceChild,
828
- withInProcessScratch
829
- };