@akagilnc/pi-workflow-roles 0.1.4035 → 0.1.4062

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/acp-host/production-host.js +476 -250
  2. package/dist/doctor-auditor.js +1 -1
  3. package/dist/dossier-resolution.js +21 -8
  4. package/dist/gatekeeper-role.js +34 -27
  5. package/dist/headless-host/description.js +7 -8
  6. package/dist/headless-host/production-host.js +503 -264
  7. package/dist/host-contracts.js +16 -0
  8. package/dist/inspector-contracts.js +8 -0
  9. package/dist/packaged-role-registry.js +1 -1
  10. package/dist/pi/role-turn-host.js +43 -13
  11. package/dist/public-cli/case-dossier-delivery.js +60 -1
  12. package/dist/public-cli/inspector-run.js +17 -3
  13. package/dist/public-cli/instruction-seat-run.js +9 -6
  14. package/dist/public-cli/main.js +239 -112
  15. package/dist/public-cli/notary-run.js +7 -4
  16. package/dist/public-cli/post-admission.js +66 -59
  17. package/dist/public-cli/run-lifecycle.js +3 -0
  18. package/dist/public-cli/settlement.js +24 -7
  19. package/dist/public-role-summons.js +8 -0
  20. package/dist/submission-ledger.js +30 -8
  21. package/dist/user-dialogue-stdin.js +33 -0
  22. package/extensions/role-runtime.ts +1 -0
  23. package/package.json +1 -1
  24. package/resources/836-deleted-machine-instruction-inventory.md +1 -1
  25. package/src/doctor-auditor.ts +1 -1
  26. package/src/dossier-resolution.ts +26 -8
  27. package/src/external-host-turn-loop.ts +9 -0
  28. package/src/gatekeeper-pass-envelope.ts +6 -0
  29. package/src/gatekeeper-role.ts +47 -28
  30. package/src/headless-host/description.ts +8 -11
  31. package/src/headless-host/role-turn-host.ts +20 -5
  32. package/src/host-contracts.ts +22 -3
  33. package/src/inspector-contracts.ts +7 -0
  34. package/src/judge-role.ts +4 -0
  35. package/src/navigator-work-context.ts +3 -4
  36. package/src/notary-role.ts +1 -0
  37. package/src/packaged-role-registry.ts +1 -1
  38. package/src/pi/adapter.ts +19 -4
  39. package/src/pi/role-turn-host.ts +48 -14
  40. package/src/public-cli/case-dossier-delivery.ts +86 -1
  41. package/src/public-cli/inspector-run.ts +26 -2
  42. package/src/public-cli/instruction-seat-run.ts +17 -9
  43. package/src/public-cli/invocation.ts +2 -0
  44. package/src/public-cli/notary-run.ts +13 -4
  45. package/src/public-cli/post-admission.ts +74 -65
  46. package/src/public-cli/run-lifecycle.ts +3 -0
  47. package/src/public-cli/settlement.ts +32 -6
  48. package/src/public-role-summons.ts +31 -7
  49. package/src/role-envelope.ts +9 -30
  50. package/src/role-runtime-dependencies.ts +1 -0
  51. package/src/role-runtime.ts +95 -19
  52. package/src/submission-ledger.ts +48 -13
  53. package/src/user-dialogue-stdin.ts +37 -0
  54. package/src/worker-role.ts +4 -0
@@ -15,3 +15,19 @@ export class ExplicitInternalActivationError extends Error {
15
15
  }
16
16
  }
17
17
  }
18
+ /** Gate review officers (察院 / 符宝郎 / 审刑院). Single authority for seat checks. */
19
+ export function isOfficerReviewSeat(role) {
20
+ return role === "notary" || role === "inspector" || role === "auditor";
21
+ }
22
+ /** Per-turn run directory; adapters must project any child-process identity. */
23
+ export function runDirectoryFromHostContext(context) {
24
+ return typeof context.runDirectory === "string" && context.runDirectory.trim() !== ""
25
+ ? context.runDirectory
26
+ : undefined;
27
+ }
28
+ /** Per-turn court attempt; absence never inherits ambient process identity. */
29
+ export function courtAttemptIdFromHostContext(context) {
30
+ return typeof context.courtAttemptId === "string" && context.courtAttemptId.trim() !== ""
31
+ ? context.courtAttemptId
32
+ : undefined;
33
+ }
@@ -1,5 +1,12 @@
1
1
  const INSPECTOR_OUTPUT_TOOL_NAME = "ak_inspector_output";
2
2
  const INSPECTOR_ACCEPTED_TEXT = "\u5BDF\u9662\u56DE\u6267\u5DF2\u63A5\u53D7";
3
+ const INSPECTOR_SOURCE_RUN_FLAG = {
4
+ name: "ak-inspector-source-run",
5
+ definition: {
6
+ description: "\u5BDF\u9662\u521D\u94F8\u7ED1\u5B9A\u7684\u7236 run \u7EDD\u5BF9\u8DEF\u5F84",
7
+ type: "string"
8
+ }
9
+ };
3
10
  function validateRecordedInspectorOutput(value) {
4
11
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
5
12
  throw new Error("Inspector output has no execution discriminator");
@@ -18,5 +25,6 @@ function validateRecordedInspectorOutput(value) {
18
25
  export {
19
26
  INSPECTOR_ACCEPTED_TEXT,
20
27
  INSPECTOR_OUTPUT_TOOL_NAME,
28
+ INSPECTOR_SOURCE_RUN_FLAG,
21
29
  validateRecordedInspectorOutput
22
30
  };
@@ -158,7 +158,7 @@ const PUBLIC_ROLE_RECORDS = [
158
158
  role: "inspector",
159
159
  phases: [null],
160
160
  outputTool: INSPECTOR_OUTPUT_TOOL_NAME,
161
- inputFlag: void 0,
161
+ inputFlag: "ak-inspector-source-run",
162
162
  phaseFlag: void 0,
163
163
  activationStage: "load-and-install",
164
164
  sessionMaterials: INSPECTOR_SESSION_MATERIALS
@@ -10,9 +10,10 @@ import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:pa
10
10
  import { platform } from "node:process";
11
11
  import { promisify } from "node:util";
12
12
  import { randomUUID } from "node:crypto";
13
- import { ExplicitInternalActivationError } from "../host-contracts.js";
14
- import { applyEngineChildEnv } from "../engine-detour.js";
13
+ import { ExplicitInternalActivationError, isOfficerReviewSeat } from "../host-contracts.js";
14
+ import { applyEngineChildEnv, ENGINE_MODEL_FLAG_NAME, normalizeEngineName } from "../engine-detour.js";
15
15
  import { projectActivationFlags } from "../role-activation-flags.js";
16
+ import { encodeUserDialogueStdin } from "../user-dialogue-stdin.js";
16
17
  /** Package-relative Internal role entrypoint (ADR 0052; same path as public-cli registry). */
17
18
  const INTERNAL_ROLE_ENTRYPOINT_RELATIVE = "extensions/role-runtime.ts";
18
19
  export function resolveInternalRoleEntrypoint(packageRoot) {
@@ -95,17 +96,10 @@ export function applyPiNativeSkillInvocation(methods, prompt) {
95
96
  * Pi last-hop argv after `--no-extensions -e entry` (#819).
96
97
  * Activation flag membership comes from middle-layer projectActivationFlags;
97
98
  * this function only renders session coords, controlled constants, and pairs.
98
- * Single forced method → Pi-native `/skill:` on the argv prompt (#822).
99
+ * User dialogue is not an argv element (#879): it rides spawn stdin.
99
100
  */
100
101
  export function buildPiTurnExtraArgs(request, authority, extraPiArgs = []) {
101
102
  const { sessionFile, sessionDirectory } = authority.decode(request.principal);
102
- const rawPrompt = request.continuation.kind === "initial" || request.continuation.kind === "resume"
103
- ? request.continuation.prompt
104
- : (() => {
105
- const _exhaustive = request.continuation;
106
- return _exhaustive;
107
- })();
108
- const prompt = applyPiNativeSkillInvocation(request.methods, rawPrompt);
109
103
  return [
110
104
  "--no-skills",
111
105
  ...buildMethodArgs(request.methods),
@@ -119,12 +113,28 @@ export function buildPiTurnExtraArgs(request, authority, extraPiArgs = []) {
119
113
  ...extraPiArgs,
120
114
  // Envelope assembly = projectActivationFlags; pi only renders argv pairs.
121
115
  ...activationFlagsToPiArgv(projectActivationFlags(request)),
116
+ ...piEngineModelArgs(request),
122
117
  "--mode",
123
118
  "json",
124
119
  ...buildSeatModelCliArgs(request.model),
125
- prompt,
126
120
  ];
127
121
  }
122
+ /** Engine name stays on child env; model has no env fallback (#883 / #879). */
123
+ function piEngineModelArgs(request) {
124
+ const model = normalizeEngineName(request.engineModel);
125
+ if (model === undefined)
126
+ return [];
127
+ return [`--${ENGINE_MODEL_FLAG_NAME}`, model];
128
+ }
129
+ function piUserDialogueBody(request) {
130
+ const rawPrompt = request.continuation.kind === "initial" || request.continuation.kind === "resume"
131
+ ? request.continuation.prompt
132
+ : (() => {
133
+ const _exhaustive = request.continuation;
134
+ return _exhaustive;
135
+ })();
136
+ return applyPiNativeSkillInvocation(request.methods, rawPrompt);
137
+ }
128
138
  const execFileAsync = promisify(execFile);
129
139
  async function resolveSelectedPi(command, cwd, env) {
130
140
  const searchPath = env.PATH ?? (platform === "win32" ? (process.env.PATH ?? "") : "/usr/bin:/bin");
@@ -173,11 +183,22 @@ export function createDefaultPiSpawnRunner(options) {
173
183
  const child = spawn(piIdentity.executable, [...args], {
174
184
  cwd: spawnOptions.cwd,
175
185
  env: spawnOptions.env,
176
- stdio: ["ignore", "ignore", "pipe"],
186
+ stdio: ["pipe", "ignore", "pipe"],
177
187
  });
188
+ if (child.stdin === null) {
189
+ throw new Error("Pi child stdin pipe was not created");
190
+ }
178
191
  if (child.stderr === null) {
179
192
  throw new Error("Pi child stderr pipe was not created");
180
193
  }
194
+ let stdinDeliveryError;
195
+ child.stdin.on("error", (error) => {
196
+ stdinDeliveryError ??= error;
197
+ });
198
+ if (spawnOptions.stdin !== undefined) {
199
+ child.stdin.write(spawnOptions.stdin);
200
+ }
201
+ child.stdin.end();
181
202
  let stderr = "";
182
203
  let timedOut = false;
183
204
  // No default wall clock. Only an explicit caller budget arms a timer (ADR 0010).
@@ -248,6 +269,10 @@ export function createDefaultPiSpawnRunner(options) {
248
269
  reject(executionError);
249
270
  return;
250
271
  }
272
+ if (stdinDeliveryError !== undefined) {
273
+ reject(stdinDeliveryError);
274
+ return;
275
+ }
251
276
  resolveResult({
252
277
  code,
253
278
  stderr,
@@ -275,8 +300,11 @@ export function createPiRoleTurnHost(config) {
275
300
  async executeTurn(request) {
276
301
  // #617 DK-7: Pi argv gets projected native paths once; never record bytes.
277
302
  // Pi already owns its own session file, so only sitian prior volume rides in.
303
+ // #879: station-child officer dialogue keeps peer words — do not splice
304
+ // host-transition priorNativePaths into the review prompt body.
278
305
  let turnRequest = request;
279
- const paths = request.hostTransition?.priorNativeKind === "sitian"
306
+ const officerStationChild = request.stationChild === true && isOfficerReviewSeat(request.activation.role);
307
+ const paths = !officerStationChild && request.hostTransition?.priorNativeKind === "sitian"
280
308
  ? request.hostTransition.priorNativePaths
281
309
  : undefined;
282
310
  if (request.continuation.kind === "resume"
@@ -293,6 +321,7 @@ export function createPiRoleTurnHost(config) {
293
321
  const roleEntry = await realpath(resolveInternalRoleEntrypoint(config.packageRoot));
294
322
  const extraArgs = buildPiTurnExtraArgs(turnRequest, config.principalAuthority, config.extraPiArgs ?? []);
295
323
  const args = buildExplicitInternalActivationArgs(roleEntry, extraArgs);
324
+ const stdin = encodeUserDialogueStdin(piUserDialogueBody(turnRequest));
296
325
  // Shared envelope isolates this call's court identity: omitting courtAttemptId
297
326
  // must not inherit a parent process.env.AK_ROLE_COURT_ATTEMPT (#637).
298
327
  const env = {
@@ -330,6 +359,7 @@ export function createPiRoleTurnHost(config) {
330
359
  return await spawnRunner(args, {
331
360
  cwd: request.cwd,
332
361
  env,
362
+ stdin,
333
363
  ...(timeoutMs === undefined ? {} : { timeoutMs }),
334
364
  ...(request.signal === undefined ? {} : { signal: request.signal }),
335
365
  });
@@ -5,11 +5,23 @@
5
5
  * 只读已有案卷:不刷新、不生成、不校验内容、不新增拒收或停工条件。
6
6
  * 机器文本仅中立标识材料(ADR 0073),用途说明归角色材料所有。
7
7
  *
8
- * 递送挂载点唯一:`post-admission` 在 beforeDispatch 之后为每个公共入口追加本段。
8
+ * 递送挂载点唯一:`post-admission` 在 beforeDispatch 之后为每个公共入口挂载。
9
+ * 普通入口把本段追加进 continuation;station-child 审核轮次走 attachments
10
+ * 冻结 + role-runtime `loadCaseDossierReadingMaterial` → readingMaterial →
11
+ * systemPrompt.materials fold(#879:对话 instruction 保持父腿 payload 原文;
12
+ * 起居录作独立附件面,不新造 RoleTurnRequest.materials)。
9
13
  */
14
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
15
+ import { tmpdir } from "node:os";
16
+ import { join } from "node:path";
10
17
  import { resolveTicketProvenanceVolume } from "../ticket-provenance.js";
18
+ import { freezeAttachmentsIntoRun, } from "./invocation.js";
11
19
  /** Section heading of the system-delivered dossier pointer (presentation only). */
12
20
  const CASE_DOSSIER_SECTION_HEADING = "## 本票起居录(系统随案提供)";
21
+ /** Stable freeze key under run/attachments/ for station-child 0081 delivery. */
22
+ const CASE_DOSSIER_ATTACH_KEY = "case-dossier";
23
+ /** Leaf name of the frozen pointer section (content = purpose + paths). */
24
+ const CASE_DOSSIER_ATTACH_FILE = "case-dossier-pointer.md";
13
25
  /** Pointer only — presence/absence is for the role to observe at the path. */
14
26
  function describeDossierFile(path) {
15
27
  return path;
@@ -32,3 +44,50 @@ export async function projectCaseDossierPointerSection(input) {
32
44
  `记录卷宗:${describeDossierFile(volume.recordFile)}`,
33
45
  ].join("\n");
34
46
  }
47
+ /**
48
+ * ADR 0081 delivery for station-child officer turns (#879): freeze the same
49
+ * pointer section through the existing attachments seam. Role-runtime loads
50
+ * that freeze via loadCaseDossierReadingMaterial onto readingMaterial; the
51
+ * envelope then folds it into systemPrompt.materials. Peer dialogue instruction
52
+ * stays the parent payload; never RoleTurnRequest.materials.
53
+ * Returns frozen attachments, or undefined when unbound (no dossier).
54
+ */
55
+ export async function deliverCaseDossierAsAttachment(input) {
56
+ const section = await projectCaseDossierPointerSection({
57
+ ticketNumber: input.ticketNumber,
58
+ projectRoot: input.projectRoot,
59
+ home: input.home,
60
+ });
61
+ if (section === undefined)
62
+ return undefined;
63
+ // Stage in OS temp only — never leave a run-local .case-dossier-stage copy.
64
+ const stagingDir = await mkdtemp(join(tmpdir(), "ak-case-dossier-"));
65
+ try {
66
+ const stagingPath = join(stagingDir, CASE_DOSSIER_ATTACH_FILE);
67
+ await writeFile(stagingPath, `${section}\n`, "utf8");
68
+ return await freezeAttachmentsIntoRun([stagingPath], input.runDirectory, CASE_DOSSIER_ATTACH_KEY);
69
+ }
70
+ finally {
71
+ await rm(stagingDir, { recursive: true, force: true });
72
+ }
73
+ }
74
+ /**
75
+ * Load a previously frozen case-dossier attachment as reading material
76
+ * (existing agent-start / systemPrompt.materials fold — not dialogue prompt,
77
+ * not RoleTurnRequest.materials). Undefined when the run has no such freeze.
78
+ */
79
+ export async function loadCaseDossierReadingMaterial(runDirectory) {
80
+ const frozenPath = join(runDirectory, "attachments", CASE_DOSSIER_ATTACH_KEY, `00-${CASE_DOSSIER_ATTACH_FILE}`);
81
+ let section;
82
+ try {
83
+ section = await readFile(frozenPath, "utf8");
84
+ }
85
+ catch (error) {
86
+ if (error.code === "ENOENT")
87
+ return undefined;
88
+ throw error;
89
+ }
90
+ if (section.trim() === "")
91
+ return undefined;
92
+ return { kind: "case-dossier-pointer", frozenPath, section };
93
+ }
@@ -1,16 +1,24 @@
1
1
  import { engineSessionMaterialFromOptions, pickEngineAxis } from "../package-resources/engine-material.js";
2
2
  import { CliUsageError } from "./cli-errors.js";
3
3
  import { tryResumeSameTicketSeatRun } from "./seat-ticket-binding.js";
4
- import { admitInspectorInvocation, buildInspectorTransportPrompt, } from "./invocation.js";
4
+ import { admitInspectorInvocation, buildInspectorTransportPrompt, persistAdmittedSourceRunPath, } from "./invocation.js";
5
5
  import { prepareSummonsResumeMaterials, runPostAdmissionOneShot, runPostAdmissionSeatResume, resumeTurnRequestProjectionOptions, } from "./post-admission.js";
6
6
  import { loadResumableInspectorRun, markRunAdmitted, parentRunPathFromGatePointerInstruction, } from "./run-lifecycle.js";
7
7
  import { presentStructuralRejection, trySettleInspectorTerminalResult, } from "./settlement.js";
8
8
  import { projectRoleTurnRequest, } from "./turn-request.js";
9
+ function inspectorParentRunPath(admitted) {
10
+ if (typeof admitted.sourceRunPath === "string" && admitted.sourceRunPath.trim() !== "") {
11
+ return admitted.sourceRunPath;
12
+ }
13
+ return parentRunPathFromGatePointerInstruction(admitted.instruction);
14
+ }
9
15
  /** Project admitted invocation onto the host-neutral turn request. */
10
16
  export function buildInspectorTurnRequest(admitted, options) {
17
+ const sourceRun = inspectorParentRunPath(admitted);
11
18
  return projectRoleTurnRequest(admitted, {
12
19
  activation: {
13
20
  role: "inspector",
21
+ ...(sourceRun === undefined ? {} : { sourceRun }),
14
22
  },
15
23
  }, options);
16
24
  }
@@ -34,7 +42,7 @@ export async function runPublicInspector(argv, env, io, parseInspectorArgv) {
34
42
  // #753/#786: gate re-ask / verbatim submission body ride summons.instruction on resume.
35
43
  const parentRunPath = parentRunPathFromGatePointerInstruction(parsed.instruction);
36
44
  if (parentRunPath !== undefined) {
37
- const resumeInstruction = env.reviewReask;
45
+ const resumeInstruction = env.reviewReask ?? env.gateReviewInstruction;
38
46
  const summons = {
39
47
  sourceRunPath: parentRunPath,
40
48
  ...(resumeInstruction === undefined
@@ -79,6 +87,10 @@ export async function runPublicInspector(argv, env, io, parseInspectorArgv) {
79
87
  throw error;
80
88
  }
81
89
  await markRunAdmitted(admitted, env.principalAuthority);
90
+ if (parentRunPath !== undefined) {
91
+ await persistAdmittedSourceRunPath(admitted, parentRunPath);
92
+ admitted = { ...admitted, sourceRunPath: parentRunPath };
93
+ }
82
94
  const engineMaterial = engineSessionMaterialFromOptions({
83
95
  ...pickEngineAxis(env),
84
96
  packageRoot: env.packageRoot,
@@ -95,7 +107,9 @@ export async function runPublicInspector(argv, env, io, parseInspectorArgv) {
95
107
  : { correlationId: env.correlationId }),
96
108
  continuation: {
97
109
  kind: "initial",
98
- prompt: buildInspectorTransportPrompt(admitted, engineMaterial),
110
+ // #879: gate first mint uses parent payload as content; binding stays typed activation.
111
+ prompt: (env.reviewReask ?? env.gateReviewInstruction)
112
+ ?? buildInspectorTransportPrompt(admitted, engineMaterial),
99
113
  },
100
114
  });
101
115
  return await runPostAdmissionOneShot({
@@ -152,8 +152,9 @@ export async function runPublicInstructionSeat(argv, env, io, role, parseArgv) {
152
152
  return { exitCode: 2 };
153
153
  }
154
154
  }
155
- // #756/#786: auditor reask / verbatim submission body ride summons.instruction on resume.
156
- const resumeInstruction = env.reviewReask;
155
+ // #756/#879: auditor reask / verbatim submission body ride summons.instruction.
156
+ // Binding pointer stays --source-run / argv 卷宗指针; content is body or reask.
157
+ const resumeInstruction = env.reviewReask ?? env.gateReviewInstruction;
157
158
  const summons = {
158
159
  ...(resumeInstruction === undefined
159
160
  ? {
@@ -225,10 +226,12 @@ export async function runPublicInstructionSeat(argv, env, io, role, parseArgv) {
225
226
  : { correlationId: env.correlationId }),
226
227
  continuation: {
227
228
  kind: "initial",
228
- prompt: buildInstructionTransportPrompt(admitted, engineSessionMaterialFromOptions({
229
- ...pickEngineAxis(env),
230
- packageRoot: env.packageRoot,
231
- })),
229
+ // #879: gate first mint uses parent payload as content when present.
230
+ prompt: (env.reviewReask ?? env.gateReviewInstruction)
231
+ ?? buildInstructionTransportPrompt(admitted, engineSessionMaterialFromOptions({
232
+ ...pickEngineAxis(env),
233
+ packageRoot: env.packageRoot,
234
+ })),
232
235
  },
233
236
  });
234
237
  return await runPostAdmissionOneShot({