@osolmaz/pi-workflows 0.14.0 → 0.15.1

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 (235) hide show
  1. package/README.md +78 -110
  2. package/dist/builtins/autoimplement.workflow.js +3 -1
  3. package/dist/builtins/autoimplement.workflow.js.map +1 -1
  4. package/dist/builtins/change-verification.workflow.js +7 -2
  5. package/dist/builtins/change-verification.workflow.js.map +1 -1
  6. package/dist/builtins/metadata.d.ts +22 -0
  7. package/dist/builtins/metadata.js +10 -0
  8. package/dist/builtins/metadata.js.map +1 -0
  9. package/dist/builtins/monitor.workflow.js +4 -1
  10. package/dist/builtins/monitor.workflow.js.map +1 -1
  11. package/dist/builtins/sanity-check.workflow.js +4 -1
  12. package/dist/builtins/sanity-check.workflow.js.map +1 -1
  13. package/dist/builtins/workspace-preparation.workflow.js +3 -1
  14. package/dist/builtins/workspace-preparation.workflow.js.map +1 -1
  15. package/dist/controllers/index.d.ts +0 -1
  16. package/dist/controllers/index.js +0 -1
  17. package/dist/controllers/index.js.map +1 -1
  18. package/dist/controllers/sqlite.d.ts +51 -0
  19. package/dist/controllers/sqlite.js +433 -57
  20. package/dist/controllers/sqlite.js.map +1 -1
  21. package/dist/controllers/store.d.ts +1 -0
  22. package/dist/extension/controller-command.d.ts +22 -0
  23. package/dist/extension/controller-command.js +32 -0
  24. package/dist/extension/controller-command.js.map +1 -0
  25. package/dist/extension/index.d.ts +2 -9
  26. package/dist/extension/index.js +876 -3447
  27. package/dist/extension/index.js.map +1 -1
  28. package/dist/extension/message-card.d.ts +13 -0
  29. package/dist/extension/message-card.js +46 -0
  30. package/dist/extension/message-card.js.map +1 -0
  31. package/dist/extension/step-message.d.ts +5 -6
  32. package/dist/extension/step-message.js +41 -52
  33. package/dist/extension/step-message.js.map +1 -1
  34. package/dist/host/child-worker-supervisor.d.ts +50 -0
  35. package/dist/host/child-worker-supervisor.js +159 -0
  36. package/dist/host/child-worker-supervisor.js.map +1 -0
  37. package/dist/host/client.d.ts +48 -0
  38. package/dist/host/client.js +216 -0
  39. package/dist/host/client.js.map +1 -0
  40. package/dist/host/controller-worker-entry.d.ts +2 -0
  41. package/dist/host/controller-worker-entry.js +244 -0
  42. package/dist/host/controller-worker-entry.js.map +1 -0
  43. package/dist/host/controller-worker-protocol.d.ts +36 -0
  44. package/dist/host/controller-worker-protocol.js +49 -0
  45. package/dist/host/controller-worker-protocol.js.map +1 -0
  46. package/dist/host/controller-worker-supervisor.d.ts +21 -0
  47. package/dist/host/controller-worker-supervisor.js +54 -0
  48. package/dist/host/controller-worker-supervisor.js.map +1 -0
  49. package/dist/host/host-entry.d.ts +2 -0
  50. package/dist/host/host-entry.js +23 -0
  51. package/dist/host/host-entry.js.map +1 -0
  52. package/dist/host/processes.d.ts +17 -12
  53. package/dist/host/processes.js +154 -50
  54. package/dist/host/processes.js.map +1 -1
  55. package/dist/host/protocol.d.ts +38 -0
  56. package/dist/host/protocol.js +156 -0
  57. package/dist/host/protocol.js.map +1 -0
  58. package/dist/host/resolver-entry.d.ts +49 -0
  59. package/dist/host/resolver-entry.js +149 -0
  60. package/dist/host/resolver-entry.js.map +1 -0
  61. package/dist/host/rpc-executor.d.ts +14 -3
  62. package/dist/host/rpc-executor.js +63 -30
  63. package/dist/host/rpc-executor.js.map +1 -1
  64. package/dist/host/runner.d.ts +95 -29
  65. package/dist/host/runner.js +2311 -348
  66. package/dist/host/runner.js.map +1 -1
  67. package/dist/host/state.d.ts +174 -0
  68. package/dist/host/state.js +689 -0
  69. package/dist/host/state.js.map +1 -0
  70. package/dist/host/worker-entry.d.ts +10 -0
  71. package/dist/host/worker-entry.js +446 -0
  72. package/dist/host/worker-entry.js.map +1 -0
  73. package/dist/host/worker-protocol.d.ts +31 -0
  74. package/dist/host/worker-protocol.js +122 -0
  75. package/dist/host/worker-protocol.js.map +1 -0
  76. package/dist/host/worker-store.d.ts +80 -0
  77. package/dist/host/worker-store.js +91 -0
  78. package/dist/host/worker-store.js.map +1 -0
  79. package/dist/host/worker-supervisor.d.ts +22 -0
  80. package/dist/host/worker-supervisor.js +54 -0
  81. package/dist/host/worker-supervisor.js.map +1 -0
  82. package/dist/render/canvas.d.ts +2 -1
  83. package/dist/render/canvas.js +40 -15
  84. package/dist/render/canvas.js.map +1 -1
  85. package/dist/render/graph-render.d.ts +7 -3
  86. package/dist/render/graph-render.js +125 -74
  87. package/dist/render/graph-render.js.map +1 -1
  88. package/dist/state/database.js +3 -1
  89. package/dist/state/database.js.map +1 -1
  90. package/dist/state/index.d.ts +1 -0
  91. package/dist/state/index.js +1 -0
  92. package/dist/state/index.js.map +1 -1
  93. package/dist/state/schema.d.ts +1 -1
  94. package/dist/state/schema.js +171 -3
  95. package/dist/state/schema.js.map +1 -1
  96. package/dist/state/viewer.d.ts +46 -0
  97. package/dist/state/viewer.js +249 -0
  98. package/dist/state/viewer.js.map +1 -0
  99. package/dist/viewer/cli.d.ts +1 -1
  100. package/dist/viewer/cli.js +47 -18
  101. package/dist/viewer/cli.js.map +1 -1
  102. package/dist/workflows/composition.js +25 -2
  103. package/dist/workflows/composition.js.map +1 -1
  104. package/dist/workflows/definition.d.ts +3 -1
  105. package/dist/workflows/definition.js +25 -0
  106. package/dist/workflows/definition.js.map +1 -1
  107. package/dist/workflows/engine.d.ts +1 -0
  108. package/dist/workflows/engine.js +157 -42
  109. package/dist/workflows/engine.js.map +1 -1
  110. package/dist/workflows/errors.d.ts +3 -1
  111. package/dist/workflows/errors.js +4 -7
  112. package/dist/workflows/errors.js.map +1 -1
  113. package/dist/workflows/human-decision.d.ts +3 -0
  114. package/dist/workflows/human-decision.js +31 -0
  115. package/dist/workflows/human-decision.js.map +1 -1
  116. package/dist/workflows/index.d.ts +1 -1
  117. package/dist/workflows/index.js +1 -1
  118. package/dist/workflows/index.js.map +1 -1
  119. package/dist/workflows/schema.js +17 -6
  120. package/dist/workflows/schema.js.map +1 -1
  121. package/dist/{viewer → workflows}/session-reducer.d.ts +3 -1
  122. package/dist/{viewer → workflows}/session-reducer.js +4 -0
  123. package/dist/workflows/session-reducer.js.map +1 -0
  124. package/dist/workflows/store.d.ts +87 -1
  125. package/dist/workflows/store.js +892 -93
  126. package/dist/workflows/store.js.map +1 -1
  127. package/dist/workflows/tool-input.d.ts +0 -26
  128. package/dist/workflows/tool-input.js +2 -50
  129. package/dist/workflows/tool-input.js.map +1 -1
  130. package/dist/workflows/types.d.ts +36 -4
  131. package/docs/2026-08-30-out-of-process-workflow-host-plan.md +353 -0
  132. package/docs/CONTROLLERS.md +11 -11
  133. package/docs/DEFERRED_TURNS.md +23 -2
  134. package/docs/SQLITE_STATE.md +41 -31
  135. package/docs/WORKFLOW_HOST.md +452 -0
  136. package/docs/development.md +46 -30
  137. package/docs/live-replay-protocol.md +129 -100
  138. package/docs/plans/2026-08-27-workflow-terminal-restart-plan.md +42 -0
  139. package/docs/plans/2026-08-28-piw-incremental-viewer-plan.md +293 -0
  140. package/docs/plans/piw-viewer-experience-implementation-plan.md +11 -1
  141. package/docs/plans/tui-viewer-implementation-plan.md +5 -0
  142. package/docs/tui-viewer.md +18 -3
  143. package/docs/workflows.md +162 -210
  144. package/examples/workflows/command-batch.workflow.ts +2 -0
  145. package/examples/workflows/shell.workflow.ts +2 -1
  146. package/herdr-plugin.toml +1 -1
  147. package/package.json +1 -1
  148. package/src/builtins/autoimplement.workflow.ts +3 -0
  149. package/src/builtins/change-verification.workflow.ts +7 -2
  150. package/src/builtins/metadata.ts +9 -0
  151. package/src/builtins/monitor.workflow.ts +4 -0
  152. package/src/builtins/sanity-check.workflow.ts +4 -0
  153. package/src/builtins/workspace-preparation.workflow.ts +3 -1
  154. package/src/controllers/index.ts +0 -5
  155. package/src/controllers/sqlite.ts +709 -76
  156. package/src/controllers/store.ts +1 -0
  157. package/src/extension/controller-command.ts +45 -0
  158. package/src/extension/index.ts +944 -4163
  159. package/src/extension/message-card.ts +61 -0
  160. package/src/extension/step-message.ts +58 -63
  161. package/src/host/child-worker-supervisor.ts +183 -0
  162. package/src/host/client.ts +293 -0
  163. package/src/host/controller-worker-entry.ts +311 -0
  164. package/src/host/controller-worker-protocol.ts +104 -0
  165. package/src/host/controller-worker-supervisor.ts +79 -0
  166. package/src/host/host-entry.ts +23 -0
  167. package/src/host/processes.ts +171 -54
  168. package/src/host/protocol.ts +196 -0
  169. package/src/host/resolver-entry.ts +241 -0
  170. package/src/host/rpc-executor.ts +76 -34
  171. package/src/host/runner.ts +2813 -422
  172. package/src/host/state.ts +1160 -0
  173. package/src/host/worker-entry.ts +533 -0
  174. package/src/host/worker-protocol.ts +165 -0
  175. package/src/host/worker-store.ts +229 -0
  176. package/src/host/worker-supervisor.ts +74 -0
  177. package/src/render/canvas.ts +44 -10
  178. package/src/render/graph-render.ts +145 -90
  179. package/src/state/database.ts +2 -1
  180. package/src/state/index.ts +14 -0
  181. package/src/state/schema.ts +171 -3
  182. package/src/state/viewer.ts +356 -0
  183. package/src/viewer/cli.ts +49 -17
  184. package/src/workflows/composition.ts +36 -2
  185. package/src/workflows/definition.ts +32 -0
  186. package/src/workflows/engine.ts +157 -54
  187. package/src/workflows/errors.ts +11 -2
  188. package/src/workflows/human-decision.ts +49 -0
  189. package/src/workflows/index.ts +2 -0
  190. package/src/workflows/schema.ts +19 -6
  191. package/src/{viewer → workflows}/session-reducer.ts +11 -1
  192. package/src/workflows/store.ts +1316 -108
  193. package/src/workflows/tool-input.ts +3 -69
  194. package/src/workflows/types.ts +32 -4
  195. package/dist/controllers/workflow-engine-scheduler.d.ts +0 -29
  196. package/dist/controllers/workflow-engine-scheduler.js +0 -175
  197. package/dist/controllers/workflow-engine-scheduler.js.map +0 -1
  198. package/dist/extension/controller-host.d.ts +0 -48
  199. package/dist/extension/controller-host.js +0 -110
  200. package/dist/extension/controller-host.js.map +0 -1
  201. package/dist/extension/deferred-turn-coordinator.d.ts +0 -32
  202. package/dist/extension/deferred-turn-coordinator.js +0 -143
  203. package/dist/extension/deferred-turn-coordinator.js.map +0 -1
  204. package/dist/extension/deferred-turn.d.ts +0 -44
  205. package/dist/extension/deferred-turn.js +0 -110
  206. package/dist/extension/deferred-turn.js.map +0 -1
  207. package/dist/extension/executor.d.ts +0 -86
  208. package/dist/extension/executor.js +0 -311
  209. package/dist/extension/executor.js.map +0 -1
  210. package/dist/extension/follow-up-coordinator.d.ts +0 -27
  211. package/dist/extension/follow-up-coordinator.js +0 -131
  212. package/dist/extension/follow-up-coordinator.js.map +0 -1
  213. package/dist/extension/recorder.d.ts +0 -84
  214. package/dist/extension/recorder.js +0 -528
  215. package/dist/extension/recorder.js.map +0 -1
  216. package/dist/extension/restart-policy.d.ts +0 -38
  217. package/dist/extension/restart-policy.js +0 -116
  218. package/dist/extension/restart-policy.js.map +0 -1
  219. package/dist/extension/session-events.d.ts +0 -133
  220. package/dist/extension/session-events.js +0 -61
  221. package/dist/extension/session-events.js.map +0 -1
  222. package/dist/extension/terminal-decision.d.ts +0 -51
  223. package/dist/extension/terminal-decision.js +0 -110
  224. package/dist/extension/terminal-decision.js.map +0 -1
  225. package/dist/viewer/session-reducer.js.map +0 -1
  226. package/src/controllers/workflow-engine-scheduler.ts +0 -246
  227. package/src/extension/controller-host.ts +0 -167
  228. package/src/extension/deferred-turn-coordinator.ts +0 -171
  229. package/src/extension/deferred-turn.ts +0 -166
  230. package/src/extension/executor.ts +0 -411
  231. package/src/extension/follow-up-coordinator.ts +0 -151
  232. package/src/extension/recorder.ts +0 -655
  233. package/src/extension/restart-policy.ts +0 -163
  234. package/src/extension/session-events.ts +0 -121
  235. package/src/extension/terminal-decision.ts +0 -172
@@ -1,166 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import type {
3
- WorkflowTurnIntentCause,
4
- WorkflowTurnIntentFacts,
5
- WorkflowTurnIntentRecord,
6
- WorkflowTurnIntentResolution,
7
- } from "../controllers/sqlite.js";
8
-
9
- export const DEFERRED_TURN_MESSAGE_TYPE = "pi-workflows-deferred-turn";
10
- export const DEFERRED_TURN_MESSAGE_SCHEMA = "pi-workflows.deferred-turn-message.v1";
11
- const FACTS_SCHEMA = "pi-workflows.deferred-turn-facts.v1";
12
- const MAX_REASON_CHARS = 8_192;
13
-
14
- export type DeferredTurnSource = {
15
- runId: string;
16
- workflowName: string;
17
- targetSessionId: string;
18
- cause: WorkflowTurnIntentCause;
19
- sourceEventId: string;
20
- observedState: string;
21
- nodeId?: string | null;
22
- attemptId?: string | null;
23
- reason?: string | null;
24
- handoff?: boolean;
25
- };
26
-
27
- export type DeferredTurnDescriptor = {
28
- intentId: string;
29
- sourceEventId: string;
30
- runId: string;
31
- workflowRef: string;
32
- targetSessionId: string;
33
- cause: WorkflowTurnIntentCause;
34
- nodeId: string | null;
35
- attemptId: string | null;
36
- fallbackFacts: WorkflowTurnIntentFacts;
37
- };
38
-
39
- export type DeferredTurnMessageDetails = {
40
- schema: typeof DEFERRED_TURN_MESSAGE_SCHEMA;
41
- turnIntentId: string;
42
- runId: string;
43
- cause: WorkflowTurnIntentCause;
44
- };
45
-
46
- export function deferredTurnSourceEventId(options: {
47
- runId: string;
48
- cause: WorkflowTurnIntentCause;
49
- nodeId?: string | null;
50
- attemptId?: string | null;
51
- source?: string;
52
- }): string {
53
- const parts = [
54
- options.runId,
55
- options.source ?? "run",
56
- options.nodeId ?? "$run",
57
- options.attemptId ?? "$none",
58
- options.cause,
59
- ];
60
- return `turn-source:${digest(parts)}`;
61
- }
62
-
63
- export function createDeferredTurnDescriptor(source: DeferredTurnSource): DeferredTurnDescriptor {
64
- const nodeId = source.nodeId ?? null;
65
- const attemptId = source.attemptId ?? null;
66
- const fallbackFacts = createDeferredTurnFacts(source);
67
- return {
68
- intentId: `deferred-turn:${digest([
69
- source.targetSessionId,
70
- source.runId,
71
- source.sourceEventId,
72
- nodeId ?? "$run",
73
- attemptId ?? "$none",
74
- source.cause,
75
- ])}`,
76
- sourceEventId: source.sourceEventId,
77
- runId: source.runId,
78
- workflowRef: source.workflowName,
79
- targetSessionId: source.targetSessionId,
80
- cause: source.cause,
81
- nodeId,
82
- attemptId,
83
- fallbackFacts,
84
- };
85
- }
86
-
87
- export function createDeferredTurnFacts(source: DeferredTurnSource): WorkflowTurnIntentFacts {
88
- return {
89
- schema: FACTS_SCHEMA,
90
- workflowName: source.workflowName,
91
- runId: source.runId,
92
- observedState: source.observedState,
93
- cause: source.cause,
94
- nodeId: source.nodeId ?? null,
95
- attemptId: source.attemptId ?? null,
96
- reason: boundedReason(source.reason),
97
- handoff: source.handoff ?? false,
98
- };
99
- }
100
-
101
- export function deferredTurnMessageId(
102
- intentId: string,
103
- resolution: WorkflowTurnIntentResolution,
104
- ): string {
105
- return `turn-message:${digest([intentId, resolution])}`;
106
- }
107
-
108
- export function deferredTurnMessageDetails(
109
- intent: WorkflowTurnIntentRecord,
110
- ): DeferredTurnMessageDetails {
111
- return {
112
- schema: DEFERRED_TURN_MESSAGE_SCHEMA,
113
- turnIntentId: intent.intentId,
114
- runId: intent.runId,
115
- cause: intent.cause,
116
- };
117
- }
118
-
119
- export function buildDeferredTurnContent(intent: WorkflowTurnIntentRecord): string {
120
- const facts = intent.fallbackFacts;
121
- const source = [
122
- facts.nodeId === null ? null : `node ${facts.nodeId}`,
123
- facts.attemptId === null ? null : `attempt ${facts.attemptId}`,
124
- ]
125
- .filter((part): part is string => part !== null)
126
- .join(", ");
127
- const reason =
128
- facts.reason === null
129
- ? ""
130
- : ` Reason: ${facts.reason}${/[.!?]$/.test(facts.reason) ? "" : "."}`;
131
- const sourceText = source.length === 0 ? "" : ` Source: ${source}.`;
132
- if (facts.cause === "launchFailed") {
133
- return [
134
- `Workflow ${facts.workflowName} failed to start (run ${facts.runId}).`,
135
- `${sourceText}${reason}`.trim(),
136
- "Inspect the durable workflow state before you explain the outcome or start a corrected workflow.",
137
- ]
138
- .filter((part) => part.length > 0)
139
- .join(" ");
140
- }
141
- if (facts.handoff) {
142
- return [
143
- `Workflow ${facts.workflowName} was handed to another runner (run ${facts.runId}).`,
144
- `Observed state: ${facts.observedState}.${sourceText}${reason}`,
145
- "Inspect the durable workflow state before you explain the outcome or take any authorized corrective action.",
146
- ].join(" ");
147
- }
148
- return [
149
- `Workflow ${facts.workflowName} ended with state ${facts.observedState} (run ${facts.runId}).`,
150
- `${sourceText}${reason}`.trim(),
151
- "Inspect the durable workflow state before you explain the outcome or take any authorized corrective action.",
152
- ]
153
- .filter((part) => part.length > 0)
154
- .join(" ");
155
- }
156
-
157
- function boundedReason(value: string | null | undefined): string | null {
158
- if (value === null || value === undefined) return null;
159
- const trimmed = value.trim();
160
- if (trimmed.length === 0) return null;
161
- return trimmed.length <= MAX_REASON_CHARS ? trimmed : trimmed.slice(0, MAX_REASON_CHARS);
162
- }
163
-
164
- function digest(parts: readonly string[]): string {
165
- return createHash("sha256").update(JSON.stringify(parts)).digest("hex");
166
- }
@@ -1,411 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import type { AssistantMessage } from "@earendil-works/pi-ai";
3
- import type {
4
- AgentStepExecutor,
5
- AgentStepRequest,
6
- AgentStepSubmission,
7
- ConversationRange,
8
- } from "../workflows/types.js";
9
-
10
- export type SubmissionResult =
11
- | { accepted: true; message: string }
12
- | { accepted: false; message: string };
13
-
14
- export type PromptDeliveryKind = "step" | "reminder" | "resume";
15
-
16
- export type PromptDelivery = {
17
- prompt: string;
18
- contract: AgentStepRequest["contract"];
19
- presentation?: AgentStepRequest["presentation"];
20
- kind: PromptDeliveryKind;
21
- /** True when the agent is known to be mid-run, so delivery must be queued. */
22
- streaming: boolean;
23
- };
24
-
25
- /**
26
- * Bracketing hooks for conversation linkage: a mark is taken when the step
27
- * prompt is first delivered, and the recorded entry range since that mark is
28
- * attached to the accepted submission.
29
- */
30
- export type ConversationHooks = {
31
- beginAttempt?: (contract: AgentStepRequest["contract"]) => void;
32
- recoverAssistant?: (contract: AgentStepRequest["contract"]) => AgentStepSubmission | undefined;
33
- mark: () => number;
34
- rangeSince: (mark: number) => ConversationRange | undefined;
35
- };
36
-
37
- export type ConversationStepExecutorOptions = {
38
- /** Deliver a prompt into the pi conversation. */
39
- sendPrompt: (delivery: PromptDelivery) => void;
40
- /** Reminders sent when the agent settles without submitting. Default 2. */
41
- maxNudges?: number;
42
- /** Conversation linkage hooks, wired to the session recorder. */
43
- conversation?: ConversationHooks;
44
- /** Called when the engine aborts a pending agent step. */
45
- onAbort?: (contract: AgentStepRequest["contract"], reason: unknown) => void;
46
- };
47
-
48
- type PendingStep = {
49
- request: AgentStepRequest;
50
- resolve: (submission: AgentStepSubmission) => void;
51
- reject: (error: unknown) => void;
52
- nudgesSent: number;
53
- /** Conversation mark taken when the prompt was first delivered. */
54
- mark: number | null;
55
- /** Latest finalized assistant message observed for this attempt. */
56
- assistantMessage?: AssistantMessage;
57
- cleanup: () => void;
58
- /** Resolves when this step stops being the pending step. */
59
- cleared: Promise<void>;
60
- markCleared: () => void;
61
- };
62
-
63
- const DEFAULT_MAX_NUDGES = 2;
64
-
65
- /**
66
- * AgentStepExecutor that runs steps inside the current pi conversation. The
67
- * engine hands it a prompt; it delivers the prompt as a model-facing workflow
68
- * message and resolves once the model submits an accepted output through the `workflow`
69
- * tool. If the agent settles without submitting, it nudges the model a
70
- * bounded number of times before failing the step.
71
- */
72
- export class ConversationStepExecutor implements AgentStepExecutor {
73
- readonly assistantMessageMode = "visible" as const;
74
- private readonly sendPrompt: (delivery: PromptDelivery) => void;
75
- private readonly maxNudges: number;
76
- private readonly conversation: ConversationHooks | undefined;
77
- private readonly onAbort: ConversationStepExecutorOptions["onAbort"];
78
- private pending: PendingStep | null = null;
79
- private streaming = false;
80
- private heldByUser = false;
81
-
82
- constructor(options: ConversationStepExecutorOptions) {
83
- this.sendPrompt = options.sendPrompt;
84
- this.maxNudges = options.maxNudges ?? DEFAULT_MAX_NUDGES;
85
- this.conversation = options.conversation;
86
- this.onAbort = options.onAbort;
87
- }
88
-
89
- /** Track agent streaming state (wire to agent_start / agent_settled). */
90
- setStreaming(streaming: boolean): void {
91
- this.streaming = streaming;
92
- }
93
-
94
- get pendingStepId(): string | null {
95
- return this.pending?.request.contract.nodeId ?? null;
96
- }
97
-
98
- get pendingCompletion(): "submit" | "assistant" | null {
99
- return this.pending === null ? null : completionKind(this.pending.request);
100
- }
101
-
102
- /**
103
- * Hold the pending step for the user: no nudges are sent while held, so an
104
- * escape-interrupted conversation stays quiet until the user resumes.
105
- */
106
- hold(): void {
107
- this.heldByUser = true;
108
- }
109
-
110
- get held(): boolean {
111
- return this.heldByUser;
112
- }
113
-
114
- /**
115
- * Release a user hold. When a step is still pending, its prompt is
116
- * re-delivered so the model picks the step back up.
117
- */
118
- release(): void {
119
- if (!this.heldByUser) {
120
- return;
121
- }
122
- this.heldByUser = false;
123
- const pending = this.pending;
124
- if (!pending) {
125
- return;
126
- }
127
- try {
128
- this.conversation?.beginAttempt?.(pending.request.contract);
129
- this.sendPrompt(this.delivery(pending.request, pending.request.prompt, "resume"));
130
- } catch (error) {
131
- this.clearPending();
132
- pending.reject(error);
133
- }
134
- }
135
-
136
- async runAgentStep(request: AgentStepRequest, signal: AbortSignal): Promise<AgentStepSubmission> {
137
- if (this.pending) {
138
- throw new Error("Another workflow step is already awaiting output");
139
- }
140
- if (completionKind(request) === "assistant") {
141
- const recovered = this.conversation?.recoverAssistant?.(request.contract);
142
- if (recovered !== undefined) {
143
- return recovered;
144
- }
145
- }
146
- return await new Promise<AgentStepSubmission>((resolve, reject) => {
147
- const onAbort = () => {
148
- const reason: unknown = signal.reason ?? new Error("Workflow step aborted");
149
- if (this.pending?.request !== request) {
150
- return;
151
- }
152
- this.clearPending();
153
- try {
154
- this.onAbort?.(request.contract, reason);
155
- } finally {
156
- reject(reason);
157
- }
158
- };
159
- signal.addEventListener("abort", onAbort, { once: true });
160
- let markCleared!: () => void;
161
- const cleared = new Promise<void>((resolveCleared) => {
162
- markCleared = resolveCleared;
163
- });
164
- this.conversation?.beginAttempt?.(request.contract);
165
- this.pending = {
166
- request,
167
- resolve,
168
- reject,
169
- nudgesSent: 0,
170
- mark: this.conversation?.mark() ?? null,
171
- cleanup: () => signal.removeEventListener("abort", onAbort),
172
- cleared,
173
- markCleared,
174
- };
175
- if (signal.aborted) {
176
- onAbort();
177
- return;
178
- }
179
- try {
180
- this.sendPrompt(this.delivery(request, request.prompt, "step"));
181
- } catch (error) {
182
- // A failed delivery must not leave the step installed, or every
183
- // subsequent agent node would fail with "already awaiting output".
184
- this.clearPending();
185
- reject(error);
186
- }
187
- });
188
- }
189
-
190
- /** Called by the `workflow` tool when the model submits a step output. */
191
- async submit(stepId: string, attemptId: string, output: unknown): Promise<SubmissionResult> {
192
- const pending = this.pending;
193
- if (!pending) {
194
- return {
195
- accepted: false,
196
- message:
197
- "No workflow step is awaiting output. Do not call the workflow tool outside an active workflow step.",
198
- };
199
- }
200
- const expected = pending.request.contract.nodeId;
201
- if (stepId !== expected) {
202
- return {
203
- accepted: false,
204
- message: `Wrong step id ${JSON.stringify(stepId)}; the pending step is ${JSON.stringify(expected)}.`,
205
- };
206
- }
207
- // Loops revisit the same node id, so a delayed duplicate submission from
208
- // an earlier attempt would otherwise be accepted as this attempt's output.
209
- const expectedAttempt = pending.request.contract.attemptId;
210
- if (attemptId !== expectedAttempt) {
211
- return {
212
- accepted: false,
213
- message: `Stale attempt id ${JSON.stringify(attemptId)} for step ${JSON.stringify(
214
- stepId,
215
- )}; the pending attempt is ${JSON.stringify(expectedAttempt)}. Use the attempt id from the latest step contract.`,
216
- };
217
- }
218
- if (completionKind(pending.request) === "assistant") {
219
- return {
220
- accepted: false,
221
- message:
222
- "This step completes with a normal assistant response. Do not submit workflow output.",
223
- };
224
- }
225
- // Race validation against the step being cleared: a hung `validate`
226
- // callback must not leave this tool call (and therefore pi) blocked after
227
- // a timeout or cancel already resolved the run.
228
- const result = await Promise.race([
229
- pending.request.accept(output),
230
- pending.cleared.then(() => null),
231
- ]);
232
- // The step may have timed out or been cancelled (and a newer step
233
- // installed) while validation was awaited; a stale submission must not
234
- // clear or resolve the newer pending step.
235
- if (result === null || this.pending !== pending) {
236
- return {
237
- accepted: false,
238
- message: `Step ${JSON.stringify(stepId)} is no longer awaiting output.`,
239
- };
240
- }
241
- if (!result.ok) {
242
- return {
243
- accepted: false,
244
- message: `Output rejected for step ${JSON.stringify(stepId)}: ${result.error}`,
245
- };
246
- }
247
- this.clearPending();
248
- const conversation =
249
- pending.mark !== null ? this.conversation?.rangeSince(pending.mark) : undefined;
250
- pending.resolve({
251
- output: result.value,
252
- ...(conversation !== undefined ? { conversation } : {}),
253
- });
254
- return {
255
- accepted: true,
256
- message: `Output accepted for step ${JSON.stringify(stepId)}.`,
257
- };
258
- }
259
-
260
- /** Keep the latest finalized assistant message for an assistant-output step. */
261
- handleMessageEnd(message: unknown): void {
262
- const pending = this.pending;
263
- if (pending === null || completionKind(pending.request) !== "assistant") {
264
- return;
265
- }
266
- const assistant = assistantMessageLike(message);
267
- if (assistant !== undefined) {
268
- pending.assistantMessage = assistant as AssistantMessage;
269
- }
270
- }
271
-
272
- /**
273
- * Called when the agent settles. Returns true when a nudge was sent, false
274
- * when there was nothing to do. Submitted steps use bounded nudges;
275
- * assistant-output steps accept or fail the one visible response.
276
- */
277
- handleAgentSettled(): boolean {
278
- const pending = this.pending;
279
- if (!pending) {
280
- return false;
281
- }
282
- if (this.heldByUser) {
283
- // The user interrupted deliberately; reminding the model now would
284
- // steal the conversation back. The step waits for an explicit resume.
285
- return false;
286
- }
287
- if (completionKind(pending.request) === "assistant") {
288
- try {
289
- const output = visibleAssistantText(
290
- pending.assistantMessage,
291
- pending.request.contract.maxOutputChars,
292
- );
293
- const conversation =
294
- pending.mark !== null ? this.conversation?.rangeSince(pending.mark) : undefined;
295
- const assistantMessage = {
296
- sha256: createHash("sha256").update(output).digest("hex"),
297
- ...(conversation?.lastEntryId !== undefined ? { entryId: conversation.lastEntryId } : {}),
298
- ...(pending.request.contract.maxOutputChars !== undefined
299
- ? { maxChars: pending.request.contract.maxOutputChars }
300
- : {}),
301
- };
302
- this.clearPending();
303
- pending.resolve({
304
- output,
305
- assistantMessage,
306
- ...(conversation !== undefined ? { conversation } : {}),
307
- });
308
- } catch (error) {
309
- this.clearPending();
310
- pending.reject(error);
311
- }
312
- return false;
313
- }
314
- if (pending.nudgesSent >= this.maxNudges) {
315
- this.clearPending();
316
- pending.reject(
317
- new Error(
318
- `Agent settled ${pending.nudgesSent + 1} times without submitting step ${JSON.stringify(
319
- pending.request.contract.nodeId,
320
- )} via the workflow tool`,
321
- ),
322
- );
323
- return false;
324
- }
325
- pending.nudgesSent += 1;
326
- const { nodeId, attemptId } = pending.request.contract;
327
- try {
328
- this.conversation?.beginAttempt?.(pending.request.contract);
329
- this.sendPrompt(
330
- this.delivery(
331
- pending.request,
332
- [
333
- `Reminder: workflow step ${JSON.stringify(nodeId)} is still awaiting your output.`,
334
- "Complete it by calling the `workflow` tool with:",
335
- `{"action": "submit", "step": ${JSON.stringify(nodeId)}, "attempt": ${JSON.stringify(attemptId)}, "output": <your result>}`,
336
- `Expected output: ${pending.request.contract.expectedOutput ?? "a JSON object with your result"}`,
337
- ].join("\n"),
338
- "reminder",
339
- ),
340
- );
341
- } catch (error) {
342
- // No reminder turn was started, so nothing would settle the step; fail
343
- // it promptly instead of waiting out the node timeout.
344
- this.clearPending();
345
- pending.reject(error);
346
- return false;
347
- }
348
- return true;
349
- }
350
-
351
- private delivery(
352
- request: AgentStepRequest,
353
- prompt: string,
354
- kind: PromptDeliveryKind,
355
- ): PromptDelivery {
356
- return {
357
- prompt,
358
- contract: request.contract,
359
- ...(request.presentation !== undefined ? { presentation: request.presentation } : {}),
360
- kind,
361
- streaming: this.streaming,
362
- };
363
- }
364
-
365
- private clearPending(): void {
366
- this.pending?.cleanup();
367
- this.pending?.markCleared();
368
- this.pending = null;
369
- }
370
- }
371
-
372
- function completionKind(request: AgentStepRequest): "submit" | "assistant" {
373
- return request.contract.completion;
374
- }
375
-
376
- function assistantMessageLike(
377
- message: unknown,
378
- ): Pick<AssistantMessage, "role" | "content" | "stopReason" | "errorMessage"> | undefined {
379
- if (message === null || typeof message !== "object") return undefined;
380
- const candidate = message as Partial<AssistantMessage>;
381
- if (candidate.role !== "assistant" || !Array.isArray(candidate.content)) return undefined;
382
- if (typeof candidate.stopReason !== "string") return undefined;
383
- return candidate as Pick<AssistantMessage, "role" | "content" | "stopReason" | "errorMessage">;
384
- }
385
-
386
- /** Extract the exact visible text blocks from one finalized assistant message. */
387
- export function visibleAssistantText(message: unknown, maxChars?: number): string {
388
- const assistant = assistantMessageLike(message);
389
- if (assistant === undefined) {
390
- throw new Error("Assistant step settled without a final assistant message");
391
- }
392
- if (assistant.stopReason !== "stop" && assistant.stopReason !== "length") {
393
- throw new Error(
394
- assistant.errorMessage?.trim() ||
395
- `Assistant step stopped with ${JSON.stringify(assistant.stopReason)} before a final response`,
396
- );
397
- }
398
- const text = assistant.content
399
- .filter((part) => part.type === "text")
400
- .map((part) => part.text)
401
- .join("\n");
402
- if (text.trim().length === 0) {
403
- throw new Error("Assistant step returned no visible text");
404
- }
405
- if (maxChars !== undefined && text.length > maxChars) {
406
- throw new Error(
407
- `Assistant response has ${text.length} characters, above the configured limit of ${maxChars}`,
408
- );
409
- }
410
- return text;
411
- }