@atolis-hq/wake 0.3.104 → 0.3.106

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.
@@ -168,6 +168,11 @@ function contextField(runnerContext, templateName) {
168
168
  return { context: { ...runnerContext, action: templateName ?? 'prompt' } };
169
169
  }
170
170
  function agentOutcome(result) {
171
+ if (result.unverifiedCompletionReason !== undefined)
172
+ return {
173
+ kind: ActivityOutcomeKind.Blocked,
174
+ data: { status: 'BLOCKED', unverifiedCompletionReason: result.unverifiedCompletionReason },
175
+ };
171
176
  if (result.transport === ActivityRunnerTransportStatus.Ambiguous)
172
177
  return {
173
178
  kind: ActivityOutcomeKind.Blocked,
@@ -371,6 +371,22 @@ COPY . .
371
371
  ARG WAKE_BUILD_TAG
372
372
  RUN WAKE_BUILD_TAG="$WAKE_BUILD_TAG" npm run build:docker
373
373
 
374
+ RUN mkdir -p /etc/codex /usr/local/lib/wake \\
375
+ && cp /app/dist/src/execution/infrastructure/codex-stop-hook.js /usr/local/lib/wake/codex-stop-hook.js \\
376
+ && printf '%s\\n' \\
377
+ '[features]' \\
378
+ 'hooks = true' \\
379
+ '' \\
380
+ '[hooks]' \\
381
+ 'managed_dir = "/usr/local/lib/wake"' \\
382
+ '' \\
383
+ '[[hooks.Stop]]' \\
384
+ '[[hooks.Stop.hooks]]' \\
385
+ 'type = "command"' \\
386
+ 'command = "node /usr/local/lib/wake/codex-stop-hook.js"' \\
387
+ 'timeout = 10' \\
388
+ > /etc/codex/requirements.toml
389
+
374
390
  USER root
375
391
  WORKDIR /home/wake
376
392
 
@@ -418,6 +434,22 @@ ARG WAKE_VERSION=0.1.0
418
434
  RUN --mount=type=cache,target=/root/.npm \\
419
435
  npm install -g @anthropic-ai/claude-code @openai/codex "@atolis-hq/wake@\${WAKE_VERSION}"
420
436
 
437
+ RUN mkdir -p /etc/codex /usr/local/lib/wake \\
438
+ && cp /usr/local/lib/node_modules/@atolis-hq/wake/dist/src/execution/infrastructure/codex-stop-hook.js /usr/local/lib/wake/codex-stop-hook.js \\
439
+ && printf '%s\\n' \\
440
+ '[features]' \\
441
+ 'hooks = true' \\
442
+ '' \\
443
+ '[hooks]' \\
444
+ 'managed_dir = "/usr/local/lib/wake"' \\
445
+ '' \\
446
+ '[[hooks.Stop]]' \\
447
+ '[[hooks.Stop.hooks]]' \\
448
+ 'type = "command"' \\
449
+ 'command = "node /usr/local/lib/wake/codex-stop-hook.js"' \\
450
+ 'timeout = 10' \\
451
+ > /etc/codex/requirements.toml
452
+
421
453
  RUN useradd --create-home --shell /bin/bash wake \\
422
454
  && mkdir -p /home/wake/.codex-runtime \\
423
455
  && mkdir -p /home/wake/.cursor \\
@@ -108,4 +108,4 @@ export function resolveWakeVersion(options = {}) {
108
108
  return `g${headHash.slice(0, 7)}`;
109
109
  return '0.1.0-dev';
110
110
  }
111
- export const wakeVersion = "gfb06c98";
111
+ export const wakeVersion = "gf44408e";
@@ -21,6 +21,7 @@ export * from './domain/run.js';
21
21
  export * from './infrastructure/prompt-templates.js';
22
22
  export * from './infrastructure/runners/claude.js';
23
23
  export * from './infrastructure/runners/codex.js';
24
+ export * from './infrastructure/codex-stop-hook.js';
24
25
  export * from './infrastructure/runners/command.js';
25
26
  export * from './infrastructure/runners/cursor.js';
26
27
  export * from './infrastructure/runners/fake.js';
@@ -1,11 +1,18 @@
1
1
  import { RunStatus } from '../contracts/vocabulary.js';
2
2
  export function parseAgentRunnerResponse(result) {
3
3
  const parsed = parseResult(result.output);
4
+ const outcome = result.transport === RunStatus.Succeeded && result.unverifiedCompletionReason !== undefined
5
+ ? 'BLOCKED'
6
+ : result.transport === RunStatus.Succeeded
7
+ ? parsed.outcome
8
+ : 'FAILED';
4
9
  return {
5
- outcome: result.transport === RunStatus.Succeeded ? parsed.outcome : 'FAILED',
6
- displayBody: result.transport === RunStatus.Succeeded
10
+ outcome,
11
+ displayBody: result.transport === RunStatus.Succeeded && result.unverifiedCompletionReason === undefined
7
12
  ? parsed.displayBody
8
- : result.failure?.message || parsed.displayBody || 'Runner failed without a response.',
13
+ : result.unverifiedCompletionReason !== undefined
14
+ ? result.unverifiedCompletionReason
15
+ : result.failure?.message || parsed.displayBody || 'Runner failed without a response.',
9
16
  metadata: metadata(result),
10
17
  };
11
18
  }
@@ -0,0 +1,313 @@
1
+ import { readFile, readdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ export const unverifiedCodexCompletionReason = 'unverified: could not confirm background command completion from Codex structured telemetry';
5
+ /**
6
+ * Bound on how long this hook will keep forcing continuation for the same
7
+ * unresolved cell within one process segment before giving up and letting
8
+ * the turn end anyway. A retry *count* doesn't track this reliably — cycle
9
+ * length varies enormously with how long the model's own `wait` calls choose
10
+ * to yield for (observed from ~1s to 50s+ per call in production), so a
11
+ * fixed count either gives up far too early on a real multi-minute command
12
+ * or far too late on a broken loop that isn't waiting on anything real.
13
+ *
14
+ * Real observed `npm run verify`/`verify:ci` durations range from ~90s to
15
+ * over 20 minutes, so this value is a deliberate tradeoff rather than a safe
16
+ * upper bound on every legitimate case: a genuinely long-running command that
17
+ * outlasts it will have its live retry loop give up before finishing, and
18
+ * fall through to a `BLOCKED` outcome needing a human `/retry` instead of
19
+ * confirming cleanly on its own. That's an accepted cost, not a correctness
20
+ * gap — giving up here never weakens the guarantee, since the post-run
21
+ * fallback (`verifyCodexSession`) independently re-scans the same transcript
22
+ * after the process exits and still reports the run as unverified if the
23
+ * cell is genuinely still unresolved. This limit exists only to bound
24
+ * wasted time/tokens against a detection gap we haven't found yet, not to
25
+ * replace correct detection.
26
+ */
27
+ export const maxLiveHookRetryMs = 10 * 60 * 1000;
28
+ /**
29
+ * Inspect only Codex's structured function-call protocol. Command output is
30
+ * opaque except for the protocol's managed-cell and terminal-result envelopes.
31
+ *
32
+ * Exec/wait cells live in one `codex exec` process's memory and never survive
33
+ * a resume into a new process, so only the segment of the transcript since
34
+ * the current process attached (its `session_meta`/`turn_context` marker)
35
+ * can hold a cell that might still be genuinely pending. A cell referenced
36
+ * only in an earlier segment belongs to a process that has already exited
37
+ * and can never return an exit code again — scoping to the latest segment
38
+ * is what makes that structurally certain, rather than trying to recognise
39
+ * every shape of "this cell is gone" text a stale reference might produce.
40
+ */
41
+ export function inspectCodexTranscript(transcript) {
42
+ const lines = transcript.split(/\r?\n/).filter((line) => line.trim().length > 0);
43
+ const boundary = lastProcessBoundary(lines);
44
+ const telemetry = {
45
+ calls: new Map(),
46
+ pendingCells: new Set(),
47
+ resolvedCells: new Set(),
48
+ unresolvableCells: new Set(),
49
+ };
50
+ for (const line of lines.slice(boundary + 1)) {
51
+ const event = parseJson(line);
52
+ if (event === undefined)
53
+ return blocked('could not parse Codex structured telemetry');
54
+ const payload = record(event.payload);
55
+ if (payload !== undefined)
56
+ consumePayload(payload, telemetry);
57
+ }
58
+ const unresolved = [...telemetry.pendingCells].filter((cellId) => !telemetry.resolvedCells.has(cellId));
59
+ if (unresolved.length === 0)
60
+ return {};
61
+ // A cell whose own `wait` call has already reported it gone (a distinct,
62
+ // cell-identity-specific protocol error, not a general failure) can never
63
+ // return an exit code no matter how many more times it's polled. Asking
64
+ // the model to keep retrying it is not just wasted effort, it's actively
65
+ // wrong instructions — so stop retrying that specific cell immediately
66
+ // rather than waiting out the general time backstop. The cell still
67
+ // counts as unresolved for the block decision itself: it genuinely never
68
+ // confirmed completion, it just isn't worth telling the model to poll
69
+ // again.
70
+ const retryable = unresolved.filter((cellId) => !telemetry.unresolvableCells.has(cellId));
71
+ if (retryable.length === 0)
72
+ return {};
73
+ if (liveHookRetryElapsedMs(lines.slice(boundary + 1)) >= maxLiveHookRetryMs)
74
+ return {};
75
+ return blocked(`Codex cell ${retryable[0]} has no terminal exit_code; continue polling that cell`);
76
+ }
77
+ /**
78
+ * Elapsed wall-clock time since this hook's own first continuation prompt
79
+ * within the current process segment, using the transcript's own event
80
+ * timestamps rather than a call/retry count. Returns 0 (never give up) when
81
+ * there is no prior retry yet, or when a timestamp can't be established —
82
+ * giving up is the direction that stops enforcing, so any doubt should keep
83
+ * blocking rather than silently switch to time-based give-up on weak evidence.
84
+ */
85
+ function liveHookRetryElapsedMs(segment) {
86
+ let firstRetryAt;
87
+ let latestAt;
88
+ for (const line of segment) {
89
+ const event = parseJson(line);
90
+ if (event === undefined)
91
+ continue;
92
+ const at = timestampMs(event.timestamp);
93
+ if (at !== undefined)
94
+ latestAt = at;
95
+ const payload = record(event.payload);
96
+ if (payload?.type !== 'message' || payload.role !== 'user')
97
+ continue;
98
+ if (firstRetryAt === undefined &&
99
+ at !== undefined &&
100
+ userMessageText(payload.content).includes('<hook_prompt'))
101
+ firstRetryAt = at;
102
+ }
103
+ return firstRetryAt === undefined || latestAt === undefined ? 0 : latestAt - firstRetryAt;
104
+ }
105
+ function timestampMs(value) {
106
+ if (typeof value !== 'string')
107
+ return undefined;
108
+ const parsed = Date.parse(value);
109
+ return Number.isFinite(parsed) ? parsed : undefined;
110
+ }
111
+ function userMessageText(content) {
112
+ if (!Array.isArray(content))
113
+ return '';
114
+ return content
115
+ .map((item) => {
116
+ const entry = record(item);
117
+ return entry === undefined ? '' : (string(entry.text) ?? '');
118
+ })
119
+ .join('');
120
+ }
121
+ function lastProcessBoundary(lines) {
122
+ let boundary = -1;
123
+ lines.forEach((line, index) => {
124
+ const event = parseJson(line);
125
+ if (event?.type === 'session_meta' || event?.type === 'turn_context')
126
+ boundary = index;
127
+ });
128
+ return boundary;
129
+ }
130
+ function consumePayload(payload, telemetry) {
131
+ if (payload.type === 'function_call' || payload.type === 'custom_tool_call') {
132
+ recordToolCall(payload, telemetry.calls);
133
+ return;
134
+ }
135
+ if (payload.type === 'custom_tool_call_output' || payload.type === 'function_call_output')
136
+ recordToolOutput(payload, telemetry);
137
+ }
138
+ function recordToolCall(payload, calls) {
139
+ const callId = string(payload.call_id);
140
+ const name = toolName(payload.name);
141
+ if (callId === undefined || name === undefined)
142
+ return;
143
+ calls.set(callId, {
144
+ name,
145
+ ...(name === 'wait' ? cellArgument(payload.arguments ?? payload.input) : {}),
146
+ ...(name === 'exec' ? { spawnsBackgroundJob: spawnsBackgroundJob(payload.input) } : {}),
147
+ });
148
+ }
149
+ /**
150
+ * The `exec` tool is a shared JS sandbox: `tools.exec_command(...)` spawns a
151
+ * genuine one-shot background job whose cell should eventually resolve to a
152
+ * real exit code. `tools.write_stdin(...)` instead interacts with an
153
+ * already-existing, intentionally long-lived session (e.g. a dev server kept
154
+ * running for e2e checks) — that cell is never meant to terminate, so
155
+ * flagging it as an unresolved background command would be a false positive.
156
+ * Default to treating a call as job-spawning whenever it can't be positively
157
+ * identified as pure session interaction, matching the fail-closed posture
158
+ * used everywhere else in this file.
159
+ */
160
+ function spawnsBackgroundJob(input) {
161
+ if (typeof input !== 'string')
162
+ return true;
163
+ const interactsWithSession = /tools\.write_stdin\s*\(/.test(input);
164
+ const spawnsJob = /tools\.exec_command\s*\(/.test(input);
165
+ return spawnsJob || !interactsWithSession;
166
+ }
167
+ function recordToolOutput(payload, telemetry) {
168
+ const callId = string(payload.call_id);
169
+ if (callId === undefined)
170
+ return;
171
+ const call = telemetry.calls.get(callId);
172
+ if (call === undefined)
173
+ return;
174
+ const result = structuredResult(payload.output);
175
+ if (call.name === 'exec') {
176
+ if (call.spawnsBackgroundJob === true &&
177
+ result.exitCode === undefined &&
178
+ result.pendingCellId !== undefined)
179
+ telemetry.pendingCells.add(result.pendingCellId);
180
+ return;
181
+ }
182
+ if (call.cellId === undefined)
183
+ return;
184
+ if (result.exitCode !== undefined)
185
+ telemetry.resolvedCells.add(call.cellId);
186
+ if (result.notFoundCellId === call.cellId)
187
+ telemetry.unresolvableCells.add(call.cellId);
188
+ }
189
+ export async function runCodexStopHook(input) {
190
+ const payload = record(input);
191
+ const transcriptPath = payload === undefined ? undefined : string(payload.transcript_path);
192
+ if (transcriptPath === undefined)
193
+ return blocked('Stop hook received no transcript_path');
194
+ try {
195
+ return inspectCodexTranscript(await readFile(transcriptPath, 'utf8'));
196
+ }
197
+ catch {
198
+ return blocked('could not read Codex transcript');
199
+ }
200
+ }
201
+ export async function verifyCodexSession(codexHome, sessionId) {
202
+ if (codexHome === undefined || sessionId === undefined)
203
+ return postRunBlocked('could not locate Codex structured telemetry');
204
+ const transcriptPath = await transcriptForSession(join(codexHome, 'sessions'), sessionId);
205
+ if (transcriptPath === undefined)
206
+ return postRunBlocked('could not locate Codex structured telemetry');
207
+ return postRunDecision(await runCodexStopHook({ transcript_path: transcriptPath }));
208
+ }
209
+ async function transcriptForSession(directory, sessionId) {
210
+ try {
211
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
212
+ const path = join(directory, entry.name);
213
+ if (entry.isDirectory()) {
214
+ const nested = await transcriptForSession(path, sessionId);
215
+ if (nested !== undefined)
216
+ return nested;
217
+ }
218
+ else if (entry.isFile() && entry.name.endsWith(`-${sessionId}.jsonl`))
219
+ return path;
220
+ }
221
+ }
222
+ catch {
223
+ return undefined;
224
+ }
225
+ return undefined;
226
+ }
227
+ function structuredResult(value) {
228
+ const texts = outputTexts(value);
229
+ let exitCode;
230
+ let pendingCellId;
231
+ let notFoundCellId;
232
+ for (const text of texts) {
233
+ exitCode = exitCodeInText(text) ?? exitCode;
234
+ pendingCellId = /Script running with cell ID ([^\s]+)/.exec(text)?.[1] ?? pendingCellId;
235
+ // A cell-identity-specific protocol error: the runtime has discarded
236
+ // this cell's bookkeeping and no exit code will ever be available for
237
+ // it, distinct from a generic tool/script failure with a real message.
238
+ notFoundCellId = /exec cell ([^\s]+) not found/.exec(text)?.[1] ?? notFoundCellId;
239
+ }
240
+ return {
241
+ ...(exitCode === undefined ? {} : { exitCode }),
242
+ ...(pendingCellId === undefined ? {} : { pendingCellId }),
243
+ ...(notFoundCellId === undefined ? {} : { notFoundCellId }),
244
+ };
245
+ }
246
+ function exitCodeInText(text) {
247
+ const result = parseJson(text);
248
+ const code = result === undefined ? undefined : number(result.exit_code);
249
+ if (code !== undefined)
250
+ return code;
251
+ const rendered = /Exit code:\s*(-?\d+)/.exec(text)?.[1];
252
+ return rendered === undefined ? undefined : Number(rendered);
253
+ }
254
+ function outputTexts(value) {
255
+ if (typeof value === 'string')
256
+ return [value];
257
+ if (!Array.isArray(value))
258
+ return [];
259
+ return value.flatMap((item) => {
260
+ const content = record(item);
261
+ const text = content === undefined ? undefined : string(content.text);
262
+ return text === undefined ? [] : [text];
263
+ });
264
+ }
265
+ function cellArgument(value) {
266
+ const arguments_ = typeof value === 'string' ? parseJson(value) : record(value);
267
+ const cellId = arguments_ === undefined ? undefined : string(arguments_.cell_id);
268
+ return cellId === undefined ? {} : { cellId };
269
+ }
270
+ function blocked(detail) {
271
+ return { decision: 'block', reason: `${unverifiedCodexCompletionReason}: ${detail}` };
272
+ }
273
+ function postRunBlocked(detail) {
274
+ return postRunDecision(blocked(detail));
275
+ }
276
+ function postRunDecision(decision) {
277
+ return decision.decision === 'block' && decision.reason !== undefined
278
+ ? { ...decision, reason: `caught by post-run verification: ${decision.reason}` }
279
+ : decision;
280
+ }
281
+ function parseJson(value) {
282
+ try {
283
+ return record(JSON.parse(value));
284
+ }
285
+ catch {
286
+ return undefined;
287
+ }
288
+ }
289
+ function toolName(value) {
290
+ return value === 'exec' || value === 'wait' ? value : undefined;
291
+ }
292
+ function record(value) {
293
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
294
+ ? value
295
+ : undefined;
296
+ }
297
+ function string(value) {
298
+ return typeof value === 'string' ? value : undefined;
299
+ }
300
+ function number(value) {
301
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
302
+ }
303
+ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
304
+ let input = '';
305
+ process.stdin.setEncoding('utf8');
306
+ process.stdin.on('data', (chunk) => {
307
+ input += chunk;
308
+ });
309
+ process.stdin.on('end', () => {
310
+ const payload = parseJson(input);
311
+ void runCodexStopHook(payload).then((decision) => process.stdout.write(JSON.stringify(decision)));
312
+ });
313
+ }
@@ -1,5 +1,6 @@
1
1
  import { ProviderQuotaExceededFailureKind } from '../../contracts/runner.js';
2
- import { WorkspaceMode } from '../../contracts/vocabulary.js';
2
+ import { RunStatus, WorkspaceMode } from '../../contracts/vocabulary.js';
3
+ import { verifyCodexSession } from '../codex-stop-hook.js';
3
4
  import { cliRunner } from './claude.js';
4
5
  // Deliberately narrow: only genuine provider usage/rate-limit phrasing.
5
6
  // Auth/login failures (unauthorized, authentication, api key, not logged
@@ -37,13 +38,30 @@ function extractCodexErrorMessage(stdout) {
37
38
  return undefined;
38
39
  }
39
40
  export function createCodexRunner(options = {}) {
40
- return cliRunner('codex', options.command ?? 'codex', (request) => codexCommandArgs(request, options.args, options), {
41
+ const runner = cliRunner('codex', options.command ?? 'codex', (request) => codexCommandArgs(request, options.args, options), {
41
42
  ...(options.runnerTimeouts === undefined ? {} : { runnerTimeouts: options.runnerTimeouts }),
42
43
  ...(options.model === undefined ? {} : { defaultModel: options.model }),
43
44
  parseSuccessfulOutput: parseCodexOutput,
44
45
  classifyFailure: classifyCodexFailure,
45
46
  supportsSessionResume: true,
46
47
  });
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
65
  }
48
66
  export function codexCommandArgs(request, passthroughArgs = [], defaults = {}) {
49
67
  const model = request.model ?? defaults.model;
package/docker/Dockerfile CHANGED
@@ -53,6 +53,22 @@ COPY src/ src/
53
53
  ARG WAKE_BUILD_TAG
54
54
  RUN WAKE_BUILD_TAG="$WAKE_BUILD_TAG" npm run build:docker
55
55
 
56
+ RUN mkdir -p /etc/codex /usr/local/lib/wake \
57
+ && cp /app/dist/src/execution/infrastructure/codex-stop-hook.js /usr/local/lib/wake/codex-stop-hook.js \
58
+ && printf '%s\n' \
59
+ '[features]' \
60
+ 'hooks = true' \
61
+ '' \
62
+ '[hooks]' \
63
+ 'managed_dir = "/usr/local/lib/wake"' \
64
+ '' \
65
+ '[[hooks.Stop]]' \
66
+ '[[hooks.Stop.hooks]]' \
67
+ 'type = "command"' \
68
+ 'command = "node /usr/local/lib/wake/codex-stop-hook.js"' \
69
+ 'timeout = 10' \
70
+ > /etc/codex/requirements.toml
71
+
56
72
  USER root
57
73
  WORKDIR /home/wake
58
74
 
@@ -25,6 +25,22 @@ RUN test -n "$WAKE_VERSION" || (echo "WAKE_VERSION build arg is required" && exi
25
25
  RUN --mount=type=cache,target=/root/.npm \
26
26
  npm install -g @anthropic-ai/claude-code @openai/codex "@atolis-hq/wake@${WAKE_VERSION}"
27
27
 
28
+ RUN mkdir -p /etc/codex /usr/local/lib/wake \
29
+ && cp /usr/local/lib/node_modules/@atolis-hq/wake/dist/src/execution/infrastructure/codex-stop-hook.js /usr/local/lib/wake/codex-stop-hook.js \
30
+ && printf '%s\n' \
31
+ '[features]' \
32
+ 'hooks = true' \
33
+ '' \
34
+ '[hooks]' \
35
+ 'managed_dir = "/usr/local/lib/wake"' \
36
+ '' \
37
+ '[[hooks.Stop]]' \
38
+ '[[hooks.Stop.hooks]]' \
39
+ 'type = "command"' \
40
+ 'command = "node /usr/local/lib/wake/codex-stop-hook.js"' \
41
+ 'timeout = 10' \
42
+ > /etc/codex/requirements.toml
43
+
28
44
  RUN useradd --create-home --shell /bin/bash wake \
29
45
  && mkdir -p /home/wake/.codex-runtime \
30
46
  && mkdir -p /home/wake/.cursor \
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atolis-hq/wake",
3
- "version": "0.3.104",
3
+ "version": "0.3.106",
4
4
  "description": "Local autonomous agent control plane for software development",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {