@akagilnc/pi-workflow-roles 0.1.5845 → 0.1.5855

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 (66) hide show
  1. package/README.md +4 -4
  2. package/README.zh-CN.md +4 -4
  3. package/dist/acp-host/production-host.js +348 -1254
  4. package/dist/acp-host/role-turn-host.js +4 -98
  5. package/dist/headless-host/production-host.js +15731 -16582
  6. package/dist/headless-host/role-turn-host.js +6 -31
  7. package/dist/migrate-book-topology.js +31 -16
  8. package/dist/navigator-attendance.js +54 -404
  9. package/dist/navigator-invocation-identity.js +0 -2
  10. package/dist/navigator-lookup-host.js +41 -0
  11. package/dist/navigator-lookup.js +68 -0
  12. package/dist/navigator-route-table.js +42 -0
  13. package/dist/package-contracts/navigator-output.js +3 -11
  14. package/dist/packaged-role-registry.js +3 -27
  15. package/dist/public-cli/instruction-seat-run.js +4 -1
  16. package/dist/public-cli/invocation.js +13 -26
  17. package/dist/public-cli/main.js +286 -114
  18. package/dist/public-cli/option-definitions.js +24 -4
  19. package/dist/public-cli/post-admission.js +0 -9
  20. package/dist/public-cli/role-seat-runtime.js +14 -0
  21. package/dist/public-cli/settlement.js +14 -40
  22. package/dist/public-cli/terminal.js +1 -8
  23. package/dist/public-cli/turn-request.js +0 -3
  24. package/dist/public-role-summons.js +0 -1
  25. package/dist/receipt-delivery-policy.js +0 -23
  26. package/dist/role-runtime-dependencies.js +4 -11
  27. package/dist/role-runtime.js +18 -194
  28. package/dist/submission-ledger.js +19 -15
  29. package/dist/ticket-progress.js +23 -5
  30. package/extensions/role-runtime.ts +0 -16
  31. package/package.json +1 -1
  32. package/scripts/build-package.mjs +3 -7
  33. package/src/acp-host/role-turn-host.ts +8 -97
  34. package/src/headless-host/description.ts +0 -2
  35. package/src/headless-host/role-turn-host.ts +7 -32
  36. package/src/host-contracts.ts +5 -7
  37. package/src/navigator-attendance.ts +86 -549
  38. package/src/navigator-invocation-identity.ts +0 -2
  39. package/src/navigator-lookup-host.ts +45 -0
  40. package/src/navigator-lookup.ts +98 -0
  41. package/src/navigator-route-table.ts +92 -0
  42. package/src/package-contracts/navigator-output.ts +4 -15
  43. package/src/packaged-role-registry.ts +3 -32
  44. package/src/public-cli/instruction-seat-run.ts +3 -0
  45. package/src/public-cli/invocation.ts +18 -30
  46. package/src/public-cli/option-definitions.ts +25 -4
  47. package/src/public-cli/post-admission.ts +0 -11
  48. package/src/public-cli/role-seat-runtime.ts +14 -0
  49. package/src/public-cli/settlement.ts +23 -51
  50. package/src/public-cli/terminal.ts +3 -18
  51. package/src/public-cli/turn-request.ts +0 -5
  52. package/src/public-role-summons.ts +0 -8
  53. package/src/receipt-delivery-policy.ts +0 -21
  54. package/src/role-runtime-dependencies.ts +4 -11
  55. package/src/role-runtime.ts +19 -210
  56. package/src/submission-ledger.ts +23 -16
  57. package/src/ticket-progress.ts +32 -5
  58. package/dist/navigator-public-session.js +0 -205
  59. package/dist/navigator-role.js +0 -6
  60. package/dist/navigator-session-contracts.js +0 -227
  61. package/dist/navigator-work-context.js +0 -72
  62. package/resources/navigator-route-playbook.md +0 -33
  63. package/src/navigator-public-session.ts +0 -305
  64. package/src/navigator-role.ts +0 -15
  65. package/src/navigator-session-contracts.ts +0 -320
  66. package/src/navigator-work-context.ts +0 -97
@@ -1370,7 +1370,7 @@ async function runEngineDetourOnce(input) {
1370
1370
  }
1371
1371
  const command = input.argv[0];
1372
1372
  const args = input.argv.slice(1);
1373
- return await new Promise((resolve19, reject) => {
1373
+ return await new Promise((resolve17, reject) => {
1374
1374
  let settled = false;
1375
1375
  const signal = input.signal;
1376
1376
  const child = spawn(command, args, {
@@ -1400,7 +1400,7 @@ async function runEngineDetourOnce(input) {
1400
1400
  if (signal !== void 0) {
1401
1401
  signal.removeEventListener("abort", onAbort);
1402
1402
  }
1403
- resolve19(result);
1403
+ resolve17(result);
1404
1404
  };
1405
1405
  const onAbort = () => {
1406
1406
  fail3(signal !== void 0 ? abortReasonError(signal) : new Error("aborted"));
@@ -1592,20 +1592,6 @@ var init_gatekeeper_output = __esm({
1592
1592
  });
1593
1593
 
1594
1594
  // src/package-contracts/navigator-output.ts
1595
- var navigator_output_exports = {};
1596
- __export(navigator_output_exports, {
1597
- NAVIGATOR_OUTPUT_TOOL_NAME: () => NAVIGATOR_OUTPUT_TOOL_NAME,
1598
- byStatusToPlainObject: () => byStatusToPlainObject,
1599
- mergePreparedAdvice: () => mergePreparedAdvice,
1600
- navigatorAdviceBodySchema: () => navigatorAdviceBodySchema,
1601
- navigatorAdviceFields: () => navigatorAdviceFields,
1602
- navigatorOutputSchema: () => navigatorOutputSchema,
1603
- navigatorProseFromUnknown: () => navigatorProseFromUnknown,
1604
- pickPreparedProse: () => pickPreparedProse,
1605
- preparedAdviceFromUnknown: () => preparedAdviceFromUnknown,
1606
- projectLawfulNavigatorOutput: () => projectLawfulNavigatorOutput,
1607
- validateRecordedNavigatorOutput: () => validateRecordedNavigatorOutput
1608
- });
1609
1595
  import { Type as Type4 } from "typebox";
1610
1596
  function nonEmptyProse(value) {
1611
1597
  if (typeof value === "string") {
@@ -1635,37 +1621,6 @@ function byStatusFromUnknown(value) {
1635
1621
  }
1636
1622
  return out;
1637
1623
  }
1638
- function byStatusToPlainObject(byStatus) {
1639
- return Object.fromEntries(byStatus);
1640
- }
1641
- function projectLawfulNavigatorOutput(value) {
1642
- if (value === void 0 || value === null) return void 0;
1643
- if (typeof value === "string") return { prose: value };
1644
- if (isRecord(value)) {
1645
- if (typeof value.prose === "string") return { prose: value.prose };
1646
- if (value.prose !== void 0 && value.prose !== null) {
1647
- const serialized = nonEmptyProse(value.prose);
1648
- if (serialized !== void 0) return { prose: serialized };
1649
- }
1650
- const keys = Object.keys(value);
1651
- if (keys.length === 0) return { prose: "" };
1652
- return { prose: JSON.stringify(value) };
1653
- }
1654
- return { prose: String(value) };
1655
- }
1656
- function validateRecordedNavigatorOutput(value) {
1657
- const projected = projectLawfulNavigatorOutput(value);
1658
- if (projected === void 0) {
1659
- throw new Error("Navigator output is empty");
1660
- }
1661
- return projected;
1662
- }
1663
- function navigatorProseFromUnknown(value) {
1664
- const projected = projectLawfulNavigatorOutput(value);
1665
- if (projected === void 0) return void 0;
1666
- const trimmed = projected.prose.trim();
1667
- return trimmed === "" ? void 0 : projected.prose;
1668
- }
1669
1624
  function preparedAdviceFromUnknown(value) {
1670
1625
  if (value === void 0 || value === null) return void 0;
1671
1626
  if (typeof value === "string") {
@@ -1731,6 +1686,9 @@ var init_navigator_output = __esm({
1731
1686
  }),
1732
1687
  byStatus: Type4.Unknown({
1733
1688
  description: "\u6309\u4E3B\u8859\u95E8\u7ED3\u5C40 status \u9884\u5199\u7684\u6563\u6587\u5EFA\u8BAE\u3002\u952E\u4E3A status \u5B57\u9762\u91CF\uFF0C\u503C\u4E3A\u5EFA\u8BAE\u6B63\u6587\u3002\u7ED3\u7B97\u65F6\u4EE3\u7801\u53EA\u6309\u5B9E\u9645 status \u53D6\u5BF9\u5E94\u539F\u6587\uFF0C\u4E0D\u89E3\u6790\u5EFA\u8BAE\u8BED\u4E49\u3002"
1689
+ }),
1690
+ byRole: Type4.Unknown({
1691
+ description: "\u6574\u5F20\u8DEF\u7EBF\u8868\uFF1A\u952E\u4E3A\u8859\u95E8\u89D2\u8272\uFF0C\u503C\u4E3A\u8BE5\u8859\u95E8 status \u2192 \u5EFA\u8BAE\u3002\u76F4\u63A5\u5165\u53E3\u4E0D\u7ED9\u89D2\u8272\u65F6\u4F7F\u7528\u3002"
1734
1692
  })
1735
1693
  };
1736
1694
  navigatorAdviceBodySchema = openToolObject(Type4.Object(navigatorAdviceFields));
@@ -2364,15 +2322,12 @@ __export(packaged_role_registry_exports, {
2364
2322
  packagedGateSummon: () => packagedGateSummon,
2365
2323
  packagedMethodSkillNames: () => packagedMethodSkillNames,
2366
2324
  packagedModelParent: () => packagedModelParent,
2367
- packagedNavigatorSubject: () => packagedNavigatorSubject,
2368
2325
  packagedProjectsTargetBindRejection: () => packagedProjectsTargetBindRejection,
2369
2326
  packagedProvinceConfig: () => packagedProvinceConfig,
2370
- packagedPublicInstructionSubject: () => packagedPublicInstructionSubject,
2371
2327
  packagedRebindSourceOnResume: () => packagedRebindSourceOnResume,
2372
2328
  packagedResumeSourcePath: () => packagedResumeSourcePath,
2373
2329
  packagedRoleAcceptedOutputTool: () => packagedRoleAcceptedOutputTool,
2374
2330
  packagedRoleActivationFlags: () => packagedRoleActivationFlags,
2375
- packagedRoleInputFlag: () => packagedRoleInputFlag,
2376
2331
  packagedRoleMetadata: () => packagedRoleMetadata,
2377
2332
  packagedRoleOutputTool: () => packagedRoleOutputTool,
2378
2333
  packagedRolePhaseFlag: () => packagedRolePhaseFlag,
@@ -2420,9 +2375,6 @@ function packagedRoleActivationFlags(role) {
2420
2375
  if (record === void 0 || !("activationFlags" in record)) return [];
2421
2376
  return record.activationFlags;
2422
2377
  }
2423
- function packagedRoleInputFlag(role) {
2424
- return packagedRoleActivationFlags(role).find((spec) => spec.binds === "input")?.flag;
2425
- }
2426
2378
  function packagedRolePhaseFlag(role) {
2427
2379
  return packagedRoleActivationFlags(role).find((spec) => spec.binds === "phase")?.flag;
2428
2380
  }
@@ -2478,11 +2430,6 @@ function packagedAuditToolName(role) {
2478
2430
  if (record === void 0 || !("auditTool" in record)) return void 0;
2479
2431
  return record.auditTool;
2480
2432
  }
2481
- function packagedPublicInstructionSubject(role) {
2482
- return typeof role === "string" && PUBLIC_ROLE_RECORDS.some(
2483
- (record) => "navigatorSubject" in record && record.navigatorSubject === "public-instruction" && record.role === role
2484
- );
2485
- }
2486
2433
  function packagedResumeSourcePath(role) {
2487
2434
  const record = packagedRoleMetadata(role);
2488
2435
  return record !== void 0 && "resumeSourcePath" in record && record.resumeSourcePath === true;
@@ -2491,11 +2438,6 @@ function packagedProjectsTargetBindRejection(role) {
2491
2438
  const record = packagedRoleMetadata(role);
2492
2439
  return record !== void 0 && "projectTargetBindRejection" in record && record.projectTargetBindRejection === true;
2493
2440
  }
2494
- function packagedNavigatorSubject(role) {
2495
- const record = packagedRoleMetadata(role);
2496
- if (record !== void 0 && "navigatorSubject" in record) return record.navigatorSubject;
2497
- return "file";
2498
- }
2499
2441
  function packagedBoardPlacement(role) {
2500
2442
  const record = packagedRoleMetadata(role);
2501
2443
  if (record === void 0 || !("boardPlacement" in record)) return void 0;
@@ -2589,8 +2531,6 @@ var init_packaged_role_registry = __esm({
2589
2531
  settlement: "sealed",
2590
2532
  /** Factory board: court until another station has started, then marshal. */
2591
2533
  boardPlacement: "judge-history",
2592
- /** Navigator subject is the public admitted instruction when the run is bound. */
2593
- navigatorSubject: "public-instruction",
2594
2534
  activationStage: "load-and-install",
2595
2535
  receiptStatusKey: "status",
2596
2536
  sessionMaterials: [
@@ -2619,8 +2559,6 @@ var init_packaged_role_registry = __esm({
2619
2559
  reportPhase: true
2620
2560
  },
2621
2561
  boardPlacement: "marshal",
2622
- /** #1168: dispatch is first message; navigator reads admitted instruction. */
2623
- navigatorSubject: "public-instruction",
2624
2562
  activationFlags: [
2625
2563
  { field: "phase", flag: "ak-fixer-phase", binds: "phase" }
2626
2564
  ],
@@ -2649,8 +2587,6 @@ var init_packaged_role_registry = __esm({
2649
2587
  artifactFace: {
2650
2588
  reportPhase: true
2651
2589
  },
2652
- /** #1168: dispatch is first message; navigator reads admitted instruction. */
2653
- navigatorSubject: "public-instruction",
2654
2590
  activationFlags: [
2655
2591
  { field: "phase", flag: "ak-coder-phase", binds: "phase" }
2656
2592
  ],
@@ -2744,8 +2680,6 @@ var init_packaged_role_registry = __esm({
2744
2680
  artifactFace: {
2745
2681
  doctorReportFacts: true
2746
2682
  },
2747
- /** Navigator subject is the doctor case, not the case-path file bytes. */
2748
- navigatorSubject: "case",
2749
2683
  activationFlags: [
2750
2684
  { field: "casePath", from: "caseRunsPath", flag: "ak-doctor-case", binds: "input" }
2751
2685
  ],
@@ -2800,8 +2734,6 @@ var init_packaged_role_registry = __esm({
2800
2734
  gateStageLabel: "\u7B26\u5B9D\u90CE",
2801
2735
  /** Gate summon binds --source-run and keeps dialogue off the argv. */
2802
2736
  gateSummon: "source-run",
2803
- /** Navigator subject is the source-run locator, not the path file bytes. */
2804
- navigatorSubject: "source-run",
2805
2737
  activationFlags: [
2806
2738
  { field: "sourceRun", from: "sourceRunPath", flag: "ak-notary-source-run", binds: "input" },
2807
2739
  { field: "ticketNumber", flag: "ak-notary-ticket-number" }
@@ -2939,12 +2871,14 @@ var init_packaged_role_registry = __esm({
2939
2871
  role: "navigator",
2940
2872
  inCallAutoResume: false,
2941
2873
  presentSettled: "always",
2942
- summonResume: true,
2874
+ summonResume: false,
2943
2875
  admission: "instruction",
2944
2876
  sameParent: "none",
2945
2877
  phases: [null],
2946
2878
  outputTool: NAVIGATOR_OUTPUT_TOOL_NAME,
2947
2879
  settlement: "accepted",
2880
+ /** #1192: structured target seat for the lookup run; no host flag (no host runs it). */
2881
+ activationFlags: [{ field: "forRole" }],
2948
2882
  activationStage: "load-and-install",
2949
2883
  sessionMaterials: ["CLAUDE.md", "souls/navigator.md"]
2950
2884
  },
@@ -3312,11 +3246,7 @@ function currentReplyRows(terminal) {
3312
3246
  return outcome?.kind === "accepted" || outcome?.kind === "audit_escalation" ? outcome.payloads ?? [] : [];
3313
3247
  }
3314
3248
  function adviceNavigatorFact(input) {
3315
- return {
3316
- disposition: "advice",
3317
- prose: input.prose,
3318
- ...input.advisoryDiagnostic === void 0 ? {} : { advisoryDiagnostic: input.advisoryDiagnostic }
3319
- };
3249
+ return { disposition: "advice", prose: input.prose };
3320
3250
  }
3321
3251
  function formatTerminalResult(result) {
3322
3252
  const lines = [];
@@ -3346,9 +3276,6 @@ function formatTerminalResult(result) {
3346
3276
  }
3347
3277
  }
3348
3278
  lines.push(`navigator ${result.navigator.disposition}`);
3349
- if (result.navigator.advisoryDiagnostic !== void 0) {
3350
- lines.push(`navigator-advisory ${encodeTerminalField(result.navigator.advisoryDiagnostic)}`);
3351
- }
3352
3279
  if (result.navigator.disposition === "advice") {
3353
3280
  lines.push(`prose ${encodeTerminalField(result.navigator.prose)}`);
3354
3281
  } else if (result.navigator.disposition === "unavailable") {
@@ -4655,6 +4582,18 @@ function lensFromRunDirectory(runDirectory, role) {
4655
4582
  function landTicketProgressForSealedSubmission(input) {
4656
4583
  const runDirectory = runDirectoryFromHostContext(input.context);
4657
4584
  if (runDirectory === void 0) return void 0;
4585
+ return landTicketProgress({
4586
+ runDirectory,
4587
+ role: input.role,
4588
+ accepted: input.accepted,
4589
+ sealHead: input.sealHead,
4590
+ ...input.lens === void 0 ? {} : { lens: input.lens },
4591
+ sessionFile: progressSessionAbsolute(runDirectory, input.context),
4592
+ instruction: typeof input.context.summonsInstruction === "string" ? input.context.summonsInstruction : ""
4593
+ });
4594
+ }
4595
+ function landTicketProgress(input) {
4596
+ const { runDirectory } = input;
4658
4597
  const subjectDirectory = subjectDirectoryOfRun(runDirectory);
4659
4598
  if (subjectDirectory === void 0) return void 0;
4660
4599
  const lens = input.lens === "completeness" || input.lens === "correctness" ? input.lens : lensFromRunDirectory(runDirectory, input.role);
@@ -4672,10 +4611,9 @@ function landTicketProgressForSealedSubmission(input) {
4672
4611
  }
4673
4612
  const existing = unbound ? readProgressFile(progressPath) : readTicketProgressLines(subjectDirectory);
4674
4613
  const round = unbound ? "" : nextRoundFromLines(existing, input.role, lens);
4675
- const sessionFile = progressSessionAbsolute(runDirectory, input.context);
4676
- const sessionRelative = relative2(subjectDirectory, sessionFile).split(sep3).join("/");
4614
+ const sessionRelative = input.sessionFile === void 0 ? "" : relative2(subjectDirectory, input.sessionFile).split(sep3).join("/");
4677
4615
  const { status, summary } = statusAndSummaryFromPayload(input.role, input.accepted);
4678
- const instruction = typeof input.context.summonsInstruction === "string" ? input.context.summonsInstruction : "";
4616
+ const instruction = input.instruction;
4679
4617
  const line2 = {
4680
4618
  at: (/* @__PURE__ */ new Date()).toISOString(),
4681
4619
  seat: input.role,
@@ -5586,19 +5524,6 @@ var init_notary_source_run = __esm({
5586
5524
  });
5587
5525
 
5588
5526
  // src/public-cli/registry.ts
5589
- var registry_exports = {};
5590
- __export(registry_exports, {
5591
- INTERNAL_ROLE_ENTRYPOINT_RELATIVE: () => INTERNAL_ROLE_ENTRYPOINT_RELATIVE,
5592
- PUBLIC_CALLABLE_ROLES: () => PUBLIC_CALLABLE_ROLES,
5593
- PUBLIC_CLI_SUPPORT_COMMANDS: () => PUBLIC_CLI_SUPPORT_COMMANDS,
5594
- PUBLIC_CONFIGURABLE_SEATS: () => PUBLIC_CONFIGURABLE_SEATS,
5595
- PUBLIC_DETERMINISTIC_COMMANDS: () => PUBLIC_DETERMINISTIC_COMMANDS,
5596
- isPublicCallableRole: () => isPublicCallableRole,
5597
- isPublicCliSupportCommand: () => isPublicCliSupportCommand,
5598
- isPublicConfigurableSeat: () => isPublicConfigurableSeat,
5599
- listHelpCapabilities: () => listHelpCapabilities,
5600
- seatModelOnly: () => seatModelOnly
5601
- });
5602
5527
  function seatModelOnly(seat) {
5603
5528
  if (seat?.provider === void 0 || seat.model === void 0) return void 0;
5604
5529
  return seat.thinking === void 0 ? { provider: seat.provider, model: seat.model } : { provider: seat.provider, model: seat.model, thinking: seat.thinking };
@@ -5925,7 +5850,7 @@ function renderHumanOwnerOptionLines(owner, locale = "en") {
5925
5850
  }
5926
5851
  return lines;
5927
5852
  }
5928
- var ANALYST_REQUIRE_ANY_OF, ANALYST_DEFAULT_MODE, REJECTED_PUBLIC_SPELLINGS, GLOBAL_OPTIONS, SHARED_PROJECT_SEMANTICS, SHARED_ATTACH_SEMANTICS, SHARED_PHASE_SEMANTICS, GLEANER_LEFT_OPTIONS, AUDITOR_OPTIONS, CODER_OPTIONS, FIXER_OPTIONS, REVIEWER_OPTIONS, COLLECTOR_OPTIONS, DOCTOR_OPTIONS, NOTARY_OPTIONS, INSPECTOR_OPTIONS, MERGER_OPTIONS, ANALYST_OPTIONS, SEAT_OPTION_ROWS, PUBLIC_OPTION_TABLE, PUBLIC_ROLE_OPTION_OWNERS, PUBLIC_NAVIGATOR_HELP_NOTE, TOP_LEVEL_HELP, ROLE_COMMAND_HELP, SUPPORT_COMMAND_HELP, PUBLIC_COMMAND_HELP;
5853
+ var ANALYST_REQUIRE_ANY_OF, ANALYST_DEFAULT_MODE, REJECTED_PUBLIC_SPELLINGS, GLOBAL_OPTIONS, SHARED_PROJECT_SEMANTICS, SHARED_ATTACH_SEMANTICS, SHARED_PHASE_SEMANTICS, GLEANER_LEFT_OPTIONS, AUDITOR_OPTIONS, CODER_OPTIONS, FIXER_OPTIONS, REVIEWER_OPTIONS, COLLECTOR_OPTIONS, DOCTOR_OPTIONS, NAVIGATOR_OPTIONS, NOTARY_OPTIONS, INSPECTOR_OPTIONS, MERGER_OPTIONS, ANALYST_OPTIONS, SEAT_OPTION_ROWS, PUBLIC_OPTION_TABLE, PUBLIC_ROLE_OPTION_OWNERS, PUBLIC_NAVIGATOR_HELP_NOTE, TOP_LEVEL_HELP, ROLE_COMMAND_HELP, SUPPORT_COMMAND_HELP, PUBLIC_COMMAND_HELP;
5929
5854
  var init_option_definitions = __esm({
5930
5855
  "src/public-cli/option-definitions.ts"() {
5931
5856
  "use strict";
@@ -6273,6 +6198,23 @@ var init_option_definitions = __esm({
6273
6198
  }
6274
6199
  }
6275
6200
  ];
6201
+ NAVIGATOR_OPTIONS = [
6202
+ ...projectAndAttach("navigator"),
6203
+ {
6204
+ id: "role",
6205
+ owner: "navigator",
6206
+ canonical: "--role",
6207
+ aliases: [],
6208
+ valueMetavar: "role",
6209
+ required: false,
6210
+ repeatable: false,
6211
+ form: "option",
6212
+ description: {
6213
+ en: "Optional seat whose status \u2192 advice rows to show; omitted shows the whole table. The instruction text is not read.",
6214
+ zh: "\u53EF\u9009\u8859\u95E8\u89D2\u8272\uFF1A\u53EA\u663E\u793A\u8BE5\u8859\u95E8\u7684 status \u2192 \u5EFA\u8BAE\uFF1B\u7F3A\u7701\u663E\u793A\u6574\u5F20\u8868\u3002instruction \u6B63\u6587\u4E0D\u8BFB\u3002"
6215
+ }
6216
+ }
6217
+ ];
6276
6218
  NOTARY_OPTIONS = [
6277
6219
  bindOwner("notary", SHARED_PROJECT_SEMANTICS),
6278
6220
  {
@@ -6466,14 +6408,15 @@ var init_option_definitions = __esm({
6466
6408
  merger: MERGER_OPTIONS,
6467
6409
  notary: NOTARY_OPTIONS,
6468
6410
  auditor: AUDITOR_OPTIONS,
6469
- inspector: INSPECTOR_OPTIONS
6411
+ inspector: INSPECTOR_OPTIONS,
6412
+ navigator: NAVIGATOR_OPTIONS
6470
6413
  };
6471
6414
  PUBLIC_OPTION_TABLE = publicOptionTable();
6472
6415
  PUBLIC_ROLE_OPTION_OWNERS = [
6473
6416
  ...PUBLIC_CALLABLE_ROLES,
6474
6417
  "analyst"
6475
6418
  ];
6476
- PUBLIC_NAVIGATOR_HELP_NOTE = "Navigator also attends automatically on top-level public entry legs; that sidecar is unchanged by direct `ak-role navigator` calls.";
6419
+ PUBLIC_NAVIGATOR_HELP_NOTE = "Navigator also attends automatically on top-level public entry legs; the sidecar and direct `ak-role navigator` calls read the same status \u2192 advice table, with no model call.";
6477
6420
  TOP_LEVEL_HELP = {
6478
6421
  command: "top",
6479
6422
  summary: "public role CLI",
@@ -6587,10 +6530,11 @@ var init_option_definitions = __esm({
6587
6530
  },
6588
6531
  navigator: {
6589
6532
  command: "navigator",
6590
- summary: "Direct Navigator (\u6E38\u5955\u4F7F) free-form prose route advice.",
6591
- usage: ["ak-role navigator [options] [instruction]"],
6533
+ summary: "Direct Navigator (\u6E38\u5955\u4F7F) status \u2192 next-station advice table lookup; no model call.",
6534
+ usage: ["ak-role navigator [--role <role>] [options] [instruction]"],
6592
6535
  examples: [
6593
- 'ak-role navigator "\u521A\u5B8C\u6210 coder apply \u6536\u655B\uFF0C\u4E0B\u4E00\u6B65\uFF1F"'
6536
+ "ak-role navigator",
6537
+ "ak-role navigator --role coder"
6594
6538
  ]
6595
6539
  },
6596
6540
  auditor: {
@@ -7090,6 +7034,17 @@ function assignPublicSeatOption(owner, taken, fields) {
7090
7034
  fields.subject = subject;
7091
7035
  return;
7092
7036
  }
7037
+ case "role": {
7038
+ const raw = typeof value === "string" ? value.trim() : "";
7039
+ const known = PUBLIC_CALLABLE_ROLES.find((role) => role === raw);
7040
+ if (known === void 0) {
7041
+ throw new CliUsageError(
7042
+ `${owner} --role must be one of ${PUBLIC_CALLABLE_ROLES.join("|")}, got ${value ?? "(missing)"}`
7043
+ );
7044
+ }
7045
+ fields.forRole = known;
7046
+ return;
7047
+ }
7093
7048
  case "source-run": {
7094
7049
  const text = typeof value === "string" ? value : "";
7095
7050
  if (text.trim() === "") {
@@ -7221,7 +7176,8 @@ function parsePublicSeatArgv(owner, args) {
7221
7176
  ...fields.baseRevision === void 0 ? {} : { baseRevision: fields.baseRevision },
7222
7177
  ...fields.lens === void 0 ? {} : { lens: fields.lens },
7223
7178
  ...packagedEmitsAuthorityRefs(owner) ? { authorityRefs: fields.authorityRefs } : {},
7224
- ...fields.subject === void 0 ? {} : { subject: fields.subject }
7179
+ ...fields.subject === void 0 ? {} : { subject: fields.subject },
7180
+ ...fields.forRole === void 0 ? {} : { forRole: fields.forRole }
7225
7181
  };
7226
7182
  }
7227
7183
  function requireOptionPath(flag, value) {
@@ -7334,7 +7290,8 @@ async function admitPublicRole(role, parsed, env, override) {
7334
7290
  ...shared,
7335
7291
  instruction,
7336
7292
  attachmentPaths,
7337
- ...project
7293
+ ...project,
7294
+ ...parsed.forRole === void 0 ? {} : { admittedFields: { forRole: parsed.forRole } }
7338
7295
  }
7339
7296
  );
7340
7297
  case "court-materials":
@@ -7781,20 +7738,6 @@ async function materializeCountersignInvocation(admitted, options) {
7781
7738
  options.model
7782
7739
  );
7783
7740
  }
7784
- async function loadAdmittedJudgeRequest(runDirectory) {
7785
- const record = readPageSync(runDirectory, "admitted");
7786
- if (record === void 0) return void 0;
7787
- if (!packagedPublicInstructionSubject(record.role)) return void 0;
7788
- if (typeof record.instruction !== "string") return void 0;
7789
- if (typeof record.instructionEmpty !== "boolean") return void 0;
7790
- if (!Array.isArray(record.attachments)) return void 0;
7791
- const attachments = record.attachments.map((item) => normalizeAdmittedAttachment(item)).filter((item) => item !== void 0);
7792
- return {
7793
- instruction: record.instruction,
7794
- instructionEmpty: record.instructionEmpty,
7795
- attachments
7796
- };
7797
- }
7798
7741
  function parsePositivePrOption(raw) {
7799
7742
  if (raw === void 0 || raw.trim() === "") throw new CliUsageError("--pr requires a positive pull request number");
7800
7743
  try {
@@ -8148,6 +8091,7 @@ var init_invocation = __esm({
8148
8091
  init_notary_source_run();
8149
8092
  init_cli_errors();
8150
8093
  init_option_definitions();
8094
+ init_registry();
8151
8095
  init_unknown_value();
8152
8096
  }
8153
8097
  });
@@ -8483,12 +8427,13 @@ function homeFromHostContext(context, home) {
8483
8427
  const sessionParent = sessionParentFromHostContext(context);
8484
8428
  return sessionParent !== void 0 ? tryHomeFromAkRolesPath(sessionParent) : void 0;
8485
8429
  }
8486
- async function sealAcceptedSubmission(options) {
8487
- const runId = runIdentity(options.context);
8488
- const attemptId = attemptIdentity(options.context, runId);
8489
- const sessionParent = sessionParentFromHostContext(options.context);
8490
- const home = homeFromHostContext(options.context, options.home);
8491
- const sealHead = captureWorktreeHead(options.context.cwd);
8430
+ function sealAcceptedSubmission(options) {
8431
+ const runId = runIdFromRunDirectory(options.runDirectory);
8432
+ if (runId === void 0) throw new Error("\u63D0\u4EA4\u8D26\u9700\u8981\u5DF2\u53D7\u7406\u7684 run \u8EAB\u4EFD");
8433
+ const attemptId = options.courtAttemptId ?? `${runId}:initial`;
8434
+ const sealHead = captureWorktreeHead(options.cwd);
8435
+ const sessionParent = sessionFileOf(options.runDirectory);
8436
+ const home = options.home ?? tryHomeFromAkRolesPath(sessionParent);
8492
8437
  sitianReport({
8493
8438
  level: "event",
8494
8439
  kind: "sealed",
@@ -8501,15 +8446,17 @@ async function sealAcceptedSubmission(options) {
8501
8446
  accepted: options.accepted
8502
8447
  },
8503
8448
  source: "role-runtime",
8504
- cwd: options.context.cwd,
8449
+ cwd: options.cwd,
8505
8450
  ...home !== void 0 ? { home } : {},
8506
- ...sessionParent === void 0 ? {} : { sessionParent }
8451
+ sessionParent
8507
8452
  });
8508
- landTicketProgressForSealedSubmission({
8509
- context: options.context,
8453
+ landTicketProgress({
8454
+ runDirectory: options.runDirectory,
8510
8455
  role: options.role,
8511
8456
  accepted: options.accepted,
8512
- sealHead
8457
+ sealHead,
8458
+ sessionFile: void 0,
8459
+ instruction: options.instruction ?? ""
8513
8460
  });
8514
8461
  }
8515
8462
  function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (error) => {
@@ -9114,7 +9061,7 @@ function resolveLifecycleInvocationPrincipal(entries, expected) {
9114
9061
  }
9115
9062
  return { invocationId: marker.invocationId, resume: true };
9116
9063
  }
9117
- var NAVIGATOR_INVOCATION_ENTRY, NAVIGATOR_ROUTE_PLAYBOOK_FAILURE_ENTRY, NAVIGATOR_INFRASTRUCTURE_FAILURE_KIND, NAVIGATOR_INFRASTRUCTURE_FAILURE_KEYS, NAVIGATOR_INFRASTRUCTURE_FAILURE_EVIDENCE_KEYS, PACKAGED_ROLE_OUTPUT_TOOLS;
9064
+ var NAVIGATOR_INVOCATION_ENTRY, NAVIGATOR_INFRASTRUCTURE_FAILURE_KIND, NAVIGATOR_INFRASTRUCTURE_FAILURE_KEYS, NAVIGATOR_INFRASTRUCTURE_FAILURE_EVIDENCE_KEYS, PACKAGED_ROLE_OUTPUT_TOOLS;
9118
9065
  var init_navigator_invocation_identity = __esm({
9119
9066
  "src/navigator-invocation-identity.ts"() {
9120
9067
  "use strict";
@@ -9123,7 +9070,6 @@ var init_navigator_invocation_identity = __esm({
9123
9070
  init_unknown_value();
9124
9071
  init_work_subject_identity();
9125
9072
  NAVIGATOR_INVOCATION_ENTRY = "ak-navigator-invocation";
9126
- NAVIGATOR_ROUTE_PLAYBOOK_FAILURE_ENTRY = "ak-navigator-route-playbook-failure";
9127
9073
  NAVIGATOR_INFRASTRUCTURE_FAILURE_KIND = "role_infrastructure_failure";
9128
9074
  NAVIGATOR_INFRASTRUCTURE_FAILURE_KEYS = [
9129
9075
  "kind",
@@ -9405,7 +9351,7 @@ async function settleNoReceiptTerminal(admitted, authority, scope, facts) {
9405
9351
  }
9406
9352
  return attachEngineDetourToolUsage({
9407
9353
  roleOutcome,
9408
- navigator: await extractNavigatorFactFromAdmittedSession(
9354
+ navigator: isNavigatorSeat(admitted.role) ? NAVIGATOR_SEAT_OWN_FACT : await extractNavigatorFactFromAdmittedSession(
9409
9355
  coordinates.sessionFile,
9410
9356
  admitted.runDirectory,
9411
9357
  scope
@@ -9664,7 +9610,6 @@ async function appendRunAttemptHistory(source, outcome) {
9664
9610
  }
9665
9611
  function parseNavigatorAttendanceDetails(details) {
9666
9612
  const disposition = details.disposition;
9667
- const advisoryDiagnostic = typeof details.routePlaybookReadFailure === "string" ? { advisoryDiagnostic: details.routePlaybookReadFailure } : {};
9668
9613
  if (disposition === "advice" || disposition === "recommendation") {
9669
9614
  let prose;
9670
9615
  if (typeof details.prose === "string" && details.prose.trim() !== "") {
@@ -9684,29 +9629,19 @@ function parseNavigatorAttendanceDetails(details) {
9684
9629
  }
9685
9630
  }
9686
9631
  if (prose === void 0 || prose.trim() === "") {
9687
- return {
9688
- disposition: "no-advice",
9689
- ...advisoryDiagnostic
9690
- };
9632
+ return { disposition: "no-advice" };
9691
9633
  }
9692
- return adviceNavigatorFact({
9693
- prose,
9694
- ...advisoryDiagnostic
9695
- });
9634
+ return adviceNavigatorFact({ prose });
9696
9635
  }
9697
9636
  if (disposition === "unavailable") {
9698
9637
  return {
9699
9638
  disposition: "unavailable",
9700
- ...advisoryDiagnostic,
9701
9639
  source: typeof details.unavailableSource === "string" ? details.unavailableSource : "unknown",
9702
9640
  reason: typeof details.unavailableReason === "string" ? details.unavailableReason : "Navigator unavailable"
9703
9641
  };
9704
9642
  }
9705
9643
  if (disposition === "no-advice" || disposition === "arrival" || disposition === "silence") {
9706
- return {
9707
- disposition: "no-advice",
9708
- ...advisoryDiagnostic
9709
- };
9644
+ return { disposition: "no-advice" };
9710
9645
  }
9711
9646
  return {
9712
9647
  disposition: "unavailable",
@@ -9758,23 +9693,7 @@ function detourUsageContext(admitted, scope) {
9758
9693
  ...scope?.notePackageFault === void 0 ? {} : { notePackageFault: scope.notePackageFault }
9759
9694
  };
9760
9695
  }
9761
- function routePlaybookFailureMessage(entries) {
9762
- for (let i = entries.length - 1; i >= 0; i -= 1) {
9763
- const entry = entries[i];
9764
- if (entry?.type !== "custom" || entry.customType !== NAVIGATOR_ROUTE_PLAYBOOK_FAILURE_ENTRY) continue;
9765
- const data = entry.data;
9766
- if (!isRecord(data) || typeof data.message !== "string" || data.message.trim() === "") return void 0;
9767
- return data.message;
9768
- }
9769
- return void 0;
9770
- }
9771
9696
  function extractNavigatorFact(entries) {
9772
- const fact = extractNavigatorAttendanceFact(entries);
9773
- if (fact.advisoryDiagnostic !== void 0) return fact;
9774
- const message = routePlaybookFailureMessage(entries);
9775
- return message === void 0 ? fact : { ...fact, advisoryDiagnostic: message };
9776
- }
9777
- function extractNavigatorAttendanceFact(entries) {
9778
9697
  const terminal = findLatestDurablePackagedRoleTerminal(entries);
9779
9698
  if (terminal === void 0) {
9780
9699
  return {
@@ -9919,7 +9838,7 @@ async function finishLawfulSeat(admitted, coordinates, entries, roleOutcome, sco
9919
9838
  const artifacts = scope?.previewOnly === true ? [] : await publishDeclaredSeatTerminal(admitted, roleOutcome, coordinates, entries, scope);
9920
9839
  const terminal = await attachEngineDetourToolUsage({
9921
9840
  roleOutcome,
9922
- navigator: extractNavigatorFact(entries),
9841
+ navigator: isNavigatorSeat(admitted.role) ? NAVIGATOR_SEAT_OWN_FACT : extractNavigatorFact(entries),
9923
9842
  artifacts,
9924
9843
  runId: admitted.runId,
9925
9844
  ...submissionToolCallId === void 0 || submissionToolCallId.length === 0 ? {} : { submissionToolCallId }
@@ -10043,7 +9962,7 @@ async function publishFailureTerminal(admitted, failure, coordinates, onErrorPub
10043
9962
  async function settleFailureTerminalResult(admitted, failure, authority, options = {}) {
10044
9963
  const coordinates = coordinatesFromAdmitted(authority, admitted);
10045
9964
  const { sessionDirectory, sessionFile } = coordinates;
10046
- const navigator = await extractNavigatorFactFromAdmittedSession(
9965
+ const navigator = isNavigatorSeat(admitted.role) ? NAVIGATOR_SEAT_OWN_FACT : await extractNavigatorFactFromAdmittedSession(
10047
9966
  sessionFile,
10048
9967
  admitted.runDirectory,
10049
9968
  options
@@ -10117,10 +10036,10 @@ function presentFailureTerminal(terminal, io) {
10117
10036
  }
10118
10037
  function defaultNavigatorGraceSleep() {
10119
10038
  let timer;
10120
- const sleep2 = ((ms) => new Promise((resolve19) => {
10039
+ const sleep2 = ((ms) => new Promise((resolve17) => {
10121
10040
  timer = setTimeout(() => {
10122
10041
  timer = void 0;
10123
- resolve19();
10042
+ resolve17();
10124
10043
  }, ms);
10125
10044
  }));
10126
10045
  sleep2.cancel = () => {
@@ -10132,7 +10051,7 @@ function defaultNavigatorGraceSleep() {
10132
10051
  return sleep2;
10133
10052
  }
10134
10053
  function raceNavigatorGrace(work, graceMs = NAVIGATOR_POST_ROLE_GRACE_MS, sleep2 = defaultNavigatorGraceSleep()) {
10135
- return new Promise((resolve19, reject) => {
10054
+ return new Promise((resolve17, reject) => {
10136
10055
  let settled = false;
10137
10056
  const finish = (action) => {
10138
10057
  if (settled) return;
@@ -10141,15 +10060,15 @@ function raceNavigatorGrace(work, graceMs = NAVIGATOR_POST_ROLE_GRACE_MS, sleep2
10141
10060
  action();
10142
10061
  };
10143
10062
  void work.then(
10144
- (value) => finish(() => resolve19({ status: "done", value })),
10063
+ (value) => finish(() => resolve17({ status: "done", value })),
10145
10064
  (error) => finish(() => reject(error))
10146
10065
  );
10147
10066
  void sleep2(graceMs).then(() => {
10148
- finish(() => resolve19({ status: "timeout" }));
10067
+ finish(() => resolve17({ status: "timeout" }));
10149
10068
  });
10150
10069
  });
10151
10070
  }
10152
- var LifecycleReadFailure, NAVIGATOR_POST_ROLE_GRACE_MS, ATTEMPT_HISTORY_ENTRY_TYPE, EMPTY_ARTIFACT_FACE;
10071
+ var LifecycleReadFailure, NAVIGATOR_POST_ROLE_GRACE_MS, ATTEMPT_HISTORY_ENTRY_TYPE, NAVIGATOR_SEAT_OWN_FACT, EMPTY_ARTIFACT_FACE;
10153
10072
  var init_settlement = __esm({
10154
10073
  "src/public-cli/settlement.ts"() {
10155
10074
  "use strict";
@@ -10183,6 +10102,7 @@ var init_settlement = __esm({
10183
10102
  };
10184
10103
  NAVIGATOR_POST_ROLE_GRACE_MS = 1e4;
10185
10104
  ATTEMPT_HISTORY_ENTRY_TYPE = "ak_run_attempt_history";
10105
+ NAVIGATOR_SEAT_OWN_FACT = { disposition: "no-advice" };
10186
10106
  EMPTY_ARTIFACT_FACE = {};
10187
10107
  }
10188
10108
  });
@@ -10273,7 +10193,7 @@ function hostAbortedError(message = "host aborted") {
10273
10193
  function raceAgainstHostAbort(work, abortSignal, message = "host aborted") {
10274
10194
  if (abortSignal?.aborted) return Promise.reject(hostAbortedError(message));
10275
10195
  if (abortSignal === void 0) return work;
10276
- return new Promise((resolve19, reject) => {
10196
+ return new Promise((resolve17, reject) => {
10277
10197
  let settled = false;
10278
10198
  const onAbort = () => {
10279
10199
  if (settled) return;
@@ -10288,7 +10208,7 @@ function raceAgainstHostAbort(work, abortSignal, message = "host aborted") {
10288
10208
  if (settled) return;
10289
10209
  settled = true;
10290
10210
  abortSignal.removeEventListener("abort", onAbort);
10291
- resolve19(value);
10211
+ resolve17(value);
10292
10212
  },
10293
10213
  (error) => {
10294
10214
  if (settled) return;
@@ -10979,6 +10899,93 @@ var init_engine_material = __esm({
10979
10899
  }
10980
10900
  });
10981
10901
 
10902
+ // src/navigator-route-table.ts
10903
+ function navigatorRowsForRole(role) {
10904
+ return NAVIGATOR_ROUTE_TABLE[role] ?? {};
10905
+ }
10906
+ function navigatorFullTable() {
10907
+ return NAVIGATOR_ROUTE_TABLE;
10908
+ }
10909
+ var DISPOSE_BY_VERDICT, ESCALATE_TO_OWNER, DISPATCH_WORKER, SETTLED_TO_JUDGE, RESUME_SAME_WORKER, ROUTE_ROWS, NAVIGATOR_ROUTE_TABLE;
10910
+ var init_navigator_route_table = __esm({
10911
+ "src/navigator-route-table.ts"() {
10912
+ "use strict";
10913
+ DISPOSE_BY_VERDICT = "\u6309\u5224\u8BCD\u5904\u7F6E";
10914
+ ESCALATE_TO_OWNER = "\u5448\u965B\u4E0B\u88C1\u51B3";
10915
+ DISPATCH_WORKER = "\u6D3E\u5C06\u4F5C\u76D1\u5F00\u5DE5";
10916
+ SETTLED_TO_JUDGE = "\u53EF\u9001\u5927\u7406\u5BFA\u5BA1\u8BA1";
10917
+ RESUME_SAME_WORKER = "\u7EED\u4FEE\uFF0C\u52FF\u9001\u5927\u7406\u5BFA";
10918
+ ROUTE_ROWS = {
10919
+ secretariat: { converged: DISPATCH_WORKER, escalate: ESCALATE_TO_OWNER },
10920
+ countersign: { converged: DISPATCH_WORKER, continue: DISPOSE_BY_VERDICT, escalate: ESCALATE_TO_OWNER },
10921
+ notary: { converged: "\u6309\u6D41\u7A0B\u8FDB\u4E0B\u4E00\u7AD9", continue: DISPOSE_BY_VERDICT, escalate: ESCALATE_TO_OWNER },
10922
+ inspector: { converged: "\u6309\u6D41\u7A0B\u8FDB\u4E0B\u4E00\u7AD9", continue: DISPOSE_BY_VERDICT, escalate: ESCALATE_TO_OWNER },
10923
+ coder: {
10924
+ completed: "\u6D3E\u5FA1\u53F2\u53F0",
10925
+ partially_completed: SETTLED_TO_JUDGE,
10926
+ refused: SETTLED_TO_JUDGE,
10927
+ unfinished: RESUME_SAME_WORKER
10928
+ },
10929
+ fixer: {
10930
+ completed: "\u76F4\u56DE\u5927\u7406\u5BFA\u590D\u5BA1",
10931
+ partially_completed: SETTLED_TO_JUDGE,
10932
+ refused: SETTLED_TO_JUDGE,
10933
+ unfinished: RESUME_SAME_WORKER
10934
+ },
10935
+ reviewer: { completed: "\u6D3E\u5927\u7406\u5BFA\u88C1\u51B3", refused: "\u5448\u8C03\u7528\u8005\u5904\u7F6E" },
10936
+ judge: {
10937
+ converged: "\u8C03\u7528\u8005\u5408\u5E76\u3001\u5173\u7968",
10938
+ continue: DISPOSE_BY_VERDICT,
10939
+ escalate: ESCALATE_TO_OWNER
10940
+ },
10941
+ gatekeeper: { dispatch: "\u53EC\u6240\u70B9\u540D\u7684\u5B98\u5458", pass: "\u653E\u884C\uFF0C\u8FDB\u4E0B\u4E00\u7AD9" },
10942
+ merger: { completed: "\u8C03\u7528\u8005\u6536\u5C3E\u3001\u5173\u7968", escalate: ESCALATE_TO_OWNER },
10943
+ diarist: { completed: "\u7EE7\u7EED\u540E\u7EED\u8859\u95E8", escalate: ESCALATE_TO_OWNER }
10944
+ };
10945
+ NAVIGATOR_ROUTE_TABLE = ROUTE_ROWS;
10946
+ }
10947
+ });
10948
+
10949
+ // src/navigator-lookup-host.ts
10950
+ import { randomUUID as randomUUID5 } from "node:crypto";
10951
+ function targetRole(forRole) {
10952
+ const known = PACKAGED_ROLE_REGISTRY.find(({ role }) => role === forRole);
10953
+ if (known === void 0) throw new Error(`navigator lookup: unknown role ${forRole}`);
10954
+ return known.role;
10955
+ }
10956
+ function createNavigatorLookupHost() {
10957
+ return {
10958
+ async executeTurn(request) {
10959
+ const { activation } = request;
10960
+ if (activation.role !== "navigator") {
10961
+ throw new Error(`navigator lookup host cannot run ${activation.role}`);
10962
+ }
10963
+ const accepted = activation.forRole === void 0 ? { byRole: navigatorFullTable() } : { byStatus: navigatorRowsForRole(targetRole(activation.forRole)) };
10964
+ sealAcceptedSubmission({
10965
+ runDirectory: request.runDirectory,
10966
+ cwd: request.cwd,
10967
+ home: request.home,
10968
+ role: "navigator",
10969
+ accepted,
10970
+ instruction: request.continuation.prompt,
10971
+ toolCallId: `navigator-lookup:${randomUUID5()}`,
10972
+ ...request.courtAttemptId === void 0 ? {} : { courtAttemptId: request.courtAttemptId }
10973
+ });
10974
+ return { code: 0, stderr: "", timedOut: false };
10975
+ }
10976
+ };
10977
+ }
10978
+ var NAVIGATOR_LOOKUP_HOST;
10979
+ var init_navigator_lookup_host = __esm({
10980
+ "src/navigator-lookup-host.ts"() {
10981
+ "use strict";
10982
+ init_navigator_route_table();
10983
+ init_packaged_role_registry();
10984
+ init_submission_ledger();
10985
+ NAVIGATOR_LOOKUP_HOST = "lookup";
10986
+ }
10987
+ });
10988
+
10982
10989
  // src/institutional-resolution.ts
10983
10990
  function resolveConfiguredProvinceOfficer(config, officer) {
10984
10991
  const ownModel = seatModelOnly(config.seats[officer]);
@@ -11853,6 +11860,15 @@ __export(role_seat_runtime_exports, {
11853
11860
  openRoleSeatRuntime: () => openRoleSeatRuntime
11854
11861
  });
11855
11862
  function openRoleSeatRuntime(input) {
11863
+ if (isNavigatorSeat(input.role)) {
11864
+ input.afterHost?.();
11865
+ return {
11866
+ ok: true,
11867
+ roleTurnHost: createNavigatorLookupHost(),
11868
+ hostAdapters: [],
11869
+ host: NAVIGATOR_LOOKUP_HOST
11870
+ };
11871
+ }
11856
11872
  const hostAdapters = composeRoleTurnHostAdapters(
11857
11873
  input.resolution,
11858
11874
  input.principalAuthority
@@ -11883,6 +11899,8 @@ var init_role_seat_runtime = __esm({
11883
11899
  "src/public-cli/role-seat-runtime.ts"() {
11884
11900
  "use strict";
11885
11901
  init_engine_material();
11902
+ init_navigator_lookup_host();
11903
+ init_packaged_role_registry();
11886
11904
  init_config();
11887
11905
  init_host_providers();
11888
11906
  init_role_turn_host_resolution();
@@ -12539,7 +12557,6 @@ function projectRoleTurnRequest(admitted, roleDetails, options) {
12539
12557
  ...options.courtAttemptId === void 0 || options.courtAttemptId.length === 0 ? {} : { courtAttemptId: options.courtAttemptId },
12540
12558
  ...options.invocationScopeId === void 0 || options.invocationScopeId.length === 0 ? {} : { invocationScopeId: options.invocationScopeId },
12541
12559
  ...options.stationChild === void 0 ? {} : { stationChild: options.stationChild },
12542
- ...options.navigatorByStatusPrepare === void 0 ? {} : { navigatorByStatusPrepare: options.navigatorByStatusPrepare },
12543
12560
  ...options.deliveryRequestLimit === void 0 ? {} : { deliveryRequestLimit: options.deliveryRequestLimit },
12544
12561
  ...options.host === void 0 || options.host.trim() === "" ? {} : { host: options.host.trim() }
12545
12562
  };
@@ -12888,7 +12905,7 @@ var init_auto_resume = __esm({
12888
12905
  });
12889
12906
 
12890
12907
  // src/public-cli/post-admission.ts
12891
- import { randomUUID as randomUUID5 } from "node:crypto";
12908
+ import { randomUUID as randomUUID6 } from "node:crypto";
12892
12909
  function describeCaughtError(error) {
12893
12910
  if (error instanceof Error) {
12894
12911
  const code = error.code;
@@ -13512,9 +13529,6 @@ async function dispatchPostAdmissionTurn(input) {
13512
13529
  if (env.stationChild !== void 0) {
13513
13530
  turnRequest = { ...turnRequest, stationChild: env.stationChild };
13514
13531
  }
13515
- if (env.navigatorByStatusPrepare === true) {
13516
- turnRequest = { ...turnRequest, navigatorByStatusPrepare: true };
13517
- }
13518
13532
  if (typeof env.host === "string" && env.host.trim() !== "") {
13519
13533
  turnRequest = { ...turnRequest, host: env.host.trim() };
13520
13534
  }
@@ -13773,7 +13787,6 @@ function resumeTurnRequestProjectionOptions(admitted, request, env, summonsPrepa
13773
13787
  prompt
13774
13788
  },
13775
13789
  ...env.stationChild === void 0 ? {} : { stationChild: env.stationChild },
13776
- ...env.navigatorByStatusPrepare === true ? { navigatorByStatusPrepare: true } : {},
13777
13790
  // #1132: one configured ceiling, already resolved by the caller (#422).
13778
13791
  deliveryRequestLimit: deliveryLimitFromConfig(env.autoResumeLimit)
13779
13792
  };
@@ -13786,7 +13799,6 @@ function roleTurnOptions(env, admitted, continuation) {
13786
13799
  ...correlationId === void 0 || correlationId.trim() === "" ? {} : { correlationId },
13787
13800
  continuation,
13788
13801
  ...env.stationChild === void 0 ? {} : { stationChild: env.stationChild },
13789
- ...env.navigatorByStatusPrepare === true ? { navigatorByStatusPrepare: true } : {},
13790
13802
  // #1132: one configured ceiling, already resolved by the caller (#422).
13791
13803
  deliveryRequestLimit: deliveryLimitFromConfig(env.autoResumeLimit)
13792
13804
  };
@@ -13912,7 +13924,7 @@ async function runPostAdmissionSeatResume(input) {
13912
13924
  }
13913
13925
  }
13914
13926
  if (openCourtAttemptId !== void 0 || request.summons !== void 0) {
13915
- const courtAttemptId = openCourtAttemptId ?? (turnRequest.courtAttemptId !== void 0 && turnRequest.courtAttemptId.length > 0 ? turnRequest.courtAttemptId : randomUUID5());
13927
+ const courtAttemptId = openCourtAttemptId ?? (turnRequest.courtAttemptId !== void 0 && turnRequest.courtAttemptId.length > 0 ? turnRequest.courtAttemptId : randomUUID6());
13916
13928
  turnRequest = { ...turnRequest, courtAttemptId };
13917
13929
  if (openCourtAttemptId === void 0) {
13918
13930
  const court = {
@@ -14419,6 +14431,7 @@ async function reaskUnreadablePostSubmissionStatus(admitted, terminal, env, io,
14419
14431
  }
14420
14432
  async function reaskMissingTicketOnce(admitted, terminal, env, io) {
14421
14433
  if ((env.ticketReasksSpent ?? 0) >= 1) return { kind: "none" };
14434
+ if (isNavigatorSeat(admitted.role)) return { kind: "none" };
14422
14435
  if (admitted.ticketNumber !== void 0) return { kind: "none" };
14423
14436
  if (!isUnboundRunDirectory(admitted.runDirectory)) return { kind: "none" };
14424
14437
  if (terminal?.roleOutcome.kind !== "accepted" && terminal?.roleOutcome.kind !== "audit_escalation") {
@@ -15800,12 +15813,12 @@ var init_analyst_book_key = __esm({
15800
15813
  });
15801
15814
 
15802
15815
  // src/atomic-write.ts
15803
- import { randomUUID as randomUUID6 } from "node:crypto";
15816
+ import { randomUUID as randomUUID7 } from "node:crypto";
15804
15817
  import { rename as rename2, rm, writeFile as writeFile3 } from "node:fs/promises";
15805
15818
  import { dirname as dirname14, join as join22 } from "node:path";
15806
15819
  async function writeFileAtomically(destination, contents, options) {
15807
15820
  const parent = dirname14(destination);
15808
- const temporary = join22(parent, `.atomic-write-${randomUUID6()}.tmp`);
15821
+ const temporary = join22(parent, `.atomic-write-${randomUUID7()}.tmp`);
15809
15822
  try {
15810
15823
  await writeFile3(temporary, contents, options);
15811
15824
  await rename2(temporary, destination);
@@ -19304,7 +19317,6 @@ async function summonPublicRole(options) {
19304
19317
  // Nested court stations keep station-child semantics; dual-lens
19305
19318
  // ordinary Reviewer axes opt out (#946 / ADR 0082).
19306
19319
  ...options.stationChild === false ? {} : { stationChild: true },
19307
- ...options.navigatorByStatusPrepare === true ? { navigatorByStatusPrepare: true } : {},
19308
19320
  // Forward composition-root adapters so nested stations (e.g.
19309
19321
  // secretariat → diarist) select the same faux/production table (#924).
19310
19322
  ...options.hostAdapters === void 0 ? {} : { hostAdapters: options.hostAdapters },
@@ -20814,29 +20826,6 @@ function createReceiptDeliveryPolicy(limit) {
20814
20826
  deliveryTurns += 1;
20815
20827
  spend();
20816
20828
  },
20817
- /**
20818
- * Stop asking. The issued count stays whatever was actually sent (#1132 —
20819
- * do not fill the remainder up to the ceiling).
20820
- */
20821
- closeBudget() {
20822
- closed = true;
20823
- },
20824
- /**
20825
- * A nested session settled without an accepted receipt. Close so this layer
20826
- * does not open another prompt on that session. The issued count stays the
20827
- * larger of the two seams: a nested zero must not wipe prompts this layer
20828
- * already sent, and adding the two counts would bill one send twice.
20829
- */
20830
- recordNestedNoReceipt(facts) {
20831
- if (typeof facts.terminalToolCalled === "boolean") {
20832
- terminalToolCalled = terminalToolCalled || facts.terminalToolCalled;
20833
- }
20834
- if (facts.rejectedReceipts !== void 0) {
20835
- rejectedReceipts.push(...facts.rejectedReceipts);
20836
- }
20837
- if (facts.deliveryTurns !== void 0) deliveryTurns = Math.max(deliveryTurns, facts.deliveryTurns);
20838
- closed = true;
20839
- },
20840
20829
  nextAction() {
20841
20830
  if (accepted) return "accepted";
20842
20831
  if (closed) return "no-receipt";
@@ -20966,7 +20955,7 @@ init_receipt_delivery_policy();
20966
20955
  import { randomUUID as randomUUID9 } from "node:crypto";
20967
20956
  import { appendFile as appendFile2, mkdir as mkdir3, writeFile as writeFile5 } from "node:fs/promises";
20968
20957
  import { createServer } from "node:net";
20969
- import { dirname as dirname19 } from "node:path";
20958
+ import { dirname as dirname18 } from "node:path";
20970
20959
  import { fileURLToPath as fileURLToPath2 } from "node:url";
20971
20960
 
20972
20961
  // src/role-runtime.ts
@@ -20978,10 +20967,9 @@ init_host_session_record();
20978
20967
  init_submission_ledger();
20979
20968
  init_filed_submission();
20980
20969
  init_report_ticket_tool();
20981
- import { randomUUID as randomUUID7 } from "node:crypto";
20982
20970
  import { writeSync as writeSync2 } from "node:fs";
20983
- import { join as join31 } from "node:path";
20984
- import { Value as Value3 } from "typebox/value";
20971
+ import { join as join30 } from "node:path";
20972
+ import { Value as Value2 } from "typebox/value";
20985
20973
 
20986
20974
  // src/activation-trace.ts
20987
20975
  import { Type as Type17 } from "typebox";
@@ -21127,9 +21115,6 @@ function durableSessionPointer(sessionManager) {
21127
21115
  // src/activation-ledger.ts
21128
21116
  init_activation_ledger_topology();
21129
21117
 
21130
- // src/role-runtime.ts
21131
- init_session_opening_materials();
21132
-
21133
21118
  // src/stderr-jsonl.ts
21134
21119
  import { writeSync } from "node:fs";
21135
21120
  var STDERR_JSONL_WRITE_RETRY_LIMIT = 100;
@@ -21664,10 +21649,6 @@ async function commitDiaristProjection(input) {
21664
21649
  init_ticket_provenance();
21665
21650
  init_gatekeeper_role();
21666
21651
 
21667
- // src/navigator-role.ts
21668
- init_role_submission_declarations();
21669
- var NAVIGATOR_TOOL_SPEC = roleSubmissionDeclaration("navigator");
21670
-
21671
21652
  // src/auditor-role.ts
21672
21653
  init_auditor_output();
21673
21654
  init_role_submission_declarations();
@@ -21675,741 +21656,111 @@ var AUDITOR_TOOL_SPEC = roleSubmissionDeclaration("auditor");
21675
21656
 
21676
21657
  // src/navigator-attendance.ts
21677
21658
  init_navigator_invocation_identity();
21678
- init_packaged_role_registry();
21679
- init_activation_ledger_topology();
21680
- import { resolve as resolve15 } from "node:path";
21681
- import "typebox";
21682
-
21683
- // src/navigator-public-session.ts
21684
- init_host_session_record();
21685
- import { basename as basename15 } from "node:path";
21686
21659
 
21687
- // src/navigator-session-contracts.ts
21688
- init_unknown_value();
21689
- import { Type as Type19 } from "typebox";
21690
- import { Value as Value2 } from "typebox/value";
21691
- var NAVIGATOR_PREPARE_TOOL_NAME = "ak_navigator_prepare";
21692
- var NAVIGATOR_UNAVAILABLE_KEYS = /* @__PURE__ */ new Set([
21693
- "context",
21694
- "session",
21695
- "model",
21696
- "thinking",
21697
- "auth",
21698
- "quota",
21699
- "transport",
21700
- "unknown"
21701
- ]);
21702
- function navigatorUnavailableKey(value) {
21703
- return typeof value === "string" && NAVIGATOR_UNAVAILABLE_KEYS.has(value) ? value : void 0;
21704
- }
21660
+ // src/navigator-lookup.ts
21661
+ init_navigator_output();
21662
+ init_host_contracts();
21705
21663
  var NavigatorUnavailableError = class extends Error {
21706
21664
  unavailableSource;
21707
- unavailableCause;
21708
21665
  originalCause;
21709
- constructor(source, message, cause = source, originalCause) {
21666
+ constructor(source, message, originalCause) {
21710
21667
  super(message);
21711
21668
  this.name = "NavigatorUnavailableError";
21712
21669
  this.unavailableSource = source;
21713
- this.unavailableCause = cause;
21714
21670
  this.originalCause = originalCause;
21715
21671
  }
21716
21672
  };
21717
- function navigatorUnavailableError(source, error, cause = source) {
21718
- const message = errorText(error);
21719
- return error instanceof NavigatorUnavailableError ? error : new NavigatorUnavailableError(source, message, cause, error);
21673
+ function navigatorUnavailableError(source, error) {
21674
+ if (error instanceof NavigatorUnavailableError) return error;
21675
+ const message = error instanceof Error ? error.message : String(error);
21676
+ return new NavigatorUnavailableError(source, message, error);
21720
21677
  }
21721
- function navigatorProviderFailureFromStatus(status) {
21722
- if (status === 401 || status === 403) return { source: "auth", cause: "auth" };
21723
- if (status === 429) return { source: "quota", cause: "quota" };
21724
- return void 0;
21725
- }
21726
- function navigatorProviderFailureFromCode(code) {
21727
- if (typeof code === "number") return navigatorProviderFailureFromStatus(code);
21728
- if (typeof code !== "string") return void 0;
21729
- if (code === "unauthorized" || code === "authentication_failed") return { source: "auth", cause: "auth" };
21730
- if (code === "insufficient_quota" || code === "quota_exhausted") return { source: "quota", cause: "quota" };
21731
- if (code === "transport_error") return { source: "transport", cause: "transport" };
21678
+ async function ledgerHomeFor(context) {
21679
+ const { tryHomeFromAkRolesPath: tryHomeFromAkRolesPath2 } = await Promise.resolve().then(() => (init_activation_ledger_topology(), activation_ledger_topology_exports));
21680
+ for (const path of [runDirectoryFromHostContext(context), context.sessionManager?.getSessionFile?.()]) {
21681
+ if (typeof path !== "string" || path.trim() === "") continue;
21682
+ const home = tryHomeFromAkRolesPath2(path);
21683
+ if (home !== void 0 && home.length > 0) return home;
21684
+ }
21732
21685
  return void 0;
21733
21686
  }
21734
- function navigatorProviderFailureFromError(error) {
21735
- let cursor = error;
21736
- const seen = /* @__PURE__ */ new Set();
21737
- while (typeof cursor === "object" && cursor !== null && !seen.has(cursor)) {
21738
- seen.add(cursor);
21739
- if (cursor instanceof NavigatorUnavailableError) {
21740
- return { source: cursor.unavailableSource, cause: cursor.unavailableCause };
21687
+ function createNavigatorLookup(deps) {
21688
+ const summon = deps?.summonPublicRole ?? (async (options) => (await Promise.resolve().then(() => (init_public_role_summons(), public_role_summons_exports))).summonPublicRole(options));
21689
+ return async ({ context, role }) => {
21690
+ const home = await ledgerHomeFor(context);
21691
+ let summoned;
21692
+ try {
21693
+ summoned = await summon({
21694
+ role: "navigator",
21695
+ argv: ["--role", role],
21696
+ cwd: context.cwd,
21697
+ ...home === void 0 ? {} : { home },
21698
+ ...context.signal === void 0 ? {} : { signal: context.signal }
21699
+ });
21700
+ } catch (error) {
21701
+ throw navigatorUnavailableError("session", error);
21741
21702
  }
21742
- if (!isRecord(cursor)) {
21743
- cursor = cursor instanceof Error ? cursor.cause : void 0;
21744
- continue;
21703
+ const outcome = summoned.terminal?.roleOutcome;
21704
+ if (outcome === void 0) {
21705
+ const detail = summoned.stderr?.trim() || `exit ${summoned.exitCode}`;
21706
+ throw new NavigatorUnavailableError("session", `Navigator lookup produced no terminal (${detail})`);
21745
21707
  }
21746
- const fromReason = navigatorUnavailableKey(cursor.reason);
21747
- if (fromReason !== void 0) return { source: fromReason, cause: fromReason };
21748
- const statusCode = typeof cursor.statusCode === "number" ? cursor.statusCode : typeof cursor.status === "number" ? cursor.status : typeof cursor.httpStatus === "number" ? cursor.httpStatus : void 0;
21749
- const fromStatus = navigatorProviderFailureFromStatus(statusCode);
21750
- if (fromStatus !== void 0) return fromStatus;
21751
- const fromCode = navigatorProviderFailureFromCode(cursor.code);
21752
- if (fromCode !== void 0) return fromCode;
21753
- cursor = cursor.cause;
21754
- }
21755
- return void 0;
21756
- }
21757
- function navigatorProviderFailureFromDiagnostics(diagnostics) {
21758
- if (!Array.isArray(diagnostics)) return void 0;
21759
- for (const diagnostic of diagnostics) {
21760
- if (!isRecord(diagnostic)) continue;
21761
- if (diagnostic.type === "provider_transport_failure") return { source: "transport", cause: "transport" };
21762
- if (isRecord(diagnostic.error)) {
21763
- const fromCode = navigatorProviderFailureFromCode(diagnostic.error.code);
21764
- if (fromCode !== void 0) return fromCode;
21708
+ if (outcome.kind === "failure") {
21709
+ throw new NavigatorUnavailableError("session", outcome.diagnostic);
21765
21710
  }
21766
- if (isRecord(diagnostic.details)) {
21767
- const status = typeof diagnostic.details.status === "number" ? diagnostic.details.status : typeof diagnostic.details.statusCode === "number" ? diagnostic.details.statusCode : void 0;
21768
- const fromStatus = navigatorProviderFailureFromStatus(status);
21769
- if (fromStatus !== void 0) return fromStatus;
21770
- const fromCode = navigatorProviderFailureFromCode(diagnostic.details.code);
21771
- if (fromCode !== void 0) return fromCode;
21711
+ if (outcome.kind !== "accepted") {
21712
+ throw new NavigatorUnavailableError("session", `Navigator lookup settled ${outcome.kind}`);
21772
21713
  }
21773
- }
21774
- return void 0;
21775
- }
21776
- function navigatorProviderFailureFromPublicTerminal(outcome) {
21777
- const facts = outcome.decisiveFacts;
21778
- const secondary = typeof facts.secondaryEvidence === "object" && facts.secondaryEvidence !== null ? facts.secondaryEvidence : void 0;
21779
- const httpStatus = typeof secondary?.httpStatus === "number" ? secondary.httpStatus : typeof facts.httpStatus === "number" ? facts.httpStatus : typeof facts.errorCode === "number" ? facts.errorCode : void 0;
21780
- const fromStatus = navigatorProviderFailureFromStatus(httpStatus);
21781
- if (fromStatus !== void 0) return fromStatus;
21782
- const diagnostics = secondary?.diagnostics ?? facts.diagnostics;
21783
- const fromDiagnostics = navigatorProviderFailureFromDiagnostics(diagnostics);
21784
- if (fromDiagnostics !== void 0) return fromDiagnostics;
21785
- const fromCode = navigatorProviderFailureFromError({
21786
- code: secondary?.code ?? facts.errorCode
21787
- });
21788
- if (fromCode !== void 0) return fromCode;
21789
- if (outcome.cause === "provider") return { source: "transport", cause: "unknown" };
21790
- const typed = navigatorUnavailableKey(outcome.cause);
21791
- if (typed !== void 0) return { source: typed, cause: typed };
21792
- return { source: "unknown", cause: "unknown" };
21793
- }
21794
- var navigatorProviderFailureSchema = Type19.Object({
21795
- source: Type19.Union([
21796
- Type19.Literal("context"),
21797
- Type19.Literal("session"),
21798
- Type19.Literal("model"),
21799
- Type19.Literal("thinking"),
21800
- Type19.Literal("auth"),
21801
- Type19.Literal("quota"),
21802
- Type19.Literal("transport"),
21803
- Type19.Literal("unknown")
21804
- ]),
21805
- cause: Type19.Union([
21806
- Type19.Literal("context"),
21807
- Type19.Literal("session"),
21808
- Type19.Literal("model"),
21809
- Type19.Literal("thinking"),
21810
- Type19.Literal("auth"),
21811
- Type19.Literal("quota"),
21812
- Type19.Literal("transport"),
21813
- Type19.Literal("unknown")
21814
- ])
21815
- }, { additionalProperties: false });
21816
- function parseNavigatorModelSetting(value) {
21817
- const slash = value.indexOf("/");
21818
- if (slash <= 0 || slash === value.length - 1) {
21819
- throw new Error("Navigator model setting must be provider/model[:thinking]");
21820
- }
21821
- const provider = value.slice(0, slash);
21822
- const modelWithThinking = value.slice(slash + 1);
21823
- const colon = modelWithThinking.lastIndexOf(":");
21824
- const suffix = colon < 0 ? void 0 : modelWithThinking.slice(colon + 1);
21825
- const model = colon < 0 ? modelWithThinking : modelWithThinking.slice(0, colon);
21826
- if (model === "") throw new Error("Navigator model setting must include a model");
21827
- if (suffix !== void 0 && suffix.trim() === "") {
21828
- throw new Error("Navigator model setting thinking suffix must be non-blank");
21829
- }
21830
- return {
21831
- provider,
21832
- model,
21833
- ...suffix === void 0 ? {} : { thinkingLevel: suffix }
21834
- };
21835
- }
21836
- async function resolveNavigatorSeatSelection(context) {
21837
- try {
21838
- const { loadPublicCliConfig: loadPublicCliConfig2 } = await Promise.resolve().then(() => (init_config(), config_exports));
21839
- const { seatModelOnly: seatModelOnly2 } = await Promise.resolve().then(() => (init_registry(), registry_exports));
21840
- const { packageMachineHome: packageMachineHome2 } = await Promise.resolve().then(() => (init_activation_ledger_topology(), activation_ledger_topology_exports));
21841
- const homeCandidate = context.home;
21842
- const envHome = process.env.HOME;
21843
- const home = typeof homeCandidate === "string" ? homeCandidate : typeof envHome === "string" && envHome.trim() !== "" ? envHome : packageMachineHome2();
21844
- const config = await loadPublicCliConfig2(home);
21845
- const modelOnly = seatModelOnly2(config.seats.navigator);
21846
- if (modelOnly === void 0) {
21847
- const { missingResolvedSeatModelMessage: missingResolvedSeatModelMessage2 } = await Promise.resolve().then(() => (init_config(), config_exports));
21848
- throw navigatorUnavailableError(
21849
- "model",
21850
- new Error(missingResolvedSeatModelMessage2("navigator"))
21851
- );
21714
+ let prepared;
21715
+ for (const payload of outcome.payloads ?? []) {
21716
+ prepared = mergePreparedAdvice(prepared, preparedAdviceFromUnknown(payload));
21852
21717
  }
21853
- const thinkingRaw = modelOnly.thinking;
21854
- const configuredLabel = thinkingRaw === void 0 ? `${modelOnly.provider}/${modelOnly.model}` : `${modelOnly.provider}/${modelOnly.model}:${thinkingRaw}`;
21855
- return {
21856
- selection: {
21857
- provider: modelOnly.provider,
21858
- model: modelOnly.model,
21859
- ...thinkingRaw === void 0 ? {} : { thinking: thinkingRaw }
21860
- },
21861
- configuredLabel,
21862
- ...thinkingRaw === void 0 ? {} : { thinkingLevel: thinkingRaw }
21863
- };
21864
- } catch (error) {
21865
- throw navigatorUnavailableError("model", error);
21866
- }
21867
- }
21868
-
21869
- // src/navigator-public-session.ts
21870
- init_host_contracts();
21871
- init_role_run_placement();
21872
- init_cli_errors();
21873
- init_packaged_role_registry();
21874
- async function resolveNavigatorLedgerHome(context) {
21875
- const { tryHomeFromAkRolesPath: tryHomeFromAkRolesPath2 } = await Promise.resolve().then(() => (init_activation_ledger_topology(), activation_ledger_topology_exports));
21876
- const runDirectory = runDirectoryFromHostContext(context);
21877
- if (runDirectory !== void 0) {
21878
- const fromRun = tryHomeFromAkRolesPath2(runDirectory);
21879
- if (fromRun !== void 0 && fromRun.length > 0) return fromRun;
21880
- }
21881
- const parentFile = context.sessionManager?.getSessionFile?.();
21882
- if (typeof parentFile === "string" && parentFile.trim() !== "") {
21883
- const fromParent = tryHomeFromAkRolesPath2(parentFile);
21884
- if (fromParent !== void 0 && fromParent.length > 0) return fromParent;
21885
- }
21886
- return void 0;
21887
- }
21888
- function runIdFromNavigatorDirectory(runDirectory) {
21889
- const parsed = parseRunLeaf(basename15(runDirectory));
21890
- if (parsed === void 0 || parsed.role !== "navigator") return void 0;
21891
- return parsed.runId;
21892
- }
21893
- async function navigatorHostRunResumable(home, runId, runDirectory) {
21894
- const { piDurablePrincipalAuthority: piDurablePrincipalAuthority2 } = await Promise.resolve().then(() => (init_durable_principal(), durable_principal_exports));
21895
- const { loadResumablePublicRole: loadResumablePublicRole2 } = await Promise.resolve().then(() => (init_run_lifecycle(), run_lifecycle_exports));
21896
- try {
21897
- const loaded = await loadResumablePublicRole2(
21898
- home,
21899
- runId,
21900
- piDurablePrincipalAuthority2,
21901
- runDirectory === void 0 ? void 0 : { runDirectory }
21902
- );
21903
- return isNavigatorSeat(loaded.admitted.role);
21904
- } catch (error) {
21905
- if (error instanceof CliUsageError) return false;
21906
- throw error;
21907
- }
21908
- }
21909
- function createNativeNavigatorSessionFactory(deps) {
21910
- return async ({ context, tool }) => {
21911
- const entries = [];
21912
- let providerFailure;
21913
- let noReceipt;
21914
- let routePlaybookReadFailure;
21915
- let disposed = false;
21916
- let hostRun;
21917
- const summon = deps?.summonPublicRole ?? (async (options) => {
21918
- const { summonPublicRole: summonPublicRole2 } = await Promise.resolve().then(() => (init_public_role_summons(), public_role_summons_exports));
21919
- return summonPublicRole2(options);
21920
- });
21921
- const parentSessionFile = () => context.sessionManager?.getSessionFile?.();
21922
- return {
21923
- prompt: async (text) => {
21924
- if (disposed) {
21925
- throw navigatorUnavailableError("session", new Error("Navigator attendance was disposed"));
21926
- }
21927
- providerFailure = void 0;
21928
- noReceipt = void 0;
21929
- routePlaybookReadFailure = void 0;
21930
- try {
21931
- const summonHome = await resolveNavigatorLedgerHome(context);
21932
- if (disposed) return;
21933
- const resumeRunId = hostRun?.runId;
21934
- const baseSummon = {
21935
- role: "navigator",
21936
- argv: [text],
21937
- cwd: context.cwd,
21938
- // Attendance prepare always asks for structured byStatus (#1160).
21939
- // Direct `ak-role navigator` never sets this flag.
21940
- navigatorByStatusPrepare: true,
21941
- ...summonHome === void 0 ? {} : { home: summonHome },
21942
- ...context.signal === void 0 ? {} : { signal: context.signal }
21943
- };
21944
- const resumable = deps?.hostRunResumable ?? navigatorHostRunResumable;
21945
- let summoned;
21946
- if (resumeRunId === void 0 || summonHome === void 0) {
21947
- if (disposed) return;
21948
- summoned = await summon(baseSummon);
21949
- } else {
21950
- const canResume = await resumable(summonHome, resumeRunId, hostRun?.runDirectory);
21951
- if (disposed) return;
21952
- if (canResume) {
21953
- summoned = await summon({
21954
- ...baseSummon,
21955
- resumeRunId,
21956
- ...hostRun === void 0 ? {} : { resumeRunDirectory: hostRun.runDirectory }
21957
- });
21958
- } else {
21959
- hostRun = void 0;
21960
- summoned = await summon(baseSummon);
21961
- }
21962
- }
21963
- if (disposed) return;
21964
- const playbookFailure = summoned.terminal?.navigator?.advisoryDiagnostic;
21965
- routePlaybookReadFailure = typeof playbookFailure === "string" && playbookFailure.trim() !== "" ? playbookFailure : void 0;
21966
- const outcome = summoned.terminal?.roleOutcome;
21967
- if (outcome === void 0) {
21968
- const detail = summoned.stderr?.trim() || `exit ${summoned.exitCode}`;
21969
- providerFailure = { source: "transport", cause: "unknown" };
21970
- throw navigatorUnavailableError(
21971
- providerFailure.source,
21972
- new Error(`Navigator public summon produced no terminal (${detail})`),
21973
- providerFailure.cause
21974
- );
21975
- }
21976
- if (outcome.kind === "failure") {
21977
- providerFailure = navigatorProviderFailureFromPublicTerminal(outcome);
21978
- const failedAttempts = outcome.decisiveFacts.failedAttempts;
21979
- const attemptReasons = Array.isArray(failedAttempts) ? failedAttempts.map((entry, index) => {
21980
- const fact = entry !== null && typeof entry === "object" ? entry : void 0;
21981
- return `${typeof fact?.attempt === "number" ? fact.attempt + 1 : index + 1}: ${typeof fact?.diagnostic === "string" ? fact.diagnostic : outcome.diagnostic}`;
21982
- }) : [];
21983
- throw navigatorUnavailableError(
21984
- providerFailure.source,
21985
- new Error(attemptReasons.length > 0 ? attemptReasons.join("\n") : outcome.diagnostic),
21986
- providerFailure.cause
21987
- );
21988
- }
21989
- if (outcome.kind === "no_receipt") {
21990
- noReceipt = outcome;
21991
- return;
21992
- }
21993
- const runDirectory = summoned.runDirectory ?? (typeof summoned.admitted?.runDirectory === "string" ? summoned.admitted.runDirectory : void 0);
21994
- if (typeof runDirectory === "string" && runDirectory.trim() !== "") {
21995
- const nextRunId = runIdFromNavigatorDirectory(runDirectory);
21996
- if (nextRunId !== void 0) {
21997
- hostRun = { runId: nextRunId, runDirectory };
21998
- }
21999
- }
22000
- if (outcome.kind !== "accepted") {
22001
- return;
22002
- }
22003
- const {
22004
- byStatusToPlainObject: byStatusToPlainObject2,
22005
- mergePreparedAdvice: mergePreparedAdvice2,
22006
- preparedAdviceFromUnknown: preparedAdviceFromUnknown2
22007
- } = await Promise.resolve().then(() => (init_navigator_output(), navigator_output_exports));
22008
- let prepared = void 0;
22009
- for (const payload of outcome.payloads ?? []) {
22010
- prepared = mergePreparedAdvice2(prepared, preparedAdviceFromUnknown2(payload));
22011
- }
22012
- if (prepared === void 0) return;
22013
- if (disposed) return;
22014
- await tool.execute(
22015
- "navigator-public-prepare",
22016
- {
22017
- ...prepared.prose === void 0 ? {} : { prose: prepared.prose },
22018
- ...prepared.byStatus.size === 0 ? {} : { byStatus: byStatusToPlainObject2(prepared.byStatus) }
22019
- },
22020
- void 0,
22021
- void 0,
22022
- context
22023
- );
22024
- } catch (error) {
22025
- if (disposed) return;
22026
- if (error instanceof NavigatorUnavailableError) throw error;
22027
- const fact = navigatorProviderFailureFromError(error);
22028
- providerFailure = fact ?? { source: "transport", cause: "unknown" };
22029
- throw navigatorUnavailableError(providerFailure.source, error, providerFailure.cause);
22030
- }
22031
- },
22032
- providerFailure: () => providerFailure,
22033
- noReceipt: () => noReceipt,
22034
- routePlaybookReadFailure: () => routePlaybookReadFailure,
22035
- appendEntry: (customType, data) => {
22036
- entries.push({ type: "custom", customType, data });
22037
- const parent = parentSessionFile();
22038
- sitianReportSafe({
22039
- level: "event",
22040
- kind: "attendance",
22041
- cwd: context.cwd,
22042
- ...parent === void 0 ? {} : { sessionParent: parent },
22043
- payload: { customType, data },
22044
- source: "navigator-public-session"
22045
- });
22046
- },
22047
- entries: () => entries,
22048
- setModel: async (next) => {
22049
- try {
22050
- parseNavigatorModelSetting(next);
22051
- } catch (error) {
22052
- throw navigatorUnavailableError("model", error);
22053
- }
22054
- },
22055
- dispose: async () => {
22056
- disposed = true;
22057
- }
22058
- };
21718
+ return prepared;
22059
21719
  };
22060
21720
  }
22061
21721
 
22062
21722
  // src/navigator-attendance.ts
22063
- init_sitian_facade();
22064
- init_work_subject_identity();
22065
- init_receipt_delivery_policy();
22066
21723
  init_navigator_output();
22067
- init_sha256();
22068
- init_unknown_value();
21724
+ init_work_subject_identity();
22069
21725
  var NAVIGATOR_EVENT_TYPE = "ak-navigator-attendance";
22070
- var NAVIGATOR_TARGETS = PACKAGED_ROLE_REGISTRY.map(({ role, phases }) => ({ role, phases }));
22071
- var prepareSchema = navigatorAdviceBodySchema;
22072
- var INVOCATION_ENTRY = NAVIGATOR_INVOCATION_ENTRY;
22073
- var SETTLEMENT_ENTRY = "ak-navigator-settlement";
22074
- function rejectedPrepareReason(entries, start) {
22075
- const recent = entries.slice(start);
22076
- const prepareCalls = /* @__PURE__ */ new Set();
22077
- for (const entry of recent) {
22078
- if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message) || entry.message.role !== "assistant" || !Array.isArray(entry.message.content)) continue;
22079
- for (const part of entry.message.content) {
22080
- if (isRecord(part) && part.type === "toolCall" && part.name === NAVIGATOR_PREPARE_TOOL_NAME && typeof part.id === "string") prepareCalls.add(part.id);
22081
- }
22082
- }
22083
- let reason;
22084
- for (const entry of recent) {
22085
- if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message) || entry.message.role !== "toolResult" || entry.message.isError !== true) continue;
22086
- const callId = entry.message.toolCallId;
22087
- if (entry.message.toolName !== NAVIGATOR_PREPARE_TOOL_NAME || typeof callId !== "string" || !prepareCalls.has(callId)) {
22088
- return void 0;
22089
- }
22090
- const content = entry.message.content;
22091
- const text = Array.isArray(content) ? content.flatMap((part) => isRecord(part) && typeof part.text === "string" ? [part.text] : []).join("") : typeof content === "string" ? content : "";
22092
- if (text.trim() !== "") reason = text.trim();
22093
- }
22094
- return reason;
22095
- }
22096
- function normalizePreparedAdvice(value) {
22097
- return preparedAdviceFromUnknown(value);
22098
- }
22099
- function navigatorSubjectKey(subjectRoot, subject, provenance = "role_input") {
22100
- if (issueRoot(subjectRoot) !== void 0 || !subjectRoot.includes("/.ak/work/")) return subjectRoot;
22101
- if (provenance === "placeholder") return subjectRoot;
22102
- const normalized = subject.trim().replace(/\s+/g, " ");
22103
- if (normalized === "") return subjectRoot;
22104
- return `${subjectRoot}#${sha256Hex(normalized).slice(0, 32)}`;
22105
- }
22106
- function navigatorSubjectKeyForInput(subjectRoot, reference, cwd = process.cwd()) {
22107
- if (issueRoot(subjectRoot) !== void 0 || !subjectRoot.includes("/.ak/work/")) return subjectRoot;
22108
- const resolvedReference = resolve15(cwd, reference);
22109
- const marker = "/runs/";
22110
- if (resolvedReference.includes(marker)) {
22111
- return subjectRoot;
22112
- }
22113
- return navigatorSubjectKey(subjectRoot, resolvedReference);
22114
- }
22115
- function createNavigatorPrepareTool(onOutput) {
22116
- return {
22117
- name: NAVIGATOR_PREPARE_TOOL_NAME,
22118
- label: "\u6E38\u5955\u4F7F\u51C6\u5907",
22119
- description: "\u63D0\u4EA4\u6E38\u5955\u4F7F\u6563\u6587\u5EFA\u8BAE\u3002",
22120
- parameters: prepareSchema,
22121
- async execute(_id, value) {
22122
- onOutput(value);
22123
- return { content: [], details: value, terminate: true };
22124
- }
22125
- };
22126
- }
22127
21726
  function formatNavigatorReport(report) {
22128
- const playbookFailure = report.routePlaybookReadFailure === void 0 ? [] : [report.routePlaybookReadFailure];
22129
- if (report.disposition === "no-advice") return playbookFailure.join("\n");
22130
- if (report.disposition === "unavailable") {
22131
- return [...playbookFailure, ...report.unavailableReason ? [report.unavailableReason] : []].join("\n");
22132
- }
22133
- if (report.disposition === "arrival") {
22134
- return [...playbookFailure, ...report.arrivalMessage ? [report.arrivalMessage] : []].join("\n");
22135
- }
22136
- return [...playbookFailure, ...report.prose ? [report.prose] : []].join("\n");
21727
+ if (report.disposition === "no-advice") return "";
21728
+ if (report.disposition === "unavailable") return report.unavailableReason ?? "";
21729
+ if (report.disposition === "arrival") return report.arrivalMessage ?? "";
21730
+ return report.prose ?? "";
22137
21731
  }
22138
21732
  function createNavigatorAttendance(options) {
21733
+ const { subjectKey } = options;
22139
21734
  let preparation;
22140
21735
  let preparationInFlight = false;
22141
- let sessionReady;
22142
- let session;
22143
- let subjectKey = options.subjectKey;
22144
- let contextError = options.contextError;
22145
21736
  let preparedAdvice;
22146
- const invocationPrincipal = options.invocationId ?? mintNavigatorInvocationId();
22147
- let activeInvocationId = invocationPrincipal;
22148
- let outputSink;
22149
- let settlementTail = Promise.resolve();
22150
- let settlementFailure;
22151
21737
  let preparationFailure;
22152
- let observedRoutePlaybookFailure;
21738
+ let settlementTail = Promise.resolve();
22153
21739
  let disposed = false;
22154
- let closing;
21740
+ const invocationId = options.invocationId ?? mintNavigatorInvocationId();
22155
21741
  const nestCancel = new AbortController();
22156
- const sessionHostContext = () => {
21742
+ const lookupContext = () => {
22157
21743
  const parentSignal = options.context.signal;
22158
21744
  const signal = parentSignal === void 0 ? nestCancel.signal : AbortSignal.any([nestCancel.signal, parentSignal]);
22159
21745
  return { ...options.context, signal };
22160
21746
  };
22161
- const unavailable = (invocationId, reason) => {
22162
- const failure = reason instanceof NavigatorUnavailableError ? reason : navigatorUnavailableError("unknown", reason);
21747
+ const unavailable = (reason) => {
21748
+ const failure = navigatorUnavailableError("unknown", reason);
22163
21749
  return {
22164
21750
  disposition: "unavailable",
22165
21751
  unavailableReason: failure.message,
22166
- unavailableSource: failure.unavailableSource,
22167
- unavailableCause: failure.unavailableCause
21752
+ unavailableSource: failure.unavailableSource
22168
21753
  };
22169
21754
  };
22170
- const loadMaterialsAndSession = async (invocationId) => {
22171
- if (contextError !== void 0) throw navigatorUnavailableError("context", contextError);
22172
- const modelPromise = (async () => {
22173
- try {
22174
- const resolved = await resolveNavigatorSeatSelection(options.context);
22175
- return resolved.configuredLabel;
22176
- } catch (error) {
22177
- if (error instanceof NavigatorUnavailableError) throw error;
22178
- throw navigatorUnavailableError("model", error);
22179
- }
22180
- })();
22181
- const modelSetting = await modelPromise;
22182
- let model;
22183
- try {
22184
- model = parseNavigatorModelSetting(modelSetting);
22185
- } catch (error) {
22186
- throw navigatorUnavailableError("model", error);
22187
- }
22188
- const tool = createNavigatorPrepareTool((value) => {
22189
- outputSink?.(value);
22190
- });
22191
- if (session === void 0) {
22192
- sessionReady = (async () => {
22193
- let created;
22194
- try {
22195
- created = await options.createSession({
22196
- context: sessionHostContext(),
22197
- subject: subjectKey,
22198
- ...options.modelSettingPath === void 0 ? {} : { modelSettingPath: options.modelSettingPath },
22199
- tool
22200
- });
22201
- } catch (error) {
22202
- throw navigatorUnavailableError("session", error);
22203
- }
22204
- if (disposed) {
22205
- await created.dispose();
22206
- throw navigatorUnavailableError("session", new Error("Navigator attendance was disposed"));
22207
- }
22208
- try {
22209
- await created.setModel?.(modelSetting, model.thinkingLevel);
22210
- if (disposed) throw navigatorUnavailableError("session", new Error("Navigator attendance was disposed"));
22211
- created.appendEntry(INVOCATION_ENTRY, { invocationId, role: options.role, phase: options.phase, subjectKey });
22212
- if (disposed) throw navigatorUnavailableError("session", new Error("Navigator attendance was disposed"));
22213
- session = created;
22214
- return created;
22215
- } catch (error) {
22216
- if (session !== created) await created.dispose();
22217
- throw error instanceof NavigatorUnavailableError ? error : navigatorUnavailableError("session", error);
22218
- }
22219
- })();
22220
- await sessionReady;
22221
- sessionReady = void 0;
22222
- } else {
22223
- try {
22224
- await session.setModel?.(modelSetting, model.thinkingLevel);
22225
- } catch (error) {
22226
- throw error instanceof NavigatorUnavailableError ? error : navigatorUnavailableError("session", error);
22227
- }
22228
- session.appendEntry(INVOCATION_ENTRY, { invocationId, role: options.role, phase: options.phase, subjectKey });
22229
- }
22230
- if (disposed) throw navigatorUnavailableError("session", new Error("Navigator attendance was disposed"));
22231
- if (session === void 0) throw new Error("Navigator session was not created");
22232
- return session;
22233
- };
22234
- const prepare = async () => {
22235
- const invocationId = invocationPrincipal;
22236
- activeInvocationId = invocationId;
22237
- let output;
22238
- let prepareBatchRejected = false;
22239
- outputSink = (value) => {
22240
- const next = normalizePreparedAdvice(value);
22241
- if (output === void 0) {
22242
- output = value;
22243
- return;
22244
- }
22245
- const merged = mergePreparedAdvice(normalizePreparedAdvice(output), next);
22246
- output = {
22247
- ...merged?.prose === void 0 ? {} : { prose: merged.prose },
22248
- ...merged === void 0 || merged.byStatus.size === 0 ? {} : { byStatus: byStatusToPlainObject(merged.byStatus) }
22249
- };
22250
- };
22251
- const activeSession = await loadMaterialsAndSession(invocationId);
22252
- const request = JSON.stringify({
22253
- kind: "prepare",
22254
- role: options.role,
22255
- phase: options.phase,
22256
- invocationId,
22257
- subjectKey
22258
- });
22259
- try {
22260
- try {
22261
- if (disposed) throw navigatorUnavailableError("session", new Error("Navigator attendance was disposed"));
22262
- const delivery = createReceiptDeliveryPolicy(options.deliveryRequestLimit);
22263
- const promptAllowingRejectedPrepare = async (text) => {
22264
- const entryStart = activeSession.entries().length;
22265
- prepareBatchRejected = false;
22266
- let promptFailure;
22267
- try {
22268
- await activeSession.prompt(text);
22269
- } catch (error) {
22270
- promptFailure = error;
22271
- }
22272
- const providerFailure = activeSession.providerFailure?.();
22273
- if (providerFailure !== void 0) {
22274
- throw navigatorUnavailableError(providerFailure.source, promptFailure ?? "Navigator provider failure", providerFailure.cause);
22275
- }
22276
- const rejectedReason = rejectedPrepareReason(activeSession.entries(), entryStart);
22277
- if (rejectedReason !== void 0) {
22278
- output = void 0;
22279
- prepareBatchRejected = true;
22280
- delivery.recordRejected(rejectedReason);
22281
- return;
22282
- }
22283
- if (promptFailure !== void 0) throw promptFailure;
22284
- const sessionNoReceipt = activeSession.noReceipt?.();
22285
- if (sessionNoReceipt !== void 0) {
22286
- delivery.recordNestedNoReceipt(sessionNoReceipt);
22287
- return;
22288
- }
22289
- };
22290
- await promptAllowingRejectedPrepare(request);
22291
- while (output === void 0 && prepareBatchRejected && delivery.nextAction() === "request-delivery") {
22292
- delivery.recordDeliveryRequest();
22293
- await promptAllowingRejectedPrepare(request);
22294
- }
22295
- if (output === void 0 && delivery.nextAction() === "request-delivery") {
22296
- delivery.closeBudget();
22297
- }
22298
- if (output === void 0 && delivery.nextAction() === "no-receipt" && activeSession.providerFailure?.() === void 0) {
22299
- preparedAdvice = void 0;
22300
- return void 0;
22301
- }
22302
- } catch (error) {
22303
- throw error instanceof NavigatorUnavailableError ? error : navigatorUnavailableError("transport", error);
22304
- }
22305
- if (output === void 0) {
22306
- const nativeFailure = [...activeSession.entries()].reverse().find((entry) => {
22307
- if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message)) return false;
22308
- return entry.message.role === "assistant" && typeof entry.message.errorMessage === "string" && entry.message.errorMessage.trim() !== "";
22309
- });
22310
- const nativeMessage = isRecord(nativeFailure) && isRecord(nativeFailure.message) ? nativeFailure.message : void 0;
22311
- const errorMessage = nativeMessage !== void 0 && typeof nativeMessage.errorMessage === "string" ? nativeMessage.errorMessage : "Navigator did not submit direction advice";
22312
- const providerFailure = activeSession.providerFailure?.();
22313
- const source = providerFailure?.source ?? "unknown";
22314
- const cause = providerFailure?.cause ?? source;
22315
- throw navigatorUnavailableError(source, errorMessage, cause);
22316
- }
22317
- preparedAdvice = normalizePreparedAdvice(output);
22318
- return preparedAdvice;
22319
- } finally {
22320
- const playbookFailure = activeSession.routePlaybookReadFailure?.();
22321
- observedRoutePlaybookFailure = typeof playbookFailure === "string" && playbookFailure.trim() !== "" ? playbookFailure : void 0;
22322
- outputSink = void 0;
22323
- }
22324
- };
22325
- return {
22326
- setWorkContext(next) {
22327
- let closing2;
22328
- if (next.subjectKey !== subjectKey && session !== void 0) {
22329
- const previous = session;
22330
- session = void 0;
22331
- closing2 = previous.dispose();
22332
- }
22333
- subjectKey = next.subjectKey;
22334
- contextError = next.contextError;
22335
- return closing2;
22336
- },
22337
- prepare() {
22338
- if (disposed || preparation !== void 0) return;
22339
- preparationFailure = void 0;
22340
- preparedAdvice = void 0;
22341
- preparationInFlight = true;
22342
- preparation = prepare().finally(() => {
22343
- preparationInFlight = false;
22344
- });
22345
- void preparation.catch((error) => {
22346
- preparationFailure = error;
22347
- });
22348
- },
22349
- isPreparing() {
22350
- return preparationInFlight;
22351
- },
22352
- settle(settlement) {
22353
- const next = settlementTail.then(() => settleOnce(settlement));
22354
- settlementTail = next.catch((error) => {
22355
- settlementFailure = error;
22356
- });
22357
- return next;
22358
- },
22359
- dispose() {
22360
- disposed = true;
22361
- if (!nestCancel.signal.aborted) {
22362
- nestCancel.abort(navigatorUnavailableError(
22363
- "session",
22364
- new Error("Navigator attendance was disposed")
22365
- ));
22366
- }
22367
- activeInvocationId = void 0;
22368
- if (closing === void 0) {
22369
- const current = session;
22370
- session = void 0;
22371
- closing = Promise.resolve(current?.dispose()).then(() => void 0);
22372
- }
22373
- return closing;
22374
- }
22375
- };
22376
21755
  async function settleOnce(settlement) {
22377
21756
  if (disposed) return;
22378
- const invocationId = activeInvocationId ?? invocationPrincipal;
22379
21757
  let report;
22380
- const settlementFact = {
22381
- invocationId,
22382
- subjectKey,
22383
- role: settlement.role,
22384
- phase: settlement.phase,
22385
- kind: settlement.kind,
22386
- ..."status" in settlement && settlement.status !== void 0 ? { status: settlement.status } : {}
22387
- };
22388
21758
  if (settlement.kind === "arrival") {
22389
- if (sessionReady !== void 0) {
22390
- try {
22391
- await sessionReady;
22392
- } catch (error) {
22393
- preparationFailure ??= error;
22394
- }
22395
- }
22396
- session?.appendEntry(SETTLEMENT_ENTRY, settlementFact);
22397
- if (preparationFailure !== void 0) {
22398
- report = unavailable(invocationId, preparationFailure);
22399
- } else {
22400
- report = {
22401
- disposition: "arrival",
22402
- ...settlement.message === void 0 ? {} : { arrivalMessage: settlement.message }
22403
- };
22404
- }
21759
+ report = preparationFailure !== void 0 ? unavailable(preparationFailure) : {
21760
+ disposition: "arrival",
21761
+ ...settlement.message === void 0 ? {} : { arrivalMessage: settlement.message }
21762
+ };
22405
21763
  } else {
22406
- if (sessionReady !== void 0) {
22407
- try {
22408
- await sessionReady;
22409
- } catch (error) {
22410
- preparationFailure ??= error;
22411
- }
22412
- }
22413
21764
  if (preparation !== void 0) {
22414
21765
  try {
22415
21766
  await preparation;
@@ -22418,22 +21769,14 @@ function createNavigatorAttendance(options) {
22418
21769
  }
22419
21770
  preparation = void 0;
22420
21771
  }
22421
- session?.appendEntry(SETTLEMENT_ENTRY, settlementFact);
22422
21772
  if (preparationFailure !== void 0) {
22423
- report = unavailable(invocationId, preparationFailure);
21773
+ report = unavailable(preparationFailure);
22424
21774
  } else {
22425
21775
  const status = "status" in settlement ? settlement.status : void 0;
22426
21776
  const picked = pickPreparedProse(preparedAdvice, status);
22427
- if (typeof picked === "string" && picked.trim() !== "") {
22428
- report = { disposition: "advice", prose: picked };
22429
- } else {
22430
- report = { disposition: "no-advice" };
22431
- }
21777
+ report = typeof picked === "string" && picked.trim() !== "" ? { disposition: "advice", prose: picked } : { disposition: "no-advice" };
22432
21778
  }
22433
21779
  }
22434
- if (observedRoutePlaybookFailure !== void 0) {
22435
- report = { ...report, routePlaybookReadFailure: observedRoutePlaybookFailure };
22436
- }
22437
21780
  const event = {
22438
21781
  version: 1,
22439
21782
  disposition: report.disposition,
@@ -22444,8 +21787,6 @@ function createNavigatorAttendance(options) {
22444
21787
  ...report.prose === void 0 ? {} : { prose: report.prose },
22445
21788
  ...report.unavailableReason === void 0 ? {} : { unavailableReason: report.unavailableReason },
22446
21789
  ...report.unavailableSource === void 0 ? {} : { unavailableSource: report.unavailableSource },
22447
- ...report.unavailableCause === void 0 ? {} : { unavailableCause: report.unavailableCause },
22448
- ...report.routePlaybookReadFailure === void 0 ? {} : { routePlaybookReadFailure: report.routePlaybookReadFailure },
22449
21790
  ...report.arrivalMessage === void 0 ? {} : { arrivalMessage: report.arrivalMessage }
22450
21791
  };
22451
21792
  if (disposed) return;
@@ -22456,11 +21797,40 @@ function createNavigatorAttendance(options) {
22456
21797
  throw error;
22457
21798
  }
22458
21799
  preparation = void 0;
22459
- sessionReady = void 0;
22460
21800
  preparedAdvice = void 0;
22461
21801
  preparationFailure = void 0;
22462
- observedRoutePlaybookFailure = void 0;
22463
21802
  }
21803
+ return {
21804
+ prepare() {
21805
+ if (disposed || preparation !== void 0 || options.phase === "plan") return;
21806
+ preparationFailure = void 0;
21807
+ preparedAdvice = void 0;
21808
+ preparationInFlight = true;
21809
+ preparation = options.lookup({ context: lookupContext(), role: options.role }).then((prepared) => {
21810
+ preparedAdvice = prepared;
21811
+ return prepared;
21812
+ }).finally(() => {
21813
+ preparationInFlight = false;
21814
+ });
21815
+ void preparation.catch((error) => {
21816
+ preparationFailure = error;
21817
+ });
21818
+ },
21819
+ isPreparing() {
21820
+ return preparationInFlight;
21821
+ },
21822
+ settle(settlement) {
21823
+ const next = settlementTail.then(() => settleOnce(settlement));
21824
+ settlementTail = next.catch(() => void 0);
21825
+ return next;
21826
+ },
21827
+ dispose() {
21828
+ disposed = true;
21829
+ if (!nestCancel.signal.aborted) {
21830
+ nestCancel.abort(navigatorUnavailableError("session", new Error("Navigator attendance was disposed")));
21831
+ }
21832
+ }
21833
+ };
22464
21834
  }
22465
21835
 
22466
21836
  // src/role-runtime.ts
@@ -22518,7 +21888,7 @@ init_submission_errors();
22518
21888
  init_worker_submission_contracts();
22519
21889
  import { execFileSync as execFileSync3 } from "node:child_process";
22520
21890
  import { existsSync as existsSync14, lstatSync as lstatSync3, readdirSync as readdirSync4, readFileSync as readFileSync5, rmdirSync, rmSync as rmSync4 } from "node:fs";
22521
- import { resolve as resolve16 } from "node:path";
21891
+ import { resolve as resolve15 } from "node:path";
22522
21892
  var WORKER_COMMIT_BASELINE_ENTRY_TYPE = "commit-baseline";
22523
21893
  var WORKER_COMMIT_REMINDER_BOUNCE_ENTRY_TYPE = "commit-reminder-bounce";
22524
21894
  var WORKER_PREFIX_REMINDER_BOUNCE_ENTRY_TYPE = "prefix-reminder-bounce";
@@ -22566,7 +21936,7 @@ function escapeGitConfigValueRegex(value) {
22566
21936
  function unsetOwnedHooksPath(file) {
22567
21937
  const owned = [];
22568
21938
  for (const value of tryGetAll(file, "core.hooksPath")) {
22569
- if (!ownedHook(resolve16(value, HOOK_FILE))) continue;
21939
+ if (!ownedHook(resolve15(value, HOOK_FILE))) continue;
22570
21940
  try {
22571
21941
  gitFile(file, [
22572
21942
  "--unset-all",
@@ -22581,15 +21951,15 @@ function unsetOwnedHooksPath(file) {
22581
21951
  return owned;
22582
21952
  }
22583
21953
  function rmOwnedDir(dir) {
22584
- const hookPath = resolve16(dir, HOOK_FILE);
21954
+ const hookPath = resolve15(dir, HOOK_FILE);
22585
21955
  if (!ownedHook(hookPath)) return;
22586
21956
  rmSync4(hookPath, { force: true });
22587
21957
  if (existsSync14(dir) && readdirSync4(dir).length === 0) rmdirSync(dir);
22588
21958
  }
22589
21959
  function linkedGitDirs(commonDir) {
22590
- const root = resolve16(commonDir, "worktrees");
21960
+ const root = resolve15(commonDir, "worktrees");
22591
21961
  if (!existsSync14(root)) return [];
22592
- return readdirSync4(root).map((name) => resolve16(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
21962
+ return readdirSync4(root).map((name) => resolve15(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
22593
21963
  }
22594
21964
  function uninstallPackageWorkerHooks(cwd) {
22595
21965
  let inside;
@@ -22603,14 +21973,14 @@ function uninstallPackageWorkerHooks(cwd) {
22603
21973
  const clear = (configFile) => {
22604
21974
  for (const hooks of unsetOwnedHooksPath(configFile)) rmOwnedDir(hooks);
22605
21975
  };
22606
- clear(resolve16(commonDir, "config"));
22607
- clear(resolve16(commonDir, "config.worktree"));
22608
- rmOwnedDir(resolve16(commonDir, HOOKS_DIR));
22609
- const legacy = resolve16(commonDir, "hooks", HOOK_FILE);
21976
+ clear(resolve15(commonDir, "config"));
21977
+ clear(resolve15(commonDir, "config.worktree"));
21978
+ rmOwnedDir(resolve15(commonDir, HOOKS_DIR));
21979
+ const legacy = resolve15(commonDir, "hooks", HOOK_FILE);
22610
21980
  if (ownedHook(legacy)) rmSync4(legacy, { force: true });
22611
21981
  for (const gitDir of linkedGitDirs(commonDir)) {
22612
- clear(resolve16(gitDir, "config.worktree"));
22613
- rmOwnedDir(resolve16(gitDir, HOOKS_DIR));
21982
+ clear(resolve15(gitDir, "config.worktree"));
21983
+ rmOwnedDir(resolve15(gitDir, HOOKS_DIR));
22614
21984
  }
22615
21985
  }
22616
21986
  function containsWrittenReason(value) {
@@ -23153,7 +22523,7 @@ function activationStage(role, activate) {
23153
22523
  };
23154
22524
  }
23155
22525
  function validateActivationTraceRecord(record) {
23156
- if (!Value3.Check(activationTraceRecordSchema, record)) {
22526
+ if (!Value2.Check(activationTraceRecordSchema, record)) {
23157
22527
  throw new TypeError("Activation trace record does not match its closed contract");
23158
22528
  }
23159
22529
  return record;
@@ -23341,50 +22711,6 @@ function createGatekeeperRoleRuntime(roleHost, dependencies) {
23341
22711
  dependencies
23342
22712
  );
23343
22713
  }
23344
- function createNavigatorRoleRuntime(roleHost, dependencies) {
23345
- const base = createFiledOfficerRuntime(
23346
- roleHost,
23347
- {
23348
- role: "navigator",
23349
- tool: NAVIGATOR_TOOL_SPEC,
23350
- soulTag: "navigator"
23351
- },
23352
- dependencies
23353
- );
23354
- let playbookBound = false;
23355
- return {
23356
- async activate() {
23357
- await base.activate();
23358
- if (playbookBound) return;
23359
- playbookBound = true;
23360
- const loadRoutePlaybook = dependencies.loadRoutePlaybook ?? (() => readPackageMaterial("resources/navigator-route-playbook.md"));
23361
- let playbookRead;
23362
- roleHost.on("before_agent_start", async (event, ctx) => {
23363
- const basePrompt = typeof event.systemPrompt === "string" ? event.systemPrompt : "";
23364
- const parts = [];
23365
- try {
23366
- playbookRead ??= loadRoutePlaybook();
23367
- const content = await playbookRead;
23368
- dependencies.recordRoutePlaybookReadFailure?.(void 0);
23369
- if (content.trim() !== "") parts.push(content);
23370
- } catch (error) {
23371
- const message = errorText(error);
23372
- if (message.trim() !== "") {
23373
- dependencies.recordRoutePlaybookReadFailure?.(message);
23374
- parts.push(message);
23375
- }
23376
- }
23377
- if (parts.length === 0) return;
23378
- const text = parts.join("\n\n");
23379
- return {
23380
- systemPrompt: basePrompt.trim() === "" ? text : `${basePrompt}
23381
-
23382
- ${text}`
23383
- };
23384
- });
23385
- }
23386
- };
23387
- }
23388
22714
  function createAuditorRoleRuntime(roleHost, dependencies) {
23389
22715
  return createFiledOfficerRuntime(
23390
22716
  roleHost,
@@ -23431,7 +22757,7 @@ function readRoleRunCoordinates(ctx, label) {
23431
22757
  if (runDirectory === void 0) throw new Error(`${label} requires AK_ROLE_RUN_DIR`);
23432
22758
  const admitted = readPageSync(runDirectory, "admitted");
23433
22759
  if (typeof admitted?.projectRoot !== "string" || admitted.projectRoot.trim() === "") {
23434
- throw new Error(`${label} state.jsonl admitted-request row missing projectRoot (${join31(runDirectory, RUN_STATE_FILE)})`);
22760
+ throw new Error(`${label} state.jsonl admitted-request row missing projectRoot (${join30(runDirectory, RUN_STATE_FILE)})`);
23435
22761
  }
23436
22762
  return {
23437
22763
  runDirectory,
@@ -23542,21 +22868,6 @@ function createCountersignRoleRuntime(roleHost, dependencies) {
23542
22868
  dependencies
23543
22869
  );
23544
22870
  }
23545
- function lastAssistantProse(messages) {
23546
- for (let index = messages.length - 1; index >= 0; index -= 1) {
23547
- const message = messages[index];
23548
- if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
23549
- const texts = [];
23550
- for (const part of message.content) {
23551
- if (part.type === "text" && typeof part.text === "string" && part.text.length > 0) {
23552
- texts.push(part.text);
23553
- }
23554
- }
23555
- if (texts.length === 0) continue;
23556
- return texts.join("");
23557
- }
23558
- return void 0;
23559
- }
23560
22871
  function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
23561
22872
  const deliveryLimit = deliveryRequestLimit === void 0 ? deliveryLimitFromEnv(process.env) : deliveryLimitFromConfig(deliveryRequestLimit);
23562
22873
  return (envelopeHost) => {
@@ -23609,7 +22920,7 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
23609
22920
  let navigatorActivation = 0;
23610
22921
  let navigatorDeliveryClosed = false;
23611
22922
  let pendingNavigatorSettlement;
23612
- let navigatorWorkContext;
22923
+ let navigatorSubjectKey;
23613
22924
  let navigatorSessionParent;
23614
22925
  let navigatorCwd;
23615
22926
  const pendingInfrastructureFailures = /* @__PURE__ */ new Map();
@@ -23652,7 +22963,7 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
23652
22963
  const settleNavigatorProjection = async (settlement) => {
23653
22964
  const attendance = navigatorAttendance;
23654
22965
  if (settlement === void 0 || attendance === void 0) return;
23655
- const workContext = navigatorWorkContext;
22966
+ const subjectKey = navigatorSubjectKey;
23656
22967
  const pending = (async () => {
23657
22968
  const settlePromise = attendance.settle(settlement);
23658
22969
  void settlePromise.catch(() => void 0);
@@ -23663,8 +22974,7 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
23663
22974
  const report = {
23664
22975
  disposition: "unavailable",
23665
22976
  unavailableReason: "Navigator exceeded post-role delivery grace",
23666
- unavailableSource: "unknown",
23667
- unavailableCause: "unknown"
22977
+ unavailableSource: "unknown"
23668
22978
  };
23669
22979
  const event = {
23670
22980
  version: 1,
@@ -23672,10 +22982,9 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
23672
22982
  invocationId: "post-role-grace-timeout",
23673
22983
  role: settlement.role,
23674
22984
  phase: settlement.phase,
23675
- subjectKey: workContext?.subjectKey ?? "",
22985
+ subjectKey: subjectKey ?? "",
23676
22986
  unavailableReason: "Navigator exceeded post-role delivery grace",
23677
- unavailableSource: "unknown",
23678
- unavailableCause: "unknown"
22987
+ unavailableSource: "unknown"
23679
22988
  };
23680
22989
  pendingNavigatorPresentation = { event, report };
23681
22990
  }
@@ -23718,21 +23027,6 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
23718
23027
  ctx.sessionManager.appendCustomEntry?.(NOTARY_SESSION_BOUND_ENTRY, bound);
23719
23028
  }
23720
23029
  }
23721
- if (navigatorAttendance !== void 0 && navigatorWorkContext !== void 0 && navigatorWorkContext.contextError === void 0) {
23722
- if (navigatorWorkContext.subjectProvenance === "placeholder") {
23723
- const subject = prompt.trim();
23724
- if (subject !== "") {
23725
- const root = subjectPath(ctx.sessionManager.getSessionDir(), ctx.cwd);
23726
- const subjectProvenance = "user_prompt";
23727
- navigatorWorkContext = {
23728
- subjectKey: navigatorSubjectKey(root, subject, subjectProvenance),
23729
- subjectProvenance
23730
- };
23731
- await navigatorAttendance.setWorkContext(navigatorWorkContext);
23732
- }
23733
- }
23734
- }
23735
- navigatorAttendance?.prepare();
23736
23030
  if (activeReviewerParent !== void 0 && selectedRole === role) {
23737
23031
  return {
23738
23032
  systemPrompt: assembleReviewerParentSystemPrompt({
@@ -23816,47 +23110,6 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
23816
23110
  }
23817
23111
  return;
23818
23112
  }
23819
- const role = selectedRole ?? roleHost.getFlag(ROLE_FLAG.name);
23820
- if (typeof role === "string" && packagedRoleOutputTool(role) === NAVIGATOR_TOOL_SPEC.name && receiptDelivery.nextAction() !== "accepted") {
23821
- const prose = lastAssistantProse(event.messages);
23822
- if (prose !== void 0 && prose.trim() !== "") {
23823
- const accepted = { prose };
23824
- const toolCallId = `navigator-prose-exit:${randomUUID7()}`;
23825
- await sealAcceptedSubmission({
23826
- context: ctx,
23827
- role: "navigator",
23828
- accepted,
23829
- toolCallId
23830
- });
23831
- await projectClosedSubmission(
23832
- { role: "navigator", kind: "accepted", accepted },
23833
- ctx,
23834
- toolCallId
23835
- );
23836
- return;
23837
- }
23838
- if (!noReceiptRecorded) {
23839
- const runPointer = runDirectoryFromHostContext(ctx);
23840
- if (runPointer !== void 0) {
23841
- noReceiptRecorded = true;
23842
- receiptDelivery.closeBudget();
23843
- const facts = receiptDelivery.facts({
23844
- runPointer,
23845
- attemptPointer: receiptAttemptPointer(runPointer, ctx.invocationScopeId)
23846
- });
23847
- envelopeHost.appendEntry(NO_RECEIPT_LIFECYCLE_ENTRY_TYPE, facts);
23848
- sitianReportSafe({
23849
- level: "event",
23850
- kind: "no-receipt-lifecycle",
23851
- cwd: ctx.cwd,
23852
- sessionParent: ctx.sessionManager.getSessionFile(),
23853
- payload: facts,
23854
- source: "role-runtime"
23855
- });
23856
- }
23857
- }
23858
- return;
23859
- }
23860
23113
  if (receiptDelivery.nextAction() === "request-delivery") {
23861
23114
  receiptDelivery.recordDeliveryRequest();
23862
23115
  const deliveryContent = turnDialoguePrompt ?? "";
@@ -24005,14 +23258,6 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
24005
23258
  const gatekeeper = createGatekeeperRoleRuntime(roleHost, {
24006
23259
  loadSoul: () => requireRoleSoul("gatekeeper")
24007
23260
  });
24008
- const navigator = createNavigatorRoleRuntime(roleHost, {
24009
- loadSoul: () => requireRoleSoul("navigator"),
24010
- recordRoutePlaybookReadFailure: (message) => {
24011
- envelopeHost.appendEntry(NAVIGATOR_ROUTE_PLAYBOOK_FAILURE_ENTRY, {
24012
- message: message ?? ""
24013
- });
24014
- }
24015
- });
24016
23261
  const auditor = createAuditorRoleRuntime(roleHost, {
24017
23262
  loadSoul: () => requireRoleSoul("auditor")
24018
23263
  });
@@ -24119,7 +23364,7 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
24119
23364
  navigatorDeliveryClosed = false;
24120
23365
  pendingNavigatorSettlement = void 0;
24121
23366
  pendingInfrastructureFailures.clear();
24122
- navigatorWorkContext = void 0;
23367
+ navigatorSubjectKey = void 0;
24123
23368
  envelopeHost.startKeepalive(ctx);
24124
23369
  const rawRole = roleHost.getFlag(ROLE_FLAG.name);
24125
23370
  if (rawRole === void 0) return;
@@ -24148,7 +23393,9 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
24148
23393
  "gleaner-left": () => gleanerLeft.activate(),
24149
23394
  inspector: () => inspector.activate(),
24150
23395
  gatekeeper: () => gatekeeper.activate(),
24151
- navigator: () => navigator.activate(),
23396
+ navigator: async () => {
23397
+ throw new Error("navigator is a table lookup (#1192); no host runtime serves it");
23398
+ },
24152
23399
  auditor: () => auditor.activate(),
24153
23400
  diarist: () => diarist.activate(),
24154
23401
  secretariat: () => secretariat.activate(),
@@ -24164,37 +23411,16 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
24164
23411
  );
24165
23412
  }
24166
23413
  const isStationChild = roleHost.getFlag(STATION_CHILD_FLAG.name) === true;
24167
- if (dependencies.createNavigatorAttendance !== void 0 && entry.outputTool !== NAVIGATOR_TOOL_SPEC.name && !isStationChild) {
23414
+ if (dependencies.createNavigatorAttendance !== void 0 && !isNavigatorSeat(entry.role) && !isStationChild) {
24168
23415
  navigatorSessionParent = ctx.sessionManager.getSessionFile();
24169
23416
  navigatorCwd = ctx.cwd;
24170
- let work;
24171
- let contextError;
24172
- if (dependencies.loadNavigatorWorkContext === void 0) {
24173
- const fallbackSubjectKey = subjectPath(ctx.sessionManager.getSessionDir(), ctx.cwd);
24174
- contextError = new Error("Navigator work context loader is not configured");
24175
- work = { subjectKey: fallbackSubjectKey, subjectProvenance: "placeholder" };
24176
- } else {
24177
- try {
24178
- work = await dependencies.loadNavigatorWorkContext({
24179
- context: ctx,
24180
- role: entry.role,
24181
- phase: navigatorPhase(roleHost, entry.role),
24182
- getFlag: (name) => roleHost.getFlag(name)
24183
- });
24184
- contextError = work.contextError;
24185
- } catch (error) {
24186
- contextError = navigatorUnavailableError("context", error);
24187
- const fallbackSubjectKey = subjectPath(ctx.sessionManager.getSessionDir(), ctx.cwd);
24188
- work = { subjectKey: fallbackSubjectKey, subjectProvenance: "placeholder" };
24189
- }
24190
- }
24191
- navigatorWorkContext = { ...work, ...contextError === void 0 ? {} : { contextError } };
23417
+ navigatorSubjectKey = subjectPath(ctx.sessionManager.getSessionDir(), ctx.cwd);
24192
23418
  const sessionEntries = [...ctx.sessionManager.getEntries()];
24193
23419
  const invocationPhase = navigatorPhase(roleHost, entry.role);
24194
23420
  const lifecyclePrincipal = resolveLifecycleInvocationPrincipal(sessionEntries, {
24195
23421
  role: entry.role,
24196
23422
  phase: invocationPhase,
24197
- subjectKey: work.subjectKey
23423
+ subjectKey: navigatorSubjectKey
24198
23424
  });
24199
23425
  const invocationId = lifecyclePrincipal.invocationId;
24200
23426
  if (!lifecyclePrincipal.resume) {
@@ -24202,7 +23428,7 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
24202
23428
  invocationId,
24203
23429
  role: entry.role,
24204
23430
  phase: invocationPhase,
24205
- subjectKey: work.subjectKey
23431
+ subjectKey: navigatorSubjectKey
24206
23432
  };
24207
23433
  envelopeHost.appendEntry(NAVIGATOR_INVOCATION_ENTRY, data);
24208
23434
  sitianReportSafe({
@@ -24219,19 +23445,15 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
24219
23445
  context: ctx,
24220
23446
  role: entry.role,
24221
23447
  phase: invocationPhase,
24222
- subjectKey: work.subjectKey,
23448
+ subjectKey: navigatorSubjectKey,
24223
23449
  invocationId,
24224
- deliveryRequestLimit: deliveryLimit,
24225
- ...contextError === void 0 ? {} : { contextError },
24226
23450
  onEvent: (navigatorEvent, report) => {
24227
23451
  if (activation === navigatorActivation && !navigatorDeliveryClosed) {
24228
23452
  pendingNavigatorPresentation = { event: navigatorEvent, report };
24229
23453
  }
24230
23454
  }
24231
23455
  });
24232
- if (navigatorWorkContext.contextError === void 0 && navigatorWorkContext.subjectProvenance !== "placeholder") {
24233
- navigatorAttendance.prepare();
24234
- }
23456
+ navigatorAttendance.prepare();
24235
23457
  }
24236
23458
  await executeActivationStage(entry.role, activationStage(entry.role, activateByRole), { clock, writeTrace });
24237
23459
  registerReportTicketTool(roleHost, hostActions);
@@ -24294,11 +23516,11 @@ function formatPiSessionJsonlLine(entry) {
24294
23516
 
24295
23517
  // src/role-envelope.ts
24296
23518
  async function listen(server, path) {
24297
- await new Promise((resolve19, reject) => {
23519
+ await new Promise((resolve17, reject) => {
24298
23520
  server.once("error", reject);
24299
23521
  server.listen(path, () => {
24300
23522
  server.off("error", reject);
24301
- resolve19();
23523
+ resolve17();
24302
23524
  });
24303
23525
  });
24304
23526
  }
@@ -24334,7 +23556,7 @@ async function prepareRoleEnvelope(options) {
24334
23556
  const runId = request.runDirectory.split("/").filter(Boolean).at(-1) ?? randomUUID9();
24335
23557
  await mkdir3(request.runDirectory, { recursive: true });
24336
23558
  let sessionFile = options.sessionFile ?? sessionFileOf(request.runDirectory);
24337
- await mkdir3(dirname19(sessionFile), { recursive: true });
23559
+ await mkdir3(dirname18(sessionFile), { recursive: true });
24338
23560
  if (request.continuation.kind !== "resume") {
24339
23561
  try {
24340
23562
  await writeFile5(
@@ -24376,7 +23598,7 @@ async function prepareRoleEnvelope(options) {
24376
23598
  getLeafEntry: () => sessionEntries.at(-1),
24377
23599
  getLeafId: () => runId,
24378
23600
  getEntries: () => sessionEntries,
24379
- getSessionDir: () => dirname19(sessionFile),
23601
+ getSessionDir: () => dirname18(sessionFile),
24380
23602
  getSessionFile: () => sessionFile,
24381
23603
  getHeader: () => ({ type: "session", id: runId }),
24382
23604
  setSessionFile(path) {
@@ -24732,8 +23954,8 @@ async function prepareRoleEnvelope(options) {
24732
23954
  try {
24733
23955
  const closeAll = server.closeAllConnections;
24734
23956
  if (typeof closeAll === "function") closeAll.call(server);
24735
- await new Promise((resolve19, reject) => {
24736
- server.close((error) => error ? reject(error) : resolve19());
23957
+ await new Promise((resolve17, reject) => {
23958
+ server.close((error) => error ? reject(error) : resolve17());
24737
23959
  });
24738
23960
  } catch (error) {
24739
23961
  await retainPackageFault({
@@ -24872,61 +24094,6 @@ async function prepareRoleEnvelope(options) {
24872
24094
  // src/role-runtime-dependencies.ts
24873
24095
  import { readFile as readFile15 } from "node:fs/promises";
24874
24096
  init_doctor_evidence();
24875
-
24876
- // src/navigator-work-context.ts
24877
- init_role_run_placement();
24878
- init_host_contracts();
24879
- import { resolve as resolve17 } from "node:path";
24880
- init_packaged_role_registry();
24881
- init_invocation();
24882
- function navigatorInputReference(getFlag, role) {
24883
- if (getFlag === void 0) return void 0;
24884
- const name = packagedRoleInputFlag(role);
24885
- const value = name === void 0 ? void 0 : getFlag(name);
24886
- return typeof value === "string" && value !== "" ? resolve17(value) : void 0;
24887
- }
24888
- async function loadNavigatorWorkContext(options) {
24889
- const reference = navigatorInputReference(options.getFlag, options.role);
24890
- const subjectMode = packagedNavigatorSubject(options.role);
24891
- const subjectRoot = subjectPath(reference ?? options.context.sessionManager.getSessionDir(), options.context.cwd);
24892
- const subjectKey = reference === void 0 ? subjectRoot : navigatorSubjectKeyForInput(subjectRoot, reference, options.context.cwd);
24893
- const publicRunDir = runDirectoryFromHostContext(options.context);
24894
- const currentSessionDir = options.context.sessionManager.getSessionDir();
24895
- const isBoundPublicRun = publicRunDir !== void 0 && resolve17(currentSessionDir) === resolve17(sessionDirectoryOf(publicRunDir));
24896
- if (subjectMode === "public-instruction" && isBoundPublicRun) {
24897
- let admitted;
24898
- try {
24899
- admitted = await loadAdmittedJudgeRequest(publicRunDir);
24900
- } catch (error) {
24901
- throw navigatorUnavailableError("context", error);
24902
- }
24903
- if (admitted === void 0) {
24904
- throw navigatorUnavailableError(
24905
- "context",
24906
- new Error("public Judge admitted request was missing or malformed")
24907
- );
24908
- }
24909
- if (!admitted.instructionEmpty && admitted.instruction.trim() !== "") {
24910
- return {
24911
- subjectKey: subjectRoot,
24912
- subjectProvenance: "role_input"
24913
- };
24914
- }
24915
- return {
24916
- subjectKey: subjectRoot,
24917
- subjectProvenance: "placeholder"
24918
- };
24919
- }
24920
- if (reference !== void 0) {
24921
- return { subjectKey, subjectProvenance: "role_input" };
24922
- }
24923
- return {
24924
- subjectKey: subjectRoot,
24925
- subjectProvenance: "placeholder"
24926
- };
24927
- }
24928
-
24929
- // src/role-runtime-dependencies.ts
24930
24097
  init_notary_source_run();
24931
24098
  init_auditor_soul();
24932
24099
  init_packaged_role_registry();
@@ -24942,7 +24109,7 @@ function loadRegisteredRoleSoul(role) {
24942
24109
  return usesSubjectSoul(role) ? loadAuditorSoulFromSubjectInput() : loadMainRoleSessionMaterials(role);
24943
24110
  }
24944
24111
  function createRoleRuntimeDependencies(packageRoot) {
24945
- const navigatorSessionFactory = createNativeNavigatorSessionFactory();
24112
+ const navigatorLookup = createNavigatorLookup();
24946
24113
  return {
24947
24114
  packageRoot,
24948
24115
  loadRoleReferenceMaterials: loadPackagedRoleReferenceMaterials,
@@ -24950,20 +24117,13 @@ function createRoleRuntimeDependencies(packageRoot) {
24950
24117
  loadDoctorCase,
24951
24118
  loadNotarySourceRun: loadNotarySourceRunLocator,
24952
24119
  loadMergerInput: async (path) => JSON.parse(await readFile15(path, "utf8")),
24953
- loadNavigatorWorkContext: (options) => loadNavigatorWorkContext({
24954
- context: options.context,
24955
- role: options.role,
24956
- ...options.getFlag === void 0 ? {} : { getFlag: options.getFlag }
24957
- }),
24958
24120
  createNavigatorAttendance: (options) => createNavigatorAttendance({
24959
24121
  context: options.context,
24960
24122
  role: options.role,
24961
24123
  phase: options.phase,
24962
24124
  subjectKey: options.subjectKey,
24963
24125
  invocationId: options.invocationId,
24964
- createSession: navigatorSessionFactory,
24965
- ...options.deliveryRequestLimit === void 0 ? {} : { deliveryRequestLimit: options.deliveryRequestLimit },
24966
- ...options.contextError === void 0 ? {} : { contextError: options.contextError },
24126
+ lookup: navigatorLookup,
24967
24127
  onEvent: options.onEvent
24968
24128
  })
24969
24129
  };
@@ -24997,7 +24157,6 @@ init_external_host_turn_loop();
24997
24157
  init_run_lifecycle();
24998
24158
  init_settlement();
24999
24159
  init_host_session_record();
25000
- init_navigator_output();
25001
24160
  import { spawn as spawn3 } from "node:child_process";
25002
24161
  import { createInterface } from "node:readline";
25003
24162
 
@@ -25017,42 +24176,6 @@ async function resolveBoundHostSessionId(request, identity) {
25017
24176
  }
25018
24177
 
25019
24178
  // src/acp-host/role-turn-host.ts
25020
- init_unknown_value();
25021
- function acpAgentTextChunk(params) {
25022
- let kind;
25023
- let content;
25024
- let textFallback;
25025
- const nested = params.update;
25026
- if (isRecord(nested)) {
25027
- const record = nested;
25028
- kind = record.sessionUpdate;
25029
- content = record.content;
25030
- textFallback = record.text;
25031
- } else {
25032
- kind = params.sessionUpdate ?? nested;
25033
- content = params.content;
25034
- textFallback = params.text;
25035
- }
25036
- if (kind !== "agent_message_chunk" && kind !== "agent_message") return void 0;
25037
- if (typeof content === "string" && content.length > 0) return content;
25038
- if (isRecord(content)) {
25039
- const record = content;
25040
- if (typeof record.text === "string" && record.text.length > 0) return record.text;
25041
- }
25042
- if (Array.isArray(content)) {
25043
- const parts = [];
25044
- for (const part of content) {
25045
- if (typeof part === "string" && part.length > 0) parts.push(part);
25046
- else if (typeof part === "object" && part !== null) {
25047
- const record = part;
25048
- if (typeof record.text === "string" && record.text.length > 0) parts.push(record.text);
25049
- }
25050
- }
25051
- if (parts.length > 0) return parts.join("");
25052
- }
25053
- if (typeof textFallback === "string" && textFallback.length > 0) return textFallback;
25054
- return void 0;
25055
- }
25056
24179
  function acpError(code, message, cause) {
25057
24180
  return Object.assign(new Error(message, cause === void 0 ? void 0 : { cause }), { code });
25058
24181
  }
@@ -25129,19 +24252,19 @@ function connectAcpStdio(options) {
25129
24252
  terminate(error);
25130
24253
  }
25131
24254
  });
25132
- const processClosed = new Promise((resolve19) => {
24255
+ const processClosed = new Promise((resolve17) => {
25133
24256
  child.once("close", (code, signal) => {
25134
24257
  if (spawned) nativeExit = { code, timedOut: false, ...signal === null ? {} : { signal } };
25135
24258
  settleClosed(acpError("acp-closed", "ACP process closed"));
25136
- resolve19();
24259
+ resolve17();
25137
24260
  });
25138
24261
  });
25139
24262
  return Promise.resolve({
25140
24263
  request(method, params) {
25141
24264
  if (closed) return Promise.reject(terminalError);
25142
24265
  const id = ++nextId;
25143
- return new Promise((resolve19, reject) => {
25144
- pending.set(id, { resolve: resolve19, reject });
24266
+ return new Promise((resolve17, reject) => {
24267
+ pending.set(id, { resolve: resolve17, reject });
25145
24268
  child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
25146
24269
  `, (error) => {
25147
24270
  if (error === null || error === void 0) return;
@@ -25196,16 +24319,6 @@ function createAcpRoleTurnHost(config) {
25196
24319
  } else {
25197
24320
  connection = await config.connect(request);
25198
24321
  const rpc = (method, params) => connection.request(method, params);
25199
- const agentProseChunks = [];
25200
- let collectAgentProse = false;
25201
- connection.onNotification?.((method, params) => {
25202
- const isSessionUpdate = method === "session/update";
25203
- if (!isSessionUpdate) return;
25204
- if (collectAgentProse) {
25205
- const chunk = acpAgentTextChunk(params);
25206
- if (chunk !== void 0) agentProseChunks.push(chunk);
25207
- }
25208
- });
25209
24322
  const initialized = await rpc("initialize", {
25210
24323
  protocolVersion: 1,
25211
24324
  clientCapabilities: {}
@@ -25293,25 +24406,15 @@ function createAcpRoleTurnHost(config) {
25293
24406
  outputSchema: deliveredSchema
25294
24407
  }, "acp-host");
25295
24408
  let result;
25296
- agentProseChunks.length = 0;
25297
- collectAgentProse = prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME;
25298
- try {
25299
- result = await raceAgainstHostAbort(
25300
- activeConnection.request("session/prompt", {
25301
- sessionId: activeSessionId,
25302
- prompt: [{ type: "text", text: prompt }]
25303
- }),
25304
- abortSignal,
25305
- "ACP host aborted"
25306
- );
25307
- } catch (error) {
25308
- collectAgentProse = false;
25309
- agentProseChunks.length = 0;
25310
- throw error;
25311
- }
25312
- collectAgentProse = false;
24409
+ result = await raceAgainstHostAbort(
24410
+ activeConnection.request("session/prompt", {
24411
+ sessionId: activeSessionId,
24412
+ prompt: [{ type: "text", text: prompt }]
24413
+ }),
24414
+ abortSignal,
24415
+ "ACP host aborted"
24416
+ );
25313
24417
  if (result.stopReason === "refusal") {
25314
- agentProseChunks.length = 0;
25315
24418
  reportedFailure = { diagnostic: result.stopReason, details: result };
25316
24419
  return {
25317
24420
  status: "terminal",
@@ -25323,15 +24426,6 @@ function createAcpRoleTurnHost(config) {
25323
24426
  }
25324
24427
  };
25325
24428
  }
25326
- if (prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME) {
25327
- const prose = agentProseChunks.join("");
25328
- agentProseChunks.length = 0;
25329
- if (navigatorProseFromUnknown(prose) !== void 0) {
25330
- await prepared.ingestStructuredOutput({ prose });
25331
- }
25332
- } else {
25333
- agentProseChunks.length = 0;
25334
- }
25335
24429
  return { status: "delivered", stderr: activeConnection.stderr?.() ?? "" };
25336
24430
  },
25337
24431
  async afterAccepted() {
@@ -25428,12 +24522,12 @@ function createAcpRoleTurnHost(config) {
25428
24522
  // src/acp-host/seat-profile-soul.ts
25429
24523
  import { constants as constants3 } from "node:fs";
25430
24524
  import { access as access3, copyFile, lstat as lstat4, mkdir as mkdir4, readlink, symlink as symlink2, unlink as unlink3 } from "node:fs/promises";
25431
- import { dirname as dirname20, join as join32, relative as relative4, resolve as resolve18 } from "node:path";
24525
+ import { dirname as dirname19, join as join31, relative as relative4, resolve as resolve16 } from "node:path";
25432
24526
  function seatProfileName(spec, role) {
25433
24527
  return `${spec.namePrefix}${role}`;
25434
24528
  }
25435
24529
  function packageRoleSoulPath(packageRoot, role) {
25436
- return join32(packageRoot, "souls", `${role}.md`);
24530
+ return join31(packageRoot, "souls", `${role}.md`);
25437
24531
  }
25438
24532
  async function pathExists2(path) {
25439
24533
  try {
@@ -25446,20 +24540,20 @@ async function pathExists2(path) {
25446
24540
  async function ensureSeatProfileSoul(options) {
25447
24541
  const { spec, operatorHome, packageRoot, role } = options;
25448
24542
  const profileName = seatProfileName(spec, role);
25449
- const soulTarget = resolve18(packageRoleSoulPath(packageRoot, role));
24543
+ const soulTarget = resolve16(packageRoleSoulPath(packageRoot, role));
25450
24544
  if (!await pathExists2(soulTarget)) {
25451
24545
  throw new Error(`packaged role soul missing: ${soulTarget}`);
25452
24546
  }
25453
- const profilesRoot = join32(operatorHome, ...spec.profilesRootFromHome);
25454
- const profileDir = join32(profilesRoot, profileName);
25455
- const hostRoot = dirname20(profilesRoot);
25456
- const soulPath = join32(profileDir, spec.soulFileName);
24547
+ const profilesRoot = join31(operatorHome, ...spec.profilesRootFromHome);
24548
+ const profileDir = join31(profilesRoot, profileName);
24549
+ const hostRoot = dirname19(profilesRoot);
24550
+ const soulPath = join31(profileDir, spec.soulFileName);
25457
24551
  if (!await pathExists2(profileDir)) {
25458
24552
  await mkdir4(profileDir, { recursive: true });
25459
24553
  for (const name of ["auth.json", ".env", "config.yaml"]) {
25460
- const source = join32(hostRoot, name);
24554
+ const source = join31(hostRoot, name);
25461
24555
  if (!await pathExists2(source)) continue;
25462
- await copyFile(source, join32(profileDir, name));
24556
+ await copyFile(source, join31(profileDir, name));
25463
24557
  }
25464
24558
  } else {
25465
24559
  await mkdir4(profileDir, { recursive: true });