@osolmaz/pi-workflows 0.12.0 → 0.13.0

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 (257) hide show
  1. package/README.md +56 -31
  2. package/dist/builtins/autodoc.workflow.d.ts +4 -4
  3. package/dist/builtins/autoimplement.workflow.d.ts +797 -142
  4. package/dist/builtins/autoimplement.workflow.js +17 -105
  5. package/dist/builtins/autoimplement.workflow.js.map +1 -1
  6. package/dist/builtins/autoplan.workflow.d.ts +126 -13
  7. package/dist/builtins/autoplan.workflow.js +200 -29
  8. package/dist/builtins/autoplan.workflow.js.map +1 -1
  9. package/dist/builtins/catalog.js +7 -5
  10. package/dist/builtins/catalog.js.map +1 -1
  11. package/dist/builtins/index.d.ts +4 -2
  12. package/dist/builtins/index.js +3 -1
  13. package/dist/builtins/index.js.map +1 -1
  14. package/dist/builtins/monitor.workflow.d.ts +56 -23
  15. package/dist/builtins/monitor.workflow.js +508 -329
  16. package/dist/builtins/monitor.workflow.js.map +1 -1
  17. package/dist/builtins/pi-agent-group.d.ts +72 -0
  18. package/dist/builtins/pi-agent-group.js +1087 -0
  19. package/dist/builtins/pi-agent-group.js.map +1 -0
  20. package/dist/builtins/plain-summary.workflow.d.ts +32 -0
  21. package/dist/builtins/plain-summary.workflow.js +134 -0
  22. package/dist/builtins/plain-summary.workflow.js.map +1 -0
  23. package/dist/builtins/plan-approval.workflow.d.ts +39 -5
  24. package/dist/builtins/plan-approval.workflow.js +92 -14
  25. package/dist/builtins/plan-approval.workflow.js.map +1 -1
  26. package/dist/builtins/plan-change.workflow.d.ts +449 -0
  27. package/dist/builtins/plan-change.workflow.js +256 -0
  28. package/dist/builtins/plan-change.workflow.js.map +1 -0
  29. package/dist/builtins/plan-presentation.js +2 -2
  30. package/dist/builtins/plan-presentation.js.map +1 -1
  31. package/dist/builtins/sanity-check.workflow.d.ts +50 -6
  32. package/dist/builtins/sanity-check.workflow.js +150 -28
  33. package/dist/builtins/sanity-check.workflow.js.map +1 -1
  34. package/dist/controllers/effects.d.ts +3 -2
  35. package/dist/controllers/effects.js +8 -1
  36. package/dist/controllers/effects.js.map +1 -1
  37. package/dist/controllers/index.d.ts +1 -1
  38. package/dist/controllers/index.js +1 -1
  39. package/dist/controllers/index.js.map +1 -1
  40. package/dist/controllers/manager.d.ts +1 -0
  41. package/dist/controllers/manager.js +41 -17
  42. package/dist/controllers/manager.js.map +1 -1
  43. package/dist/controllers/sqlite.d.ts +107 -85
  44. package/dist/controllers/sqlite.js +1611 -1486
  45. package/dist/controllers/sqlite.js.map +1 -1
  46. package/dist/controllers/store.d.ts +9 -8
  47. package/dist/controllers/store.js +1 -31
  48. package/dist/controllers/store.js.map +1 -1
  49. package/dist/controllers/types.d.ts +3 -0
  50. package/dist/controllers/workflow-engine-scheduler.d.ts +1 -1
  51. package/dist/controllers/workflow-engine-scheduler.js +3 -5
  52. package/dist/controllers/workflow-engine-scheduler.js.map +1 -1
  53. package/dist/controllers/workflows.d.ts +2 -2
  54. package/dist/controllers/workflows.js +11 -10
  55. package/dist/controllers/workflows.js.map +1 -1
  56. package/dist/extension/controller-host.js +2 -2
  57. package/dist/extension/controller-host.js.map +1 -1
  58. package/dist/extension/decision-channels.d.ts +4 -2
  59. package/dist/extension/decision-channels.js +333 -146
  60. package/dist/extension/decision-channels.js.map +1 -1
  61. package/dist/extension/executor.d.ts +9 -2
  62. package/dist/extension/executor.js +89 -2
  63. package/dist/extension/executor.js.map +1 -1
  64. package/dist/extension/herdr-viewer.d.ts +0 -1
  65. package/dist/extension/herdr-viewer.js +0 -4
  66. package/dist/extension/herdr-viewer.js.map +1 -1
  67. package/dist/extension/index.js +209 -127
  68. package/dist/extension/index.js.map +1 -1
  69. package/dist/extension/recorder.d.ts +3 -10
  70. package/dist/extension/recorder.js +13 -22
  71. package/dist/extension/recorder.js.map +1 -1
  72. package/dist/extension/session-events.d.ts +2 -2
  73. package/dist/extension/step-message.d.ts +7 -2
  74. package/dist/extension/step-message.js +94 -2
  75. package/dist/extension/step-message.js.map +1 -1
  76. package/dist/extension/widget.js +29 -3
  77. package/dist/extension/widget.js.map +1 -1
  78. package/dist/host/rpc-executor.d.ts +3 -0
  79. package/dist/host/rpc-executor.js +2 -0
  80. package/dist/host/rpc-executor.js.map +1 -1
  81. package/dist/host/runner.d.ts +3 -6
  82. package/dist/host/runner.js +83 -32
  83. package/dist/host/runner.js.map +1 -1
  84. package/dist/render/graph-render.js +15 -10
  85. package/dist/render/graph-render.js.map +1 -1
  86. package/dist/state/database.d.ts +35 -0
  87. package/dist/state/database.js +287 -0
  88. package/dist/state/database.js.map +1 -0
  89. package/dist/state/index.d.ts +4 -0
  90. package/dist/state/index.js +5 -0
  91. package/dist/state/index.js.map +1 -0
  92. package/dist/state/json.d.ts +6 -0
  93. package/dist/state/json.js +38 -0
  94. package/dist/state/json.js.map +1 -0
  95. package/dist/state/mutation.d.ts +57 -0
  96. package/dist/state/mutation.js +255 -0
  97. package/dist/state/mutation.js.map +1 -0
  98. package/dist/state/schema.d.ts +6 -0
  99. package/dist/state/schema.js +473 -0
  100. package/dist/state/schema.js.map +1 -0
  101. package/dist/viewer/cli.d.ts +2 -2
  102. package/dist/viewer/cli.js +142 -122
  103. package/dist/viewer/cli.js.map +1 -1
  104. package/dist/viewer/render.d.ts +4 -4
  105. package/dist/viewer/render.js +9 -23
  106. package/dist/viewer/render.js.map +1 -1
  107. package/dist/viewer/session-reducer.d.ts +1 -1
  108. package/dist/viewer/session-reducer.js +1 -1
  109. package/dist/viewer/tui.d.ts +3 -3
  110. package/dist/viewer/tui.js +15 -13
  111. package/dist/viewer/tui.js.map +1 -1
  112. package/dist/viewer/watch.d.ts +2 -5
  113. package/dist/viewer/watch.js +13 -13
  114. package/dist/viewer/watch.js.map +1 -1
  115. package/dist/workflows/catalog.js +7 -2
  116. package/dist/workflows/catalog.js.map +1 -1
  117. package/dist/workflows/composition.js +20 -2
  118. package/dist/workflows/composition.js.map +1 -1
  119. package/dist/workflows/decision-presentation.d.ts +1 -1
  120. package/dist/workflows/decision-presentation.js +51 -38
  121. package/dist/workflows/decision-presentation.js.map +1 -1
  122. package/dist/workflows/definition.d.ts +6 -2
  123. package/dist/workflows/definition.js +17 -0
  124. package/dist/workflows/definition.js.map +1 -1
  125. package/dist/workflows/engine.d.ts +7 -7
  126. package/dist/workflows/engine.js +196 -115
  127. package/dist/workflows/engine.js.map +1 -1
  128. package/dist/workflows/errors.d.ts +16 -3
  129. package/dist/workflows/errors.js +18 -3
  130. package/dist/workflows/errors.js.map +1 -1
  131. package/dist/workflows/human-decision.d.ts +45 -8
  132. package/dist/workflows/human-decision.js +641 -274
  133. package/dist/workflows/human-decision.js.map +1 -1
  134. package/dist/workflows/index.d.ts +5 -6
  135. package/dist/workflows/index.js +4 -5
  136. package/dist/workflows/index.js.map +1 -1
  137. package/dist/workflows/progress.d.ts +1 -0
  138. package/dist/workflows/progress.js +15 -3
  139. package/dist/workflows/progress.js.map +1 -1
  140. package/dist/workflows/schema.js +27 -1
  141. package/dist/workflows/schema.js.map +1 -1
  142. package/dist/workflows/store.d.ts +83 -103
  143. package/dist/workflows/store.js +907 -951
  144. package/dist/workflows/store.js.map +1 -1
  145. package/dist/workflows/types.d.ts +88 -126
  146. package/docs/CONTROLLERS.md +10 -8
  147. package/docs/DEFERRED_TURNS.md +2 -2
  148. package/docs/DESIGN_PHILOSOPHY.md +4 -2
  149. package/docs/HUMAN_DECISIONS.md +36 -47
  150. package/docs/HUMAN_DECISION_PRESENTATIONS.md +14 -24
  151. package/docs/MONITOR.md +179 -237
  152. package/docs/SQLITE_STATE.md +219 -0
  153. package/docs/WORKFLOW_COMPOSITION.md +27 -26
  154. package/docs/WORKFLOW_STEP_MESSAGES.md +20 -18
  155. package/docs/WORKFLOW_UPDATES.md +10 -9
  156. package/docs/development.md +9 -9
  157. package/docs/live-replay-protocol.md +28 -37
  158. package/docs/plans/2026-08-16-workflow-updates-plan.md +1 -1
  159. package/docs/plans/2026-08-19-human-decision-gates-plan.md +1 -1
  160. package/docs/plans/2026-08-21-autoimplement-timeout-fallback-plan.md +1 -1
  161. package/docs/plans/2026-08-21-plan-change-approval-policy-plan.md +322 -0
  162. package/docs/plans/2026-08-21-sanity-check-plan.md +217 -95
  163. package/docs/plans/2026-08-22-goal-finishing-monitor-plan.md +200 -0
  164. package/docs/plans/2026-08-23-assistant-agent-completion-plan.md +701 -0
  165. package/docs/plans/2026-08-23-sqlite-state-plan.md +970 -0
  166. package/docs/plans/replayable-run-bundles-implementation-plan.md +2 -2
  167. package/docs/plans/session-event-replay-implementation-plan.md +1 -1
  168. package/docs/plans/tui-viewer-implementation-plan.md +1 -1
  169. package/docs/session-event-journal.md +63 -434
  170. package/docs/tui-viewer.md +13 -15
  171. package/docs/workflows.md +127 -53
  172. package/examples/workflows/approved-plan.workflow.ts +19 -46
  173. package/examples/workflows/plain-summary.workflow.ts +1 -0
  174. package/herdr-plugin.toml +1 -1
  175. package/package.json +7 -7
  176. package/plugins/herdr/viewer.mjs +1 -11
  177. package/schemas/human-decision-accepted-v1.schema.json +15 -3
  178. package/schemas/human-decision-continuation-v1.schema.json +10 -1
  179. package/schemas/human-decision-delivery-v1.schema.json +8 -0
  180. package/schemas/human-decision-receipt-v1.schema.json +8 -0
  181. package/schemas/human-decision-request-v1.schema.json +24 -4
  182. package/skills/autoimplement/SKILL.md +27 -0
  183. package/skills/autoplan/SKILL.md +5 -4
  184. package/skills/monitor/SKILL.md +91 -135
  185. package/skills/pi-workflows/SKILL.md +9 -8
  186. package/skills/sanity-check/SKILL.md +44 -0
  187. package/src/builtins/autoimplement.workflow.ts +19 -118
  188. package/src/builtins/autoplan.workflow.ts +290 -40
  189. package/src/builtins/catalog.ts +7 -5
  190. package/src/builtins/index.ts +18 -1
  191. package/src/builtins/monitor.workflow.ts +673 -382
  192. package/src/builtins/pi-agent-group.ts +1407 -0
  193. package/src/builtins/plain-summary.workflow.ts +185 -0
  194. package/src/builtins/plan-approval.workflow.ts +157 -24
  195. package/src/builtins/plan-change.workflow.ts +321 -0
  196. package/src/builtins/plan-presentation.ts +2 -2
  197. package/src/builtins/sanity-check.workflow.ts +248 -48
  198. package/src/controllers/effects.ts +7 -0
  199. package/src/controllers/index.ts +0 -6
  200. package/src/controllers/manager.ts +72 -32
  201. package/src/controllers/sqlite.ts +2420 -1948
  202. package/src/controllers/store.ts +17 -38
  203. package/src/controllers/types.ts +3 -0
  204. package/src/controllers/workflow-engine-scheduler.ts +4 -8
  205. package/src/controllers/workflows.ts +45 -21
  206. package/src/extension/controller-host.ts +1 -2
  207. package/src/extension/decision-channels.ts +456 -203
  208. package/src/extension/executor.ts +105 -2
  209. package/src/extension/herdr-viewer.ts +0 -5
  210. package/src/extension/index.ts +251 -151
  211. package/src/extension/recorder.ts +13 -22
  212. package/src/extension/session-events.ts +2 -2
  213. package/src/extension/step-message.ts +106 -4
  214. package/src/extension/widget.ts +32 -5
  215. package/src/host/rpc-executor.ts +4 -0
  216. package/src/host/runner.ts +93 -41
  217. package/src/render/graph-render.ts +12 -6
  218. package/src/state/database.ts +375 -0
  219. package/src/state/index.ts +29 -0
  220. package/src/state/json.ts +42 -0
  221. package/src/state/mutation.ts +435 -0
  222. package/src/state/schema.ts +475 -0
  223. package/src/viewer/cli.ts +151 -144
  224. package/src/viewer/render.ts +19 -30
  225. package/src/viewer/session-reducer.ts +1 -1
  226. package/src/viewer/tui.ts +18 -17
  227. package/src/viewer/watch.ts +13 -17
  228. package/src/workflows/catalog.ts +7 -2
  229. package/src/workflows/composition.ts +21 -3
  230. package/src/workflows/decision-presentation.ts +56 -43
  231. package/src/workflows/definition.ts +36 -3
  232. package/src/workflows/engine.ts +228 -130
  233. package/src/workflows/errors.ts +27 -3
  234. package/src/workflows/human-decision.ts +921 -349
  235. package/src/workflows/index.ts +20 -30
  236. package/src/workflows/progress.ts +18 -3
  237. package/src/workflows/schema.ts +36 -1
  238. package/src/workflows/store.ts +1300 -1163
  239. package/src/workflows/types.ts +100 -137
  240. package/dist/builtins/sanity-check-session.d.ts +0 -17
  241. package/dist/builtins/sanity-check-session.js +0 -168
  242. package/dist/builtins/sanity-check-session.js.map +0 -1
  243. package/dist/workflows/artifacts.d.ts +0 -40
  244. package/dist/workflows/artifacts.js +0 -155
  245. package/dist/workflows/artifacts.js.map +0 -1
  246. package/dist/workflows/migrate-sources.d.ts +0 -42
  247. package/dist/workflows/migrate-sources.js +0 -133
  248. package/dist/workflows/migrate-sources.js.map +0 -1
  249. package/docs/run-bundles.md +0 -481
  250. package/schemas/human-decision-accepted-v2.schema.json +0 -50
  251. package/schemas/human-decision-delivery-v2.schema.json +0 -36
  252. package/schemas/human-decision-receipt-v2.schema.json +0 -39
  253. package/schemas/human-decision-request-v2.schema.json +0 -69
  254. package/schemas/human-decision-resolution-v2.schema.json +0 -27
  255. package/src/builtins/sanity-check-session.ts +0 -205
  256. package/src/workflows/artifacts.ts +0 -188
  257. package/src/workflows/migrate-sources.ts +0 -178
@@ -1,69 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "$id": "https://github.com/osolmaz/pi-workflows/schemas/human-decision-request-v2.schema.json",
4
- "title": "pi-workflows human decision request v2",
5
- "type": "object",
6
- "additionalProperties": false,
7
- "required": [
8
- "schema",
9
- "decisionId",
10
- "requestDigest",
11
- "subjectDigest",
12
- "presentationDigest",
13
- "runId",
14
- "workflowName",
15
- "nodeId",
16
- "attemptId",
17
- "audience",
18
- "title",
19
- "subject",
20
- "presentation",
21
- "revision",
22
- "choices",
23
- "createdAt"
24
- ],
25
- "properties": {
26
- "schema": { "const": "pi-workflows.human-decision-request.v2" },
27
- "decisionId": { "type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$" },
28
- "requestDigest": { "type": "string", "pattern": "^sha256:[a-f0-9]{64}$" },
29
- "subjectDigest": { "type": "string", "pattern": "^sha256:[a-f0-9]{64}$" },
30
- "presentationDigest": { "type": "string", "pattern": "^sha256:[a-f0-9]{64}$" },
31
- "runId": { "type": "string" },
32
- "workflowName": { "type": "string" },
33
- "nodeId": { "type": "string" },
34
- "attemptId": { "type": "string" },
35
- "audience": { "type": "string" },
36
- "title": { "type": "string", "minLength": 1 },
37
- "subject": true,
38
- "presentation": {
39
- "$ref": "decision-presentation-v1.schema.json"
40
- },
41
- "revision": { "type": "integer", "minimum": 1 },
42
- "choices": {
43
- "type": "object",
44
- "minProperties": 1,
45
- "additionalProperties": {
46
- "type": "object",
47
- "additionalProperties": false,
48
- "required": ["label"],
49
- "properties": {
50
- "label": { "type": "string", "minLength": 1 },
51
- "input": {
52
- "type": "object",
53
- "additionalProperties": false,
54
- "required": ["kind", "name", "prompt", "minLength", "maxLength"],
55
- "properties": {
56
- "kind": { "const": "text" },
57
- "name": { "type": "string" },
58
- "prompt": { "type": "string", "minLength": 1 },
59
- "minLength": { "type": "integer", "minimum": 0 },
60
- "maxLength": { "type": "integer", "minimum": 1 }
61
- }
62
- }
63
- }
64
- }
65
- },
66
- "createdAt": { "type": "string", "format": "date-time" },
67
- "expiresAt": { "type": "string", "format": "date-time" }
68
- }
69
- }
@@ -1,27 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "$id": "https://github.com/osolmaz/pi-workflows/schemas/human-decision-resolution-v2.schema.json",
4
- "title": "pi-workflows human decision resolution v2",
5
- "oneOf": [
6
- {
7
- "type": "object",
8
- "additionalProperties": false,
9
- "required": ["schema", "outcome", "decision"],
10
- "properties": {
11
- "schema": { "const": "pi-workflows.human-decision-resolution.v2" },
12
- "outcome": { "const": "accepted" },
13
- "decision": { "$ref": "human-decision-accepted-v2.schema.json" }
14
- }
15
- },
16
- {
17
- "type": "object",
18
- "additionalProperties": false,
19
- "required": ["schema", "outcome", "cancellation"],
20
- "properties": {
21
- "schema": { "const": "pi-workflows.human-decision-resolution.v2" },
22
- "outcome": { "const": "cancelled" },
23
- "cancellation": { "$ref": "human-decision-cancellation-v1.schema.json" }
24
- }
25
- }
26
- ]
27
- }
@@ -1,205 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import { runCommandBatch, type CommandBatchItemResult } from "../workflows/command-batch.js";
5
- import { extractJsonValue } from "../workflows/json.js";
6
-
7
- const SESSION_TIMEOUT_MS = 15 * 60_000;
8
- const SESSION_OUTPUT_CHARS = 1_000_000;
9
- const MAX_PROMPT_CHARS = 96_000;
10
- const MAX_ERROR_CHARS = 2_000;
11
-
12
- export type IsolatedReviewRequest = {
13
- id: string;
14
- prompt: string;
15
- };
16
-
17
- export type PiInvocation = {
18
- command: string;
19
- prefixArgs: string[];
20
- };
21
-
22
- export type IsolatedReviewOptions = {
23
- invocation?: PiInvocation;
24
- timeoutMs?: number;
25
- maxOutputChars?: number;
26
- maxConcurrency?: number;
27
- };
28
-
29
- export async function runIsolatedReviewSessions(
30
- requests: IsolatedReviewRequest[],
31
- cwd: string,
32
- signal: AbortSignal,
33
- options: IsolatedReviewOptions = {},
34
- ): Promise<Record<string, unknown>> {
35
- if (requests.length === 0) return {};
36
- const ids = new Set<string>();
37
- for (const request of requests) {
38
- if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(request.id)) {
39
- throw new Error(`Invalid isolated review id: ${request.id}`);
40
- }
41
- if (ids.has(request.id)) throw new Error(`Duplicate isolated review id: ${request.id}`);
42
- ids.add(request.id);
43
- if (request.prompt.length > MAX_PROMPT_CHARS) {
44
- throw new Error(
45
- `Isolated review prompt ${request.id} exceeds ${MAX_PROMPT_CHARS} characters`,
46
- );
47
- }
48
- }
49
-
50
- const promptDir = await fs.mkdtemp(path.join(os.tmpdir(), "pi-sanity-check-"));
51
- try {
52
- const invocation = options.invocation ?? resolvePiInvocation();
53
- const items = await Promise.all(
54
- requests.map(async (request) => {
55
- const promptPath = path.join(promptDir, `${request.id}.md`);
56
- await fs.writeFile(promptPath, request.prompt, { encoding: "utf8", mode: 0o600 });
57
- return {
58
- id: request.id,
59
- command: invocation.command,
60
- args: [
61
- ...invocation.prefixArgs,
62
- "--mode",
63
- "json",
64
- "--print",
65
- "--no-session",
66
- "--no-extensions",
67
- "--no-skills",
68
- "--no-context-files",
69
- "--tools",
70
- "read,grep,find,ls",
71
- `@${promptPath}`,
72
- "Follow the attached review instructions and return only the requested JSON.",
73
- ],
74
- cwd,
75
- timeoutMs: options.timeoutMs ?? SESSION_TIMEOUT_MS,
76
- maxOutputChars: options.maxOutputChars ?? SESSION_OUTPUT_CHARS,
77
- };
78
- }),
79
- );
80
- const batch = await runCommandBatch(
81
- {
82
- items,
83
- maxConcurrency: options.maxConcurrency ?? requests.length,
84
- },
85
- { signal },
86
- );
87
- const outputs: Record<string, unknown> = {};
88
- for (const item of batch.items) {
89
- outputs[item.id] = parseSessionResult(item);
90
- }
91
- return outputs;
92
- } finally {
93
- await fs.rm(promptDir, { recursive: true, force: true });
94
- }
95
- }
96
-
97
- export function resolvePiInvocation(): PiInvocation {
98
- const currentScript = process.argv[1];
99
- const isBunVirtualScript = currentScript?.startsWith("/$bunfs/root/");
100
- const scriptName = currentScript === undefined ? "" : path.basename(currentScript).toLowerCase();
101
- const isPiPackageCli =
102
- scriptName === "cli.js" &&
103
- currentScript?.split(path.sep).some((segment) => segment === "pi-coding-agent");
104
- const isPiScript = /^(pi|pi\.[cm]?js)$/.test(scriptName) || isPiPackageCli;
105
- if (currentScript && !isBunVirtualScript && isPiScript) {
106
- return {
107
- command: process.execPath,
108
- prefixArgs: [currentScript, ...inheritedPiArgs(process.argv.slice(2))],
109
- };
110
- }
111
- const execName = path.basename(process.execPath).toLowerCase();
112
- if (/^pi(\.exe)?$/.test(execName)) {
113
- return { command: process.execPath, prefixArgs: inheritedPiArgs(process.argv.slice(1)) };
114
- }
115
- return { command: "pi", prefixArgs: [] };
116
- }
117
-
118
- export function parsePiJsonOutput(stdout: string): unknown {
119
- let finalText = "";
120
- for (const line of stdout.split("\n")) {
121
- if (!line.trim()) continue;
122
- let event: Record<string, unknown>;
123
- try {
124
- event = JSON.parse(line) as Record<string, unknown>;
125
- } catch {
126
- continue;
127
- }
128
- if (event.type !== "message_end" || !isRecord(event.message)) continue;
129
- const message = event.message;
130
- if (message.role !== "assistant") continue;
131
- if (message.stopReason === "error" || message.stopReason === "aborted") {
132
- throw new Error(
133
- boundedError(
134
- typeof message.errorMessage === "string"
135
- ? message.errorMessage
136
- : `Pi session stopped with ${String(message.stopReason)}`,
137
- ),
138
- );
139
- }
140
- const text = messageText(message.content);
141
- if (text.trim()) finalText = text;
142
- }
143
- if (!finalText) throw new Error("Isolated Pi session returned no assistant JSON output");
144
- return extractJsonValue(finalText);
145
- }
146
-
147
- function parseSessionResult(result: CommandBatchItemResult): unknown {
148
- if (result.outcome !== "succeeded") {
149
- throw new Error(
150
- `Isolated Pi session ${result.id} ${result.outcome}: ${boundedError(result.error ?? result.stderr)}`,
151
- );
152
- }
153
- if (result.stdoutTruncated) {
154
- throw new Error(`Isolated Pi session ${result.id} exceeded its output limit`);
155
- }
156
- try {
157
- return parsePiJsonOutput(result.stdout);
158
- } catch (error) {
159
- throw new Error(
160
- `Isolated Pi session ${result.id} returned invalid output: ${boundedError(errorMessage(error))}`,
161
- );
162
- }
163
- }
164
-
165
- function inheritedPiArgs(args: string[]): string[] {
166
- const inherited: string[] = [];
167
- for (let index = 0; index < args.length; index += 1) {
168
- const arg = args[index];
169
- if (arg === "--offline") {
170
- inherited.push(arg);
171
- continue;
172
- }
173
- if (arg !== "--provider" && arg !== "--model" && arg !== "--thinking") continue;
174
- const value = args[index + 1];
175
- if (value !== undefined) {
176
- inherited.push(arg, value);
177
- index += 1;
178
- }
179
- }
180
- return inherited;
181
- }
182
-
183
- function messageText(content: unknown): string {
184
- if (typeof content === "string") return content;
185
- if (!Array.isArray(content)) return "";
186
- return content
187
- .map((part) =>
188
- isRecord(part) && part.type === "text" && typeof part.text === "string" ? part.text : "",
189
- )
190
- .filter(Boolean)
191
- .join("\n");
192
- }
193
-
194
- function isRecord(value: unknown): value is Record<string, unknown> {
195
- return value !== null && typeof value === "object" && !Array.isArray(value);
196
- }
197
-
198
- function errorMessage(error: unknown): string {
199
- return error instanceof Error ? error.message : String(error);
200
- }
201
-
202
- function boundedError(message: string): string {
203
- const value = message.trim() || "unknown failure";
204
- return value.length <= MAX_ERROR_CHARS ? value : `${value.slice(0, MAX_ERROR_CHARS)}…`;
205
- }
@@ -1,188 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import fs from "node:fs/promises";
3
- import path from "node:path";
4
- import type { ArtifactRef, ArtifactValue } from "./types.js";
5
-
6
- /**
7
- * Value externalization for run bundles (see docs/run-bundles.md): string
8
- * leaves larger than the threshold are written once, content-addressed, under
9
- * `artifacts/` and replaced by `{ "$artifact": ref }`. Because artifacts are
10
- * immutable and deduplicated by hash, the same output appearing in `outputs`,
11
- * `results`, `steps`, and the trace costs one file plus small references.
12
- */
13
-
14
- export const ARTIFACT_THRESHOLD_BYTES = 4096;
15
- export const ARTIFACTS_DIR = "artifacts";
16
-
17
- const ARTIFACT_KEY = "$artifact";
18
- const ESCAPED_KEY = "$escaped";
19
-
20
- export function isArtifactValue(value: unknown): value is ArtifactValue {
21
- return (
22
- typeof value === "object" &&
23
- value !== null &&
24
- !Array.isArray(value) &&
25
- Object.keys(value).length === 1 &&
26
- ARTIFACT_KEY in value
27
- );
28
- }
29
-
30
- function isEscapedValue(value: unknown): value is { $escaped: Record<string, unknown> } {
31
- return (
32
- typeof value === "object" &&
33
- value !== null &&
34
- !Array.isArray(value) &&
35
- Object.keys(value).length === 1 &&
36
- ESCAPED_KEY in value
37
- );
38
- }
39
-
40
- /** True for a single-key object that would be misread as a sentinel. */
41
- function needsEscape(value: Record<string, unknown>): boolean {
42
- const keys = Object.keys(value);
43
- return keys.length === 1 && (keys[0] === ARTIFACT_KEY || keys[0] === ESCAPED_KEY);
44
- }
45
-
46
- /**
47
- * Writes externalized string leaves for one run bundle. Instances serialize
48
- * their writes and deduplicate by content hash, so encoding the same large
49
- * string in several value positions touches the filesystem once.
50
- */
51
- export class ArtifactWriter {
52
- private readonly runDir: string;
53
- private readonly written = new Set<string>();
54
- private chain: Promise<unknown> = Promise.resolve();
55
- private dirCreated = false;
56
-
57
- constructor(runDir: string) {
58
- this.runDir = runDir;
59
- }
60
-
61
- /** True once any artifact exists for this run. */
62
- get hasArtifacts(): boolean {
63
- return this.written.size > 0;
64
- }
65
-
66
- async externalize(text: string): Promise<ArtifactValue> {
67
- const bytes = Buffer.from(text, "utf8");
68
- const sha256 = createHash("sha256").update(bytes).digest("hex");
69
- const relativePath = `${ARTIFACTS_DIR}/sha256-${sha256}.txt`;
70
- const task = this.chain.then(async () => {
71
- if (this.written.has(sha256)) {
72
- return;
73
- }
74
- if (!this.dirCreated) {
75
- await fs.mkdir(path.join(this.runDir, ARTIFACTS_DIR), { recursive: true, mode: 0o700 });
76
- this.dirCreated = true;
77
- }
78
- const filePath = path.join(this.runDir, relativePath);
79
- // Content-addressed files are immutable; an existing file is complete
80
- // unless a previous crash left a partial write, which the temp-rename
81
- // pattern prevents.
82
- const tempPath = `${filePath}.${process.pid}.tmp`;
83
- await fs.writeFile(tempPath, bytes, { mode: 0o600 });
84
- await fs.rename(tempPath, filePath);
85
- this.written.add(sha256);
86
- });
87
- this.chain = task.catch(() => undefined);
88
- await task;
89
- return {
90
- $artifact: {
91
- path: relativePath,
92
- mediaType: "text/plain",
93
- bytes: bytes.byteLength,
94
- sha256,
95
- },
96
- };
97
- }
98
- }
99
-
100
- /**
101
- * Encode a persisted value: externalize large string leaves and escape
102
- * single-key `$artifact`/`$escaped` objects so the sentinel stays
103
- * unambiguous. Returns the original value when nothing changed.
104
- */
105
- export async function encodeValue(
106
- value: unknown,
107
- writer: ArtifactWriter,
108
- thresholdBytes: number = ARTIFACT_THRESHOLD_BYTES,
109
- ): Promise<unknown> {
110
- if (typeof value === "string") {
111
- if (Buffer.byteLength(value, "utf8") <= thresholdBytes) {
112
- return value;
113
- }
114
- return await writer.externalize(value);
115
- }
116
- if (Array.isArray(value)) {
117
- const encoded = await Promise.all(
118
- value.map((item) => encodeValue(item, writer, thresholdBytes)),
119
- );
120
- return encoded.some((item, index) => item !== value[index]) ? encoded : value;
121
- }
122
- if (typeof value === "object" && value !== null) {
123
- const record = value as Record<string, unknown>;
124
- const entries = await Promise.all(
125
- Object.entries(record).map(
126
- async ([key, item]) => [key, await encodeValue(item, writer, thresholdBytes)] as const,
127
- ),
128
- );
129
- const changed = entries.some(([key, item]) => item !== record[key]);
130
- const encoded = changed ? Object.fromEntries(entries) : record;
131
- return needsEscape(record) ? { [ESCAPED_KEY]: encoded } : encoded;
132
- }
133
- return value;
134
- }
135
-
136
- /**
137
- * Walk a persisted value, replacing every `$artifact` sentinel via `resolve`
138
- * and unwrapping `$escaped` objects. `resolve` may return the artifact
139
- * contents or a placeholder; it receives the reference untouched.
140
- */
141
- export function decodeValueWith(value: unknown, resolve: (ref: ArtifactRef) => unknown): unknown {
142
- if (isArtifactValue(value)) {
143
- return resolve(value.$artifact);
144
- }
145
- if (isEscapedValue(value)) {
146
- // The unwrapped object is user data: process its children but do not
147
- // re-test the object itself as a sentinel.
148
- return decodeChildren(value.$escaped, resolve);
149
- }
150
- if (Array.isArray(value)) {
151
- return value.map((item) => decodeValueWith(item, resolve));
152
- }
153
- if (typeof value === "object" && value !== null) {
154
- return decodeChildren(value as Record<string, unknown>, resolve);
155
- }
156
- return value;
157
- }
158
-
159
- function decodeChildren(
160
- record: Record<string, unknown>,
161
- resolve: (ref: ArtifactRef) => unknown,
162
- ): Record<string, unknown> {
163
- return Object.fromEntries(
164
- Object.entries(record).map(([key, item]) => [key, decodeValueWith(item, resolve)]),
165
- );
166
- }
167
-
168
- /** Resolve every artifact reference in `value` by reading the bundle files. */
169
- export async function resolveArtifacts(value: unknown, runDir: string): Promise<unknown> {
170
- const refs: ArtifactRef[] = [];
171
- decodeValueWith(value, (ref) => {
172
- refs.push(ref);
173
- return null;
174
- });
175
- const contents = new Map<string, string>();
176
- for (const ref of refs) {
177
- if (contents.has(ref.path)) {
178
- continue;
179
- }
180
- const resolved = path.resolve(runDir, ref.path);
181
- // A reference must never escape the bundle directory.
182
- if (!resolved.startsWith(path.resolve(runDir) + path.sep)) {
183
- throw new Error(`Artifact path escapes the bundle: ${ref.path}`);
184
- }
185
- contents.set(ref.path, await fs.readFile(resolved, "utf8"));
186
- }
187
- return decodeValueWith(value, (ref) => contents.get(ref.path) ?? null);
188
- }
@@ -1,178 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import fs from "node:fs/promises";
3
- import path from "node:path";
4
- import type { BuiltinWorkflowCatalog } from "./catalog.js";
5
- import { WorkflowRunStore, listRunBundles } from "./store.js";
6
- import type { WorkflowRunState, WorkflowSource } from "./types.js";
7
-
8
- export type LegacySourceMigrationQueue = {
9
- repairCanonicalWorkflowSourceRun(options: {
10
- runId: string;
11
- workflowName: string;
12
- workflowSourceRef: string;
13
- runnerId: string;
14
- claimToken: string;
15
- leaseMs: number;
16
- }): "unchanged" | "claimed" | false;
17
- claimLegacyWorkflowSourceRun(options: {
18
- runId: string;
19
- workflowName: string;
20
- oldWorkflowPath: string;
21
- workflowSourceRef: string;
22
- runnerId: string;
23
- claimToken: string;
24
- leaseMs: number;
25
- }): boolean;
26
- parkWorkflowRun(options: { runId: string; claimToken: string }): boolean;
27
- getWorkflowRun(runId: string):
28
- | {
29
- status: "queued" | "starting" | "running" | "parked" | "done" | "failed" | "cancelled";
30
- }
31
- | undefined;
32
- setWorkflowRunOriginSession?(runId: string, originSessionId: string): boolean;
33
- };
34
-
35
- const MIGRATION_LEASE_MS = 30_000;
36
-
37
- export type LegacySourceMigrationResult = {
38
- migratedRunIds: string[];
39
- blocked: { runId: string; reason: string }[];
40
- };
41
-
42
- /** One bounded migration for nonterminal runs created before canonical sources. */
43
- export async function migrateLegacyWorkflowSources(options: {
44
- catalog: BuiltinWorkflowCatalog;
45
- store?: WorkflowRunStore;
46
- queue?: LegacySourceMigrationQueue;
47
- }): Promise<LegacySourceMigrationResult> {
48
- const store = options.store ?? new WorkflowRunStore();
49
- const result: LegacySourceMigrationResult = { migratedRunIds: [], blocked: [] };
50
- for (const bundle of await listRunBundles(store.outputRoot)) {
51
- const state = bundle.state;
52
- if (state.status !== "running" && state.status !== "waiting") continue;
53
- if (
54
- options.queue?.setWorkflowRunOriginSession !== undefined &&
55
- bundle.sessionBinding !== null
56
- ) {
57
- options.queue.setWorkflowRunOriginSession(state.runId, bundle.sessionBinding.piSessionId);
58
- }
59
- if (state.workflowSource !== undefined) {
60
- if (options.queue === undefined) continue;
61
- const claimToken = randomUUID();
62
- const repaired = options.queue.repairCanonicalWorkflowSourceRun({
63
- runId: state.runId,
64
- workflowName: state.workflowName,
65
- workflowSourceRef: sourceRef(state.workflowSource),
66
- runnerId: `source-migration-${process.pid}`,
67
- claimToken,
68
- leaseMs: MIGRATION_LEASE_MS,
69
- });
70
- if (repaired === false) {
71
- // Another runner can own a canonical run during startup. Its source is
72
- // already safe; the normal queue lease will make it claimable later.
73
- } else if (
74
- repaired === "claimed" &&
75
- !options.queue.parkWorkflowRun({ runId: state.runId, claimToken })
76
- ) {
77
- result.blocked.push({
78
- runId: state.runId,
79
- reason: "canonical queue repair could not release its claim",
80
- });
81
- }
82
- continue;
83
- }
84
- if (state.workflowPath === undefined || state.workflowHash === undefined) {
85
- result.blocked.push({ runId: state.runId, reason: "legacy workflow identity is incomplete" });
86
- continue;
87
- }
88
- const legacyPath = {
89
- workflowName: state.workflowName,
90
- workflowPath: state.workflowPath,
91
- };
92
- const pathEntry = options.catalog.legacyPathEntry(legacyPath);
93
- let workflowSource: WorkflowSource;
94
- let workflowSourceRef: string;
95
- if (pathEntry === undefined) {
96
- workflowSource = {
97
- kind: "file",
98
- path: path.resolve(state.workflowPath),
99
- hash: state.workflowHash,
100
- };
101
- workflowSourceRef = workflowSource.path;
102
- } else {
103
- const legacy = options.catalog.matchLegacy({
104
- ...legacyPath,
105
- workflowHash: state.workflowHash,
106
- });
107
- if (legacy === undefined) {
108
- const reason = `legacy built-in ${pathEntry.id} has an unknown source revision`;
109
- result.blocked.push({ runId: state.runId, reason });
110
- continue;
111
- }
112
- workflowSource = {
113
- kind: "builtin",
114
- id: legacy.entry.id,
115
- revision: legacy.revision,
116
- };
117
- workflowSourceRef = legacy.entry.ref;
118
- }
119
- const claimToken = randomUUID();
120
- const queueIsDone = options.queue?.getWorkflowRun(state.runId)?.status === "done";
121
- if (
122
- options.queue !== undefined &&
123
- !queueIsDone &&
124
- !options.queue.claimLegacyWorkflowSourceRun({
125
- runId: state.runId,
126
- workflowName: state.workflowName,
127
- oldWorkflowPath: state.workflowPath,
128
- workflowSourceRef,
129
- runnerId: `source-migration-${process.pid}`,
130
- claimToken,
131
- leaseMs: MIGRATION_LEASE_MS,
132
- })
133
- ) {
134
- result.blocked.push({
135
- runId: state.runId,
136
- reason: "matching queue row is active or unavailable",
137
- });
138
- continue;
139
- }
140
- const migrated: WorkflowRunState = {
141
- ...state,
142
- workflowSource,
143
- };
144
- delete migrated.workflowPath;
145
- delete migrated.workflowHash;
146
- const migratedManifest = {
147
- ...bundle.manifest,
148
- workflowSource: migrated.workflowSource,
149
- };
150
- delete (migratedManifest as typeof migratedManifest & { workflowPath?: string }).workflowPath;
151
- // State is the migration commit point. Queue and manifest updates are
152
- // idempotent, so a crash before this write can safely retry.
153
- await writeJsonAtomic(path.join(bundle.runDir, "manifest.json"), migratedManifest);
154
- await writeJsonAtomic(path.join(bundle.runDir, "state.json"), migrated);
155
- if (
156
- options.queue !== undefined &&
157
- !queueIsDone &&
158
- !options.queue.parkWorkflowRun({ runId: state.runId, claimToken })
159
- ) {
160
- result.blocked.push({
161
- runId: state.runId,
162
- reason: "migration completed but its queue claim could not be released",
163
- });
164
- }
165
- result.migratedRunIds.push(state.runId);
166
- }
167
- return result;
168
- }
169
-
170
- function sourceRef(source: WorkflowSource): string {
171
- return source.kind === "builtin" ? `builtin:${source.id}` : source.path;
172
- }
173
-
174
- async function writeJsonAtomic(filePath: string, value: unknown): Promise<void> {
175
- const tempPath = `${filePath}.${process.pid}.${randomUUID()}.source-migration.tmp`;
176
- await fs.writeFile(tempPath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
177
- await fs.rename(tempPath, filePath);
178
- }