@atolis-hq/wake 0.3.114 → 0.3.116
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.
- package/dist/src/bootstrap/version.js +1 -1
- package/dist/src/execution/infrastructure/codex-stop-hook.js +34 -246
- package/dist/src/execution/infrastructure/runners/codex.js +5 -20
- package/dist/src/orchestration/contracts/event-decoder.js +1 -0
- package/dist/src/orchestration/contracts/vocabulary.js +1 -0
- package/dist/src/orchestration/domain/compiler.js +18 -5
- package/dist/src/orchestration/domain/resource-transition-compiler.js +8 -4
- package/dist/src/orchestration/domain/transition.js +2 -0
- package/package.json +1 -1
- package/dist/src/execution/infrastructure/codex-stop-hook-protocol.js +0 -209
|
@@ -1,264 +1,55 @@
|
|
|
1
|
-
import { readFile
|
|
2
|
-
import { join } from 'node:path';
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
3
2
|
import { pathToFileURL } from 'node:url';
|
|
4
|
-
|
|
5
|
-
export const unverifiedCodexCompletionReason = 'unverified: could not confirm background command completion from Codex structured telemetry';
|
|
3
|
+
export const waitBackgroundStatus = 'WAIT_BACKGROUND';
|
|
6
4
|
/**
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* to yield for (observed from ~1s to 50s+ per call in production), so a
|
|
12
|
-
* fixed count either gives up far too early on a real multi-minute command
|
|
13
|
-
* or far too late on a broken loop that isn't waiting on anything real.
|
|
14
|
-
*
|
|
15
|
-
* Real observed `npm run verify`/`verify:ci` durations range from ~90s to
|
|
16
|
-
* over 20 minutes, so this value is a deliberate tradeoff rather than a safe
|
|
17
|
-
* upper bound on every legitimate case: a genuinely long-running command that
|
|
18
|
-
* outlasts it will have its live retry loop give up before finishing, and
|
|
19
|
-
* fall through to a `BLOCKED` outcome needing a human `/retry` instead of
|
|
20
|
-
* confirming cleanly on its own. That's an accepted cost, not a correctness
|
|
21
|
-
* gap — giving up here never weakens the guarantee, since the post-run
|
|
22
|
-
* fallback (`verifyCodexSession`) independently re-scans the same transcript
|
|
23
|
-
* after the process exits and still reports the run as unverified if the
|
|
24
|
-
* cell is genuinely still unresolved. This limit exists only to bound
|
|
25
|
-
* wasted time/tokens against a detection gap we haven't found yet, not to
|
|
26
|
-
* replace correct detection.
|
|
27
|
-
*/
|
|
28
|
-
export const maxLiveHookRetryMs = 10 * 60 * 1000;
|
|
29
|
-
/**
|
|
30
|
-
* Inspect only Codex's structured function-call protocol. Command output is
|
|
31
|
-
* opaque except for the protocol's managed-cell and terminal-result envelopes.
|
|
32
|
-
*
|
|
33
|
-
* Exec/wait cells live in one `codex exec` process's memory and never survive
|
|
34
|
-
* a resume into a new process, so only the segment of the transcript since
|
|
35
|
-
* the current process attached (its `session_meta`/`turn_context` marker)
|
|
36
|
-
* can hold a cell that might still be genuinely pending. A cell referenced
|
|
37
|
-
* only in an earlier segment belongs to a process that has already exited
|
|
38
|
-
* and can never return an exit code again — scoping to the latest segment
|
|
39
|
-
* is what makes that structurally certain, rather than trying to recognise
|
|
40
|
-
* every shape of "this cell is gone" text a stale reference might produce.
|
|
5
|
+
* WAIT_BACKGROUND is a Codex-only, intermediate final response. It is not a
|
|
6
|
+
* Wake outcome: the hook rejects it and gives Codex another turn to obtain a
|
|
7
|
+
* terminal result before it reports DONE, BLOCKED, NEEDS_CLARIFICATION, or
|
|
8
|
+
* FAILED.
|
|
41
9
|
*/
|
|
42
10
|
export function inspectCodexTranscript(transcript) {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
unresolvableCells: new Set(),
|
|
50
|
-
sessionsByCell: new Map(),
|
|
51
|
-
};
|
|
52
|
-
for (const line of lines.slice(boundary + 1)) {
|
|
53
|
-
const event = parseJson(line);
|
|
54
|
-
if (event === undefined)
|
|
55
|
-
return blocked('could not parse Codex structured telemetry');
|
|
56
|
-
const payload = record(event.payload);
|
|
57
|
-
if (payload !== undefined)
|
|
58
|
-
consumePayload(payload, telemetry);
|
|
59
|
-
}
|
|
60
|
-
const unresolved = [...telemetry.pendingCells].filter((cellId) => !telemetry.resolvedCells.has(cellId));
|
|
61
|
-
if (unresolved.length === 0)
|
|
62
|
-
return {};
|
|
63
|
-
// A cell whose own `wait` call has already reported it gone (a distinct,
|
|
64
|
-
// cell-identity-specific protocol error, not a general failure) can never
|
|
65
|
-
// return an exit code no matter how many more times it's polled. Asking
|
|
66
|
-
// the model to keep retrying it is not just wasted effort, it's actively
|
|
67
|
-
// wrong instructions — so stop retrying that specific cell immediately
|
|
68
|
-
// rather than waiting out the general time backstop. The cell still
|
|
69
|
-
// counts as unresolved for the block decision itself: it genuinely never
|
|
70
|
-
// confirmed completion, it just isn't worth telling the model to poll
|
|
71
|
-
// again.
|
|
72
|
-
const retryable = unresolved.filter((cellId) => !telemetry.unresolvableCells.has(cellId));
|
|
73
|
-
if (retryable.length === 0)
|
|
74
|
-
return {};
|
|
75
|
-
if (liveHookRetryElapsedMs(lines.slice(boundary + 1)) >= maxLiveHookRetryMs)
|
|
76
|
-
return {};
|
|
77
|
-
return blocked(`Codex cell ${retryable[0]} has no terminal exit_code; continue polling that cell`);
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* Elapsed wall-clock time since this hook's own first continuation prompt
|
|
81
|
-
* within the current process segment, using the transcript's own event
|
|
82
|
-
* timestamps rather than a call/retry count. Returns 0 (never give up) when
|
|
83
|
-
* there is no prior retry yet, or when a timestamp can't be established —
|
|
84
|
-
* giving up is the direction that stops enforcing, so any doubt should keep
|
|
85
|
-
* blocking rather than silently switch to time-based give-up on weak evidence.
|
|
86
|
-
*/
|
|
87
|
-
function liveHookRetryElapsedMs(segment) {
|
|
88
|
-
let firstRetryAt;
|
|
89
|
-
let latestAt;
|
|
90
|
-
for (const line of segment) {
|
|
91
|
-
const event = parseJson(line);
|
|
92
|
-
if (event === undefined)
|
|
93
|
-
continue;
|
|
94
|
-
const at = timestampMs(event.timestamp);
|
|
95
|
-
if (at !== undefined)
|
|
96
|
-
latestAt = at;
|
|
97
|
-
const payload = record(event.payload);
|
|
98
|
-
if (payload?.type !== 'message' || payload.role !== 'user')
|
|
99
|
-
continue;
|
|
100
|
-
if (firstRetryAt === undefined &&
|
|
101
|
-
at !== undefined &&
|
|
102
|
-
userMessageText(payload.content).includes('<hook_prompt'))
|
|
103
|
-
firstRetryAt = at;
|
|
104
|
-
}
|
|
105
|
-
return firstRetryAt === undefined || latestAt === undefined ? 0 : latestAt - firstRetryAt;
|
|
106
|
-
}
|
|
107
|
-
function timestampMs(value) {
|
|
108
|
-
if (typeof value !== 'string')
|
|
109
|
-
return undefined;
|
|
110
|
-
const parsed = Date.parse(value);
|
|
111
|
-
return Number.isFinite(parsed) ? parsed : undefined;
|
|
112
|
-
}
|
|
113
|
-
function userMessageText(content) {
|
|
114
|
-
if (!Array.isArray(content))
|
|
115
|
-
return '';
|
|
116
|
-
return content
|
|
117
|
-
.map((item) => {
|
|
118
|
-
const entry = record(item);
|
|
119
|
-
return entry === undefined ? '' : (string(entry.text) ?? '');
|
|
120
|
-
})
|
|
121
|
-
.join('');
|
|
122
|
-
}
|
|
123
|
-
function lastProcessBoundary(lines) {
|
|
124
|
-
let boundary = -1;
|
|
125
|
-
lines.forEach((line, index) => {
|
|
126
|
-
const event = parseJson(line);
|
|
127
|
-
if (event?.type === 'session_meta' || event?.type === 'turn_context')
|
|
128
|
-
boundary = index;
|
|
129
|
-
});
|
|
130
|
-
return boundary;
|
|
131
|
-
}
|
|
132
|
-
function consumePayload(payload, telemetry) {
|
|
133
|
-
if (payload.type === 'function_call' || payload.type === 'custom_tool_call') {
|
|
134
|
-
recordToolCall(payload, telemetry.calls);
|
|
135
|
-
return;
|
|
136
|
-
}
|
|
137
|
-
if (payload.type === 'custom_tool_call_output' || payload.type === 'function_call_output')
|
|
138
|
-
recordToolOutput(payload, telemetry);
|
|
139
|
-
}
|
|
140
|
-
function recordToolCall(payload, calls) {
|
|
141
|
-
const callId = string(payload.call_id);
|
|
142
|
-
const name = toolName(payload.name);
|
|
143
|
-
if (callId === undefined || name === undefined)
|
|
144
|
-
return;
|
|
145
|
-
calls.set(callId, {
|
|
146
|
-
name,
|
|
147
|
-
...(name === 'wait' ? cellArgument(payload.arguments ?? payload.input) : {}),
|
|
148
|
-
...(name === 'exec' ? { spawnsBackgroundJob: spawnsBackgroundJob(payload.input) } : {}),
|
|
149
|
-
...(name === 'exec' ? writeStdinSessionArgument(payload.input) : {}),
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
/**
|
|
153
|
-
* The `exec` tool is a shared JS sandbox: `tools.exec_command(...)` spawns a
|
|
154
|
-
* genuine one-shot background job whose cell should eventually resolve to a
|
|
155
|
-
* real exit code. `tools.write_stdin(...)` instead interacts with an
|
|
156
|
-
* already-existing, intentionally long-lived session (e.g. a dev server kept
|
|
157
|
-
* running for e2e checks) — that cell is never meant to terminate, so
|
|
158
|
-
* flagging it as an unresolved background command would be a false positive.
|
|
159
|
-
* Default to treating a call as job-spawning whenever it can't be positively
|
|
160
|
-
* identified as pure session interaction, matching the fail-closed posture
|
|
161
|
-
* used everywhere else in this file.
|
|
162
|
-
*/
|
|
163
|
-
function spawnsBackgroundJob(input) {
|
|
164
|
-
if (typeof input !== 'string')
|
|
165
|
-
return true;
|
|
166
|
-
const interactsWithSession = /tools\.write_stdin\s*\(/.test(input);
|
|
167
|
-
const spawnsJob = /tools\.exec_command\s*\(/.test(input);
|
|
168
|
-
return spawnsJob || !interactsWithSession;
|
|
169
|
-
}
|
|
170
|
-
function recordToolOutput(payload, telemetry) {
|
|
171
|
-
const callId = string(payload.call_id);
|
|
172
|
-
const call = callId === undefined ? undefined : telemetry.calls.get(callId);
|
|
173
|
-
if (call === undefined)
|
|
174
|
-
return;
|
|
175
|
-
const result = structuredResult(payload.output);
|
|
176
|
-
if (call.name === 'exec')
|
|
177
|
-
return recordExecOutput(call, result, telemetry);
|
|
178
|
-
recordWaitOutput(call, result, telemetry);
|
|
179
|
-
}
|
|
180
|
-
function recordExecOutput(call, result, telemetry) {
|
|
181
|
-
if (call.spawnsBackgroundJob === true && result.exitCode === undefined && result.pendingCellId)
|
|
182
|
-
telemetry.pendingCells.add(result.pendingCellId);
|
|
183
|
-
if (call.writeStdinSessionId !== undefined && result.pendingCellId !== undefined)
|
|
184
|
-
telemetry.sessionsByCell.set(result.pendingCellId, call.writeStdinSessionId);
|
|
185
|
-
if (call.writeStdinSessionId === undefined || result.jsonExitCode === undefined)
|
|
186
|
-
return;
|
|
187
|
-
resolveSession(call.writeStdinSessionId, telemetry);
|
|
188
|
-
}
|
|
189
|
-
function resolveSession(sessionId, telemetry) {
|
|
190
|
-
for (const [cellId, recordedSessionId] of telemetry.sessionsByCell) {
|
|
191
|
-
if (recordedSessionId === sessionId)
|
|
192
|
-
telemetry.resolvedCells.add(cellId);
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
function recordWaitOutput(call, result, telemetry) {
|
|
196
|
-
if (call.cellId === undefined)
|
|
197
|
-
return;
|
|
198
|
-
if (result.exitCode !== undefined) {
|
|
199
|
-
telemetry.resolvedCells.add(call.cellId);
|
|
200
|
-
const sessionId = telemetry.sessionsByCell.get(call.cellId);
|
|
201
|
-
if (sessionId !== undefined && result.jsonExitCode !== undefined)
|
|
202
|
-
resolveSession(sessionId, telemetry);
|
|
203
|
-
}
|
|
204
|
-
if (result.sessionId !== undefined)
|
|
205
|
-
telemetry.sessionsByCell.set(call.cellId, result.sessionId);
|
|
206
|
-
if (result.notFoundCellId === call.cellId)
|
|
207
|
-
telemetry.unresolvableCells.add(call.cellId);
|
|
11
|
+
return lastAssistantMessage(transcript) === waitBackgroundStatus
|
|
12
|
+
? {
|
|
13
|
+
decision: 'block',
|
|
14
|
+
reason: 'Codex reported WAIT_BACKGROUND. Do not end this turn. Poll every command still running from this turn and report a normal terminal status only after each has settled.',
|
|
15
|
+
}
|
|
16
|
+
: {};
|
|
208
17
|
}
|
|
209
18
|
export async function runCodexStopHook(input) {
|
|
210
19
|
const payload = record(input);
|
|
211
20
|
const transcriptPath = payload === undefined ? undefined : string(payload.transcript_path);
|
|
212
21
|
if (transcriptPath === undefined)
|
|
213
|
-
return
|
|
22
|
+
return {};
|
|
214
23
|
try {
|
|
215
24
|
return inspectCodexTranscript(await readFile(transcriptPath, 'utf8'));
|
|
216
25
|
}
|
|
217
26
|
catch {
|
|
218
|
-
return
|
|
27
|
+
return {};
|
|
219
28
|
}
|
|
220
29
|
}
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
232
|
-
const path = join(directory, entry.name);
|
|
233
|
-
if (entry.isDirectory()) {
|
|
234
|
-
const nested = await transcriptForSession(path, sessionId);
|
|
235
|
-
if (nested !== undefined)
|
|
236
|
-
return nested;
|
|
237
|
-
}
|
|
238
|
-
else if (entry.isFile() && entry.name.endsWith(`-${sessionId}.jsonl`))
|
|
239
|
-
return path;
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
catch {
|
|
243
|
-
return undefined;
|
|
30
|
+
function lastAssistantMessage(transcript) {
|
|
31
|
+
const lines = transcript.split(/\r?\n/);
|
|
32
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
33
|
+
const event = parseJson(lines[index] ?? '');
|
|
34
|
+
const payload = event === undefined ? undefined : record(event.payload);
|
|
35
|
+
if (payload?.type !== 'message' ||
|
|
36
|
+
payload.role !== 'assistant' ||
|
|
37
|
+
payload.phase !== 'final_answer')
|
|
38
|
+
continue;
|
|
39
|
+
return messageText(payload.content);
|
|
244
40
|
}
|
|
245
41
|
return undefined;
|
|
246
42
|
}
|
|
247
|
-
function
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
return
|
|
257
|
-
}
|
|
258
|
-
function postRunDecision(decision) {
|
|
259
|
-
return decision.decision === 'block' && decision.reason !== undefined
|
|
260
|
-
? { ...decision, reason: `caught by post-run verification: ${decision.reason}` }
|
|
261
|
-
: decision;
|
|
43
|
+
function messageText(content) {
|
|
44
|
+
if (!Array.isArray(content))
|
|
45
|
+
return undefined;
|
|
46
|
+
const texts = content.map((item) => {
|
|
47
|
+
const entry = record(item);
|
|
48
|
+
if (entry?.type !== 'output_text')
|
|
49
|
+
return undefined;
|
|
50
|
+
return string(entry.text);
|
|
51
|
+
});
|
|
52
|
+
return texts.every((text) => text !== undefined) ? texts.join('') : undefined;
|
|
262
53
|
}
|
|
263
54
|
function parseJson(value) {
|
|
264
55
|
try {
|
|
@@ -268,9 +59,6 @@ function parseJson(value) {
|
|
|
268
59
|
return undefined;
|
|
269
60
|
}
|
|
270
61
|
}
|
|
271
|
-
function toolName(value) {
|
|
272
|
-
return value === 'exec' || value === 'wait' ? value : undefined;
|
|
273
|
-
}
|
|
274
62
|
function record(value) {
|
|
275
63
|
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
276
64
|
? value
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { ProviderQuotaExceededFailureKind } from '../../contracts/runner.js';
|
|
2
|
-
import {
|
|
3
|
-
import { verifyCodexSession } from '../codex-stop-hook.js';
|
|
2
|
+
import { WorkspaceMode } from '../../contracts/vocabulary.js';
|
|
4
3
|
import { cliRunner } from './claude.js';
|
|
5
4
|
// Deliberately narrow: only genuine provider usage/rate-limit phrasing.
|
|
6
5
|
// Auth/login failures (unauthorized, authentication, api key, not logged
|
|
@@ -45,23 +44,7 @@ export function createCodexRunner(options = {}) {
|
|
|
45
44
|
classifyFailure: classifyCodexFailure,
|
|
46
45
|
supportsSessionResume: true,
|
|
47
46
|
});
|
|
48
|
-
return
|
|
49
|
-
supportsSessionResume: true,
|
|
50
|
-
async start(request, signal) {
|
|
51
|
-
const execution = await runner.start(request, signal);
|
|
52
|
-
return {
|
|
53
|
-
...execution,
|
|
54
|
-
result: execution.result.then(async (result) => {
|
|
55
|
-
if (result.transport !== RunStatus.Succeeded)
|
|
56
|
-
return result;
|
|
57
|
-
const decision = await verifyCodexSession(options.codexHome ?? process.env.CODEX_HOME, result.sessionId);
|
|
58
|
-
return decision.decision === undefined
|
|
59
|
-
? result
|
|
60
|
-
: { ...result, unverifiedCompletionReason: decision.reason };
|
|
61
|
-
}),
|
|
62
|
-
};
|
|
63
|
-
},
|
|
64
|
-
};
|
|
47
|
+
return runner;
|
|
65
48
|
}
|
|
66
49
|
export function codexCommandArgs(request, passthroughArgs = [], defaults = {}) {
|
|
67
50
|
const model = request.model ?? defaults.model;
|
|
@@ -79,9 +62,11 @@ export function codexCommandArgs(request, passthroughArgs = [], defaults = {}) {
|
|
|
79
62
|
: ['-c', `model_reasoning_effort=${request.effort ?? defaults.effort}`]),
|
|
80
63
|
...(request.resumeSessionId === undefined ? [] : ['resume', request.resumeSessionId]),
|
|
81
64
|
...passthroughArgs,
|
|
82
|
-
request.prompt
|
|
65
|
+
`${request.prompt}\n\n${waitBackgroundInstruction}`,
|
|
83
66
|
];
|
|
84
67
|
}
|
|
68
|
+
// Work around Codex's missing background-command lifecycle contract (https://github.com/openai/codex/issues/32505, https://github.com/openai/codex/issues/34866).
|
|
69
|
+
const waitBackgroundInstruction = `When a command you started is still running or lacks a terminal result, do not report a normal Wake outcome. Make your entire final response exactly WAIT_BACKGROUND. Wake will reject that stop attempt and ask you to continue. After that hook prompt, poll the still-running command and report a normal terminal status only after it has settled. Do not use WAIT_BACKGROUND for a human-input or implementation blocker.`;
|
|
85
70
|
function codexSandboxMode(workspaceMode) {
|
|
86
71
|
return workspaceMode === WorkspaceMode.Branch ? 'danger-full-access' : 'workspace-write';
|
|
87
72
|
}
|
|
@@ -98,6 +98,7 @@ const transitionTargetSchema = z.discriminatedUnion('kind', [
|
|
|
98
98
|
signal: brandedStringSchema(signalName),
|
|
99
99
|
})
|
|
100
100
|
.strict(),
|
|
101
|
+
z.object({ kind: z.literal(TransitionTargetKind.ResourceTransitionWait) }).strict(),
|
|
101
102
|
]);
|
|
102
103
|
const resourceTransitionSchema = z
|
|
103
104
|
.object({
|
|
@@ -3,6 +3,7 @@ export const TransitionTargetKind = defineClosedVocabulary({
|
|
|
3
3
|
Stage: 'stage',
|
|
4
4
|
Complete: 'complete',
|
|
5
5
|
AwaitSignal: 'await-signal',
|
|
6
|
+
ResourceTransitionWait: 'resource-transition-wait',
|
|
6
7
|
});
|
|
7
8
|
export const WorkflowStatus = defineClosedVocabulary({
|
|
8
9
|
Active: 'active',
|
|
@@ -10,7 +10,7 @@ export function compileWorkflow(name, input, activities, knownWorkflowNames = [n
|
|
|
10
10
|
const config = workflowDefinitionConfigSchema.parse(input);
|
|
11
11
|
const rawStageNames = Object.keys(config.stages);
|
|
12
12
|
for (const candidate of rawStageNames) {
|
|
13
|
-
if (
|
|
13
|
+
if (isReservedRouteTarget(candidate))
|
|
14
14
|
throw new Error(`Reserved stage name: ${candidate}`);
|
|
15
15
|
}
|
|
16
16
|
const stageNames = rawStageNames.map(stageName);
|
|
@@ -84,12 +84,18 @@ function compileStage(context, rawStageName, stage, allStages) {
|
|
|
84
84
|
([outcomeKind, route]) => {
|
|
85
85
|
if (!definition.outcomeKinds.includes(outcomeKind))
|
|
86
86
|
throw new Error(`Workflow outcome route ${outcomeKind} is not declared by Activity ${definition.name}`);
|
|
87
|
-
if (!
|
|
87
|
+
if (!isReservedRouteTarget(route.then) && !(route.then in allStages))
|
|
88
88
|
throw new Error(`Unknown transition target: ${route.then}`);
|
|
89
89
|
if (route.await !== undefined && route.watchGates !== undefined)
|
|
90
90
|
throw new Error(`Route ${compiledWorkflowName}:${rawStageName}:${outcomeKind} cannot configure both await and watchGates`);
|
|
91
91
|
if (route.resourceTransitions !== undefined && outcomeKind !== ActivityOutcomeKind.Done)
|
|
92
92
|
throw new Error(`Route ${compiledWorkflowName}:${rawStageName}:${outcomeKind} resourceTransitions are only valid on done`);
|
|
93
|
+
if (route.then === 'wait' && outcomeKind !== ActivityOutcomeKind.Done)
|
|
94
|
+
throw new Error('then: wait is only valid on done');
|
|
95
|
+
if (route.then === 'wait' && route.resourceTransitions === undefined)
|
|
96
|
+
throw new Error('then: wait requires resourceTransitions');
|
|
97
|
+
if (route.then === 'wait' && (route.await !== undefined || route.watchGates !== undefined))
|
|
98
|
+
throw new Error('then: wait cannot configure await or watchGates');
|
|
93
99
|
const followOns = route.activities?.map((activity) => ({
|
|
94
100
|
use: activityName(activity.use),
|
|
95
101
|
with: activities.validateInput(activityName(activity.use), activity.with),
|
|
@@ -115,7 +121,11 @@ function compileStage(context, rawStageName, stage, allStages) {
|
|
|
115
121
|
...(route.resourceTransitions === undefined
|
|
116
122
|
? {}
|
|
117
123
|
: {
|
|
118
|
-
resourceTransitions: compileResourceTransitions(route.resourceTransitions,
|
|
124
|
+
resourceTransitions: compileResourceTransitions(route.resourceTransitions, {
|
|
125
|
+
inheritedThen: route.then,
|
|
126
|
+
outcomeKind,
|
|
127
|
+
requiresExplicitTarget: route.then === 'wait',
|
|
128
|
+
}, allStages, isReservedRouteTarget, compileTarget),
|
|
119
129
|
}),
|
|
120
130
|
id: `${compiledWorkflowName}:${rawStageName}:${outcomeKind}`,
|
|
121
131
|
});
|
|
@@ -136,7 +146,7 @@ function compileWatchGates(workflow, rawStageName, outcomeKind, entries, declare
|
|
|
136
146
|
if (!declaredWatchIds.has(normalized.watch))
|
|
137
147
|
throw new Error(`Unknown watch reference in workflow "${workflow}" stage "${rawStageName}": "${normalized.watch}"`);
|
|
138
148
|
const onRejectThen = normalized.onReject?.then ?? rawStageName;
|
|
139
|
-
if (!
|
|
149
|
+
if (!isReservedTerminalTarget(onRejectThen) && !(onRejectThen in allStages))
|
|
140
150
|
throw new Error(`Unknown watchGates onReject target: ${onRejectThen}`);
|
|
141
151
|
return Object.freeze({
|
|
142
152
|
watch: watchId(normalized.watch),
|
|
@@ -170,11 +180,14 @@ function compileCommands(config, activities) {
|
|
|
170
180
|
}),
|
|
171
181
|
]));
|
|
172
182
|
}
|
|
173
|
-
const
|
|
183
|
+
const isReservedRouteTarget = (target) => target === ActivityOutcomeKind.Done || target === 'await-human' || target === 'wait';
|
|
184
|
+
const isReservedTerminalTarget = (target) => target === ActivityOutcomeKind.Done || target === 'await-human';
|
|
174
185
|
function compileTarget(target, outcomeKind) {
|
|
175
186
|
if (target === ActivityOutcomeKind.Done)
|
|
176
187
|
return { kind: TransitionTargetKind.Complete };
|
|
177
188
|
if (target === 'await-human')
|
|
178
189
|
return { kind: TransitionTargetKind.AwaitSignal, signal: signalName(outcomeKind) };
|
|
190
|
+
if (target === 'wait')
|
|
191
|
+
return { kind: TransitionTargetKind.ResourceTransitionWait };
|
|
179
192
|
return { kind: TransitionTargetKind.Stage, stage: stageName(target) };
|
|
180
193
|
}
|
|
@@ -1,12 +1,16 @@
|
|
|
1
|
-
export function compileResourceTransitions(entries,
|
|
1
|
+
export function compileResourceTransitions(entries, context, allStages, isReservedTarget, compileTarget) {
|
|
2
2
|
return Object.freeze(entries.map((entry) => {
|
|
3
|
-
const then = entry.then ?? inheritedThen;
|
|
4
|
-
if (
|
|
3
|
+
const then = entry.then ?? context.inheritedThen;
|
|
4
|
+
if (context.requiresExplicitTarget && entry.then === undefined)
|
|
5
|
+
throw new Error('resourceTransitions under then: wait require then');
|
|
6
|
+
if (then === 'wait')
|
|
7
|
+
throw new Error('resourceTransitions cannot target wait');
|
|
8
|
+
if (!isReservedTarget(then) && !(then in allStages))
|
|
5
9
|
throw new Error(`Unknown resourceTransitions target: ${then}`);
|
|
6
10
|
return Object.freeze({
|
|
7
11
|
event: entry.events[0],
|
|
8
12
|
...(!('where' in entry) || entry.where === undefined ? {} : { where: entry.where }),
|
|
9
|
-
target: compileTarget(then, outcomeKind),
|
|
13
|
+
target: compileTarget(then, context.outcomeKind),
|
|
10
14
|
});
|
|
11
15
|
}));
|
|
12
16
|
}
|
|
@@ -65,5 +65,7 @@ export function resumeToTarget(events, definition, state, input, target) {
|
|
|
65
65
|
events.push(stateDraft(state, input, OrchestrationEventType.SignalWaitStarted, { signalKind: target.signal }, events.length + 1));
|
|
66
66
|
return;
|
|
67
67
|
}
|
|
68
|
+
if (target.kind === TransitionTargetKind.ResourceTransitionWait)
|
|
69
|
+
throw new Error('resource-transition wait must be resumed by a resource transition');
|
|
68
70
|
pushStageEntry(events, definition, state, input, target.stage);
|
|
69
71
|
}
|
package/package.json
CHANGED
|
@@ -1,209 +0,0 @@
|
|
|
1
|
-
export function structuredResult(value) {
|
|
2
|
-
return outputTexts(value).reduce(mergeResult, {});
|
|
3
|
-
}
|
|
4
|
-
function mergeResult(result, text) {
|
|
5
|
-
const jsonExitCode = jsonExitCodeInText(text);
|
|
6
|
-
const session = sessionIdInText(text);
|
|
7
|
-
const legacyExitCode = legacyExitCodeInText(text);
|
|
8
|
-
const exitCode = jsonExitCode ?? legacyExitCode;
|
|
9
|
-
return {
|
|
10
|
-
...result,
|
|
11
|
-
...(jsonExitCode === undefined ? {} : { jsonExitCode }),
|
|
12
|
-
...(exitCode === undefined ? {} : { exitCode }),
|
|
13
|
-
...(session === undefined ? {} : { sessionId: session }),
|
|
14
|
-
...matchValue(text, /Script running with cell ID ([^\s]+)/, 'pendingCellId'),
|
|
15
|
-
...matchValue(text, /exec cell ([^\s]+) not found/, 'notFoundCellId'),
|
|
16
|
-
};
|
|
17
|
-
}
|
|
18
|
-
function matchValue(text, pattern, key) {
|
|
19
|
-
const value = pattern.exec(text)?.[1];
|
|
20
|
-
return value === undefined ? {} : { [key]: value };
|
|
21
|
-
}
|
|
22
|
-
function jsonExitCodeInText(text) {
|
|
23
|
-
const result = parseJson(text);
|
|
24
|
-
return result === undefined ? undefined : number(result.exit_code);
|
|
25
|
-
}
|
|
26
|
-
function legacyExitCodeInText(text) {
|
|
27
|
-
const rendered = /Exit code:\s*(-?\d+)/.exec(text)?.[1];
|
|
28
|
-
return rendered === undefined ? undefined : Number(rendered);
|
|
29
|
-
}
|
|
30
|
-
function sessionIdInText(text) {
|
|
31
|
-
const result = parseJson(text);
|
|
32
|
-
return result === undefined ? undefined : sessionId(result.session_id);
|
|
33
|
-
}
|
|
34
|
-
function outputTexts(value) {
|
|
35
|
-
if (typeof value === 'string')
|
|
36
|
-
return [value];
|
|
37
|
-
if (!Array.isArray(value))
|
|
38
|
-
return [];
|
|
39
|
-
return value.flatMap((item) => {
|
|
40
|
-
const content = record(item);
|
|
41
|
-
const text = content === undefined ? undefined : string(content.text);
|
|
42
|
-
return text === undefined ? [] : [text];
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
export function writeStdinSessionArgument(input) {
|
|
46
|
-
if (typeof input !== 'string')
|
|
47
|
-
return {};
|
|
48
|
-
const code = codeMask(input);
|
|
49
|
-
const calls = [...code.matchAll(/\btools\.write_stdin\s*\(\s*\{/g)];
|
|
50
|
-
if (calls.length !== 1)
|
|
51
|
-
return {};
|
|
52
|
-
const call = calls[0];
|
|
53
|
-
if (call === undefined || call.index === undefined)
|
|
54
|
-
return {};
|
|
55
|
-
const openObject = call.index + call[0].lastIndexOf('{');
|
|
56
|
-
const literal = directSessionIdArgument(input, code, openObject);
|
|
57
|
-
return literal === undefined ? {} : { writeStdinSessionId: literal };
|
|
58
|
-
}
|
|
59
|
-
function directSessionIdArgument(source, code, openObject) {
|
|
60
|
-
const literals = directSessionLiterals(source, code, openObject);
|
|
61
|
-
return literals.length === 1 ? literals[0] : undefined;
|
|
62
|
-
}
|
|
63
|
-
function directSessionLiterals(source, code, openObject) {
|
|
64
|
-
const literals = [];
|
|
65
|
-
let depth = 1;
|
|
66
|
-
for (let index = openObject + 1; index < code.length && depth > 0; index += 1) {
|
|
67
|
-
depth = nextDepth(code[index], depth);
|
|
68
|
-
if (depth !== 1 || !isSessionIdAt(code, index))
|
|
69
|
-
continue;
|
|
70
|
-
const literal = literalAtProperty(source, code, index);
|
|
71
|
-
if (literal === undefined)
|
|
72
|
-
return [];
|
|
73
|
-
literals.push(literal);
|
|
74
|
-
}
|
|
75
|
-
return literals;
|
|
76
|
-
}
|
|
77
|
-
function nextDepth(character, depth) {
|
|
78
|
-
if (character === '{' || character === '[' || character === '(')
|
|
79
|
-
return depth + 1;
|
|
80
|
-
if (character === '}' || character === ']' || character === ')')
|
|
81
|
-
return depth - 1;
|
|
82
|
-
return depth;
|
|
83
|
-
}
|
|
84
|
-
function isSessionIdAt(code, index) {
|
|
85
|
-
const name = 'session_id';
|
|
86
|
-
return (code.startsWith(name, index) &&
|
|
87
|
-
!/[A-Za-z0-9_$]/.test(code[index - 1] ?? '') &&
|
|
88
|
-
!/[A-Za-z0-9_$]/.test(code[index + name.length] ?? ''));
|
|
89
|
-
}
|
|
90
|
-
function literalAtProperty(source, code, index) {
|
|
91
|
-
let valueStart = index + 'session_id'.length;
|
|
92
|
-
while (/\s/.test(code[valueStart] ?? ''))
|
|
93
|
-
valueStart += 1;
|
|
94
|
-
return code[valueStart] === ':' ? sourceSessionLiteralAt(source, valueStart + 1) : undefined;
|
|
95
|
-
}
|
|
96
|
-
function codeMask(source) {
|
|
97
|
-
const characters = source.split('');
|
|
98
|
-
for (let index = 0; index < characters.length; index += 1)
|
|
99
|
-
index = maskAt(characters, index);
|
|
100
|
-
return characters.join('');
|
|
101
|
-
}
|
|
102
|
-
function maskAt(characters, index) {
|
|
103
|
-
const character = characters[index];
|
|
104
|
-
if (character === '/' && characters[index + 1] === '/')
|
|
105
|
-
return maskLineComment(characters, index);
|
|
106
|
-
if (character === '/' && characters[index + 1] === '*')
|
|
107
|
-
return maskBlockComment(characters, index);
|
|
108
|
-
return isQuote(character) ? maskQuoted(characters, index, character) : index;
|
|
109
|
-
}
|
|
110
|
-
function maskLineComment(characters, index) {
|
|
111
|
-
while (index < characters.length && characters[index] !== '\n')
|
|
112
|
-
characters[index++] = ' ';
|
|
113
|
-
return index;
|
|
114
|
-
}
|
|
115
|
-
function maskBlockComment(characters, index) {
|
|
116
|
-
characters[index++] = ' ';
|
|
117
|
-
characters[index++] = ' ';
|
|
118
|
-
while (index < characters.length && !(characters[index] === '*' && characters[index + 1] === '/'))
|
|
119
|
-
characters[index++] = ' ';
|
|
120
|
-
characters[index++] = ' ';
|
|
121
|
-
characters[index] = ' ';
|
|
122
|
-
return index;
|
|
123
|
-
}
|
|
124
|
-
function isQuote(value) {
|
|
125
|
-
return value === '"' || value === "'" || value === '`';
|
|
126
|
-
}
|
|
127
|
-
function maskQuoted(characters, index, quote) {
|
|
128
|
-
characters[index++] = ' ';
|
|
129
|
-
while (index < characters.length) {
|
|
130
|
-
const current = characters[index];
|
|
131
|
-
characters[index++] = ' ';
|
|
132
|
-
if (current === '\\') {
|
|
133
|
-
characters[index++] = ' ';
|
|
134
|
-
continue;
|
|
135
|
-
}
|
|
136
|
-
if (current === quote)
|
|
137
|
-
break;
|
|
138
|
-
}
|
|
139
|
-
return index;
|
|
140
|
-
}
|
|
141
|
-
function sourceSessionLiteralAt(source, start) {
|
|
142
|
-
while (/\s/.test(source[start] ?? ''))
|
|
143
|
-
start += 1;
|
|
144
|
-
const numeric = sourceNumberLiteralAt(source, start);
|
|
145
|
-
if (numeric !== undefined)
|
|
146
|
-
return sessionId(numeric);
|
|
147
|
-
if (source[start] === "'")
|
|
148
|
-
return sessionId(singleQuotedStringAt(source, start));
|
|
149
|
-
if (source[start] !== '"')
|
|
150
|
-
return undefined;
|
|
151
|
-
const quoted = doubleQuotedStringAt(source, start);
|
|
152
|
-
return quoted === undefined ? undefined : sessionId(quoted);
|
|
153
|
-
}
|
|
154
|
-
function doubleQuotedStringAt(source, start) {
|
|
155
|
-
let end = start + 1;
|
|
156
|
-
while (end < source.length) {
|
|
157
|
-
if (source[end] === '\\') {
|
|
158
|
-
end += 2;
|
|
159
|
-
continue;
|
|
160
|
-
}
|
|
161
|
-
if (source[end] === '"') {
|
|
162
|
-
const value = parseJson(`{"value":${source.slice(start, end + 1)}}`);
|
|
163
|
-
return value === undefined ? undefined : string(value.value);
|
|
164
|
-
}
|
|
165
|
-
end += 1;
|
|
166
|
-
}
|
|
167
|
-
return undefined;
|
|
168
|
-
}
|
|
169
|
-
function sourceNumberLiteralAt(source, start) {
|
|
170
|
-
const match = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y;
|
|
171
|
-
match.lastIndex = start;
|
|
172
|
-
const literal = match.exec(source)?.[0];
|
|
173
|
-
if (literal === undefined || /[A-Za-z0-9_$.]/.test(source[start + literal.length] ?? ''))
|
|
174
|
-
return undefined;
|
|
175
|
-
const value = Number(literal);
|
|
176
|
-
return Number.isFinite(value) ? value : undefined;
|
|
177
|
-
}
|
|
178
|
-
function singleQuotedStringAt(source, start) {
|
|
179
|
-
let end = start + 1;
|
|
180
|
-
while (end < source.length && source[end] !== "'") {
|
|
181
|
-
if (source[end] === '\\')
|
|
182
|
-
return undefined;
|
|
183
|
-
end += 1;
|
|
184
|
-
}
|
|
185
|
-
return end < source.length ? source.slice(start + 1, end) : undefined;
|
|
186
|
-
}
|
|
187
|
-
function parseJson(value) {
|
|
188
|
-
try {
|
|
189
|
-
return record(JSON.parse(value));
|
|
190
|
-
}
|
|
191
|
-
catch {
|
|
192
|
-
return undefined;
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
function record(value) {
|
|
196
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
197
|
-
? value
|
|
198
|
-
: undefined;
|
|
199
|
-
}
|
|
200
|
-
function string(value) {
|
|
201
|
-
return typeof value === 'string' ? value : undefined;
|
|
202
|
-
}
|
|
203
|
-
function number(value) {
|
|
204
|
-
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
205
|
-
}
|
|
206
|
-
function sessionId(value) {
|
|
207
|
-
const text = string(value);
|
|
208
|
-
return text === undefined || text.length === 0 ? number(value) : text;
|
|
209
|
-
}
|