@akagilnc/pi-workflow-roles 0.1.4239 → 0.1.4259

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.
@@ -3484,6 +3484,10 @@ ${paths.join("\n")}`
3484
3484
  };
3485
3485
  if (request.courtAttemptId === void 0) delete env.AK_ROLE_COURT_ATTEMPT;
3486
3486
  else env.AK_ROLE_COURT_ATTEMPT = request.courtAttemptId;
3487
+ if (request.invocationScopeId === void 0) delete env.AK_ROLE_INVOCATION_SCOPE;
3488
+ else env.AK_ROLE_INVOCATION_SCOPE = request.invocationScopeId;
3489
+ if (request.host === void 0 || request.host.trim() === "") delete env.AK_ROLE_HOST;
3490
+ else env.AK_ROLE_HOST = request.host.trim();
3487
3491
  applyEngineChildEnv(env, request.engine);
3488
3492
  if (typeof process.env.AK_ROLE_AUDITOR_SOURCE_RUN === "string" && process.env.AK_ROLE_AUDITOR_SOURCE_RUN.trim() !== "") {
3489
3493
  env.AK_ROLE_AUDITOR_SOURCE_RUN = process.env.AK_ROLE_AUDITOR_SOURCE_RUN;
@@ -10857,9 +10861,209 @@ var init_case_dossier_delivery = __esm({
10857
10861
  }
10858
10862
  });
10859
10863
 
10864
+ // src/engine-detour-usage.ts
10865
+ import { randomUUID as randomUUID4 } from "node:crypto";
10866
+ import { readFileSync as readFileSync3 } from "node:fs";
10867
+ import { dirname as dirname14, join as join23 } from "node:path";
10868
+ function engineDetourStdoutByteLength(stdout) {
10869
+ return Buffer.byteLength(stdout, "utf8");
10870
+ }
10871
+ function engineDetourCallIdentity(input) {
10872
+ const scope = input.invocationScopeId ?? "";
10873
+ return `engine-detour-call:${scope}:${input.toolCallId}`;
10874
+ }
10875
+ function reportEngineDetourCall(input) {
10876
+ const payload = {
10877
+ tool: ENGINE_DETOUR_TOOL_NAME,
10878
+ toolCallId: input.toolCallId,
10879
+ durationMs: input.durationMs
10880
+ };
10881
+ if (input.code !== void 0) payload.code = input.code;
10882
+ if (input.stdoutByteLength !== void 0) {
10883
+ payload.stdoutByteLength = input.stdoutByteLength;
10884
+ }
10885
+ if (input.invocationScopeId !== void 0) {
10886
+ payload.invocationScopeId = input.invocationScopeId;
10887
+ }
10888
+ if (input.runId !== void 0) payload.runId = input.runId;
10889
+ const subject = input.runId === void 0 ? void 0 : {
10890
+ runId: input.runId,
10891
+ ...input.invocationScopeId === void 0 ? {} : { invocationScopeId: input.invocationScopeId }
10892
+ };
10893
+ const pointer = sitianReport({
10894
+ level: "event",
10895
+ kind: ENGINE_DETOUR_CALL_KIND,
10896
+ identity: engineDetourCallIdentity({
10897
+ toolCallId: input.toolCallId,
10898
+ ...input.invocationScopeId === void 0 ? {} : { invocationScopeId: input.invocationScopeId }
10899
+ }),
10900
+ cwd: input.cwd,
10901
+ sessionParent: input.sessionParent,
10902
+ source: "engine-detour-tool",
10903
+ payload,
10904
+ raw: {
10905
+ sessionFile: input.sessionParent,
10906
+ entryId: input.toolCallId
10907
+ },
10908
+ ...input.home === void 0 ? {} : { home: input.home },
10909
+ ...input.host === void 0 ? {} : { host: input.host },
10910
+ ...subject === void 0 ? {} : { subject }
10911
+ });
10912
+ return {
10913
+ toolCallId: input.toolCallId,
10914
+ durationMs: input.durationMs,
10915
+ ...input.code === void 0 ? {} : { code: input.code },
10916
+ ...input.stdoutByteLength === void 0 ? {} : { stdoutByteLength: input.stdoutByteLength },
10917
+ recordPointer: pointer
10918
+ };
10919
+ }
10920
+ function isRecord7(value) {
10921
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10922
+ }
10923
+ function callFactFromSitianPayload(payload, pointer) {
10924
+ if (!isRecord7(payload)) return void 0;
10925
+ if (payload.tool !== ENGINE_DETOUR_TOOL_NAME) return void 0;
10926
+ if (typeof payload.toolCallId !== "string" || payload.toolCallId.length === 0) {
10927
+ return void 0;
10928
+ }
10929
+ if (typeof payload.durationMs !== "number" || !Number.isFinite(payload.durationMs)) {
10930
+ return void 0;
10931
+ }
10932
+ return {
10933
+ toolCallId: payload.toolCallId,
10934
+ durationMs: payload.durationMs,
10935
+ ...typeof payload.code === "number" ? { code: payload.code } : {},
10936
+ ...typeof payload.stdoutByteLength === "number" ? { stdoutByteLength: payload.stdoutByteLength } : {},
10937
+ recordPointer: pointer
10938
+ };
10939
+ }
10940
+ function invocationScopeIdOfRecord(record4) {
10941
+ if (isRecord7(record4.subject)) {
10942
+ const fromSubject = record4.subject.invocationScopeId;
10943
+ if (typeof fromSubject === "string" && fromSubject.length > 0) return fromSubject;
10944
+ }
10945
+ if (isRecord7(record4.payload)) {
10946
+ const fromPayload = record4.payload.invocationScopeId;
10947
+ if (typeof fromPayload === "string" && fromPayload.length > 0) return fromPayload;
10948
+ }
10949
+ return void 0;
10950
+ }
10951
+ async function readEngineDetourToolUsage(input) {
10952
+ if (!input.engineMounted) return void 0;
10953
+ const { recordFile } = resolveSitianRecordPath({
10954
+ level: "event",
10955
+ kind: ENGINE_DETOUR_CALL_KIND,
10956
+ sessionParent: input.sessionParent,
10957
+ ...input.home === void 0 ? {} : { home: input.home },
10958
+ ...input.cwd === void 0 ? {} : { cwd: input.cwd }
10959
+ });
10960
+ const { records } = await readSitianRecords(recordFile);
10961
+ const calls = [];
10962
+ for (const record4 of records) {
10963
+ if (record4.kind !== ENGINE_DETOUR_CALL_KIND) continue;
10964
+ const boundScope = invocationScopeIdOfRecord(record4);
10965
+ if (input.invocationScopeId !== void 0 && input.invocationScopeId.length > 0) {
10966
+ if (boundScope !== input.invocationScopeId) continue;
10967
+ } else if (boundScope !== void 0) {
10968
+ continue;
10969
+ }
10970
+ const pointer = {
10971
+ identity: record4.identity,
10972
+ recordFile,
10973
+ kind: record4.kind,
10974
+ level: record4.level
10975
+ };
10976
+ const fact = callFactFromSitianPayload(record4.payload, pointer);
10977
+ if (fact === void 0) continue;
10978
+ calls.push(fact);
10979
+ }
10980
+ return { callCount: calls.length, calls };
10981
+ }
10982
+ function projectEngineDetourToolUsageForPublicTerminal(usage, options) {
10983
+ if (options.discloseRecordFile) return usage;
10984
+ return {
10985
+ callCount: usage.callCount,
10986
+ calls: usage.calls.map((call) => ({
10987
+ toolCallId: call.toolCallId,
10988
+ durationMs: call.durationMs,
10989
+ ...call.code === void 0 ? {} : { code: call.code },
10990
+ ...call.stdoutByteLength === void 0 ? {} : { stdoutByteLength: call.stdoutByteLength },
10991
+ recordPointer: {
10992
+ identity: call.recordPointer.identity,
10993
+ kind: call.recordPointer.kind,
10994
+ level: call.recordPointer.level,
10995
+ recordFile: ENGINE_DETOUR_CALL_RECORD_FILE_RELATIVE
10996
+ }
10997
+ }))
10998
+ };
10999
+ }
11000
+ function readInvocationRecord(runDirectory) {
11001
+ try {
11002
+ const raw = JSON.parse(
11003
+ readFileSync3(join23(runDirectory, "invocation.json"), "utf8")
11004
+ );
11005
+ return isRecord7(raw) ? raw : void 0;
11006
+ } catch (error) {
11007
+ if (error?.code === "ENOENT") return void 0;
11008
+ throw error;
11009
+ }
11010
+ }
11011
+ async function readInvocationEngineMounted(runDirectory) {
11012
+ const raw = readInvocationRecord(runDirectory);
11013
+ if (raw === void 0) return false;
11014
+ return typeof raw.engine === "string" && raw.engine.trim() !== "";
11015
+ }
11016
+ function readInvocationSelectedHost(runDirectory) {
11017
+ const raw = readInvocationRecord(runDirectory);
11018
+ if (raw === void 0) return void 0;
11019
+ return typeof raw.host === "string" && raw.host.trim() !== "" ? raw.host.trim() : void 0;
11020
+ }
11021
+ function withEngineDetourToolUsageFact(outcome, usage) {
11022
+ if (usage === void 0) return outcome;
11023
+ const prior = isRecord7(outcome.decisiveFacts) ? outcome.decisiveFacts : {};
11024
+ return {
11025
+ ...outcome,
11026
+ decisiveFacts: {
11027
+ ...prior,
11028
+ [ENGINE_DETOUR_TOOL_USAGE_FACT_KEY]: usage
11029
+ }
11030
+ };
11031
+ }
11032
+ function runDirectoryFromSessionDirectory(sessionDirectory) {
11033
+ return dirname14(sessionDirectory);
11034
+ }
11035
+ function sessionFileFromSessionDirectory(sessionDirectory) {
11036
+ return join23(sessionDirectory, "session.jsonl");
11037
+ }
11038
+ function mintEngineDetourInvocationScope(input) {
11039
+ const engine = input.effectiveEngine?.trim();
11040
+ if (engine === void 0 || engine.length === 0) return void 0;
11041
+ return randomUUID4();
11042
+ }
11043
+ function withEngineDetourInvocationScope(request, invocationScopeId) {
11044
+ if (invocationScopeId === void 0 || invocationScopeId.length === 0) {
11045
+ return request;
11046
+ }
11047
+ if (typeof request.invocationScopeId === "string" && request.invocationScopeId.length > 0) {
11048
+ return request;
11049
+ }
11050
+ return { ...request, invocationScopeId };
11051
+ }
11052
+ var ENGINE_DETOUR_CALL_KIND, ENGINE_DETOUR_TOOL_USAGE_FACT_KEY, ENGINE_DETOUR_CALL_RECORD_FILE_RELATIVE;
11053
+ var init_engine_detour_usage = __esm({
11054
+ "src/engine-detour-usage.ts"() {
11055
+ "use strict";
11056
+ init_engine_detour();
11057
+ init_sitian_facade();
11058
+ ENGINE_DETOUR_CALL_KIND = "engine-detour-call";
11059
+ ENGINE_DETOUR_TOOL_USAGE_FACT_KEY = "engineDetourToolUsage";
11060
+ ENGINE_DETOUR_CALL_RECORD_FILE_RELATIVE = `session/${ENGINE_DETOUR_CALL_KIND}/records.jsonl`;
11061
+ }
11062
+ });
11063
+
10860
11064
  // src/host-transition-prior-native.ts
10861
11065
  import { access as access3, readdir as readdir5 } from "node:fs/promises";
10862
- import { dirname as dirname14, join as join23 } from "node:path";
11066
+ import { dirname as dirname15, join as join24 } from "node:path";
10863
11067
  function isEnoent3(error) {
10864
11068
  return typeof error === "object" && error !== null && error.code === "ENOENT";
10865
11069
  }
@@ -10873,7 +11077,7 @@ async function listPiNativeRecordPaths(sessionFile) {
10873
11077
  }
10874
11078
  }
10875
11079
  async function listSitianRecordPaths(sessionParent) {
10876
- const sessionRoot = dirname14(sessionParent);
11080
+ const sessionRoot = dirname15(sessionParent);
10877
11081
  let entries;
10878
11082
  try {
10879
11083
  entries = await readdir5(sessionRoot, { withFileTypes: true });
@@ -10884,7 +11088,7 @@ async function listSitianRecordPaths(sessionParent) {
10884
11088
  const recordPaths = [];
10885
11089
  for (const entry of entries) {
10886
11090
  if (!entry.isDirectory()) continue;
10887
- const recordFile = join23(sessionRoot, entry.name, "records.jsonl");
11091
+ const recordFile = join24(sessionRoot, entry.name, "records.jsonl");
10888
11092
  try {
10889
11093
  await access3(recordFile);
10890
11094
  recordPaths.push(recordFile);
@@ -11276,12 +11480,12 @@ var init_reviewer_dispatch = __esm({
11276
11480
 
11277
11481
  // src/public-cli/reviewer-dispatch-rejection.ts
11278
11482
  import { readFile as readFile17, unlink as unlink3 } from "node:fs/promises";
11279
- import { join as join24 } from "node:path";
11483
+ import { join as join25 } from "node:path";
11280
11484
  function isReviewerPreflightViolation(value) {
11281
11485
  return typeof value === "string" && REVIEWER_PREFLIGHT_VIOLATIONS.includes(value);
11282
11486
  }
11283
11487
  function reviewerDispatchRejectionPath(runDirectory) {
11284
- return join24(runDirectory, REVIEWER_DISPATCH_REJECTION_FILE);
11488
+ return join25(runDirectory, REVIEWER_DISPATCH_REJECTION_FILE);
11285
11489
  }
11286
11490
  async function clearReviewerDispatchRejection(runDirectory) {
11287
11491
  try {
@@ -11333,8 +11537,8 @@ var init_reviewer_dispatch_rejection = __esm({
11333
11537
 
11334
11538
  // src/analyst-gate-cycles-read.ts
11335
11539
  import { readdir as readdir6 } from "node:fs/promises";
11336
- import { join as join25 } from "node:path";
11337
- function isRecord7(value) {
11540
+ import { join as join26 } from "node:path";
11541
+ function isRecord8(value) {
11338
11542
  return typeof value === "object" && value !== null && !Array.isArray(value);
11339
11543
  }
11340
11544
  function isParentAttemptBindingRow(row) {
@@ -11364,7 +11568,7 @@ function isGateTerminatingToolName(toolName) {
11364
11568
  function acceptedGateReceiptIds(rows) {
11365
11569
  const accepted = /* @__PURE__ */ new Set();
11366
11570
  for (const row of rows) {
11367
- const message = isRecord7(row.message) ? row.message : void 0;
11571
+ const message = isRecord8(row.message) ? row.message : void 0;
11368
11572
  if (message?.role !== "toolResult") continue;
11369
11573
  if (typeof message.toolCallId !== "string" || message.toolCallId.length === 0) continue;
11370
11574
  if (message.isError === false) accepted.add(message.toolCallId);
@@ -11399,7 +11603,7 @@ function nearestAttemptBindingBefore(rows, beforeIndex) {
11399
11603
  for (let i = beforeIndex - 1; i >= 0; i -= 1) {
11400
11604
  const row = rows[i];
11401
11605
  if (!isParentAttemptBindingRow(row)) continue;
11402
- if (!isRecord7(row.data) || !isRecord7(row.data.parent)) continue;
11606
+ if (!isRecord8(row.data) || !isRecord8(row.data.parent)) continue;
11403
11607
  const id = row.data.parent.attemptEntryId;
11404
11608
  const sessionFile = row.data.parent.sessionFile;
11405
11609
  return {
@@ -11414,10 +11618,10 @@ function extractAllAcceptedGateToolCalls(rows) {
11414
11618
  const out = [];
11415
11619
  for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) {
11416
11620
  const row = rows[rowIndex];
11417
- const message = isRecord7(row.message) ? row.message : void 0;
11621
+ const message = isRecord8(row.message) ? row.message : void 0;
11418
11622
  if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
11419
11623
  for (const part of message.content) {
11420
- if (!isRecord7(part) || part.type !== "toolCall") continue;
11624
+ if (!isRecord8(part) || part.type !== "toolCall") continue;
11421
11625
  if (typeof part.id !== "string" || part.id.length === 0) continue;
11422
11626
  if (typeof part.name !== "string" || part.name.length === 0) continue;
11423
11627
  if (!isGateTerminatingToolName(part.name)) continue;
@@ -11425,7 +11629,7 @@ function extractAllAcceptedGateToolCalls(rows) {
11425
11629
  const binding = nearestAttemptBindingBefore(rows, rowIndex);
11426
11630
  out.push({
11427
11631
  toolName: part.name,
11428
- args: isRecord7(part.arguments) ? part.arguments : void 0,
11632
+ args: isRecord8(part.arguments) ? part.arguments : void 0,
11429
11633
  accepted: true,
11430
11634
  rowIndex,
11431
11635
  ...binding
@@ -11548,17 +11752,17 @@ function pairGateRounds(volumes) {
11548
11752
  return rounds.sort((a, b) => a.officerStartedAt.localeCompare(b.officerStartedAt)).map((round, index) => ({ ...round, roundIndex: index + 1 }));
11549
11753
  }
11550
11754
  async function resolveOfficerSessionFromPointerFile(pointerPath) {
11551
- const { readFile: readFile26 } = await import("node:fs/promises");
11755
+ const { readFile: readFile25 } = await import("node:fs/promises");
11552
11756
  let raw;
11553
11757
  try {
11554
- raw = JSON.parse(await readFile26(pointerPath, "utf8"));
11758
+ raw = JSON.parse(await readFile25(pointerPath, "utf8"));
11555
11759
  } catch (error) {
11556
11760
  throw new Error(
11557
11761
  `direct officer run pointer unreadable in ${pointerPath}: ${error instanceof Error ? error.message : String(error)}`,
11558
11762
  { cause: error }
11559
11763
  );
11560
11764
  }
11561
- if (!isRecord7(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
11765
+ if (!isRecord8(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
11562
11766
  throw new Error(`direct officer run pointer has unknown shape in ${pointerPath}`);
11563
11767
  }
11564
11768
  const sessionFile = raw.sessionFile;
@@ -11583,7 +11787,7 @@ async function readAnalystGateCyclesFromAuditorRoles(auditorRolesDirectory, opti
11583
11787
  throw error;
11584
11788
  }
11585
11789
  for (const name of names) {
11586
- const path = join25(directory, name);
11790
+ const path = join26(directory, name);
11587
11791
  const fromPointer = name.endsWith(".pointer.json");
11588
11792
  const sessionPath = fromPointer ? await resolveOfficerSessionFromPointerFile(path) : path;
11589
11793
  if (sessionPath === void 0) continue;
@@ -11722,7 +11926,7 @@ var init_audit_escalation = __esm({
11722
11926
  });
11723
11927
 
11724
11928
  // src/run-terminal-artifacts.ts
11725
- import { basename as basename8, dirname as dirname15, join as join26 } from "node:path";
11929
+ import { basename as basename8, dirname as dirname16, join as join27 } from "node:path";
11726
11930
  function runIdFromRunDirectory(runDirectory) {
11727
11931
  const name = basename8(runDirectory);
11728
11932
  const at = name.lastIndexOf("@");
@@ -11737,7 +11941,7 @@ var init_run_terminal_artifacts = __esm({
11737
11941
  });
11738
11942
 
11739
11943
  // src/submission-ledger.ts
11740
- import { join as join27 } from "node:path";
11944
+ import { join as join28 } from "node:path";
11741
11945
  function runIdentity(context) {
11742
11946
  const directory = runDirectoryFromHostContext(context);
11743
11947
  if (directory !== void 0) {
@@ -11759,7 +11963,7 @@ async function submissionRecordFile(cwd, runId, scope) {
11759
11963
  if (sessionParent === void 0) {
11760
11964
  const discoveredRun = await findRunDirectoryById(scope.home, runId);
11761
11965
  if (discoveredRun === void 0) return void 0;
11762
- sessionParent = join27(discoveredRun, "session", "session.jsonl");
11966
+ sessionParent = join28(discoveredRun, "session", "session.jsonl");
11763
11967
  }
11764
11968
  return resolveSitianRecordPathInLedger({
11765
11969
  level: "event",
@@ -11964,13 +12168,13 @@ function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (er
11964
12168
  const sessionParentFromContext = (context) => {
11965
12169
  const runDirectory = runDirectoryFromHostContext(context);
11966
12170
  if (runDirectory !== void 0) {
11967
- return join27(runDirectory, "session", "session.jsonl");
12171
+ return join28(runDirectory, "session", "session.jsonl");
11968
12172
  }
11969
12173
  const sessionFile = context.sessionManager.getSessionFile?.();
11970
12174
  if (typeof sessionFile === "string" && sessionFile.length > 0) return sessionFile;
11971
12175
  const sessionDir = context.sessionManager.getSessionDir?.();
11972
12176
  if (typeof sessionDir === "string" && sessionDir.length > 0) {
11973
- return join27(sessionDir, "session.jsonl");
12177
+ return join28(sessionDir, "session.jsonl");
11974
12178
  }
11975
12179
  return void 0;
11976
12180
  };
@@ -12133,15 +12337,15 @@ var init_submission_ledger = __esm({
12133
12337
  // src/session-opening-materials.ts
12134
12338
  import { existsSync as existsSync8 } from "node:fs";
12135
12339
  import { readFile as readFile18 } from "node:fs/promises";
12136
- import { dirname as dirname16, join as join28 } from "node:path";
12340
+ import { dirname as dirname17, join as join29 } from "node:path";
12137
12341
  import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
12138
12342
  function resolvePackageRootDir(moduleUrl = import.meta.url) {
12139
- let dir = dirname16(fileURLToPath(moduleUrl));
12343
+ let dir = dirname17(fileURLToPath(moduleUrl));
12140
12344
  for (let i = 0; i < 8; i += 1) {
12141
- if (existsSync8(join28(dir, "package.json")) && existsSync8(join28(dir, "souls"))) {
12345
+ if (existsSync8(join29(dir, "package.json")) && existsSync8(join29(dir, "souls"))) {
12142
12346
  return dir;
12143
12347
  }
12144
- const parent = dirname16(dir);
12348
+ const parent = dirname17(dir);
12145
12349
  if (parent === dir) break;
12146
12350
  dir = parent;
12147
12351
  }
@@ -13502,13 +13706,13 @@ function resolveAuditDossier(source) {
13502
13706
  }
13503
13707
  return { status: "ok", runDirectory };
13504
13708
  }
13505
- function isRecord8(value) {
13709
+ function isRecord9(value) {
13506
13710
  return typeof value === "object" && value !== null && !Array.isArray(value);
13507
13711
  }
13508
13712
  function readDoctorAuditSubjects(context) {
13509
13713
  const entries = context.sessionManager.getEntries?.() ?? [];
13510
13714
  for (const entry of entries) {
13511
- if (isRecord8(entry) && entry.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
13715
+ if (isRecord9(entry) && entry.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
13512
13716
  return { status: "ok" };
13513
13717
  }
13514
13718
  }
@@ -13543,7 +13747,7 @@ var init_dossier_resolution = __esm({
13543
13747
  // src/package-resources/method-skill.ts
13544
13748
  import { createHash as createHash6 } from "node:crypto";
13545
13749
  import { readFile as readFile19, realpath as realpath7 } from "node:fs/promises";
13546
- import { join as join29 } from "node:path";
13750
+ import { join as join30 } from "node:path";
13547
13751
  function gitBlobOid(bytes) {
13548
13752
  const body = typeof bytes === "string" ? Buffer.from(bytes, "utf8") : Buffer.from(bytes);
13549
13753
  const header = Buffer.from(`blob ${body.byteLength}\0`, "utf8");
@@ -13560,16 +13764,16 @@ function packagedMethodSkillRelativeDirectory(name) {
13560
13764
  return `${METHOD_SKILL_RELATIVE_ROOT}/${name}`;
13561
13765
  }
13562
13766
  function resolvePackagedMethodSkillRoot(packageRoot, name) {
13563
- return join29(packageRoot, packagedMethodSkillRelativeDirectory(name));
13767
+ return join30(packageRoot, packagedMethodSkillRelativeDirectory(name));
13564
13768
  }
13565
13769
  function resolvePackagedMethodSkillPath(packageRoot, name) {
13566
- return join29(resolvePackagedMethodSkillRoot(packageRoot, name), "SKILL.md");
13770
+ return join30(resolvePackagedMethodSkillRoot(packageRoot, name), "SKILL.md");
13567
13771
  }
13568
- function isRecord9(value) {
13772
+ function isRecord10(value) {
13569
13773
  return typeof value === "object" && value !== null && !Array.isArray(value);
13570
13774
  }
13571
13775
  function parseProvenance(raw, expectedName) {
13572
- if (!isRecord9(raw)) {
13776
+ if (!isRecord10(raw)) {
13573
13777
  throw new Error(`Packaged method provenance must be an object for ${expectedName}`);
13574
13778
  }
13575
13779
  if (raw.name !== expectedName) {
@@ -13583,7 +13787,7 @@ function parseProvenance(raw, expectedName) {
13583
13787
  if (typeof raw.packageAdaptation !== "string" || raw.packageAdaptation.trim() === "") {
13584
13788
  throw new Error(`Packaged method provenance packageAdaptation must be nonblank`);
13585
13789
  }
13586
- if (!isRecord9(raw.upstream)) {
13790
+ if (!isRecord10(raw.upstream)) {
13587
13791
  throw new Error(`Packaged method provenance upstream must be an object`);
13588
13792
  }
13589
13793
  const upstream = raw.upstream;
@@ -13610,12 +13814,12 @@ function parseProvenance(raw, expectedName) {
13610
13814
  `Packaged method provenance upstream must include nonblank tag or version`
13611
13815
  );
13612
13816
  }
13613
- if (!isRecord9(raw.files)) {
13817
+ if (!isRecord10(raw.files)) {
13614
13818
  throw new Error(`Packaged method provenance files must be an object`);
13615
13819
  }
13616
13820
  const files = {};
13617
13821
  for (const [rel, entry] of Object.entries(raw.files)) {
13618
- if (!isRecord9(entry)) {
13822
+ if (!isRecord10(entry)) {
13619
13823
  throw new Error(`Packaged method provenance file entry must be an object: ${rel}`);
13620
13824
  }
13621
13825
  if (typeof entry.sha256 !== "string" || !SHA256_RE.test(entry.sha256)) {
@@ -13657,8 +13861,8 @@ function parseProvenance(raw, expectedName) {
13657
13861
  }
13658
13862
  async function loadPackagedMethodSkillMaterial(packageRoot, name) {
13659
13863
  const rootDirectory = resolvePackagedMethodSkillRoot(packageRoot, name);
13660
- const skillPathConfigured = join29(rootDirectory, "SKILL.md");
13661
- const provenancePath = join29(rootDirectory, "provenance.json");
13864
+ const skillPathConfigured = join30(rootDirectory, "SKILL.md");
13865
+ const provenancePath = join30(rootDirectory, "provenance.json");
13662
13866
  let provenanceRaw;
13663
13867
  try {
13664
13868
  provenanceRaw = await readFile19(provenancePath, "utf8");
@@ -13675,7 +13879,7 @@ async function loadPackagedMethodSkillMaterial(packageRoot, name) {
13675
13879
  }
13676
13880
  const provenance = parseProvenance(provenanceJson, name);
13677
13881
  for (const [rel, expected] of Object.entries(provenance.files)) {
13678
- const absolute = join29(rootDirectory, rel);
13882
+ const absolute = join30(rootDirectory, rel);
13679
13883
  let bytes;
13680
13884
  try {
13681
13885
  bytes = await readFile19(absolute);
@@ -13958,11 +14162,11 @@ var init_navigator_invocation_identity = __esm({
13958
14162
  });
13959
14163
 
13960
14164
  // src/receipt-delivery-policy.ts
13961
- function isRecord10(value) {
14165
+ function isRecord11(value) {
13962
14166
  return typeof value === "object" && value !== null && !Array.isArray(value);
13963
14167
  }
13964
14168
  function parseNoReceiptLifecycleFacts(input) {
13965
- if (!isRecord10(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord10(item) && typeof item.reason === "string")) {
14169
+ if (!isRecord11(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord11(item) && typeof item.reason === "string")) {
13966
14170
  throw new TypeError("malformed no-receipt lifecycle facts");
13967
14171
  }
13968
14172
  return {
@@ -14180,16 +14384,16 @@ var init_terminal = __esm({
14180
14384
  });
14181
14385
 
14182
14386
  // src/public-cli/settlement.ts
14183
- import { randomUUID as randomUUID4 } from "node:crypto";
14387
+ import { randomUUID as randomUUID5 } from "node:crypto";
14184
14388
  import { appendFile as appendFile2, readFile as readFile20, readdir as readdir7, writeFile as writeFile10 } from "node:fs/promises";
14185
- import { dirname as dirname17, join as join30 } from "node:path";
14389
+ import { dirname as dirname18, join as join31 } from "node:path";
14186
14390
  function sealedLedgerHome(admitted) {
14187
14391
  return homeFromRunDirectory(admitted.runDirectory);
14188
14392
  }
14189
14393
  function ledgerReadScope(admitted, scope) {
14190
14394
  return {
14191
14395
  home: sealedLedgerHome(admitted),
14192
- sessionParent: join30(admitted.runDirectory, "session", "session.jsonl"),
14396
+ sessionParent: join31(admitted.runDirectory, "session", "session.jsonl"),
14193
14397
  ...scope?.courtAttemptId === void 0 || scope.courtAttemptId.length === 0 ? {} : { attemptId: scope.courtAttemptId }
14194
14398
  };
14195
14399
  }
@@ -14252,7 +14456,7 @@ async function attachRecordedSubmissions(admitted, terminal, scope) {
14252
14456
  await recordedSubmissionPayloads(admitted, void 0)
14253
14457
  );
14254
14458
  }
14255
- async function settleHostEndedNoReceipt(admitted, authority) {
14459
+ async function settleHostEndedNoReceipt(admitted, authority, scope) {
14256
14460
  const facts = noReceiptLifecycleFacts({
14257
14461
  terminalToolCalled: false,
14258
14462
  rejectedReceipts: [],
@@ -14274,7 +14478,8 @@ async function settleHostEndedNoReceipt(admitted, authority) {
14274
14478
  artifacts: [],
14275
14479
  runId: admitted.runId
14276
14480
  },
14277
- coordinates.sessionDirectory
14481
+ coordinates.sessionDirectory,
14482
+ detourGateContext(admitted, scope)
14278
14483
  );
14279
14484
  }
14280
14485
  async function closedLedgerOutcome(admitted, role, scope) {
@@ -14612,12 +14817,12 @@ async function readSitianRetainedAuditorProviderStop(sessionFile) {
14612
14817
  kind: "auditor",
14613
14818
  sessionParent: sessionFile,
14614
14819
  // Path is driven by sessionParent when under ledger home; cwd is a fallback only.
14615
- cwd: dirname17(sessionFile)
14820
+ cwd: dirname18(sessionFile)
14616
14821
  });
14617
14822
  const { records } = await readSitianRecords(recordFile);
14618
14823
  for (let i = records.length - 1; i >= 0; i -= 1) {
14619
14824
  const payload = records[i]?.payload;
14620
- if (!isRecord11(payload) || !isRecord11(payload.response)) continue;
14825
+ if (!isRecord12(payload) || !isRecord12(payload.response)) continue;
14621
14826
  if (typeof payload.type === "string") continue;
14622
14827
  const stop = sessionProviderStopFromAssistant(payload.response);
14623
14828
  if (stop !== void 0) return stop;
@@ -14638,7 +14843,7 @@ async function readSessionProviderStop(sessionFile) {
14638
14843
  }
14639
14844
  }
14640
14845
  async function readBoundEvidenceChildKnownFailure(sessionFile) {
14641
- const childDirectory = join30(dirname17(sessionFile), "evidence-children");
14846
+ const childDirectory = join31(dirname18(sessionFile), "evidence-children");
14642
14847
  let names;
14643
14848
  try {
14644
14849
  names = await readdir7(childDirectory);
@@ -14649,12 +14854,12 @@ async function readBoundEvidenceChildKnownFailure(sessionFile) {
14649
14854
  for (const file of names.filter((name) => name.endsWith(".jsonl")).sort().reverse()) {
14650
14855
  let entries;
14651
14856
  try {
14652
- entries = await readBoundSessionEntries(join30(childDirectory, file));
14857
+ entries = await readBoundSessionEntries(join31(childDirectory, file));
14653
14858
  } catch (error) {
14654
14859
  throw sessionReadFailure(error, "failed to read discovered evidence-child session");
14655
14860
  }
14656
14861
  const header = entries.find((entry) => entry.type === "session");
14657
- if (!isRecord11(header) || header.parentSession !== sessionFile) continue;
14862
+ if (!isRecord12(header) || header.parentSession !== sessionFile) continue;
14658
14863
  const stop = extractSessionProviderStop(entries);
14659
14864
  if (stop === void 0) continue;
14660
14865
  const primary = knownFailureFromProviderStop(stop);
@@ -14687,12 +14892,12 @@ async function loadBoundAuditorVolumes(sessionFile) {
14687
14892
  return body.startsWith("\u672C\u6B21\u914D\u7F6E\u7684\u52B3\u52A1\u5F15\u64CE\u53CA\u5176\u624B\u518C\uFF1A") || body.startsWith("- engine:");
14688
14893
  };
14689
14894
  const isResumeEnvelope = (msg) => {
14690
- if (!isRecord11(msg) || msg.role !== "user") return false;
14895
+ if (!isRecord12(msg) || msg.role !== "user") return false;
14691
14896
  const text = typeof msg.text === "string" ? msg.text : typeof msg.content === "string" ? msg.content : void 0;
14692
14897
  if (isResumeEnvelopeBytes(text)) return true;
14693
14898
  const content = msg.content;
14694
14899
  if (Array.isArray(content)) {
14695
- return content.some((p) => isRecord11(p) && (isResumeEnvelopeBytes(p.text) || isResumeEnvelopeBytes(p.content)));
14900
+ return content.some((p) => isRecord12(p) && (isResumeEnvelopeBytes(p.text) || isResumeEnvelopeBytes(p.content)));
14696
14901
  }
14697
14902
  return false;
14698
14903
  };
@@ -14704,7 +14909,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
14704
14909
  latestParentUserIndex = i;
14705
14910
  break;
14706
14911
  }
14707
- const childDirectories = [join30(dirname17(sessionFile), "auditor-roles")];
14912
+ const childDirectories = [join31(dirname18(sessionFile), "auditor-roles")];
14708
14913
  const valid = [];
14709
14914
  let sawAnyDirectory = false;
14710
14915
  for (const childDirectory of childDirectories) {
@@ -14719,12 +14924,12 @@ async function loadBoundAuditorVolumes(sessionFile) {
14719
14924
  for (const file of names.filter((name) => name.endsWith(".jsonl")).sort().reverse()) {
14720
14925
  let entries;
14721
14926
  try {
14722
- entries = await readBoundSessionEntries(join30(childDirectory, file));
14927
+ entries = await readBoundSessionEntries(join31(childDirectory, file));
14723
14928
  } catch (error) {
14724
14929
  throw sessionReadFailure(error, "failed to read discovered auditor session");
14725
14930
  }
14726
14931
  const header = entries.find((entry) => entry.type === "session");
14727
- if (!isRecord11(header)) continue;
14932
+ if (!isRecord12(header)) continue;
14728
14933
  const bindingIndexes = [];
14729
14934
  for (let i = 0; i < entries.length; i += 1) {
14730
14935
  const entry = entries[i];
@@ -14738,7 +14943,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
14738
14943
  end: idx + 1 < bindingIndexes.length ? bindingIndexes[idx + 1] : entries.length
14739
14944
  })) : [{ entry: void 0, start: 0, end: entries.length }];
14740
14945
  for (const { entry: bindingEntry, start, end } of bindingPasses) {
14741
- const bindingParent = bindingEntry !== void 0 && isRecord11(bindingEntry.data) && isRecord11(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
14946
+ const bindingParent = bindingEntry !== void 0 && isRecord12(bindingEntry.data) && isRecord12(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
14742
14947
  const attemptEntryId = typeof bindingParent?.attemptEntryId === "string" ? bindingParent.attemptEntryId : void 0;
14743
14948
  const attemptEntryIndex = attemptEntryId === void 0 ? -1 : parentEntries.findIndex((entry) => entry.id === attemptEntryId);
14744
14949
  const boundSessionFile = typeof bindingParent?.sessionFile === "string" ? bindingParent.sessionFile : typeof header.parentSession === "string" ? header.parentSession : void 0;
@@ -14765,12 +14970,12 @@ function complianceFailureFromAuditorVolumes(volumes) {
14765
14970
  if (stop === void 0) continue;
14766
14971
  for (let i = entries.length - 1; i >= 0; i -= 1) {
14767
14972
  const entry = entries[i];
14768
- if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord11(entry.data)) continue;
14769
- const parent = isRecord11(entry.data.parent) ? entry.data.parent : void 0;
14770
- const failure2 = isRecord11(entry.data.failure) ? entry.data.failure : void 0;
14973
+ if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord12(entry.data)) continue;
14974
+ const parent = isRecord12(entry.data.parent) ? entry.data.parent : void 0;
14975
+ const failure2 = isRecord12(entry.data.failure) ? entry.data.failure : void 0;
14771
14976
  if (parent?.sessionId !== parentId || parent.sessionFile !== sessionFile || parent.attemptEntryId !== attemptEntryId) continue;
14772
14977
  if (failure2 === void 0) continue;
14773
- const identity = isRecord11(failure2.identity) ? failure2.identity : void 0;
14978
+ const identity = isRecord12(failure2.identity) ? failure2.identity : void 0;
14774
14979
  const typedCause = failure2.cause === "provider" || failure2.cause === "activation" || failure2.cause === "session" || failure2.cause === "output" || failure2.cause === "timeout" ? failure2.cause : void 0;
14775
14980
  return {
14776
14981
  ...typedCause === void 0 ? {} : { cause: typedCause },
@@ -14779,7 +14984,7 @@ function complianceFailureFromAuditorVolumes(volumes) {
14779
14984
  ...typeof identity.code === "string" || typeof identity.code === "number" ? { code: identity.code } : {}
14780
14985
  } },
14781
14986
  ...typeof failure2.diagnostic === "string" ? { diagnostic: failure2.diagnostic } : {},
14782
- ...isRecord11(failure2.details) ? { details: failure2.details } : {}
14987
+ ...isRecord12(failure2.details) ? { details: failure2.details } : {}
14783
14988
  };
14784
14989
  }
14785
14990
  }
@@ -14826,9 +15031,9 @@ function typedFailedTerminatingToolKnownFailure(entries) {
14826
15031
  if (classification.kind !== "infrastructure") continue;
14827
15032
  if (typeof message.toolCallId !== "string" || typeof message.toolName !== "string") continue;
14828
15033
  if (boundRoleToolCallForResult(attemptEntries, i, message, message.toolName) === void 0) continue;
14829
- const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord11(part) && part.type === "text" && typeof part.text === "string") : void 0;
14830
- const diagnostic = isRecord11(textPart) ? textPart.text : void 0;
14831
- const details = isRecord11(message.details) ? message.details : classification.fact;
15034
+ const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord12(part) && part.type === "text" && typeof part.text === "string") : void 0;
15035
+ const diagnostic = isRecord12(textPart) ? textPart.text : void 0;
15036
+ const details = isRecord12(message.details) ? message.details : classification.fact;
14832
15037
  return {
14833
15038
  cause: "activation",
14834
15039
  identity: { name: message.toolName, code: message.toolCallId },
@@ -14986,7 +15191,7 @@ function controlledFailureInputFromResolution(resolution) {
14986
15191
  } : {}
14987
15192
  };
14988
15193
  }
14989
- function isRecord11(value) {
15194
+ function isRecord12(value) {
14990
15195
  return typeof value === "object" && value !== null && !Array.isArray(value);
14991
15196
  }
14992
15197
  function toolResultText(message) {
@@ -15011,7 +15216,7 @@ function extractCollectorTargetBindRejection(entries) {
15011
15216
  const diagnostic = toolResultText(message);
15012
15217
  if (diagnostic.length === 0) return void 0;
15013
15218
  const details = message.details;
15014
- const code = isRecord11(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
15219
+ const code = isRecord12(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
15015
15220
  return code === void 0 ? { diagnostic } : { diagnostic, code };
15016
15221
  }
15017
15222
  return void 0;
@@ -15072,7 +15277,7 @@ function boundRoleToolCallForResult(entries, resultIndex, message, outputToolNam
15072
15277
  const candidateMessage = entries[index]?.message;
15073
15278
  if (candidateMessage?.role === "assistant" && Array.isArray(candidateMessage.content)) {
15074
15279
  for (const part of candidateMessage.content) {
15075
- if (!isRecord11(part) || part.type !== "toolCall" || part.id !== callId) {
15280
+ if (!isRecord12(part) || part.type !== "toolCall" || part.id !== callId) {
15076
15281
  continue;
15077
15282
  }
15078
15283
  if (part.name !== outputToolName) return void 0;
@@ -15109,7 +15314,7 @@ async function appendRunAttemptHistory(source, outcome) {
15109
15314
  type: "custom",
15110
15315
  customType: ATTEMPT_HISTORY_ENTRY_TYPE,
15111
15316
  data: attemptData,
15112
- id: randomUUID4(),
15317
+ id: randomUUID5(),
15113
15318
  parentId,
15114
15319
  timestamp: timestamp2
15115
15320
  })}
@@ -15144,7 +15349,7 @@ function parseNavigatorAttendanceDetails(details) {
15144
15349
  const advisoryDiagnostic = typeof details.routePlaybookReadFailure === "string" ? { advisoryDiagnostic: details.routePlaybookReadFailure } : {};
15145
15350
  if (disposition === "recommendation") {
15146
15351
  const next = details.next;
15147
- if (!isRecord11(next) || typeof next.role !== "string") {
15352
+ if (!isRecord12(next) || typeof next.role !== "string") {
15148
15353
  return {
15149
15354
  disposition: "unavailable",
15150
15355
  source: "unknown",
@@ -15152,7 +15357,7 @@ function parseNavigatorAttendanceDetails(details) {
15152
15357
  };
15153
15358
  }
15154
15359
  const reason = typeof details.reason === "string" ? details.reason : "";
15155
- const route = Array.isArray(details.route) ? details.route.filter(isRecord11).map((target) => ({
15360
+ const route = Array.isArray(details.route) ? details.route.filter(isRecord12).map((target) => ({
15156
15361
  role: String(target.role),
15157
15362
  phase: navigatorPhaseValue(target.phase)
15158
15363
  })) : void 0;
@@ -15215,18 +15420,50 @@ function projectTerminalGateFact(rounds) {
15215
15420
  };
15216
15421
  }
15217
15422
  async function extractGateFactFromSessionDirectory(sessionDirectory, options = {}) {
15218
- const directories = [join30(sessionDirectory, "auditor-roles")];
15219
- const parentSessionFile = options.parentSessionFile ?? join30(sessionDirectory, "session.jsonl");
15423
+ const directories = [join31(sessionDirectory, "auditor-roles")];
15424
+ const parentSessionFile = options.parentSessionFile ?? join31(sessionDirectory, "session.jsonl");
15220
15425
  const rounds = await readAnalystGateCyclesFromAuditorRoles(directories, {
15221
15426
  parentSessionFile
15222
15427
  });
15223
15428
  return projectTerminalGateFact(rounds);
15224
15429
  }
15430
+ async function attachEngineDetourToolUsage(base, sessionDirectory, gateContext = {}) {
15431
+ const runDirectory = typeof gateContext.runDirectory === "string" && gateContext.runDirectory.length > 0 ? gateContext.runDirectory : runDirectoryFromSessionDirectory(sessionDirectory);
15432
+ const engineMounted = await readInvocationEngineMounted(runDirectory);
15433
+ if (!engineMounted) return base;
15434
+ const invocationScopeId = typeof gateContext.invocationScopeId === "string" && gateContext.invocationScopeId.length > 0 ? gateContext.invocationScopeId : void 0;
15435
+ const sessionFile = sessionFileFromSessionDirectory(sessionDirectory);
15436
+ const usage = await readEngineDetourToolUsage({
15437
+ sessionParent: sessionFile,
15438
+ engineMounted: true,
15439
+ ...invocationScopeId === void 0 ? {} : { invocationScopeId },
15440
+ cwd: runDirectory
15441
+ });
15442
+ const projected = usage === void 0 ? void 0 : projectEngineDetourToolUsageForPublicTerminal(usage, {
15443
+ // Resumable Terminal: run ID only in resume.command — relative openable path.
15444
+ discloseRecordFile: base.resume === void 0
15445
+ });
15446
+ return {
15447
+ ...base,
15448
+ roleOutcome: withEngineDetourToolUsageFact(base.roleOutcome, projected)
15449
+ };
15450
+ }
15451
+ function detourGateContext(admitted, scope) {
15452
+ return {
15453
+ runDirectory: admitted.runDirectory,
15454
+ ...scope?.courtAttemptId === void 0 || scope.courtAttemptId.length === 0 ? {} : { courtAttemptId: scope.courtAttemptId },
15455
+ ...scope?.invocationScopeId === void 0 || scope.invocationScopeId.length === 0 ? {} : { invocationScopeId: scope.invocationScopeId }
15456
+ };
15457
+ }
15225
15458
  async function withOptionalGateProjection(base, sessionDirectory, gateContext = {}) {
15226
15459
  const secondaryEvidence = base.roleOutcome.kind === "failure" ? base.roleOutcome.decisiveFacts.secondaryEvidence : void 0;
15227
- if (isRecord11(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && (secondaryEvidence.stage === "gatekeeper" || secondaryEvidence.stage === "inspector" || secondaryEvidence.stage === "notary")) return base;
15228
- const gate = await extractGateFactFromSessionDirectory(sessionDirectory, gateContext);
15229
- return gate === void 0 ? base : { ...base, gate };
15460
+ const skipGate = isRecord12(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && (secondaryEvidence.stage === "gatekeeper" || secondaryEvidence.stage === "inspector" || secondaryEvidence.stage === "notary");
15461
+ let next = base;
15462
+ if (!skipGate) {
15463
+ const gate = await extractGateFactFromSessionDirectory(sessionDirectory, gateContext);
15464
+ if (gate !== void 0) next = { ...base, gate };
15465
+ }
15466
+ return attachEngineDetourToolUsage(next, sessionDirectory, gateContext);
15230
15467
  }
15231
15468
  function extractNavigatorFact(entries) {
15232
15469
  const terminal = findLatestDurablePackagedRoleTerminal(entries);
@@ -15264,7 +15501,7 @@ function extractNavigatorFact(entries) {
15264
15501
  const entry = entries[i];
15265
15502
  if (entry?.type === "custom_message" && entry.customType === "ak-navigator-attendance") {
15266
15503
  const details = entry.message?.details ?? entry.details;
15267
- if (!isRecord11(details)) {
15504
+ if (!isRecord12(details)) {
15268
15505
  return {
15269
15506
  disposition: "unavailable",
15270
15507
  source: "unknown",
@@ -15314,8 +15551,8 @@ async function extractNavigatorFactFromAdmittedSession(sessionFile) {
15314
15551
  async function publishJudgeArtifacts(admitted, roleOutcome, coordinates) {
15315
15552
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
15316
15553
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
15317
- const reportPath = join30(artifactsDir, "report.json");
15318
- const evidencePath = join30(artifactsDir, "evidence.json");
15554
+ const reportPath = join31(artifactsDir, "report.json");
15555
+ const evidencePath = join31(artifactsDir, "evidence.json");
15319
15556
  await writeFile10(
15320
15557
  reportPath,
15321
15558
  `${JSON.stringify(
@@ -15385,7 +15622,8 @@ async function settleLawfulJudgeTerminalResult(admitted, authority, scope) {
15385
15622
  artifacts,
15386
15623
  runId: admitted.runId
15387
15624
  },
15388
- coordinates.sessionDirectory
15625
+ coordinates.sessionDirectory,
15626
+ detourGateContext(admitted, scope)
15389
15627
  );
15390
15628
  }
15391
15629
  async function trySettleJudgeTerminalResult(admitted, authority, scope) {
@@ -15397,7 +15635,7 @@ function extractDoctorCandidateCostFact(entries) {
15397
15635
  const entry = entries[i];
15398
15636
  if (entry?.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
15399
15637
  const data = entry.data;
15400
- return isRecord11(data) ? data.cost : void 0;
15638
+ return isRecord12(data) ? data.cost : void 0;
15401
15639
  }
15402
15640
  }
15403
15641
  return void 0;
@@ -15408,7 +15646,7 @@ function extractDoctorCandidateAuditNoReceiptFact(entries) {
15408
15646
  const entry = entries[i];
15409
15647
  if (entry?.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
15410
15648
  const data = entry.data;
15411
- return isRecord11(data) ? data.auditNoReceipt : void 0;
15649
+ return isRecord12(data) ? data.auditNoReceipt : void 0;
15412
15650
  }
15413
15651
  }
15414
15652
  return void 0;
@@ -15416,8 +15654,8 @@ function extractDoctorCandidateAuditNoReceiptFact(entries) {
15416
15654
  async function publishDoctorArtifacts(admitted, roleOutcome, coordinates, options = {}) {
15417
15655
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
15418
15656
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
15419
- const reportPath = join30(artifactsDir, "report.json");
15420
- const evidencePath = join30(artifactsDir, "evidence.json");
15657
+ const reportPath = join31(artifactsDir, "report.json");
15658
+ const evidencePath = join31(artifactsDir, "evidence.json");
15421
15659
  await writeFile10(
15422
15660
  reportPath,
15423
15661
  `${JSON.stringify(
@@ -15479,7 +15717,8 @@ async function settleLawfulDoctorTerminalResult(admitted, authority, scope) {
15479
15717
  artifacts: artifacts2,
15480
15718
  runId: admitted.runId
15481
15719
  },
15482
- sessionDirectory
15720
+ sessionDirectory,
15721
+ detourGateContext(admitted, scope)
15483
15722
  );
15484
15723
  }
15485
15724
  const roleOutcome = sealed;
@@ -15502,7 +15741,8 @@ async function settleLawfulDoctorTerminalResult(admitted, authority, scope) {
15502
15741
  artifacts,
15503
15742
  runId: admitted.runId
15504
15743
  },
15505
- sessionDirectory
15744
+ sessionDirectory,
15745
+ detourGateContext(admitted, scope)
15506
15746
  );
15507
15747
  }
15508
15748
  async function trySettleDoctorTerminalResult(admitted, authority, scope) {
@@ -15533,12 +15773,17 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
15533
15773
  spec.toolName
15534
15774
  );
15535
15775
  if (residual !== void 0) {
15536
- const details = isRecord11(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
15537
- const failed = await settleFailureTerminalResult(admitted, {
15538
- cause: "output",
15539
- diagnostic: residual.diagnostic,
15540
- details
15541
- }, authority);
15776
+ const details = isRecord12(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
15777
+ const failed = await settleFailureTerminalResult(
15778
+ admitted,
15779
+ {
15780
+ cause: "output",
15781
+ diagnostic: residual.diagnostic,
15782
+ details
15783
+ },
15784
+ authority,
15785
+ scope ?? {}
15786
+ );
15542
15787
  return withSubmissions(failed, submissions);
15543
15788
  }
15544
15789
  }
@@ -15553,7 +15798,8 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
15553
15798
  artifacts: [],
15554
15799
  runId: admitted.runId
15555
15800
  },
15556
- sessionDirectory
15801
+ sessionDirectory,
15802
+ detourGateContext(admitted, scope)
15557
15803
  ),
15558
15804
  submissions
15559
15805
  );
@@ -15568,7 +15814,8 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
15568
15814
  artifacts: [],
15569
15815
  runId: admitted.runId
15570
15816
  },
15571
- sessionDirectory
15817
+ sessionDirectory,
15818
+ detourGateContext(admitted, scope)
15572
15819
  ),
15573
15820
  submissions
15574
15821
  );
@@ -15648,7 +15895,7 @@ function publicationAttemptFromError(path, error) {
15648
15895
  }
15649
15896
  function uniqueFailureFallbackDirs(runDirectory, baseDir) {
15650
15897
  const dirs = [];
15651
- for (const dir of [baseDir, runDirectory, dirname17(runDirectory)]) {
15898
+ for (const dir of [baseDir, runDirectory, dirname18(runDirectory)]) {
15652
15899
  if (!dirs.includes(dir)) dirs.push(dir);
15653
15900
  }
15654
15901
  return dirs;
@@ -15670,7 +15917,7 @@ async function writeFailureJsonRetainingCause(preferredCandidates, uniqueFallbac
15670
15917
  const candidates = [
15671
15918
  ...preferredCandidates,
15672
15919
  // One unique name per fallback dir — collisions on fixed names cannot exhaust this.
15673
- ...uniqueFallbackDirs.map((dir) => join30(dir, `${stem}.${randomUUID4()}.json`))
15920
+ ...uniqueFallbackDirs.map((dir) => join31(dir, `${stem}.${randomUUID5()}.json`))
15674
15921
  ];
15675
15922
  for (let i = 0; i < candidates.length; i += 1) {
15676
15923
  const path = candidates[i];
@@ -15721,20 +15968,20 @@ async function publishFailureArtifacts(admitted, failure2, authority) {
15721
15968
  baseDir
15722
15969
  );
15723
15970
  const errorCandidates = underArtifacts ? [
15724
- join30(baseDir, "error.json"),
15725
- join30(baseDir, "error.settlement.json"),
15726
- join30(admitted.runDirectory, "error.settlement.json")
15971
+ join31(baseDir, "error.json"),
15972
+ join31(baseDir, "error.settlement.json"),
15973
+ join31(admitted.runDirectory, "error.settlement.json")
15727
15974
  ] : [
15728
- join30(baseDir, "error.settlement.json"),
15729
- join30(baseDir, "error.json")
15975
+ join31(baseDir, "error.settlement.json"),
15976
+ join31(baseDir, "error.json")
15730
15977
  ];
15731
15978
  const evidenceCandidates = underArtifacts ? [
15732
- join30(baseDir, "evidence.json"),
15733
- join30(baseDir, "evidence.settlement.json"),
15734
- join30(admitted.runDirectory, "evidence.settlement.json")
15979
+ join31(baseDir, "evidence.json"),
15980
+ join31(baseDir, "evidence.settlement.json"),
15981
+ join31(admitted.runDirectory, "evidence.settlement.json")
15735
15982
  ] : [
15736
- join30(baseDir, "evidence.settlement.json"),
15737
- join30(baseDir, "evidence.json")
15983
+ join31(baseDir, "evidence.settlement.json"),
15984
+ join31(baseDir, "evidence.json")
15738
15985
  ];
15739
15986
  const errorPayloadBase = {
15740
15987
  kind: "error",
@@ -15816,7 +16063,8 @@ async function settleFailureTerminalResult(admitted, failure2, authority, option
15816
16063
  artifacts: [],
15817
16064
  runId: admitted.runId
15818
16065
  },
15819
- sessionDirectory
16066
+ sessionDirectory,
16067
+ detourGateContext(admitted, options)
15820
16068
  );
15821
16069
  }
15822
16070
  } catch {
@@ -15854,7 +16102,8 @@ async function settleFailureTerminalResult(admitted, failure2, authority, option
15854
16102
  artifacts: [],
15855
16103
  resume: options.resume
15856
16104
  },
15857
- sessionDirectory
16105
+ sessionDirectory,
16106
+ detourGateContext(admitted, options)
15858
16107
  );
15859
16108
  }
15860
16109
  const roleOutcome = {
@@ -15871,7 +16120,8 @@ async function settleFailureTerminalResult(admitted, failure2, authority, option
15871
16120
  artifacts,
15872
16121
  runId: admitted.runId
15873
16122
  },
15874
- sessionDirectory
16123
+ sessionDirectory,
16124
+ detourGateContext(admitted, options)
15875
16125
  );
15876
16126
  }
15877
16127
  function presentFailureTerminal(terminal, io) {
@@ -15945,6 +16195,7 @@ var init_settlement = __esm({
15945
16195
  init_compliance_transport();
15946
16196
  init_collector_ledger();
15947
16197
  init_engine_detour();
16198
+ init_engine_detour_usage();
15948
16199
  init_judge_output();
15949
16200
  init_collector_output();
15950
16201
  init_worker_output();
@@ -15978,9 +16229,9 @@ var init_settlement = __esm({
15978
16229
 
15979
16230
  // src/public-cli/auto-resume.ts
15980
16231
  import { constants as fsConstants2 } from "node:fs";
15981
- import { randomUUID as randomUUID5 } from "node:crypto";
16232
+ import { randomUUID as randomUUID6 } from "node:crypto";
15982
16233
  import { lstat as lstat6, mkdir as mkdir4, open as open2 } from "node:fs/promises";
15983
- import { join as join31 } from "node:path";
16234
+ import { join as join32 } from "node:path";
15984
16235
  async function persistReturnedRunState(admitted, authority, options) {
15985
16236
  if (options?.lawful === true) {
15986
16237
  await markRunTerminal(admitted.runDirectory);
@@ -16095,7 +16346,7 @@ function jsonSafeReplacer() {
16095
16346
  };
16096
16347
  }
16097
16348
  async function writeHardenedArtifactFile(artifactsDir, namePrefix, payload) {
16098
- const filePath = join31(artifactsDir, `${namePrefix}-${randomUUID5()}.json`);
16349
+ const filePath = join32(artifactsDir, `${namePrefix}-${randomUUID6()}.json`);
16099
16350
  const body = `${JSON.stringify(payload, jsonSafeReplacer(), 2)}
16100
16351
  `;
16101
16352
  const noFollowFlag = typeof fsConstants2.O_NOFOLLOW === "number" ? fsConstants2.O_NOFOLLOW : 0;
@@ -16366,9 +16617,9 @@ var init_auto_resume = __esm({
16366
16617
  });
16367
16618
 
16368
16619
  // src/public-cli/post-admission.ts
16369
- import { randomUUID as randomUUID6 } from "node:crypto";
16370
- import { readFile as readFile21, writeFile as writeFile11 } from "node:fs/promises";
16371
- import { isAbsolute as isAbsolute8, join as join32, resolve as resolve13 } from "node:path";
16620
+ import { randomUUID as randomUUID7 } from "node:crypto";
16621
+ import { writeFile as writeFile11 } from "node:fs/promises";
16622
+ import { isAbsolute as isAbsolute8, join as join33, resolve as resolve13 } from "node:path";
16372
16623
  function describeCaughtError(error) {
16373
16624
  if (error instanceof Error) {
16374
16625
  const code = error.code;
@@ -16413,7 +16664,7 @@ async function recordBestEffortPostDispatchDiagnostic(admitted, env, diagnostic,
16413
16664
  try {
16414
16665
  const artifactsDir = await ensureRealArtifactsDirectory(admitted.runDirectory);
16415
16666
  await writeFile11(
16416
- join32(artifactsDir, `post-admission-diagnostic-${randomUUID6()}.json`),
16667
+ join33(artifactsDir, `post-admission-diagnostic-${randomUUID7()}.json`),
16417
16668
  `${JSON.stringify({ version: 1, ...payload }, null, 2)}
16418
16669
  `,
16419
16670
  { encoding: "utf8", flag: "wx" }
@@ -16427,15 +16678,6 @@ async function recordBestEffortPostDispatchDiagnostic(admitted, env, diagnostic,
16427
16678
  }
16428
16679
  }
16429
16680
  }
16430
- async function readInvocationHost(runDirectory) {
16431
- try {
16432
- const raw = JSON.parse(await readFile21(join32(runDirectory, "invocation.json"), "utf8"));
16433
- return typeof raw.host === "string" && raw.host.trim() !== "" ? raw.host : void 0;
16434
- } catch (error) {
16435
- if (error.code === "ENOENT") return void 0;
16436
- throw error;
16437
- }
16438
- }
16439
16681
  async function presentControlledFailure(admitted, failureInput, adapters, authority, io, persistRunState = true) {
16440
16682
  const hasThrown = Object.hasOwn(failureInput, "thrown");
16441
16683
  const resumeObservation = await resolveControlledFailureResumeObservation({
@@ -16475,7 +16717,10 @@ async function presentControlledFailure(admitted, failureInput, adapters, author
16475
16717
  admitted,
16476
16718
  failure2,
16477
16719
  authority,
16478
- resumable ? { resume: { command: renderResumeCommand(admitted.runId) } } : {}
16720
+ {
16721
+ ...resumable ? { resume: { command: renderResumeCommand(admitted.runId) } } : {},
16722
+ ...failureInput.invocationScopeId === void 0 || failureInput.invocationScopeId.length === 0 ? {} : { invocationScopeId: failureInput.invocationScopeId }
16723
+ }
16479
16724
  )
16480
16725
  );
16481
16726
  presentFailureTerminal(terminal, io);
@@ -16544,12 +16789,12 @@ async function dispatchPostAdmissionTurn(input) {
16544
16789
  return {
16545
16790
  ...await presentControlledFailure(
16546
16791
  admitted,
16547
- {
16792
+ withEngineDetourInvocationScope({
16548
16793
  timedOut: false,
16549
16794
  code: null,
16550
16795
  stderr: "",
16551
16796
  thrown: error
16552
- },
16797
+ }, request.invocationScopeId),
16553
16798
  adapters,
16554
16799
  env.principalAuthority,
16555
16800
  io,
@@ -16570,7 +16815,7 @@ async function dispatchPostAdmissionTurn(input) {
16570
16815
  return {
16571
16816
  ...await presentControlledFailure(
16572
16817
  admitted,
16573
- missingCredential,
16818
+ withEngineDetourInvocationScope(missingCredential, request.invocationScopeId),
16574
16819
  adapters,
16575
16820
  env.principalAuthority,
16576
16821
  io,
@@ -16584,7 +16829,7 @@ async function dispatchPostAdmissionTurn(input) {
16584
16829
  const principalCoordinates = admitted.principal === void 0 ? void 0 : env.principalAuthority.decode(admitted.principal);
16585
16830
  let hostTransition;
16586
16831
  try {
16587
- previousHost = await readInvocationHost(admitted.runDirectory);
16832
+ previousHost = readInvocationSelectedHost(admitted.runDirectory);
16588
16833
  hostTransition = previousHost !== void 0 && liveHost !== void 0 && principalCoordinates !== void 0 ? await projectHostTransitionPriorNative({
16589
16834
  previousHost,
16590
16835
  liveHost,
@@ -16594,12 +16839,12 @@ async function dispatchPostAdmissionTurn(input) {
16594
16839
  return {
16595
16840
  ...await presentControlledFailure(
16596
16841
  admitted,
16597
- {
16842
+ withEngineDetourInvocationScope({
16598
16843
  timedOut: false,
16599
16844
  code: null,
16600
16845
  stderr: "",
16601
16846
  thrown: error
16602
- },
16847
+ }, request.invocationScopeId),
16603
16848
  adapters,
16604
16849
  env.principalAuthority,
16605
16850
  io,
@@ -16616,12 +16861,12 @@ async function dispatchPostAdmissionTurn(input) {
16616
16861
  } catch (error) {
16617
16862
  const settled2 = await presentControlledFailure(
16618
16863
  admitted,
16619
- {
16864
+ withEngineDetourInvocationScope({
16620
16865
  timedOut: false,
16621
16866
  code: null,
16622
16867
  stderr: "",
16623
16868
  thrown: error
16624
- },
16869
+ }, request.invocationScopeId),
16625
16870
  adapters,
16626
16871
  env.principalAuthority,
16627
16872
  io,
@@ -16640,6 +16885,9 @@ async function dispatchPostAdmissionTurn(input) {
16640
16885
  if (hostTransition !== void 0) {
16641
16886
  turnRequest = { ...turnRequest, hostTransition };
16642
16887
  }
16888
+ if (typeof liveHost === "string" && liveHost.trim() !== "") {
16889
+ turnRequest = { ...turnRequest, host: liveHost.trim() };
16890
+ }
16643
16891
  if (isStationChildOfficerDialogue(admitted.role, env)) {
16644
16892
  await deliverCaseDossierAsAttachment({
16645
16893
  ticketNumber: admitted.ticketNumber,
@@ -16676,12 +16924,12 @@ async function dispatchPostAdmissionTurn(input) {
16676
16924
  } catch (error) {
16677
16925
  const settled2 = await settleAfterTurnStarted(
16678
16926
  admitted,
16679
- {
16927
+ withEngineDetourInvocationScope({
16680
16928
  timedOut: false,
16681
16929
  code: null,
16682
16930
  stderr: "",
16683
16931
  thrown: error
16684
- },
16932
+ }, request.invocationScopeId),
16685
16933
  adapters,
16686
16934
  env.principalAuthority,
16687
16935
  io,
@@ -16692,7 +16940,7 @@ async function dispatchPostAdmissionTurn(input) {
16692
16940
  let stderrLogWriteFailure;
16693
16941
  try {
16694
16942
  await writeFile11(
16695
- join32(admitted.runDirectory, "stderr.log"),
16943
+ join33(admitted.runDirectory, "stderr.log"),
16696
16944
  result.stderr,
16697
16945
  "utf8"
16698
16946
  );
@@ -16705,7 +16953,10 @@ async function dispatchPostAdmissionTurn(input) {
16705
16953
  io
16706
16954
  );
16707
16955
  }
16708
- const courtScope = request.courtAttemptId === void 0 || request.courtAttemptId.length === 0 ? void 0 : { courtAttemptId: request.courtAttemptId };
16956
+ const courtScope = (request.courtAttemptId === void 0 || request.courtAttemptId.length === 0) && (request.invocationScopeId === void 0 || request.invocationScopeId.length === 0) ? void 0 : {
16957
+ ...request.courtAttemptId === void 0 || request.courtAttemptId.length === 0 ? {} : { courtAttemptId: request.courtAttemptId },
16958
+ ...request.invocationScopeId === void 0 || request.invocationScopeId.length === 0 ? {} : { invocationScopeId: request.invocationScopeId }
16959
+ };
16709
16960
  let settled;
16710
16961
  let settledOutcome;
16711
16962
  let hostSignalFailed = false;
@@ -16755,12 +17006,12 @@ async function dispatchPostAdmissionTurn(input) {
16755
17006
  } catch (error) {
16756
17007
  const settledFailure = await settleAfterTurnStarted(
16757
17008
  admitted,
16758
- {
17009
+ withEngineDetourInvocationScope({
16759
17010
  timedOut: false,
16760
17011
  code: result.code,
16761
17012
  stderr: result.stderr,
16762
17013
  thrown: error
16763
- },
17014
+ }, request.invocationScopeId),
16764
17015
  adapters,
16765
17016
  env.principalAuthority,
16766
17017
  io,
@@ -16775,13 +17026,13 @@ async function dispatchPostAdmissionTurn(input) {
16775
17026
  } catch (error) {
16776
17027
  const failed = await settleAfterTurnStarted(
16777
17028
  admitted,
16778
- {
17029
+ withEngineDetourInvocationScope({
16779
17030
  timedOut: false,
16780
17031
  code: null,
16781
17032
  stderr: "",
16782
17033
  thrown: error,
16783
17034
  skipRunStateWrite: true
16784
- },
17035
+ }, request.invocationScopeId),
16785
17036
  adapters,
16786
17037
  env.principalAuthority,
16787
17038
  io,
@@ -16797,7 +17048,7 @@ async function dispatchPostAdmissionTurn(input) {
16797
17048
  const stderrLogWriteDetails = stderrLogWriteFailure === void 0 ? void 0 : { stderrLogWriteFailure: describeCaughtError(stderrLogWriteFailure) };
16798
17049
  const failed = await settleAfterTurnStarted(
16799
17050
  admitted,
16800
- {
17051
+ withEngineDetourInvocationScope({
16801
17052
  timedOut: result.timedOut,
16802
17053
  code: result.code,
16803
17054
  stderr: result.stderr,
@@ -16811,7 +17062,7 @@ async function dispatchPostAdmissionTurn(input) {
16811
17062
  details: { ...resolutionInput.knownFailure.details ?? {}, ...stderrLogWriteDetails }
16812
17063
  }
16813
17064
  } : { knownDetails: stderrLogWriteDetails }
16814
- },
17065
+ }, request.invocationScopeId),
16815
17066
  adapters,
16816
17067
  env.principalAuthority,
16817
17068
  io,
@@ -16822,12 +17073,12 @@ async function dispatchPostAdmissionTurn(input) {
16822
17073
  if (stderrLogWriteFailure !== void 0) {
16823
17074
  const failed = await settleAfterTurnStarted(
16824
17075
  admitted,
16825
- {
17076
+ withEngineDetourInvocationScope({
16826
17077
  timedOut: false,
16827
17078
  code: result.code,
16828
17079
  stderr: result.stderr,
16829
17080
  thrown: stderrLogWriteFailure
16830
- },
17081
+ }, request.invocationScopeId),
16831
17082
  adapters,
16832
17083
  env.principalAuthority,
16833
17084
  io,
@@ -16837,7 +17088,7 @@ async function dispatchPostAdmissionTurn(input) {
16837
17088
  }
16838
17089
  const noReceipt = await attachRecordedSubmissions(
16839
17090
  admitted,
16840
- await settleHostEndedNoReceipt(admitted, env.principalAuthority),
17091
+ await settleHostEndedNoReceipt(admitted, env.principalAuthority, courtScope),
16841
17092
  courtScope
16842
17093
  );
16843
17094
  if (persistRunState) {
@@ -16846,13 +17097,13 @@ async function dispatchPostAdmissionTurn(input) {
16846
17097
  } catch (error) {
16847
17098
  const failed = await settleAfterTurnStarted(
16848
17099
  admitted,
16849
- {
17100
+ withEngineDetourInvocationScope({
16850
17101
  timedOut: false,
16851
17102
  code: null,
16852
17103
  stderr: "",
16853
17104
  thrown: error,
16854
17105
  skipRunStateWrite: true
16855
- },
17106
+ }, request.invocationScopeId),
16856
17107
  adapters,
16857
17108
  env.principalAuthority,
16858
17109
  io,
@@ -16921,7 +17172,7 @@ function resumeTurnRequestProjectionOptions(admitted, request, env, summonsPrepa
16921
17172
  kind: "resume",
16922
17173
  prompt
16923
17174
  },
16924
- ...request.message === void 0 ? {} : { courtAttemptId: randomUUID6() },
17175
+ ...request.message === void 0 ? {} : { courtAttemptId: randomUUID7() },
16925
17176
  ...env.stationChild === void 0 ? {} : { stationChild: env.stationChild }
16926
17177
  };
16927
17178
  }
@@ -16939,7 +17190,7 @@ async function dispatchAfterWriterLease(input) {
16939
17190
  }
16940
17191
  function isAlreadyFrozenSummonsAttachment(runDirectory, attachmentPath) {
16941
17192
  const absolute = isAbsolute8(attachmentPath) ? attachmentPath : resolve13(attachmentPath);
16942
- return pathContainedIn(join32(runDirectory, "attachments"), absolute);
17193
+ return pathContainedIn(join33(runDirectory, "attachments"), absolute);
16943
17194
  }
16944
17195
  async function prepareSummonsResumeMaterials(runDirectory, summons) {
16945
17196
  if (summons === void 0) return void 0;
@@ -17018,7 +17269,7 @@ async function runPostAdmissionSeatResume(input) {
17018
17269
  }
17019
17270
  let turnRequest = await input.buildTurnRequest(admittedForBuild, request);
17020
17271
  if (openCourtAttemptId !== void 0 || request.summons !== void 0 || request.message !== void 0) {
17021
- const courtAttemptId = openCourtAttemptId ?? (turnRequest.courtAttemptId !== void 0 && turnRequest.courtAttemptId.length > 0 ? turnRequest.courtAttemptId : randomUUID6());
17272
+ const courtAttemptId = openCourtAttemptId ?? (turnRequest.courtAttemptId !== void 0 && turnRequest.courtAttemptId.length > 0 ? turnRequest.courtAttemptId : randomUUID7());
17022
17273
  turnRequest = { ...turnRequest, courtAttemptId };
17023
17274
  if (openCourtAttemptId === void 0) {
17024
17275
  const court = {
@@ -17034,6 +17285,9 @@ async function runPostAdmissionSeatResume(input) {
17034
17285
  if (input.env.stationChild === true) {
17035
17286
  let firstTurn;
17036
17287
  const stationAdapters = withOnceSuccessfulBeforeDispatch(adapters);
17288
+ const invocationScopeId = mintEngineDetourInvocationScope({
17289
+ ...input.effectiveEngine === void 0 ? {} : { effectiveEngine: input.effectiveEngine }
17290
+ });
17037
17291
  return await runWithAutoResumeLoop({
17038
17292
  admitted: loaded.admitted,
17039
17293
  principalAuthority: input.env.principalAuthority,
@@ -17060,7 +17314,10 @@ async function runPostAdmissionSeatResume(input) {
17060
17314
  }
17061
17315
  };
17062
17316
  }
17063
- const turnRequest = await buildRequestAfterLease();
17317
+ const turnRequest = withEngineDetourInvocationScope(
17318
+ await buildRequestAfterLease(),
17319
+ invocationScopeId
17320
+ );
17064
17321
  firstTurn = turnRequest;
17065
17322
  return turnRequest;
17066
17323
  },
@@ -17131,6 +17388,11 @@ async function runPostAdmissionOneShot(input) {
17131
17388
  async function runPostAdmissionResumable(input) {
17132
17389
  const { admitted, env, io, buildInitialRequest, buildResumeRequest, effectiveEngine } = input;
17133
17390
  const adapters = withOnceSuccessfulBeforeDispatch(input.adapters);
17391
+ const invocationScopeId = mintEngineDetourInvocationScope({
17392
+ ...effectiveEngine === void 0 ? {} : { effectiveEngine }
17393
+ });
17394
+ const buildScopedInitial = () => withEngineDetourInvocationScope(buildInitialRequest(), invocationScopeId);
17395
+ const buildScopedResume = () => withEngineDetourInvocationScope(buildResumeRequest(), invocationScopeId);
17134
17396
  return runWithAutoResumeLoop({
17135
17397
  admitted,
17136
17398
  principalAuthority: env.principalAuthority,
@@ -17138,8 +17400,8 @@ async function runPostAdmissionResumable(input) {
17138
17400
  io,
17139
17401
  sessionAppender: env.sessionAppender,
17140
17402
  autoResumeLimit: env.autoResumeLimit,
17141
- buildInitialPayload: buildInitialRequest,
17142
- buildResumePayload: buildResumeRequest,
17403
+ buildInitialPayload: buildScopedInitial,
17404
+ buildResumePayload: buildScopedResume,
17143
17405
  dispatch: async (request, lease, _isFirst, attemptIo) => {
17144
17406
  const result = await dispatchPostAdmissionTurn({
17145
17407
  admitted,
@@ -17187,6 +17449,9 @@ async function runPostAdmissionManualResume(input) {
17187
17449
  }
17188
17450
  throw error;
17189
17451
  }
17452
+ const invocationScopeId = mintEngineDetourInvocationScope({
17453
+ ...effectiveEngine === void 0 ? {} : { effectiveEngine }
17454
+ });
17190
17455
  const result = await dispatchAfterWriterLease({
17191
17456
  lease,
17192
17457
  build: async () => {
@@ -17198,6 +17463,7 @@ async function runPostAdmissionManualResume(input) {
17198
17463
  }
17199
17464
  request = await buildRequestAfterLease();
17200
17465
  }
17466
+ request = withEngineDetourInvocationScope(request, invocationScopeId);
17201
17467
  return request;
17202
17468
  },
17203
17469
  dispatch: (turnRequest) => dispatchPostAdmissionTurn({
@@ -17237,6 +17503,7 @@ var init_post_admission = __esm({
17237
17503
  init_session_identity();
17238
17504
  init_host_contracts();
17239
17505
  init_case_dossier_delivery();
17506
+ init_engine_detour_usage();
17240
17507
  init_host_transition_prior_native();
17241
17508
  init_public_run_credentials();
17242
17509
  init_run_lifecycle();
@@ -17271,6 +17538,7 @@ function projectRoleTurnRequest(admitted, roleDetails, options) {
17271
17538
  ...options.correlationId === void 0 || options.correlationId.trim() === "" ? {} : { correlationId: options.correlationId },
17272
17539
  ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs },
17273
17540
  ...options.courtAttemptId === void 0 || options.courtAttemptId.length === 0 ? {} : { courtAttemptId: options.courtAttemptId },
17541
+ ...options.invocationScopeId === void 0 || options.invocationScopeId.length === 0 ? {} : { invocationScopeId: options.invocationScopeId },
17274
17542
  ...options.stationChild === void 0 ? {} : { stationChild: options.stationChild }
17275
17543
  };
17276
17544
  }
@@ -18289,7 +18557,7 @@ __export(public_role_summons_exports, {
18289
18557
  summonPublicRole: () => summonPublicRole
18290
18558
  });
18291
18559
  import { existsSync as existsSync10 } from "node:fs";
18292
- import { join as join33 } from "node:path";
18560
+ import { join as join34 } from "node:path";
18293
18561
  function createCapturingIo() {
18294
18562
  const chunks = [];
18295
18563
  return {
@@ -18312,7 +18580,7 @@ function parentDir(path) {
18312
18580
  function walkPackageRoot(start) {
18313
18581
  let dir = start;
18314
18582
  for (let i = 0; i < 12; i += 1) {
18315
- if (existsSync10(join33(dir, "package.json")) && existsSync10(join33(dir, "souls"))) {
18583
+ if (existsSync10(join34(dir, "package.json")) && existsSync10(join34(dir, "souls"))) {
18316
18584
  return dir;
18317
18585
  }
18318
18586
  const parent = parentDir(dir);
@@ -18406,7 +18674,7 @@ async function createSummonEnv(options) {
18406
18674
  async function summonPublicRole(options) {
18407
18675
  const packageRoot = resolveSummonsPackageRoot(options.packageRoot);
18408
18676
  const home = await resolveSummonHome(options);
18409
- const agentDir = options.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join33(home, ".pi", "agent");
18677
+ const agentDir = options.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join34(home, ".pi", "agent");
18410
18678
  const {
18411
18679
  loadCredentialProviders: loadCredentialProviders2,
18412
18680
  loadPublicCliConfig: loadPublicCliConfig2,
@@ -18788,12 +19056,12 @@ __export(session_assistant_usage_exports, {
18788
19056
  sessionFileFromPublicSummon: () => sessionFileFromPublicSummon,
18789
19057
  usageFromPublicSummon: () => usageFromPublicSummon
18790
19058
  });
18791
- import { join as join34 } from "node:path";
19059
+ import { join as join35 } from "node:path";
18792
19060
  async function readAssistantUsageFromSessionFile(sessionFile) {
18793
- const { readFile: readFile26 } = await import("node:fs/promises");
19061
+ const { readFile: readFile25 } = await import("node:fs/promises");
18794
19062
  let text;
18795
19063
  try {
18796
- text = await readFile26(sessionFile, "utf8");
19064
+ text = await readFile25(sessionFile, "utf8");
18797
19065
  } catch (error) {
18798
19066
  if (error?.code === "ENOENT") return void 0;
18799
19067
  throw error;
@@ -18858,7 +19126,7 @@ async function readAssistantUsageFromSessionFile(sessionFile) {
18858
19126
  }
18859
19127
  function sessionFileFromPublicSummon(summoned) {
18860
19128
  if (typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "") {
18861
- return join34(summoned.runDirectory, "session", "session.jsonl");
19129
+ return join35(summoned.runDirectory, "session", "session.jsonl");
18862
19130
  }
18863
19131
  const fromArtifacts = summoned.terminal?.artifacts?.map((a) => a.path).find((p) => typeof p === "string" && p.endsWith("session.jsonl"));
18864
19132
  if (fromArtifacts !== void 0) return fromArtifacts;
@@ -18867,7 +19135,7 @@ function sessionFileFromPublicSummon(summoned) {
18867
19135
  const facts = outcome.decisiveFacts;
18868
19136
  const pointer = facts?.runPointer;
18869
19137
  if (typeof pointer === "string" && pointer.trim() !== "") {
18870
- return join34(pointer, "session", "session.jsonl");
19138
+ return join35(pointer, "session", "session.jsonl");
18871
19139
  }
18872
19140
  return void 0;
18873
19141
  }
@@ -19047,7 +19315,7 @@ var init_doctor_auditor = __esm({
19047
19315
 
19048
19316
  // src/archivist-record-topology.ts
19049
19317
  import { createHash as createHash7 } from "node:crypto";
19050
- import { join as join35 } from "node:path";
19318
+ import { join as join36 } from "node:path";
19051
19319
  function resolveNavigatorWorkSubjectPlacement(input) {
19052
19320
  let ledgerHome;
19053
19321
  if (input.parentSessionFile !== void 0 && input.parentSessionFile.length > 0) {
@@ -19060,7 +19328,7 @@ function resolveNavigatorWorkSubjectPlacement(input) {
19060
19328
  const digest = createHash7("sha256").update(input.subject).digest("hex").slice(0, 32);
19061
19329
  return {
19062
19330
  ledgerHome,
19063
- sessionDir: join35(
19331
+ sessionDir: join36(
19064
19332
  activationBookDirectory(ledgerHome, resolveBookKeyFromGit(input.cwd)),
19065
19333
  NAVIGATOR_RECORD_KIND,
19066
19334
  digest
@@ -19094,19 +19362,19 @@ import {
19094
19362
  mkdirSync as mkdirSync2,
19095
19363
  openSync,
19096
19364
  readdirSync as readdirSync2,
19097
- readFileSync as readFileSync3,
19365
+ readFileSync as readFileSync4,
19098
19366
  readSync,
19099
19367
  realpathSync as realpathSync2,
19100
19368
  statSync as statSync3,
19101
19369
  writeFileSync as writeFileSync2
19102
19370
  } from "node:fs";
19103
- import { dirname as dirname18, resolve as resolve14, join as join36 } from "node:path";
19371
+ import { dirname as dirname19, resolve as resolve14, join as join37 } from "node:path";
19104
19372
  import { StringDecoder } from "node:string_decoder";
19105
19373
  import { SessionManager } from "@earendil-works/pi-coding-agent";
19106
19374
  function readCurrentSession(sessionDir) {
19107
- const ledger = join36(sessionDir, CURRENT_SESSION_LEDGER);
19375
+ const ledger = join37(sessionDir, CURRENT_SESSION_LEDGER);
19108
19376
  try {
19109
- const value = JSON.parse(readFileSync3(ledger, "utf8"));
19377
+ const value = JSON.parse(readFileSync4(ledger, "utf8"));
19110
19378
  if (typeof value !== "object" || value === null || typeof value.sessionFile !== "string" || value.sessionFile.length === 0) {
19111
19379
  throw new Error("sessionFile is missing");
19112
19380
  }
@@ -19119,7 +19387,7 @@ function readCurrentSession(sessionDir) {
19119
19387
  }
19120
19388
  }
19121
19389
  function writeCurrentSession(sessionDir, sessionFile) {
19122
- const ledger = join36(sessionDir, CURRENT_SESSION_LEDGER);
19390
+ const ledger = join37(sessionDir, CURRENT_SESSION_LEDGER);
19123
19391
  try {
19124
19392
  writeFileSync2(ledger, `${JSON.stringify({ sessionFile })}
19125
19393
  `, { flag: "wx" });
@@ -19135,7 +19403,7 @@ function isCurrentSessionClaimRace(error) {
19135
19403
  return errnoCode(error.cause) === "EEXIST";
19136
19404
  }
19137
19405
  function currentSessionLedgerPath(sessionDir) {
19138
- return join36(sessionDir, CURRENT_SESSION_LEDGER);
19406
+ return join37(sessionDir, CURRENT_SESSION_LEDGER);
19139
19407
  }
19140
19408
  function readBoundedSessionHeader(filePath) {
19141
19409
  const fd = openSync(filePath, "r");
@@ -19222,7 +19490,7 @@ function mostRecentNavigatorSessionFile(sessionDir, cwd) {
19222
19490
  const matched = [];
19223
19491
  for (const name of names) {
19224
19492
  if (!name.endsWith(".jsonl")) continue;
19225
- const filePath = join36(absoluteSessionDir, name);
19493
+ const filePath = join37(absoluteSessionDir, name);
19226
19494
  let st;
19227
19495
  try {
19228
19496
  st = statSync3(filePath);
@@ -19334,7 +19602,7 @@ function createRecordSessionOpen(options) {
19334
19602
  if (!physicallyContainedIn(ledgerHome, parentResolved)) {
19335
19603
  throw new Error("Durable record ownership requires a parent session inside the ledger home");
19336
19604
  }
19337
- sessionDir = join36(dirname18(parentResolved), options.kind);
19605
+ sessionDir = join37(dirname19(parentResolved), options.kind);
19338
19606
  parentSession = parentFile;
19339
19607
  mayResumeSameNest = options.kind === WORKER_SUBMISSION_GATE_KIND;
19340
19608
  }
@@ -19383,7 +19651,7 @@ function createRecordSession(options) {
19383
19651
  return createRecordSessionOpen(options).session;
19384
19652
  }
19385
19653
  function bookDirectOfficerRunPointer(options) {
19386
- const nest = join36(dirname18(options.parentSessionFile), "auditor-roles");
19654
+ const nest = join37(dirname19(options.parentSessionFile), "auditor-roles");
19387
19655
  mkdirSync2(nest, { recursive: true });
19388
19656
  const pointer = {
19389
19657
  version: 1,
@@ -19393,7 +19661,7 @@ function bookDirectOfficerRunPointer(options) {
19393
19661
  ...options.runDirectory !== void 0 && options.runDirectory.trim() !== "" ? { runDirectory: options.runDirectory } : {}
19394
19662
  };
19395
19663
  writeFileSync2(
19396
- join36(nest, `${options.officer}.pointer.json`),
19664
+ join37(nest, `${options.officer}.pointer.json`),
19397
19665
  `${JSON.stringify(pointer)}
19398
19666
  `,
19399
19667
  "utf8"
@@ -19416,10 +19684,10 @@ var init_archivist_record_entry = __esm({
19416
19684
  });
19417
19685
 
19418
19686
  // src/headless-host/production-host.ts
19419
- import { randomUUID as randomUUID9 } from "node:crypto";
19687
+ import { randomUUID as randomUUID10 } from "node:crypto";
19420
19688
 
19421
19689
  // src/role-runtime-dependencies.ts
19422
- import { readFile as readFile24 } from "node:fs/promises";
19690
+ import { readFile as readFile23 } from "node:fs/promises";
19423
19691
  import { fileURLToPath as fileURLToPath2 } from "node:url";
19424
19692
 
19425
19693
  // src/canonical-skill-binding.ts
@@ -20468,7 +20736,7 @@ ${helpContext}
20468
20736
  // src/navigator-work-context.ts
20469
20737
  init_doctor_evidence();
20470
20738
  init_host_contracts();
20471
- import { readFile as readFile22 } from "node:fs/promises";
20739
+ import { readFile as readFile21 } from "node:fs/promises";
20472
20740
  import { resolve as resolve16 } from "node:path";
20473
20741
  init_notary_source_run();
20474
20742
  init_packaged_role_registry();
@@ -20481,7 +20749,7 @@ function navigatorInputReference(getFlag, role) {
20481
20749
  }
20482
20750
  async function loadNavigatorWorkContext(options) {
20483
20751
  const reference = navigatorInputReference(options.getFlag, options.role);
20484
- const input = reference === void 0 || options.role === "doctor" || options.role === "notary" ? void 0 : await readFile22(reference, "utf8");
20752
+ const input = reference === void 0 || options.role === "doctor" || options.role === "notary" ? void 0 : await readFile21(reference, "utf8");
20485
20753
  const subjectRoot = subjectPath(reference ?? options.context.sessionManager.getSessionDir(), options.context.cwd);
20486
20754
  let subjectKey = reference === void 0 ? subjectRoot : navigatorSubjectKeyForInput(subjectRoot, reference, options.context.cwd);
20487
20755
  let subject = input ?? `work subject: ${subjectKey}`;
@@ -20538,7 +20806,7 @@ async function loadNavigatorWorkContext(options) {
20538
20806
  let authorityMaterial;
20539
20807
  for (const path of authorityFiles) {
20540
20808
  try {
20541
- const content = await readFile22(path, "utf8");
20809
+ const content = await readFile21(path, "utf8");
20542
20810
  if (content.trim() !== "") {
20543
20811
  authorityMaterial = content;
20544
20812
  break;
@@ -20563,7 +20831,7 @@ async function loadNavigatorWorkContext(options) {
20563
20831
  init_notary_source_run();
20564
20832
 
20565
20833
  // src/package-resources/method-skill-binding.ts
20566
- import { dirname as dirname20 } from "node:path";
20834
+ import { dirname as dirname21 } from "node:path";
20567
20835
  init_method_skill();
20568
20836
  async function loadPackagedCanonicalSkillBinding(packageRoot, name) {
20569
20837
  const material = await loadPackagedMethodSkillMaterial(packageRoot, name);
@@ -20571,7 +20839,7 @@ async function loadPackagedCanonicalSkillBinding(packageRoot, name) {
20571
20839
  const snapshot = Object.freeze({
20572
20840
  raw: material.raw,
20573
20841
  path: material.skillPath,
20574
- baseDir: dirname20(material.skillPath),
20842
+ baseDir: dirname21(material.skillPath),
20575
20843
  body: material.body,
20576
20844
  snapshotIdentity: Object.freeze({ text: material.raw })
20577
20845
  });
@@ -20596,8 +20864,8 @@ init_host_contracts();
20596
20864
  init_sitian_facade();
20597
20865
  init_submission_ledger();
20598
20866
  init_collector_ledger();
20599
- import { readFileSync as readFileSync5, writeSync as writeSync4 } from "node:fs";
20600
- import { join as join39 } from "node:path";
20867
+ import { readFileSync as readFileSync6, writeSync as writeSync4 } from "node:fs";
20868
+ import { join as join40 } from "node:path";
20601
20869
  import { Value as Value4 } from "typebox/value";
20602
20870
 
20603
20871
  // src/activation-trace.ts
@@ -20647,7 +20915,7 @@ import {
20647
20915
  openSync as openSync2,
20648
20916
  writeSync
20649
20917
  } from "node:fs";
20650
- import { dirname as dirname21, isAbsolute as isAbsolute10, resolve as resolve18 } from "node:path";
20918
+ import { dirname as dirname22, isAbsolute as isAbsolute10, resolve as resolve18 } from "node:path";
20651
20919
 
20652
20920
  // src/activation-ledger-session.ts
20653
20921
  init_activation_ledger_topology();
@@ -20796,7 +21064,7 @@ function appendActivationLedgerLine(ledgerPath, line2, options) {
20796
21064
  }
20797
21065
  const resolvedLedger = resolve18(ledgerPath);
20798
21066
  const resolvedHome = resolve18(options.ledgerHome);
20799
- const parent = dirname21(resolvedLedger);
21067
+ const parent = dirname22(resolvedLedger);
20800
21068
  ensureRealDirectoryTree(resolvedHome, parent);
20801
21069
  assertLedgerFileInsideHome(resolvedLedger, resolvedHome);
20802
21070
  if (typeof constants2.O_NOFOLLOW !== "number") {
@@ -21010,7 +21278,15 @@ init_engine_material();
21010
21278
 
21011
21279
  // src/engine-detour-tool.ts
21012
21280
  init_engine_detour();
21281
+ init_engine_detour_usage();
21282
+ import { basename as basename9 } from "node:path";
21013
21283
  import { Type as Type16 } from "typebox";
21284
+ function basenameRunId(runDirectory) {
21285
+ const leaf = basename9(runDirectory);
21286
+ const at = leaf.indexOf("@");
21287
+ if (at <= 0) return void 0;
21288
+ return leaf.slice(0, at);
21289
+ }
21014
21290
  var engineDetourArgsSchema = Type16.Object(
21015
21291
  {
21016
21292
  argv: Type16.Array(Type16.String({ minLength: 1 }), {
@@ -21027,6 +21303,9 @@ function isCallerCancellation(error, signal) {
21027
21303
  }
21028
21304
  return false;
21029
21305
  }
21306
+ function asError(error, fallback) {
21307
+ return error instanceof Error ? error : new Error(String(error).trim() || fallback);
21308
+ }
21030
21309
  function createEngineDetourToolDefinition(input) {
21031
21310
  const engineName = input.engineName;
21032
21311
  const engineModel = input.engineModel;
@@ -21047,6 +21326,45 @@ function createEngineDetourToolDefinition(input) {
21047
21326
  ctx
21048
21327
  );
21049
21328
  }
21329
+ const sessionParent = ctx.sessionManager?.getSessionFile?.();
21330
+ const startedAt = Date.now();
21331
+ const runDirectory = typeof ctx.runDirectory === "string" && ctx.runDirectory.length > 0 ? ctx.runDirectory : void 0;
21332
+ const runId = runDirectory === void 0 ? void 0 : basenameRunId(runDirectory);
21333
+ const invocationScopeId = typeof ctx.invocationScopeId === "string" && ctx.invocationScopeId.trim() !== "" ? ctx.invocationScopeId.trim() : void 0;
21334
+ const host = typeof ctx.host === "string" && ctx.host.trim() !== "" ? ctx.host.trim() : void 0;
21335
+ const recordCall = (observed2) => {
21336
+ if (typeof sessionParent !== "string" || sessionParent.length === 0) return;
21337
+ reportEngineDetourCall({
21338
+ toolCallId,
21339
+ durationMs: Math.max(0, Date.now() - startedAt),
21340
+ cwd: ctx.cwd,
21341
+ sessionParent,
21342
+ ...runId === void 0 ? {} : { runId },
21343
+ ...invocationScopeId === void 0 ? {} : { invocationScopeId },
21344
+ ...host === void 0 ? {} : { host },
21345
+ ...observed2.code === void 0 ? {} : { code: observed2.code },
21346
+ ...observed2.stdoutByteLength === void 0 ? {} : { stdoutByteLength: observed2.stdoutByteLength }
21347
+ });
21348
+ };
21349
+ const failAfterLedger = (engineCause, observed2, aggregateMessage) => {
21350
+ try {
21351
+ recordCall(observed2);
21352
+ } catch (recordError) {
21353
+ input.fail(
21354
+ new AggregateError(
21355
+ [
21356
+ engineCause,
21357
+ asError(recordError, "engine detour usage ledger write failed")
21358
+ ],
21359
+ aggregateMessage,
21360
+ { cause: engineCause }
21361
+ ),
21362
+ toolCallId,
21363
+ ctx
21364
+ );
21365
+ }
21366
+ input.fail(engineCause, toolCallId, ctx);
21367
+ };
21050
21368
  let result;
21051
21369
  try {
21052
21370
  result = await runEngineDetourOnce({
@@ -21056,16 +21374,22 @@ function createEngineDetourToolDefinition(input) {
21056
21374
  });
21057
21375
  } catch (error) {
21058
21376
  if (isCallerCancellation(error, signal)) throw error;
21059
- const cause = error instanceof Error ? error : new Error(String(error).trim() || "\u52B3\u52A1\u5F15\u64CE spawn \u5931\u8D25");
21060
- input.fail(cause, toolCallId, ctx);
21377
+ return failAfterLedger(
21378
+ asError(error, "\u52B3\u52A1\u5F15\u64CE spawn \u5931\u8D25"),
21379
+ {},
21380
+ "engine detour spawn and usage ledger both failed"
21381
+ );
21061
21382
  }
21383
+ const stdoutByteLength = engineDetourStdoutByteLength(result.stdout);
21384
+ const observed = { code: result.code, stdoutByteLength };
21062
21385
  if (isEngineDetourFailure(result)) {
21063
- input.fail(
21386
+ return failAfterLedger(
21064
21387
  new Error(engineDetourFailureDiagnostic(result)),
21065
- toolCallId,
21066
- ctx
21388
+ observed,
21389
+ "engine detour child-close and usage ledger both failed"
21067
21390
  );
21068
21391
  }
21392
+ recordCall(observed);
21069
21393
  return {
21070
21394
  content: [{ type: "text", text: result.stdout }],
21071
21395
  details: {
@@ -21106,8 +21430,8 @@ init_collector_github();
21106
21430
  // src/collector-handbook.ts
21107
21431
  init_atomic_write();
21108
21432
  init_activation_ledger_topology();
21109
- import { readFile as readFile23 } from "node:fs/promises";
21110
- import { join as join38, sep as sep5 } from "node:path";
21433
+ import { readFile as readFile22 } from "node:fs/promises";
21434
+ import { join as join39, sep as sep5 } from "node:path";
21111
21435
 
21112
21436
  // src/collector-tool-schemas.ts
21113
21437
  init_open_tool_schema();
@@ -21222,7 +21546,7 @@ function resolveCollectorHandbookRoot(sessionPath) {
21222
21546
  throw new Error(`\u901A\u8FDB\u53F8\u624B\u518C\u62D2\u7EDD\u4E0D\u5B89\u5168 bookKey ${JSON.stringify(bookKey)}`);
21223
21547
  }
21224
21548
  const ledgerHome = resolveActivationLedgerHomeForPath(sessionPath);
21225
- const root = join38(activationBookDirectory(ledgerHome, bookKey), "collector-handbook");
21549
+ const root = join39(activationBookDirectory(ledgerHome, bookKey), "collector-handbook");
21226
21550
  return { ledgerHome, bookKey, root };
21227
21551
  }
21228
21552
  function collectorHandbookRepoFileName(repositoryCanonical) {
@@ -21234,9 +21558,9 @@ function collectorHandbookRepoFileName(repositoryCanonical) {
21234
21558
  return `${repositoryCanonical.replaceAll("/", "__")}.md`;
21235
21559
  }
21236
21560
  function createCollectorHandbookStore(input) {
21237
- const generalPath = join38(input.handbookRoot, "general.md");
21238
- const repoDir = join38(input.handbookRoot, "repos");
21239
- const repoPath = join38(repoDir, collectorHandbookRepoFileName(input.repositoryCanonical));
21561
+ const generalPath = join39(input.handbookRoot, "general.md");
21562
+ const repoDir = join39(input.handbookRoot, "repos");
21563
+ const repoPath = join39(repoDir, collectorHandbookRepoFileName(input.repositoryCanonical));
21240
21564
  const assertHandbookBudget = (body, label) => {
21241
21565
  const byteLength = Buffer.byteLength(body, "utf8");
21242
21566
  if (byteLength > COLLECTOR_HANDBOOK_MAX_BYTES) {
@@ -21250,7 +21574,7 @@ function createCollectorHandbookStore(input) {
21250
21574
  ensureRealDirectoryTree(input.ledgerHome, parentDir2);
21251
21575
  assertLedgerFileInsideHome(path, input.ledgerHome);
21252
21576
  try {
21253
- const body = await readFile23(path, "utf8");
21577
+ const body = await readFile22(path, "utf8");
21254
21578
  assertHandbookBudget(body, "\u6B63\u6587");
21255
21579
  return body;
21256
21580
  } catch (error) {
@@ -22509,7 +22833,7 @@ init_sitian_facade();
22509
22833
  init_submission_errors();
22510
22834
  init_submission_errors();
22511
22835
  import { execFileSync as execFileSync4 } from "node:child_process";
22512
- import { existsSync as existsSync12, lstatSync as lstatSync3, readdirSync as readdirSync3, readFileSync as readFileSync4, rmdirSync, rmSync } from "node:fs";
22836
+ import { existsSync as existsSync12, lstatSync as lstatSync3, readdirSync as readdirSync3, readFileSync as readFileSync5, rmdirSync, rmSync } from "node:fs";
22513
22837
  import { resolve as resolve19 } from "node:path";
22514
22838
  var WORKER_SUBMISSION_GATE_RECORD_KIND = WORKER_SUBMISSION_GATE_KIND;
22515
22839
  var WORKER_COMMIT_BASELINE_ENTRY_TYPE = "commit-baseline";
@@ -22551,7 +22875,7 @@ function tryGetAll(file, key) {
22551
22875
  }
22552
22876
  function ownedHook(path) {
22553
22877
  if (!existsSync12(path)) return false;
22554
- return readFileSync4(path, "utf8").includes(HOOK_MARKER);
22878
+ return readFileSync5(path, "utf8").includes(HOOK_MARKER);
22555
22879
  }
22556
22880
  function escapeGitConfigValueRegex(value) {
22557
22881
  return value.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
@@ -22606,7 +22930,7 @@ function uninstallPackageWorkerHooks(cwd) {
22606
22930
  rmOwnedDir(resolve19(gitDir, HOOKS_DIR));
22607
22931
  }
22608
22932
  }
22609
- function isRecord12(value) {
22933
+ function isRecord13(value) {
22610
22934
  return typeof value === "object" && value !== null && !Array.isArray(value);
22611
22935
  }
22612
22936
  function unfinishedReasonPresent(details) {
@@ -22622,7 +22946,7 @@ function readGateState(session) {
22622
22946
  if (entry.type !== "custom") continue;
22623
22947
  if (entry.customType === WORKER_COMMIT_BASELINE_ENTRY_TYPE) {
22624
22948
  const data = entry.data;
22625
- if (isRecord12(data) && (data.head === null || typeof data.head === "string")) {
22949
+ if (isRecord13(data) && (data.head === null || typeof data.head === "string")) {
22626
22950
  baseline = data.head;
22627
22951
  }
22628
22952
  } else if (entry.customType === WORKER_COMMIT_REMINDER_BOUNCE_ENTRY_TYPE) {
@@ -23593,8 +23917,8 @@ function readDiaristRunCoordinates(ctx) {
23593
23917
  if (runDirectory === void 0) {
23594
23918
  throw new Error("diarist accept requires AK_ROLE_RUN_DIR");
23595
23919
  }
23596
- const admittedPath = join39(runDirectory, "admitted-request.json");
23597
- const admitted = JSON.parse(readFileSync5(admittedPath, "utf8"));
23920
+ const admittedPath = join40(runDirectory, "admitted-request.json");
23921
+ const admitted = JSON.parse(readFileSync6(admittedPath, "utf8"));
23598
23922
  if (typeof admitted.projectRoot !== "string" || admitted.projectRoot.trim() === "") {
23599
23923
  throw new Error(`diarist admitted-request missing projectRoot (${admittedPath})`);
23600
23924
  }
@@ -24573,13 +24897,13 @@ function createRoleRuntimeDependencies(packageRoot) {
24573
24897
  packageRoot,
24574
24898
  loadJudgeSoul: () => loadMainRoleSessionMaterials("judge"),
24575
24899
  loadFixerSoul: () => loadMainRoleSessionMaterials("fixer"),
24576
- loadFixPacket: (path) => readFile24(path, "utf8"),
24900
+ loadFixPacket: (path) => readFile23(path, "utf8"),
24577
24901
  loadCoderSoul: () => loadMainRoleSessionMaterials("coder"),
24578
- loadCoderTask: (path) => readFile24(path, "utf8"),
24902
+ loadCoderTask: (path) => readFile23(path, "utf8"),
24579
24903
  loadReviewerSoul: () => loadMainRoleSessionMaterials("reviewer"),
24580
24904
  createReviewerPinnedGitReader: () => createReviewerPinnedGitReader(),
24581
24905
  loadCollectorSoul: () => loadMainRoleSessionMaterials("collector"),
24582
- loadCollectorHandbookSeed: () => readFile24(collectorHandbookSeedPath, "utf8"),
24906
+ loadCollectorHandbookSeed: () => readFile23(collectorHandbookSeedPath, "utf8"),
24583
24907
  createCollectorTransport: () => createGhCollectorGitHubTransport(),
24584
24908
  loadDoctorSoul: () => loadMainRoleSessionMaterials("doctor"),
24585
24909
  loadDoctorCase,
@@ -24593,7 +24917,7 @@ function createRoleRuntimeDependencies(packageRoot) {
24593
24917
  loadDiaristSoul: () => loadMainRoleSessionMaterials("diarist"),
24594
24918
  loadNotarySourceRun: loadNotarySourceRunLocator,
24595
24919
  loadMergerSoul: () => loadMainRoleSessionMaterials("merger"),
24596
- loadMergerInput: async (path) => JSON.parse(await readFile24(path, "utf8")),
24920
+ loadMergerInput: async (path) => JSON.parse(await readFile23(path, "utf8")),
24597
24921
  async loadCanonicalSkillBinding(name) {
24598
24922
  if (name === "tdd") {
24599
24923
  return loadPackagedCanonicalSkillBinding(packageRoot, "tdd");
@@ -24619,7 +24943,7 @@ function createRoleRuntimeDependencies(packageRoot) {
24619
24943
  authority: options.authority,
24620
24944
  invocationId: options.invocationId,
24621
24945
  loadSoul: () => loadMainRoleSessionMaterials("navigator"),
24622
- loadRoutePlaybook: () => readFile24(navigatorRoutePlaybookPath, "utf8"),
24946
+ loadRoutePlaybook: () => readFile23(navigatorRoutePlaybookPath, "utf8"),
24623
24947
  loadRoleHelp: async (role) => formatNavigatorRoleHelp(role),
24624
24948
  createSession: navigatorSessionFactory,
24625
24949
  ...options.contextError === void 0 ? {} : { contextError: options.contextError },
@@ -24630,10 +24954,10 @@ function createRoleRuntimeDependencies(packageRoot) {
24630
24954
 
24631
24955
  // src/role-envelope.ts
24632
24956
  init_engine_detour();
24633
- import { randomUUID as randomUUID7 } from "node:crypto";
24634
- import { mkdir as mkdir5, readFile as readFile25, writeFile as writeFile12 } from "node:fs/promises";
24957
+ import { randomUUID as randomUUID8 } from "node:crypto";
24958
+ import { mkdir as mkdir5, readFile as readFile24, writeFile as writeFile12 } from "node:fs/promises";
24635
24959
  import { createServer } from "node:net";
24636
- import { basename as basename9, dirname as dirname22, join as join40 } from "node:path";
24960
+ import { basename as basename10, dirname as dirname23, join as join41 } from "node:path";
24637
24961
  import { fileURLToPath as fileURLToPath3 } from "node:url";
24638
24962
 
24639
24963
  // src/gatekeeper-pass-envelope.ts
@@ -24756,16 +25080,16 @@ async function prepareRoleEnvelope(options) {
24756
25080
  let rejection;
24757
25081
  let infrastructureRoundFailure;
24758
25082
  const hostAbort = new AbortController();
24759
- const runId = request.runDirectory.split("/").filter(Boolean).at(-1) ?? randomUUID7();
25083
+ const runId = request.runDirectory.split("/").filter(Boolean).at(-1) ?? randomUUID8();
24760
25084
  await mkdir5(request.runDirectory, { recursive: true });
24761
25085
  for (const method of request.methods) {
24762
25086
  if (method.kind !== "skill") continue;
24763
- const name = basename9(dirname22(method.path));
24764
- const raw = await readFile25(method.path, "utf8");
25087
+ const name = basename10(dirname23(method.path));
25088
+ const raw = await readFile24(method.path, "utf8");
24765
25089
  methodSkills.set(name, { path: method.path, body: stripSkillFrontmatter(raw).trim() });
24766
25090
  }
24767
- let sessionFile = options.sessionFile ?? join40(request.runDirectory, "session", "session.jsonl");
24768
- await mkdir5(dirname22(sessionFile), { recursive: true });
25091
+ let sessionFile = options.sessionFile ?? join41(request.runDirectory, "session", "session.jsonl");
25092
+ await mkdir5(dirname23(sessionFile), { recursive: true });
24769
25093
  if (request.continuation.kind !== "resume") {
24770
25094
  try {
24771
25095
  await writeFile12(
@@ -24790,11 +25114,13 @@ async function prepareRoleEnvelope(options) {
24790
25114
  model: request.model === void 0 ? void 0 : { provider: request.model.provider },
24791
25115
  runDirectory: request.runDirectory,
24792
25116
  ...request.courtAttemptId === void 0 ? {} : { courtAttemptId: request.courtAttemptId },
25117
+ ...request.invocationScopeId === void 0 ? {} : { invocationScopeId: request.invocationScopeId },
25118
+ ...request.host === void 0 || request.host.trim() === "" ? {} : { host: request.host.trim() },
24793
25119
  sessionManager: {
24794
25120
  getLeafEntry: () => sessionEntries.at(-1),
24795
25121
  getLeafId: () => runId,
24796
25122
  getEntries: () => sessionEntries,
24797
- getSessionDir: () => dirname22(sessionFile),
25123
+ getSessionDir: () => dirname23(sessionFile),
24798
25124
  getSessionFile: () => sessionFile,
24799
25125
  getHeader: () => ({ type: "session", id: runId }),
24800
25126
  setSessionFile(path) {
@@ -24895,7 +25221,7 @@ async function prepareRoleEnvelope(options) {
24895
25221
  }
24896
25222
  };
24897
25223
  createRoleRuntimeExtension(options.dependencies)(envelope);
24898
- const token = randomUUID7();
25224
+ const token = randomUUID8();
24899
25225
  const server = createServer((socket) => serveSocket(socket));
24900
25226
  function rememberProjectedRejection(details, toolCallId, content) {
24901
25227
  if (typeof details !== "object" || details === null) return;
@@ -24976,7 +25302,7 @@ async function prepareRoleEnvelope(options) {
24976
25302
  async function invokeAkTool(name, args) {
24977
25303
  const tool = tools.get(name);
24978
25304
  if (tool === void 0) throw new Error(`Unknown AK tool: ${name}`);
24979
- const toolCallId = randomUUID7();
25305
+ const toolCallId = randomUUID8();
24980
25306
  calls.push({ toolCallId, toolName: name });
24981
25307
  sessionEntries.push({
24982
25308
  type: "message",
@@ -25169,7 +25495,7 @@ async function prepareRoleEnvelope(options) {
25169
25495
  message: { role: "user", content: prompt }
25170
25496
  });
25171
25497
  }
25172
- const methodPrompt = (await Promise.all(request.methods.map(({ path }) => readFile25(path, "utf8")))).join("\n\n");
25498
+ const methodPrompt = (await Promise.all(request.methods.map(({ path }) => readFile24(path, "utf8")))).join("\n\n");
25173
25499
  const promptResults = await emit("before_agent_start", {
25174
25500
  prompt,
25175
25501
  systemPrompt: methodPrompt,
@@ -25230,7 +25556,7 @@ async function prepareRoleEnvelope(options) {
25230
25556
  init_session_identity();
25231
25557
 
25232
25558
  // src/headless-host/description.ts
25233
- import { join as join41 } from "node:path";
25559
+ import { join as join42 } from "node:path";
25234
25560
  function isClaudePrintDescription(description) {
25235
25561
  return description.protocol === "claude-print";
25236
25562
  }
@@ -25238,7 +25564,7 @@ function isCodexExecDescription(description) {
25238
25564
  return description.protocol === "codex-exec";
25239
25565
  }
25240
25566
  function resolveHeadlessBinary(description, operatorHome) {
25241
- return join41(operatorHome, ...description.binaryFromHome);
25567
+ return join42(operatorHome, ...description.binaryFromHome);
25242
25568
  }
25243
25569
  function headlessTurnArgs(options) {
25244
25570
  const { description } = options;
@@ -25491,10 +25817,10 @@ function headlessMcpConfigDocument(mcpServers) {
25491
25817
 
25492
25818
  // src/headless-host/role-turn-host.ts
25493
25819
  import { spawn as spawn4, spawnSync } from "node:child_process";
25494
- import { randomUUID as randomUUID8 } from "node:crypto";
25820
+ import { randomUUID as randomUUID9 } from "node:crypto";
25495
25821
  import { existsSync as existsSync13 } from "node:fs";
25496
25822
  import { writeFile as writeFile13 } from "node:fs/promises";
25497
- import { dirname as dirname23, isAbsolute as isAbsolute11, join as join42, resolve as resolve20 } from "node:path";
25823
+ import { dirname as dirname24, isAbsolute as isAbsolute11, join as join43, resolve as resolve20 } from "node:path";
25498
25824
 
25499
25825
  // src/external-host-turn-loop.ts
25500
25826
  init_host_contracts();
@@ -25713,8 +26039,8 @@ function formatCodexFailurePayload(payload) {
25713
26039
  function cwdIsGitWorkTree(cwd) {
25714
26040
  let dir = cwd;
25715
26041
  for (; ; ) {
25716
- if (existsSync13(join42(dir, ".git"))) return true;
25717
- const parent = dirname23(dir);
26042
+ if (existsSync13(join43(dir, ".git"))) return true;
26043
+ const parent = dirname24(dir);
25718
26044
  if (parent === dir) return false;
25719
26045
  dir = parent;
25720
26046
  }
@@ -25916,21 +26242,21 @@ function createHeadlessRoleTurnHost(config) {
25916
26242
  let sessionId = await config.sessionIdentity.load(request.principal);
25917
26243
  let sessionKind = request.continuation.kind === "resume" && sessionId !== void 0 && sessionId !== "" ? "resume" : "new";
25918
26244
  if (sessionKind === "new" && !codex) {
25919
- sessionId = randomUUID8();
26245
+ sessionId = randomUUID9();
25920
26246
  await config.sessionIdentity.bind(request.principal, sessionId);
25921
26247
  }
25922
26248
  const env = { ...process.env, ...config.env ?? {} };
25923
- const systemPromptPath = join42(request.runDirectory, "headless-system-prompt.txt");
26249
+ const systemPromptPath = join43(request.runDirectory, "headless-system-prompt.txt");
25924
26250
  await writeFile13(systemPromptPath, systemPrompt, "utf8");
25925
26251
  let mcpConfigPath;
25926
26252
  let outputSchemaPath;
25927
26253
  if (codex) {
25928
- outputSchemaPath = join42(request.runDirectory, "headless-output-schema.json");
26254
+ outputSchemaPath = join43(request.runDirectory, "headless-output-schema.json");
25929
26255
  const closed = closeJsonSchemaForCodex(prepared.jsonSchema);
25930
26256
  await writeFile13(outputSchemaPath, `${JSON.stringify(closed, null, 2)}
25931
26257
  `, "utf8");
25932
26258
  } else {
25933
- mcpConfigPath = join42(request.runDirectory, "headless-mcp-config.json");
26259
+ mcpConfigPath = join43(request.runDirectory, "headless-mcp-config.json");
25934
26260
  await writeFile13(
25935
26261
  mcpConfigPath,
25936
26262
  `${JSON.stringify(headlessMcpConfigDocument(prepared.mcpServers), null, 2)}
@@ -26157,7 +26483,7 @@ function createProductionHeadlessRoleTurnHost(options) {
26157
26483
  sessionFile: sessionIdentity.resolveSessionFile(request.principal),
26158
26484
  // Same MCP relay as ACP so intermediate AK tools stay reachable;
26159
26485
  // headless adapter projects the row into --mcp-config.
26160
- socketPath: `/tmp/ak-headless-mcp-${randomUUID9()}.sock`,
26486
+ socketPath: `/tmp/ak-headless-mcp-${randomUUID10()}.sock`,
26161
26487
  // Schema channel owns the terminating receipt; hide it from MCP list.
26162
26488
  listTerminatingToolOnMcp: false
26163
26489
  })