@agimon-ai/po-workflow 0.0.0-alpha.37 → 0.0.0-alpha.39

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 (29) hide show
  1. package/dist/{RecoverWorkflowService-BLehH1qi.cjs → RecoverWorkflowService-CEYR10KF.cjs} +136 -445
  2. package/dist/RecoverWorkflowService-CEYR10KF.cjs.map +1 -0
  3. package/dist/{RecoverWorkflowService-BOCa93OS.mjs → RecoverWorkflowService-CY8wIc3A.mjs} +137 -434
  4. package/dist/RecoverWorkflowService-CY8wIc3A.mjs.map +1 -0
  5. package/dist/cli.cjs +94 -1592
  6. package/dist/cli.cjs.map +1 -1
  7. package/dist/cli.mjs +95 -1593
  8. package/dist/cli.mjs.map +1 -1
  9. package/dist/extensions/native.mjs +2 -0
  10. package/dist/extensions/native.mjs.map +1 -1
  11. package/dist/extensions/server.cjs +40 -25
  12. package/dist/extensions/server.cjs.map +1 -1
  13. package/dist/extensions/server.mjs +40 -25
  14. package/dist/extensions/server.mjs.map +1 -1
  15. package/dist/extensions/web.mjs +5 -3
  16. package/dist/extensions/web.mjs.map +1 -1
  17. package/dist/index.cjs +1 -1
  18. package/dist/index.d.mts +2 -1
  19. package/dist/index.d.mts.map +1 -1
  20. package/dist/index.mjs +1 -1
  21. package/dist/{workflowLaunchCommand-GGqimmTC.mjs → workflowLaunchCommand-7WRoiOKJ.mjs} +5 -3
  22. package/dist/workflowLaunchCommand-7WRoiOKJ.mjs.map +1 -0
  23. package/dist/{workflowLaunchCommand-C69Nn3k5.cjs → workflowLaunchCommand-C7anFsDH.cjs} +5 -3
  24. package/dist/workflowLaunchCommand-C7anFsDH.cjs.map +1 -0
  25. package/package.json +20 -20
  26. package/dist/RecoverWorkflowService-BLehH1qi.cjs.map +0 -1
  27. package/dist/RecoverWorkflowService-BOCa93OS.mjs.map +0 -1
  28. package/dist/workflowLaunchCommand-C69Nn3k5.cjs.map +0 -1
  29. package/dist/workflowLaunchCommand-GGqimmTC.mjs.map +0 -1
package/dist/cli.cjs CHANGED
@@ -1,297 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  const require_workflowCommandTemplate = require("./workflowCommandTemplate-w6rOCJpw.cjs");
3
- const require_RecoverWorkflowService = require("./RecoverWorkflowService-BLehH1qi.cjs");
3
+ const require_RecoverWorkflowService = require("./RecoverWorkflowService-CEYR10KF.cjs");
4
4
  let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
5
5
  let node_path = require("node:path");
6
6
  let _agimon_ai_po_core_telemetry = require("@agimon-ai/po-core/telemetry");
7
7
  let commander = require("commander");
8
8
  let _agimon_ai_po_core_nodePlatform = require("@agimon-ai/po-core/nodePlatform");
9
- let _agimon_ai_po_logsink_telemetry_node = require("@agimon-ai/po-logsink/telemetry/node");
10
- //#region src/bin/workflowRuntime.ts
11
- let runtime;
12
- let logger;
13
- /** The standalone executable admits ambient facts once, before any engine service is constructed. */
14
- function getCliWorkflowRuntime() {
15
- if (runtime) return runtime;
16
- const environment = Object.freeze({ ...process.env });
17
- const cwd = process.cwd();
18
- const homeDirectory = _agimon_ai_po_core_platform.nodeHost.homeDirectory();
19
- const temporaryDirectory = _agimon_ai_po_core_platform.nodeHost.temporaryDirectory();
20
- const execution = (0, _agimon_ai_po_core_nodePlatform.createNodePlatform)({
21
- homeDirectory,
22
- temporaryDirectory
23
- }).env(cwd);
24
- runtime = require_RecoverWorkflowService.createWorkflowRuntime({
25
- baseEnvironment: environment,
26
- cwd,
27
- homeDirectory,
28
- temporaryDirectory,
29
- fs: execution,
30
- shell: execution,
31
- workflowHost: require_RecoverWorkflowService.createWorkflowHost({
32
- environment,
33
- cwd,
34
- homeDirectory,
35
- temporaryDirectory,
36
- cliPath: require_RecoverWorkflowService.resolveWorkflowCliPath()
37
- })
38
- });
39
- return runtime;
40
- }
41
- /** One telemetry backend per standalone CLI invocation. */
42
- function getCliWorkflowLogger() {
43
- return logger ??= createCliWorkflowLogger({
44
- info: (message) => console.info(message),
45
- warn: (message) => console.error(message),
46
- error: (message) => console.error(message)
47
- });
48
- }
49
- /** Hook commands treat a missing or unreadable file as absent. */
50
- async function readCliTextFile(filePath) {
51
- const { fs, ioContext } = getCliWorkflowRuntime();
52
- try {
53
- return (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.readTextFile(filePath, ioContext));
54
- } catch {
55
- return null;
56
- }
57
- }
58
- async function writeCliTextFile(filePath, content, createParent = false) {
59
- const { fs, ioContext } = getCliWorkflowRuntime();
60
- if (createParent) (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.createDir((0, node_path.dirname)(filePath), { recursive: true }, ioContext));
61
- (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.writeFile(filePath, content, ioContext));
62
- }
63
- let installedServiceName = "workflow-mcp";
64
- let telemetry;
65
- function getTelemetry(serviceName) {
66
- const runtime = getCliWorkflowRuntime();
67
- return telemetry ??= (0, _agimon_ai_po_core_telemetry.createPoTelemetry)({
68
- packageName: "@agimon-ai/po-workflow",
69
- serviceName,
70
- workspaceRoot: runtime.cwd,
71
- cwd: runtime.cwd,
72
- env: { ...runtime.baseEnvironment }
73
- });
74
- }
75
- function createCliWorkflowLogger(baseLogger) {
76
- return {
77
- ...baseLogger,
78
- async event(level, name, options = {}) {
79
- const telemetry = getTelemetry(installedServiceName);
80
- if (level === "error" || level === "fatal") await telemetry.recordError(name, options.exception, options.attributes);
81
- else if (level === "warn") await telemetry.recordWarning(name, options.exception, options.attributes);
82
- else if (level === "debug" || level === "trace") await telemetry.recordDebug(name, options.attributes);
83
- else await telemetry.recordEvent(name, options.attributes);
84
- },
85
- runInSpan: (name, attributes, work, parent) => getTelemetry(installedServiceName).runInSpan(name, attributes, work, parent),
86
- flush: flushOtelErrorLogger
87
- };
88
- }
89
- async function flushOtelErrorLogger() {
90
- await telemetry?.flush();
91
- }
92
- function installOtelErrorLogger(options) {
93
- installedServiceName = options.serviceName;
94
- getTelemetry(installedServiceName);
95
- }
96
- //#endregion
97
- //#region src/bin/workflowCommands/antigravityStopHook.ts
98
- const STATUS_FILE_ENV_KEY$2 = "WORKFLOW_STATUS_FILE";
99
- const STATUS_FILE_COMPLETION_VALUE$2 = "YES\n";
100
- const STOP_HOOK_DEBUG_LOG_PATH$2 = ["tmp", "antigravity-stop-hook.json"];
101
- const ANTIGRAVITY_PENDING_WORK_REASON = "In-progress work is still running. Continue the execution loop until background tasks finish.";
102
- const ANTIGRAVITY_NORMAL_TERMINATION_REASON = "model_stop";
103
- const STDIN_READ_TIMEOUT_MS$3 = 1e4;
104
- const STDIN_UNREADABLE_REASON$2 = "stdin unreadable: empty payload or read timed out";
105
- function createDefaultDeps() {
106
- const runtime = getCliWorkflowRuntime();
107
- return {
108
- readStdin: readStdin$2,
109
- readStatusFile: readCliTextFile,
110
- writeDebugLog: async (entry) => {
111
- await writeStopHookDebugLog$1((0, node_path.join)(runtime.cwd, ...STOP_HOOK_DEBUG_LOG_PATH$2), entry);
112
- },
113
- writeStdout: (output) => {
114
- runtime.workflowHost.writeStdout(output);
115
- },
116
- writeStatusFile: async (statusFilePath) => {
117
- await writeCliTextFile(statusFilePath, STATUS_FILE_COMPLETION_VALUE$2);
118
- },
119
- workflowStatusFile: runtime.baseEnvironment[STATUS_FILE_ENV_KEY$2]
120
- };
121
- }
122
- async function runAntigravityStopHook(deps = createDefaultDeps()) {
123
- const statusFilePath = deps.workflowStatusFile;
124
- if (!statusFilePath) return;
125
- let rawInput;
126
- try {
127
- rawInput = await deps.readStdin();
128
- } catch (error) {
129
- await completeWorkflow$2(deps, statusFilePath, "", null, `stdin read failed: ${errorMessage$2(error)}`);
130
- return;
131
- }
132
- if (rawInput.trim().length === 0) {
133
- await completeWorkflow$2(deps, statusFilePath, rawInput, null, STDIN_UNREADABLE_REASON$2);
134
- return;
135
- }
136
- const hookInput = parseAntigravityStopHookInput(rawInput);
137
- if (!hookInput?.conversationId) {
138
- await logAntigravityStopHookDecision(deps, rawInput, hookInput, {
139
- decision: "ignore",
140
- reason: hookInput ? "missing conversation id" : "invalid stop hook JSON"
141
- });
142
- return;
143
- }
144
- const statusFileState = classifyWorkflowStatusFile$2(await deps.readStatusFile(statusFilePath));
145
- if (statusFileState.status !== "unbound") {
146
- await logAntigravityStopHookDecision(deps, rawInput, hookInput, {
147
- decision: "ignore",
148
- reason: workflowStatusFileIgnoreReason$2(statusFileState.status)
149
- });
150
- return;
151
- }
152
- if (!hookInput.fullyIdle) {
153
- deps.writeStdout?.(antigravityContinueOutput(ANTIGRAVITY_PENDING_WORK_REASON));
154
- await logAntigravityStopHookDecision(deps, rawInput, hookInput, {
155
- decision: "continue",
156
- reason: ANTIGRAVITY_PENDING_WORK_REASON
157
- });
158
- return;
159
- }
160
- if (hasText(hookInput.error) || hookInput.terminationReason !== ANTIGRAVITY_NORMAL_TERMINATION_REASON) {
161
- await logAntigravityStopHookDecision(deps, rawInput, hookInput, {
162
- decision: "ignore",
163
- reason: hasText(hookInput.error) ? "stop hook reported an error" : `unsupported termination reason: ${hookInput.terminationReason ?? "missing"}`
164
- });
165
- return;
166
- }
167
- await completeWorkflow$2(deps, statusFilePath, rawInput, hookInput);
168
- }
169
- async function completeWorkflow$2(deps, statusFilePath, rawInput, hookInput, reason) {
170
- const gate = await (deps.gateStepDecision ?? (() => require_RecoverWorkflowService.gateStepDecision(getCliWorkflowRuntime())))();
171
- if (gate.action === "block") {
172
- deps.writeStdout?.(antigravityContinueOutput(gate.message));
173
- await logAntigravityStopHookDecision(deps, rawInput, hookInput, {
174
- decision: "continue",
175
- reason: gate.message
176
- });
177
- return;
178
- }
179
- try {
180
- await deps.writeStatusFile(statusFilePath);
181
- await logAntigravityStopHookDecision(deps, rawInput, hookInput, {
182
- decision: "complete",
183
- reason
184
- });
185
- } catch (error) {
186
- await logAntigravityStopHookDecision(deps, rawInput, hookInput, {
187
- decision: "error",
188
- reason: `status-file write failed: ${errorMessage$2(error)}`
189
- });
190
- }
191
- }
192
- function errorMessage$2(error) {
193
- return error instanceof Error ? error.message : String(error);
194
- }
195
- function parseAntigravityStopHookInput(rawInput) {
196
- try {
197
- const parsed = JSON.parse(rawInput);
198
- if (!isRecord$3(parsed)) return null;
199
- return {
200
- conversationId: typeof parsed.conversationId === "string" ? parsed.conversationId : void 0,
201
- transcriptPath: normalizeTranscriptPath$1(parsed.transcriptPath),
202
- terminationReason: typeof parsed.terminationReason === "string" ? parsed.terminationReason : void 0,
203
- error: typeof parsed.error === "string" ? parsed.error : void 0,
204
- fullyIdle: parsed.fullyIdle === true
205
- };
206
- } catch {
207
- return null;
208
- }
209
- }
210
- function antigravityContinueOutput(reason) {
211
- return `${JSON.stringify({
212
- decision: "continue",
213
- reason
214
- })}\n`;
215
- }
216
- function normalizeTranscriptPath$1(value) {
217
- return typeof value === "string" && value.trim().length > 0 ? value : null;
218
- }
219
- function hasText(value) {
220
- return typeof value === "string" && value.trim().length > 0;
221
- }
222
- function classifyWorkflowStatusFile$2(rawStatus) {
223
- if (rawStatus === null) return { status: "missing" };
224
- const trimmed = rawStatus.trim();
225
- if (!trimmed) return { status: "unbound" };
226
- if (trimmed === STATUS_FILE_COMPLETION_VALUE$2.trim()) return { status: "completed" };
227
- try {
228
- const parsed = JSON.parse(trimmed);
229
- return typeof parsed.sessionId === "string" && parsed.sessionId.length > 0 ? {
230
- status: "bound",
231
- sessionId: parsed.sessionId
232
- } : { status: "invalid" };
233
- } catch {
234
- return { status: "invalid" };
235
- }
236
- }
237
- function workflowStatusFileIgnoreReason$2(status) {
238
- switch (status) {
239
- case "bound": return "workflow status file is bound to a session";
240
- case "completed": return "workflow status file already completed";
241
- case "invalid": return "invalid workflow status file binding";
242
- case "missing": return "missing workflow status file";
243
- }
244
- }
245
- function isRecord$3(value) {
246
- return typeof value === "object" && value !== null;
247
- }
248
- async function readStdin$2() {
249
- const chunks = [];
250
- const collect = (async () => {
251
- for await (const chunk of process.stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
252
- })();
253
- collect.catch(() => {});
254
- let timer;
255
- const timeout = new Promise((resolve) => {
256
- timer = setTimeout(() => {
257
- process.stdin.destroy();
258
- resolve();
259
- }, STDIN_READ_TIMEOUT_MS$3);
260
- });
261
- try {
262
- await Promise.race([collect, timeout]);
263
- } finally {
264
- if (timer) clearTimeout(timer);
265
- }
266
- return Buffer.concat(chunks).toString("utf8");
267
- }
268
- async function logAntigravityStopHookDecision(deps, rawInput, input, decision) {
269
- try {
270
- await deps.writeDebugLog?.({
271
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
272
- rawInput,
273
- input,
274
- decision
275
- });
276
- } catch {}
277
- }
278
- async function writeStopHookDebugLog$1(filePath, entry) {
279
- const entries = await readStopHookDebugLog$1(filePath);
280
- entries.push(entry);
281
- await writeCliTextFile(filePath, `${JSON.stringify(entries.slice(-50), null, 2)}\n`, true);
282
- }
283
- async function readStopHookDebugLog$1(filePath) {
284
- try {
285
- const parsed = JSON.parse(await readCliTextFile(filePath) ?? "");
286
- return Array.isArray(parsed) ? parsed : [];
287
- } catch {
288
- return [];
289
- }
290
- }
291
- const antigravityStopHookCommand = new commander.Command("antigravity-stop-hook").description(`Antigravity stop hook: reads Stop hook JSON on stdin and marks ${STATUS_FILE_ENV_KEY$2} when the execution is fully idle`).action(async () => {
292
- await runAntigravityStopHook();
293
- });
294
- //#endregion
295
9
  //#region src/constants/workflowCommands.ts
296
10
  const LIST_WORKFLOW_STATUSES_COMMAND_NAME = "list-workflow-statuses";
297
11
  const LIST_WORKFLOW_STATUSES_COMMAND_DESCRIPTION = "List tracked workflow runs and their current stages";
@@ -309,539 +23,8 @@ const STOP_WORKFLOW_COMMAND_NAME = "stop-workflow";
309
23
  const STOP_WORKFLOW_COMMAND_DESCRIPTION = "Request a running workflow to stop gracefully";
310
24
  const DESCRIBE_RUN_COMMAND_NAME = "describe-run";
311
25
  const DESCRIBE_RUN_COMMAND_DESCRIPTION = "Describe a workflow run directory and report declared artifact status";
312
- const CHECK_CODEX_QUOTA_COMMAND_NAME = "check-codex-quota";
313
- const CHECK_CODEX_QUOTA_COMMAND_DESCRIPTION = "Check whether Codex quota is currently blocking new work";
314
26
  const LAUNCH_PROCESS_COMMAND_NAME = "launch-process";
315
27
  //#endregion
316
- //#region src/models/WorkflowCommandError.ts
317
- /**
318
- * Structured error raised by workflow CLI commands.
319
- */
320
- var WorkflowCommandError = class extends Error {
321
- code;
322
- context;
323
- constructor(message, code, context = {}, options) {
324
- super(message, options);
325
- this.code = code;
326
- this.context = context;
327
- this.name = "WorkflowCommandError";
328
- }
329
- };
330
- //#endregion
331
- //#region src/bin/workflowCommands/checkCodexQuota.ts
332
- /**
333
- * Check Codex Quota Command
334
- *
335
- * DESIGN PATTERNS:
336
- * - Command pattern with Commander for CLI argument parsing
337
- * - Service delegation for business logic
338
- *
339
- * CODING STANDARDS:
340
- * - Use async action handlers for asynchronous operations
341
- * - Handle errors gracefully with process.exit()
342
- *
343
- * AVOID:
344
- * - Exiting with generic success codes for hard quota failures
345
- * - Ignoring quota-state edge cases without logging useful context
346
- */
347
- const DEFAULT_SUCCESS_EXIT_CODE = 0;
348
- const QUOTA_BLOCKED_EXIT_CODE = 2;
349
- const QUOTA_UNREADABLE_MESSAGE = "Codex quota status is unavailable; continuing without a preflight quota block.";
350
- const QUOTA_BLOCKED_ERROR_CODE = "CODEX_QUOTA_BLOCKED";
351
- const QUOTA_UNREADABLE_ERROR_CODE = "CODEX_QUOTA_UNREADABLE";
352
- function createCheckCodexQuotaCommand(dependencies = {}) {
353
- const createService = dependencies.createService ?? (() => new require_RecoverWorkflowService.CodexQuotaService(getCliWorkflowRuntime()));
354
- const exit = dependencies.exit ?? ((code) => process.exit(code));
355
- const logError = dependencies.logError ?? ((message, error) => console.error(message, error));
356
- const writeStdout = dependencies.writeStdout ?? ((message) => process.stdout.write(message));
357
- return new commander.Command(CHECK_CODEX_QUOTA_COMMAND_NAME).description(CHECK_CODEX_QUOTA_COMMAND_DESCRIPTION).action(async () => {
358
- try {
359
- const status = await createService().getQuotaStatus();
360
- const payload = JSON.stringify({
361
- blockingLimit: status?.blockingLimit ?? null,
362
- planType: status?.planType ?? null
363
- }, null, 2);
364
- writeStdout(`${payload}\n`);
365
- if (status?.blockingLimit) {
366
- const commandError = new WorkflowCommandError(`Codex quota is blocking work at ${status.blockingLimit.limitId}/${status.blockingLimit.window}.`, QUOTA_BLOCKED_ERROR_CODE, {
367
- command: CHECK_CODEX_QUOTA_COMMAND_NAME,
368
- limitId: status.blockingLimit.limitId,
369
- limitName: status.blockingLimit.limitName,
370
- window: status.blockingLimit.window
371
- });
372
- logError(`${commandError.message} [${commandError.code}]`, commandError);
373
- exit(QUOTA_BLOCKED_EXIT_CODE);
374
- return;
375
- }
376
- exit(DEFAULT_SUCCESS_EXIT_CODE);
377
- } catch (error) {
378
- const commandError = new WorkflowCommandError(QUOTA_UNREADABLE_MESSAGE, QUOTA_UNREADABLE_ERROR_CODE, { command: CHECK_CODEX_QUOTA_COMMAND_NAME }, { cause: error });
379
- logError(`${commandError.message} [${commandError.code}]`, commandError);
380
- writeStdout(`${JSON.stringify({
381
- blockingLimit: null,
382
- planType: null,
383
- warning: commandError.message
384
- }, null, 2)}\n`);
385
- exit(DEFAULT_SUCCESS_EXIT_CODE);
386
- }
387
- });
388
- }
389
- const checkCodexQuotaCommand = createCheckCodexQuotaCommand();
390
- //#endregion
391
- //#region src/bin/workflowCommands/claudeStopHook.ts
392
- const STATUS_FILE_ENV_KEY$1 = "WORKFLOW_STATUS_FILE";
393
- const CLAUDE_PROJECT_DIR_ENV_KEY = "CLAUDE_PROJECT_DIR";
394
- const WORKFLOW_RUN_DIR_ENV_KEY$1 = "WORKFLOW_RUN_DIR";
395
- const WORKFLOW_STEP_ARTIFACTS_ENV_KEY$1 = "WORKFLOW_STEP_ARTIFACTS";
396
- const STATUS_FILE_COMPLETION_VALUE$1 = "YES\n";
397
- const STOP_HOOK_DEBUG_LOG_PATH$1 = ["tmp", "claude-stop-hook.json"];
398
- const STOP_HOOK_EVENT_NAME$1 = "Stop";
399
- const PENDING_WORK_BLOCK_REASON$1 = "In-progress work is still running. Wait for spawned agents and running tool calls to finish before ending the turn.";
400
- const STOP_HOOK_ACTIVE_COMPLETION_PREFIX = "completing after a stop-hook continuation despite";
401
- const STOP_HOOK_ACTIVE_COMPLETION_SUFFIX = "active background task(s); blocking again would risk the Stop block-cap force-override leaving the run unsignaled";
402
- const NOTIFICATION_HOOK_EVENT_NAME = "Notification";
403
- const NOTIFICATION_DEBUG_LOG_PATH = ["tmp", "claude-notification-hook.json"];
404
- const NOTIFICATION_COMPLETION_TYPES = /* @__PURE__ */ new Set([
405
- "idle_prompt",
406
- "permission_prompt",
407
- "elicitation_dialog"
408
- ]);
409
- const NOTIFICATION_TRANSIENT_TYPES = /* @__PURE__ */ new Set([
410
- "auth_success",
411
- "elicitation_complete",
412
- "elicitation_response"
413
- ]);
414
- const STDIN_READ_TIMEOUT_MS$2 = 1e4;
415
- const STDIN_UNREADABLE_REASON$1 = "stdin unreadable: empty payload or read timed out";
416
- const TERMINAL_BACKGROUND_TASK_STATUSES = /* @__PURE__ */ new Set([
417
- "aborted",
418
- "cancelled",
419
- "canceled",
420
- "completed",
421
- "crashed",
422
- "done",
423
- "error",
424
- "failed",
425
- "killed",
426
- "not_running",
427
- "retired",
428
- "settled",
429
- "stopped",
430
- "success",
431
- "succeeded"
432
- ]);
433
- function createDefaultStopHookDeps$1() {
434
- const runtime = getCliWorkflowRuntime();
435
- return {
436
- findStepArtifactWarnings: findStepArtifactWarningsFromEnvironment$1,
437
- readStdin: readStdin$1,
438
- readStatusFile: readCliTextFile,
439
- writeDebugLog: async (entry) => {
440
- await appendHookDebugLog((0, node_path.join)(runtime.cwd, ...STOP_HOOK_DEBUG_LOG_PATH$1), entry);
441
- },
442
- writeStdout: (output) => {
443
- runtime.workflowHost.writeStdout(output);
444
- },
445
- writeStatusFile: async (statusFilePath) => {
446
- await writeCliTextFile(statusFilePath, STATUS_FILE_COMPLETION_VALUE$1);
447
- },
448
- workflowStatusFile: runtime.baseEnvironment[STATUS_FILE_ENV_KEY$1]
449
- };
450
- }
451
- function createDefaultSessionStartHookDeps$1() {
452
- return {
453
- readStdin: readStdin$1,
454
- workflowStatusFile: getCliWorkflowRuntime().baseEnvironment[STATUS_FILE_ENV_KEY$1]
455
- };
456
- }
457
- async function runClaudeSessionStartHook(deps = createDefaultSessionStartHookDeps$1()) {
458
- if (!deps.workflowStatusFile) return;
459
- if ((await deps.readStdin()).trim().length === 0) return;
460
- }
461
- async function runClaudeStopHook(deps = createDefaultStopHookDeps$1()) {
462
- const statusFilePath = deps.workflowStatusFile;
463
- let rawInput;
464
- try {
465
- rawInput = await deps.readStdin();
466
- } catch (error) {
467
- if (!statusFilePath) {
468
- await logClaudeStopHookDecision(deps, "", null, {
469
- decision: "ignore",
470
- reason: `missing ${STATUS_FILE_ENV_KEY$1}; stdin read failed: ${errorMessage$1(error)}`
471
- });
472
- return;
473
- }
474
- await completeWorkflow$1(deps, statusFilePath, "", null, `stdin read failed: ${errorMessage$1(error)}`);
475
- return;
476
- }
477
- if (!statusFilePath) {
478
- await logClaudeStopHookDecision(deps, rawInput, parseClaudeStopHookInput(rawInput), {
479
- decision: "ignore",
480
- reason: `missing ${STATUS_FILE_ENV_KEY$1}`
481
- });
482
- return;
483
- }
484
- if (rawInput.trim().length === 0) {
485
- await completeWorkflow$1(deps, statusFilePath, rawInput, null, STDIN_UNREADABLE_REASON$1);
486
- return;
487
- }
488
- const hookInput = parseClaudeStopHookInput(rawInput);
489
- if (!hookInput) {
490
- await logClaudeStopHookDecision(deps, rawInput, null, {
491
- decision: "ignore",
492
- reason: "invalid stop hook JSON"
493
- });
494
- return;
495
- }
496
- if (hookInput.hook_event_name && hookInput.hook_event_name !== STOP_HOOK_EVENT_NAME$1) {
497
- await logClaudeStopHookDecision(deps, rawInput, hookInput, {
498
- decision: "ignore",
499
- reason: `unsupported hook event: ${hookInput.hook_event_name}`
500
- });
501
- return;
502
- }
503
- const statusFileState = classifyWorkflowStatusFile$1(await deps.readStatusFile(statusFilePath));
504
- if (!isActiveWorkflowStatusFileState(statusFileState)) {
505
- await logClaudeStopHookDecision(deps, rawInput, hookInput, {
506
- decision: "ignore",
507
- reason: workflowStatusFileIgnoreReason$1(statusFileState.status)
508
- });
509
- return;
510
- }
511
- const blockingBackgroundTaskCount = hookInput.background_tasks.filter(isBlockingBackgroundTask).length;
512
- if (blockingBackgroundTaskCount > 0 && !hookInput.stop_hook_active) {
513
- deps.writeStdout?.(stopHookBlockOutput$1(PENDING_WORK_BLOCK_REASON$1));
514
- await logClaudeStopHookDecision(deps, rawInput, hookInput, {
515
- decision: "block",
516
- reason: PENDING_WORK_BLOCK_REASON$1
517
- });
518
- return;
519
- }
520
- let artifactWarnings;
521
- try {
522
- artifactWarnings = await deps.findStepArtifactWarnings?.() ?? [];
523
- } catch (error) {
524
- const reason = `Required step artifacts could not be checked: ${errorMessage$1(error)}`;
525
- deps.writeStdout?.(stopHookBlockOutput$1(reason));
526
- await logClaudeStopHookDecision(deps, rawInput, hookInput, {
527
- decision: "block",
528
- reason
529
- });
530
- return;
531
- }
532
- if (artifactWarnings.length > 0) {
533
- const reason = formatStepArtifactBlockReason$1(artifactWarnings);
534
- deps.writeStdout?.(stopHookBlockOutput$1(reason));
535
- await logClaudeStopHookDecision(deps, rawInput, hookInput, {
536
- decision: "block",
537
- reason
538
- });
539
- return;
540
- }
541
- const completionReason = blockingBackgroundTaskCount > 0 ? `${STOP_HOOK_ACTIVE_COMPLETION_PREFIX} ${blockingBackgroundTaskCount} ${STOP_HOOK_ACTIVE_COMPLETION_SUFFIX}` : void 0;
542
- await completeWorkflow$1(deps, statusFilePath, rawInput, hookInput, completionReason);
543
- }
544
- async function completeWorkflow$1(deps, statusFilePath, rawInput, hookInput, reason) {
545
- const gate = await (deps.gateStepDecision ?? (() => require_RecoverWorkflowService.gateStepDecision(getCliWorkflowRuntime())))();
546
- if (gate.action === "block") {
547
- deps.writeStdout?.(stopHookBlockOutput$1(gate.message));
548
- await logClaudeStopHookDecision(deps, rawInput, hookInput, {
549
- decision: "block",
550
- reason: gate.message
551
- });
552
- return;
553
- }
554
- try {
555
- await deps.writeStatusFile(statusFilePath);
556
- await logClaudeStopHookDecision(deps, rawInput, hookInput, {
557
- decision: "complete",
558
- reason
559
- });
560
- } catch (error) {
561
- await logClaudeStopHookDecision(deps, rawInput, hookInput, {
562
- decision: "error",
563
- reason: `status-file write failed: ${errorMessage$1(error)}`
564
- });
565
- }
566
- }
567
- function errorMessage$1(error) {
568
- return error instanceof Error ? error.message : String(error);
569
- }
570
- function stopHookBlockOutput$1(reason) {
571
- return `${JSON.stringify({
572
- decision: "block",
573
- reason,
574
- suppressOutput: true
575
- })}\n`;
576
- }
577
- async function findStepArtifactWarningsFromEnvironment$1() {
578
- const env = getCliWorkflowRuntime().baseEnvironment;
579
- if (env["WORKFLOW_DECISION_FILE"]) return [];
580
- const rawSnapshots = env[WORKFLOW_STEP_ARTIFACTS_ENV_KEY$1];
581
- if (!rawSnapshots) return [];
582
- const runDir = env[WORKFLOW_RUN_DIR_ENV_KEY$1];
583
- if (!runDir) throw new Error(`missing ${WORKFLOW_RUN_DIR_ENV_KEY$1}`);
584
- const snapshots = parseStepArtifactSnapshots$1(rawSnapshots);
585
- return new require_RecoverWorkflowService.RunDirectoryService(getCliWorkflowRuntime()).findStepArtifactWarnings(runDir, snapshots);
586
- }
587
- function parseStepArtifactSnapshots$1(rawSnapshots) {
588
- const parsed = JSON.parse(rawSnapshots);
589
- if (!Array.isArray(parsed) || !parsed.every((entry) => isRecord$2(entry) && typeof entry.path === "string" && (entry.fingerprint === void 0 || typeof entry.fingerprint === "string"))) throw new Error(`invalid ${WORKFLOW_STEP_ARTIFACTS_ENV_KEY$1}`);
590
- return parsed;
591
- }
592
- function formatStepArtifactBlockReason$1(warnings) {
593
- return `Required step artifacts are incomplete. Update them before stopping:\n${warnings.map(require_RecoverWorkflowService.formatArtifactWarning).join("\n")}`;
594
- }
595
- function parseClaudeStopHookInput(rawInput) {
596
- try {
597
- const parsed = JSON.parse(rawInput);
598
- if (!isRecord$2(parsed)) return null;
599
- const backgroundTasks = Array.isArray(parsed.background_tasks) ? parsed.background_tasks : [];
600
- const sessionCrons = Array.isArray(parsed.session_crons) ? parsed.session_crons : [];
601
- return {
602
- hook_event_name: typeof parsed.hook_event_name === "string" ? parsed.hook_event_name : void 0,
603
- session_id: typeof parsed.session_id === "string" ? parsed.session_id : void 0,
604
- stop_hook_active: parsed.stop_hook_active === true,
605
- background_tasks: backgroundTasks,
606
- session_crons: sessionCrons
607
- };
608
- } catch {
609
- return null;
610
- }
611
- }
612
- function isBlockingBackgroundTask(task) {
613
- if (!isRecord$2(task)) return true;
614
- const status = normalizeBackgroundTaskStatus(task.status);
615
- return !status || !TERMINAL_BACKGROUND_TASK_STATUSES.has(status);
616
- }
617
- function normalizeBackgroundTaskStatus(status) {
618
- return typeof status === "string" && status.trim().length > 0 ? status.trim().toLowerCase().replaceAll("-", "_") : null;
619
- }
620
- function classifyWorkflowStatusFile$1(rawStatus) {
621
- if (rawStatus === null) return { status: "missing" };
622
- const trimmed = rawStatus.trim();
623
- if (!trimmed) return { status: "unbound" };
624
- if (trimmed === STATUS_FILE_COMPLETION_VALUE$1.trim()) return { status: "completed" };
625
- try {
626
- const parsed = JSON.parse(trimmed);
627
- return typeof parsed.sessionId === "string" && parsed.sessionId.length > 0 ? {
628
- status: "bound",
629
- sessionId: parsed.sessionId
630
- } : { status: "invalid" };
631
- } catch {
632
- return { status: "invalid" };
633
- }
634
- }
635
- function isActiveWorkflowStatusFileState(statusFileState) {
636
- return statusFileState.status === "bound" || statusFileState.status === "unbound";
637
- }
638
- function workflowStatusFileIgnoreReason$1(status) {
639
- switch (status) {
640
- case "completed": return "workflow status file already completed";
641
- case "invalid": return "invalid workflow status file binding";
642
- case "missing": return "missing workflow status file";
643
- case "unbound": return "workflow status file is unbound";
644
- }
645
- }
646
- function isRecord$2(value) {
647
- return typeof value === "object" && value !== null;
648
- }
649
- async function readStdin$1() {
650
- const chunks = [];
651
- const collect = (async () => {
652
- for await (const chunk of process.stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
653
- })();
654
- collect.catch(() => {});
655
- let timer;
656
- const timeout = new Promise((resolve) => {
657
- timer = setTimeout(() => {
658
- process.stdin.destroy();
659
- resolve();
660
- }, STDIN_READ_TIMEOUT_MS$2);
661
- });
662
- try {
663
- await Promise.race([collect, timeout]);
664
- } finally {
665
- if (timer) clearTimeout(timer);
666
- }
667
- return Buffer.concat(chunks).toString("utf8");
668
- }
669
- async function logClaudeStopHookDecision(deps, rawInput, input, decision) {
670
- try {
671
- await deps.writeDebugLog?.({
672
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
673
- rawInput,
674
- input,
675
- decision,
676
- runtime: hookRuntimeContext(deps.workflowStatusFile),
677
- workflowStatusFile: deps.workflowStatusFile
678
- });
679
- } catch {}
680
- }
681
- async function appendHookDebugLog(filePath, entry) {
682
- const entries = await readHookDebugLog(filePath);
683
- entries.push(entry);
684
- await writeCliTextFile(filePath, `${JSON.stringify(entries.slice(-50), null, 2)}\n`, true);
685
- }
686
- async function readHookDebugLog(filePath) {
687
- try {
688
- const parsed = JSON.parse(await readCliTextFile(filePath) ?? "");
689
- return Array.isArray(parsed) ? parsed : [];
690
- } catch {
691
- return [];
692
- }
693
- }
694
- function createDefaultNotificationHookDeps() {
695
- const runtime = getCliWorkflowRuntime();
696
- return {
697
- readStdin: readStdin$1,
698
- readStatusFile: readCliTextFile,
699
- writeDebugLog: async (entry) => {
700
- await appendHookDebugLog((0, node_path.join)(runtime.cwd, ...NOTIFICATION_DEBUG_LOG_PATH), entry);
701
- },
702
- writeStatusFile: async (statusFilePath) => {
703
- await writeCliTextFile(statusFilePath, STATUS_FILE_COMPLETION_VALUE$1);
704
- },
705
- workflowStatusFile: runtime.baseEnvironment[STATUS_FILE_ENV_KEY$1]
706
- };
707
- }
708
- /**
709
- * Fallback completion signal for interactive runs whose turn ends in a state where the Stop
710
- * hook never fires: idle after a Stop block-cap override, a mid-turn stall, or an
711
- * un-bypassable permission/elicitation prompt that a headless workflow can never answer.
712
- * On such a notification it marks `WORKFLOW_STATUS_FILE` complete so the runner can advance.
713
- * It is idempotent with the Stop hook: an already-completed status file is left untouched,
714
- * and does not complete unless `WORKFLOW_STATUS_FILE` is set, so it never affects ordinary sessions.
715
- *
716
- * Unlike the Stop hook this does NOT complete on an unreadable/garbled payload: Stop and
717
- * StopFailure remain the primary signals, so completing on a malformed notification would be
718
- * needlessly aggressive.
719
- */
720
- async function runClaudeNotificationHook(deps = createDefaultNotificationHookDeps()) {
721
- const statusFilePath = deps.workflowStatusFile;
722
- let rawInput;
723
- try {
724
- rawInput = await deps.readStdin();
725
- } catch (error) {
726
- await logClaudeNotificationHookDecision(deps, "", null, {
727
- decision: "ignore",
728
- reason: `stdin read failed: ${errorMessage$1(error)}`
729
- });
730
- return;
731
- }
732
- if (!statusFilePath) {
733
- await logClaudeNotificationHookDecision(deps, rawInput, parseClaudeNotificationHookInput(rawInput), {
734
- decision: "ignore",
735
- reason: `missing ${STATUS_FILE_ENV_KEY$1}`
736
- });
737
- return;
738
- }
739
- if (rawInput.trim().length === 0) {
740
- await logClaudeNotificationHookDecision(deps, rawInput, null, {
741
- decision: "ignore",
742
- reason: STDIN_UNREADABLE_REASON$1
743
- });
744
- return;
745
- }
746
- const hookInput = parseClaudeNotificationHookInput(rawInput);
747
- if (!hookInput) {
748
- await logClaudeNotificationHookDecision(deps, rawInput, null, {
749
- decision: "ignore",
750
- reason: "invalid notification hook JSON"
751
- });
752
- return;
753
- }
754
- if (hookInput.hook_event_name && hookInput.hook_event_name !== NOTIFICATION_HOOK_EVENT_NAME) {
755
- await logClaudeNotificationHookDecision(deps, rawInput, hookInput, {
756
- decision: "ignore",
757
- reason: `unsupported hook event: ${hookInput.hook_event_name}`
758
- });
759
- return;
760
- }
761
- if (!notificationSignalsCompletion(hookInput.notification_type)) {
762
- await logClaudeNotificationHookDecision(deps, rawInput, hookInput, {
763
- decision: "ignore",
764
- reason: `notification type does not signal completion: ${hookInput.notification_type ?? "unknown"}`
765
- });
766
- return;
767
- }
768
- const statusFileState = classifyWorkflowStatusFile$1(await deps.readStatusFile(statusFilePath));
769
- if (!isActiveWorkflowStatusFileState(statusFileState)) {
770
- await logClaudeNotificationHookDecision(deps, rawInput, hookInput, {
771
- decision: "ignore",
772
- reason: workflowStatusFileIgnoreReason$1(statusFileState.status)
773
- });
774
- return;
775
- }
776
- try {
777
- await deps.writeStatusFile(statusFilePath);
778
- await logClaudeNotificationHookDecision(deps, rawInput, hookInput, {
779
- decision: "complete",
780
- reason: `notification:${hookInput.notification_type ?? "unspecified"}`
781
- });
782
- } catch (error) {
783
- await logClaudeNotificationHookDecision(deps, rawInput, hookInput, {
784
- decision: "error",
785
- reason: `status-file write failed: ${errorMessage$1(error)}`
786
- });
787
- }
788
- }
789
- function parseClaudeNotificationHookInput(rawInput) {
790
- try {
791
- const parsed = JSON.parse(rawInput);
792
- if (!isRecord$2(parsed)) return null;
793
- return {
794
- hook_event_name: typeof parsed.hook_event_name === "string" ? parsed.hook_event_name : void 0,
795
- session_id: typeof parsed.session_id === "string" ? parsed.session_id : void 0,
796
- notification_type: normalizeNotificationType(parsed.notification_type ?? parsed.type ?? parsed.matcher),
797
- message: typeof parsed.message === "string" ? parsed.message : void 0
798
- };
799
- } catch {
800
- return null;
801
- }
802
- }
803
- function normalizeNotificationType(value) {
804
- return typeof value === "string" && value.trim().length > 0 ? value.trim().toLowerCase().replaceAll("-", "_") : void 0;
805
- }
806
- function notificationSignalsCompletion(notificationType) {
807
- if (!notificationType) return true;
808
- if (NOTIFICATION_TRANSIENT_TYPES.has(notificationType)) return false;
809
- return NOTIFICATION_COMPLETION_TYPES.has(notificationType);
810
- }
811
- async function logClaudeNotificationHookDecision(deps, rawInput, input, decision) {
812
- try {
813
- await deps.writeDebugLog?.({
814
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
815
- rawInput,
816
- input,
817
- decision,
818
- runtime: hookRuntimeContext(deps.workflowStatusFile),
819
- workflowStatusFile: deps.workflowStatusFile
820
- });
821
- } catch {}
822
- }
823
- function hookRuntimeContext(workflowStatusFile) {
824
- const { baseEnvironment: env, cwd } = getCliWorkflowRuntime();
825
- const runtime = {
826
- cwd,
827
- workflowStatusFilePresent: Boolean(workflowStatusFile)
828
- };
829
- const claudeProjectDir = env[CLAUDE_PROJECT_DIR_ENV_KEY];
830
- if (claudeProjectDir) runtime.claudeProjectDir = claudeProjectDir;
831
- const workflowRunDir = env[WORKFLOW_RUN_DIR_ENV_KEY$1];
832
- if (workflowRunDir) runtime.workflowRunDir = workflowRunDir;
833
- return runtime;
834
- }
835
- const claudeSessionStartHookCommand = new commander.Command("claude-session-start-hook").description(`Claude Code SessionStart hook compatibility no-op for ${STATUS_FILE_ENV_KEY$1}`).action(async () => {
836
- await runClaudeSessionStartHook();
837
- });
838
- const claudeStopHookCommand = new commander.Command("claude-stop-hook").description(`Claude Code stop hook: reads Stop hook JSON on stdin and marks ${STATUS_FILE_ENV_KEY$1} when the root session is complete`).action(async () => {
839
- await runClaudeStopHook();
840
- });
841
- const claudeNotificationHookCommand = new commander.Command("claude-notification-hook").description(`Claude Code Notification hook: marks ${STATUS_FILE_ENV_KEY$1} complete when an interactive run goes idle or stalls waiting for input a headless workflow cannot answer (fallback for Stop hooks that never fire)`).action(async () => {
842
- await runClaudeNotificationHook();
843
- });
844
- //#endregion
845
28
  //#region src/services/WorkflowLauncherService/index.ts
846
29
  const SESSION_NAME_PREFIX = "workflow-";
847
30
  const MAX_SESSION_NAME_LENGTH = 80;
@@ -996,6 +179,79 @@ var WorkflowLauncherService = class {
996
179
  }
997
180
  };
998
181
  //#endregion
182
+ //#region src/bin/workflowRuntime.ts
183
+ let runtime;
184
+ let logger;
185
+ /** The standalone executable admits ambient facts once, before any engine service is constructed. */
186
+ function getCliWorkflowRuntime() {
187
+ if (runtime) return runtime;
188
+ const environment = Object.freeze({ ...process.env });
189
+ const cwd = process.cwd();
190
+ const homeDirectory = _agimon_ai_po_core_platform.nodeHost.homeDirectory();
191
+ const temporaryDirectory = _agimon_ai_po_core_platform.nodeHost.temporaryDirectory();
192
+ const execution = (0, _agimon_ai_po_core_nodePlatform.createNodePlatform)({
193
+ homeDirectory,
194
+ temporaryDirectory
195
+ }).env(cwd);
196
+ runtime = require_RecoverWorkflowService.createWorkflowRuntime({
197
+ baseEnvironment: environment,
198
+ cwd,
199
+ homeDirectory,
200
+ temporaryDirectory,
201
+ fs: execution,
202
+ shell: execution,
203
+ workflowHost: require_RecoverWorkflowService.createWorkflowHost({
204
+ environment,
205
+ cwd,
206
+ homeDirectory,
207
+ temporaryDirectory,
208
+ cliPath: require_RecoverWorkflowService.resolveWorkflowCliPath()
209
+ })
210
+ });
211
+ return runtime;
212
+ }
213
+ /** One telemetry backend per standalone CLI invocation. */
214
+ function getCliWorkflowLogger() {
215
+ return logger ??= createCliWorkflowLogger({
216
+ info: (message) => console.info(message),
217
+ warn: (message) => console.error(message),
218
+ error: (message) => console.error(message)
219
+ });
220
+ }
221
+ let installedServiceName = "workflow-mcp";
222
+ let telemetry;
223
+ function getTelemetry(serviceName) {
224
+ const runtime = getCliWorkflowRuntime();
225
+ return telemetry ??= (0, _agimon_ai_po_core_telemetry.createPoTelemetry)({
226
+ packageName: "@agimon-ai/po-workflow",
227
+ serviceName,
228
+ workspaceRoot: runtime.cwd,
229
+ cwd: runtime.cwd,
230
+ env: { ...runtime.baseEnvironment }
231
+ });
232
+ }
233
+ function createCliWorkflowLogger(baseLogger) {
234
+ return {
235
+ ...baseLogger,
236
+ async event(level, name, options = {}) {
237
+ const telemetry = getTelemetry(installedServiceName);
238
+ if (level === "error" || level === "fatal") await telemetry.recordError(name, options.exception, options.attributes);
239
+ else if (level === "warn") await telemetry.recordWarning(name, options.exception, options.attributes);
240
+ else if (level === "debug" || level === "trace") await telemetry.recordDebug(name, options.attributes);
241
+ else await telemetry.recordEvent(name, options.attributes);
242
+ },
243
+ runInSpan: (name, attributes, work, parent) => getTelemetry(installedServiceName).runInSpan(name, attributes, work, parent),
244
+ flush: flushOtelErrorLogger
245
+ };
246
+ }
247
+ async function flushOtelErrorLogger() {
248
+ await telemetry?.flush();
249
+ }
250
+ function installOtelErrorLogger(options) {
251
+ installedServiceName = options.serviceName;
252
+ getTelemetry(installedServiceName);
253
+ }
254
+ //#endregion
999
255
  //#region src/bin/workflowCommands/closeLauncher.ts
1000
256
  function resolveLauncher(options, env) {
1001
257
  if (options.launcher) return options.launcher;
@@ -1071,738 +327,20 @@ function createCloseLauncherCommand(dependencies = {}) {
1071
327
  }
1072
328
  const closeLauncherCommand = createCloseLauncherCommand();
1073
329
  //#endregion
1074
- //#region src/bin/workflowCommands/codexStopHook.ts
1075
- const STATUS_FILE_ENV_KEY = "WORKFLOW_STATUS_FILE";
1076
- const WORKFLOW_RUN_DIR_ENV_KEY = "WORKFLOW_RUN_DIR";
1077
- const WORKFLOW_STEP_ARTIFACTS_ENV_KEY = "WORKFLOW_STEP_ARTIFACTS";
1078
- const STATUS_FILE_COMPLETION_VALUE = "YES\n";
1079
- const STOP_HOOK_DEBUG_LOG_PATH = ["tmp", "codex-stop-hook.json"];
1080
- const TRANSCRIPT_READ_CHUNK_BYTES = 65536;
1081
- const SESSION_META_ITEM_TYPE = "session_meta";
1082
- const STOP_HOOK_EVENT_NAME = "Stop";
1083
- const PENDING_WORK_BLOCK_REASON = "In-progress work is still running. Wait for spawned agents and running tool calls to finish before ending the turn.";
1084
- const FOLLOW_UP_TURN_BLOCK_REASON = "This Stop event belongs to a follow-up user turn, not the original workflow turn. Continue the workflow job and only stop when the workflow instructions are complete.";
1085
- const STDIN_READ_TIMEOUT_MS$1 = 1e4;
1086
- const STDIN_UNREADABLE_REASON = "stdin unreadable: empty payload or read timed out";
1087
- const SUB_AGENT_SOURCE_KEYS = ["sub_agent", "subagent"];
1088
- const IN_PROGRESS_STATUSES = /* @__PURE__ */ new Set([
1089
- "InProgress",
1090
- "PendingInit",
1091
- "Running",
1092
- "in_progress",
1093
- "inProgress",
1094
- "pending_init",
1095
- "pendingInit",
1096
- "running"
1097
- ]);
1098
- const TRACKED_IN_PROGRESS_ITEM_TYPES = /* @__PURE__ */ new Set([
1099
- "CollabAgentToolCall",
1100
- "CommandExecution",
1101
- "DynamicToolCall",
1102
- "ImageGeneration",
1103
- "McpToolCall",
1104
- "collab_agent_tool_call",
1105
- "collabAgentToolCall",
1106
- "command_execution",
1107
- "commandExecution",
1108
- "custom_tool_call",
1109
- "dynamic_tool_call",
1110
- "dynamicToolCall",
1111
- "image_generation_call",
1112
- "imageGeneration",
1113
- "local_shell_call",
1114
- "mcp_tool_call",
1115
- "mcpToolCall"
1116
- ]);
1117
- const COLLAB_AGENT_TOOL_CALL_ITEM_TYPES = /* @__PURE__ */ new Set([
1118
- "CollabAgentToolCall",
1119
- "collab_agent_tool_call",
1120
- "collabAgentToolCall"
1121
- ]);
1122
- const USER_MESSAGE_ITEM_TYPES = /* @__PURE__ */ new Set([
1123
- "UserMessage",
1124
- "user_message",
1125
- "userMessage"
1126
- ]);
1127
- const MAX_TRANSCRIPT_PATH_SEARCH_ENTRIES = 5e3;
1128
- function createDefaultStopHookDeps() {
1129
- const runtime = getCliWorkflowRuntime();
1130
- return {
1131
- findStepArtifactWarnings: findStepArtifactWarningsFromEnvironment,
1132
- readStdin,
1133
- readStatusFile: readCliTextFile,
1134
- readTranscriptHead,
1135
- readTranscriptState,
1136
- emitTranscriptMetrics: emitCodexTranscriptMetrics,
1137
- writeDebugLog: async (entry) => {
1138
- await writeStopHookDebugLog((0, node_path.join)(runtime.cwd, ...STOP_HOOK_DEBUG_LOG_PATH), entry);
1139
- },
1140
- writeStdout: (output) => {
1141
- runtime.workflowHost.writeStdout(output);
1142
- },
1143
- writeStatusFile: async (statusFilePath) => {
1144
- await writeCliTextFile(statusFilePath, STATUS_FILE_COMPLETION_VALUE);
1145
- },
1146
- workflowStatusFile: runtime.baseEnvironment[STATUS_FILE_ENV_KEY]
1147
- };
1148
- }
1149
- function createDefaultSessionStartHookDeps() {
1150
- return {
1151
- readStdin,
1152
- readStatusFile: readCliTextFile,
1153
- writeSessionBinding: async (statusFilePath, sessionId) => {
1154
- await writeCliTextFile(statusFilePath, `${JSON.stringify({ sessionId })}\n`);
1155
- },
1156
- workflowStatusFile: getCliWorkflowRuntime().baseEnvironment[STATUS_FILE_ENV_KEY]
1157
- };
1158
- }
1159
- async function runCodexSessionStartHook(deps = createDefaultSessionStartHookDeps()) {
1160
- const statusFilePath = deps.workflowStatusFile;
1161
- if (!statusFilePath) return;
1162
- const rawInput = await deps.readStdin();
1163
- if (rawInput.trim().length === 0) return;
1164
- const hookInput = parseCodexSessionStartHookInput(rawInput);
1165
- if (!hookInput?.session_id) return;
1166
- const currentStatus = await deps.readStatusFile(statusFilePath);
1167
- if (currentStatus === null || currentStatus.trim().length > 0) return;
1168
- await deps.writeSessionBinding(statusFilePath, hookInput.session_id);
1169
- }
1170
- async function runCodexStopHook(deps = createDefaultStopHookDeps()) {
1171
- const statusFilePath = deps.workflowStatusFile;
1172
- if (!statusFilePath) return;
1173
- let rawInput;
1174
- try {
1175
- rawInput = await deps.readStdin();
1176
- } catch (error) {
1177
- await logCodexStopHookDecision(deps, "", null, {
1178
- decision: "ignore",
1179
- reason: `stdin read failed: ${errorMessage(error)}`
1180
- });
1181
- return;
1182
- }
1183
- if (rawInput.trim().length === 0) {
1184
- await logCodexStopHookDecision(deps, rawInput, null, {
1185
- decision: "ignore",
1186
- reason: STDIN_UNREADABLE_REASON
1187
- });
1188
- return;
1189
- }
1190
- const hookInput = parseCodexStopHookInput(rawInput);
1191
- if (!hookInput) {
1192
- await logCodexStopHookDecision(deps, rawInput, null, {
1193
- decision: "ignore",
1194
- reason: "invalid stop hook JSON"
1195
- });
1196
- return;
1197
- }
1198
- if (hookInput.hook_event_name && hookInput.hook_event_name !== STOP_HOOK_EVENT_NAME) {
1199
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1200
- decision: "ignore",
1201
- reason: `unsupported hook event: ${hookInput.hook_event_name}`
1202
- });
1203
- return;
1204
- }
1205
- const statusFileState = classifyWorkflowStatusFile(await deps.readStatusFile(statusFilePath));
1206
- if (statusFileState.status !== "bound") {
1207
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1208
- decision: "ignore",
1209
- reason: workflowStatusFileIgnoreReason(statusFileState.status)
1210
- });
1211
- return;
1212
- }
1213
- if (!hookInput.session_id || hookInput.session_id !== statusFileState.sessionId) {
1214
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1215
- decision: "ignore",
1216
- reason: "stop hook session is not bound to the workflow status file"
1217
- });
1218
- return;
1219
- }
1220
- const transcriptPath = normalizeTranscriptPath(hookInput.transcript_path);
1221
- if (!transcriptPath) {
1222
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1223
- decision: "ignore",
1224
- reason: "missing transcript path"
1225
- });
1226
- return;
1227
- }
1228
- const transcriptState = await readCodexStopHookTranscriptState(deps, transcriptPath);
1229
- const sessionMeta = transcriptState.sessionMeta;
1230
- if (!sessionMeta) {
1231
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1232
- decision: "ignore",
1233
- reason: "missing transcript session metadata"
1234
- });
1235
- return;
1236
- }
1237
- if (hookInput.session_id && sessionMeta.id && hookInput.session_id !== sessionMeta.id) {
1238
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1239
- decision: "ignore",
1240
- reason: "stop hook session does not match transcript session"
1241
- });
1242
- return;
1243
- }
1244
- if (isSubagentSessionSource(sessionMeta.source)) {
1245
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1246
- decision: "ignore",
1247
- reason: "transcript session is a subagent"
1248
- });
1249
- return;
1250
- }
1251
- const hasBackgroundTasks = hookInput.hasTaskRegistry && (hookInput.background_tasks?.length ?? 0) > 0;
1252
- const hasSessionCrons = hookInput.hasTaskRegistry && (hookInput.session_crons?.length ?? 0) > 0;
1253
- if (!hookInput.hasTaskRegistry && Boolean(transcriptState.initialUserTurnId) && Boolean(hookInput.turn_id) && hookInput.turn_id !== transcriptState.initialUserTurnId && !hookInput.stop_hook_active) {
1254
- deps.writeStdout?.(stopHookBlockOutput(FOLLOW_UP_TURN_BLOCK_REASON));
1255
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1256
- decision: "block",
1257
- reason: FOLLOW_UP_TURN_BLOCK_REASON
1258
- });
1259
- return;
1260
- }
1261
- if (hasBackgroundTasks || !hookInput.hasTaskRegistry && transcriptState.hasPendingWork) {
1262
- deps.writeStdout?.(stopHookBlockOutput(PENDING_WORK_BLOCK_REASON));
1263
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1264
- decision: "block",
1265
- reason: PENDING_WORK_BLOCK_REASON
1266
- });
1267
- return;
1268
- }
1269
- if (hasSessionCrons) {
1270
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1271
- decision: "ignore",
1272
- reason: "session crons are still scheduled"
1273
- });
1274
- return;
1275
- }
1276
- let artifactWarnings;
1277
- try {
1278
- artifactWarnings = await deps.findStepArtifactWarnings?.() ?? [];
1279
- } catch (error) {
1280
- const reason = `Required step artifacts could not be checked: ${errorMessage(error)}`;
1281
- deps.writeStdout?.(stopHookBlockOutput(reason));
1282
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1283
- decision: "block",
1284
- reason
1285
- });
1286
- return;
1287
- }
1288
- if (artifactWarnings.length > 0) {
1289
- const reason = formatStepArtifactBlockReason(artifactWarnings);
1290
- deps.writeStdout?.(stopHookBlockOutput(reason));
1291
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1292
- decision: "block",
1293
- reason
1294
- });
1295
- return;
1296
- }
1297
- await emitTranscriptMetricsSafely(deps, transcriptPath);
1298
- await completeWorkflow(deps, statusFilePath, rawInput, hookInput);
1299
- }
1300
- async function emitTranscriptMetricsSafely(deps, transcriptPath) {
1301
- try {
1302
- await deps.emitTranscriptMetrics?.(transcriptPath);
1303
- } catch {}
1304
- }
1305
- async function completeWorkflow(deps, statusFilePath, rawInput, hookInput, reason) {
1306
- const gate = await (deps.gateStepDecision ?? (() => require_RecoverWorkflowService.gateStepDecision(getCliWorkflowRuntime())))();
1307
- if (gate.action === "block") {
1308
- deps.writeStdout?.(stopHookBlockOutput(gate.message));
1309
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1310
- decision: "block",
1311
- reason: gate.message
1312
- });
1313
- return;
1314
- }
1315
- try {
1316
- await deps.writeStatusFile(statusFilePath);
1317
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1318
- decision: "complete",
1319
- reason
1320
- });
1321
- } catch (error) {
1322
- await logCodexStopHookDecision(deps, rawInput, hookInput, {
1323
- decision: "error",
1324
- reason: `status-file write failed: ${errorMessage(error)}`
1325
- });
1326
- }
1327
- }
1328
- function errorMessage(error) {
1329
- return error instanceof Error ? error.message : String(error);
1330
- }
1331
- function stopHookBlockOutput(reason) {
1332
- return `${JSON.stringify({
1333
- decision: "block",
1334
- reason,
1335
- suppressOutput: true
1336
- })}\n`;
1337
- }
1338
- async function findStepArtifactWarningsFromEnvironment() {
1339
- const env = getCliWorkflowRuntime().baseEnvironment;
1340
- if (env["WORKFLOW_DECISION_FILE"]) return [];
1341
- const rawSnapshots = env[WORKFLOW_STEP_ARTIFACTS_ENV_KEY];
1342
- if (!rawSnapshots) return [];
1343
- const runDir = env[WORKFLOW_RUN_DIR_ENV_KEY];
1344
- if (!runDir) throw new Error(`missing ${WORKFLOW_RUN_DIR_ENV_KEY}`);
1345
- const snapshots = parseStepArtifactSnapshots(rawSnapshots);
1346
- return new require_RecoverWorkflowService.RunDirectoryService(getCliWorkflowRuntime()).findStepArtifactWarnings(runDir, snapshots);
1347
- }
1348
- function parseStepArtifactSnapshots(rawSnapshots) {
1349
- const parsed = JSON.parse(rawSnapshots);
1350
- if (!Array.isArray(parsed) || !parsed.every((entry) => isRecord$1(entry) && typeof entry.path === "string" && (entry.fingerprint === void 0 || typeof entry.fingerprint === "string"))) throw new Error(`invalid ${WORKFLOW_STEP_ARTIFACTS_ENV_KEY}`);
1351
- return parsed;
1352
- }
1353
- function formatStepArtifactBlockReason(warnings) {
1354
- return `Required step artifacts are incomplete. Update them before stopping:\n${warnings.map(require_RecoverWorkflowService.formatArtifactWarning).join("\n")}`;
1355
- }
1356
- async function readCodexStopHookTranscriptState(deps, transcriptPath) {
1357
- if (deps.readTranscriptState) return deps.readTranscriptState(transcriptPath);
1358
- if (deps.readTranscriptHead === readTranscriptHead) return readTranscriptState(transcriptPath);
1359
- return {
1360
- sessionMeta: await deps.readTranscriptHead(transcriptPath),
1361
- hasPendingWork: false
1362
- };
1363
- }
1364
- function parseCodexSessionStartHookInput(rawInput) {
1365
- try {
1366
- const parsed = JSON.parse(rawInput);
1367
- if (!isRecord$1(parsed)) return null;
1368
- return { session_id: typeof parsed.session_id === "string" ? parsed.session_id : void 0 };
1369
- } catch {
1370
- return null;
1371
- }
1372
- }
1373
- function parseCodexStopHookInput(rawInput) {
1374
- try {
1375
- const parsed = JSON.parse(rawInput);
1376
- if (!isRecord$1(parsed)) return null;
1377
- const backgroundTasks = Array.isArray(parsed.background_tasks) ? parsed.background_tasks : void 0;
1378
- const sessionCrons = Array.isArray(parsed.session_crons) ? parsed.session_crons : void 0;
1379
- return {
1380
- hook_event_name: typeof parsed.hook_event_name === "string" ? parsed.hook_event_name : void 0,
1381
- session_id: typeof parsed.session_id === "string" ? parsed.session_id : void 0,
1382
- turn_id: typeof parsed.turn_id === "string" ? parsed.turn_id : void 0,
1383
- transcript_path: normalizeTranscriptPath(parsed.transcript_path),
1384
- stop_hook_active: parsed.stop_hook_active === true,
1385
- background_tasks: backgroundTasks,
1386
- session_crons: sessionCrons,
1387
- hasTaskRegistry: backgroundTasks !== void 0 || sessionCrons !== void 0
1388
- };
1389
- } catch {
1390
- return null;
1391
- }
1392
- }
1393
- function normalizeTranscriptPath(value) {
1394
- return typeof value === "string" && value.trim().length > 0 ? value : null;
1395
- }
1396
- function classifyWorkflowStatusFile(rawStatus) {
1397
- if (rawStatus === null) return { status: "missing" };
1398
- const trimmed = rawStatus.trim();
1399
- if (!trimmed) return { status: "unbound" };
1400
- if (trimmed === STATUS_FILE_COMPLETION_VALUE.trim()) return { status: "completed" };
1401
- try {
1402
- const parsed = JSON.parse(trimmed);
1403
- return typeof parsed.sessionId === "string" && parsed.sessionId.length > 0 ? {
1404
- status: "bound",
1405
- sessionId: parsed.sessionId
1406
- } : { status: "invalid" };
1407
- } catch {
1408
- return { status: "invalid" };
1409
- }
1410
- }
1411
- function workflowStatusFileIgnoreReason(status) {
1412
- switch (status) {
1413
- case "completed": return "workflow status file already completed";
1414
- case "invalid": return "invalid workflow status file binding";
1415
- case "missing": return "missing workflow status file";
1416
- case "unbound": return "workflow status file is unbound";
1417
- }
1418
- }
1419
- function isSubagentSessionSource(source) {
1420
- if (typeof source === "string") return source.startsWith("subagent_") || source.startsWith("internal_");
1421
- if (!isRecord$1(source)) return false;
1422
- return SUB_AGENT_SOURCE_KEYS.some((key) => key in source);
1423
- }
1424
- function isRecord$1(value) {
1425
- return typeof value === "object" && value !== null;
1426
- }
1427
- async function readStdin() {
1428
- const chunks = [];
1429
- const collect = (async () => {
1430
- for await (const chunk of process.stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
1431
- })();
1432
- collect.catch(() => {});
1433
- let timer;
1434
- const timeout = new Promise((resolve) => {
1435
- timer = setTimeout(() => {
1436
- process.stdin.destroy();
1437
- resolve();
1438
- }, STDIN_READ_TIMEOUT_MS$1);
1439
- });
1440
- try {
1441
- await Promise.race([collect, timeout]);
1442
- } finally {
1443
- if (timer) clearTimeout(timer);
1444
- }
1445
- return Buffer.concat(chunks).toString("utf8");
1446
- }
1447
- async function logCodexStopHookDecision(deps, rawInput, input, decision) {
1448
- try {
1449
- await deps.writeDebugLog?.({
1450
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1451
- rawInput,
1452
- input,
1453
- decision
1454
- });
1455
- } catch {}
1456
- }
1457
- async function writeStopHookDebugLog(filePath, entry) {
1458
- const entries = await readStopHookDebugLog(filePath);
1459
- entries.push(entry);
1460
- await writeCliTextFile(filePath, `${JSON.stringify(entries.slice(-50), null, 2)}\n`, true);
1461
- }
1462
- async function readStopHookDebugLog(filePath) {
1463
- try {
1464
- const parsed = JSON.parse(await readCliTextFile(filePath) ?? "");
1465
- return Array.isArray(parsed) ? parsed : [];
1466
- } catch {
1467
- return [];
1468
- }
1469
- }
1470
- /** Lines of a transcript before `endByteOffset`, read in bounded chunks so a long rollout never loads whole. */
1471
- async function* readTranscriptLines(transcriptPath, endByteOffset) {
1472
- const { fs, ioContext } = getCliWorkflowRuntime();
1473
- const reader = (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.openBinaryReader(transcriptPath, void 0, ioContext));
1474
- try {
1475
- const size = (0, _agimon_ai_po_core_platform.getOrThrow)(await reader.info(ioContext)).size;
1476
- const end = endByteOffset === void 0 ? size : Math.min(size, endByteOffset);
1477
- const decoder = new TextDecoder();
1478
- let pending = "";
1479
- for (let offset = 0; offset < end;) {
1480
- const chunk = (0, _agimon_ai_po_core_platform.getOrThrow)(await reader.read(offset, Math.min(TRANSCRIPT_READ_CHUNK_BYTES, end - offset), ioContext));
1481
- if (chunk.length === 0) break;
1482
- offset += chunk.length;
1483
- const lines = (pending + decoder.decode(chunk, { stream: true })).split("\n");
1484
- pending = lines.pop() ?? "";
1485
- yield* lines;
1486
- }
1487
- pending += decoder.decode();
1488
- if (pending) yield pending;
1489
- } finally {
1490
- await reader.close(ioContext);
1491
- }
1492
- }
1493
- async function readTranscriptHead(transcriptPath) {
1494
- return (await readTranscriptState(transcriptPath)).sessionMeta;
1495
- }
1496
- async function readTranscriptState(transcriptPath) {
1497
- const resolvedTranscriptPath = (0, node_path.resolve)(getCliWorkflowRuntime().cwd, transcriptPath);
1498
- const segments = await resolveTranscriptSegments(resolvedTranscriptPath);
1499
- const accumulator = {
1500
- activeItems: /* @__PURE__ */ new Set(),
1501
- agentStatuses: /* @__PURE__ */ new Map()
1502
- };
1503
- let sessionMeta = null;
1504
- for (const segment of segments) {
1505
- const segmentSessionMeta = await scanTranscriptSegment(segment, accumulator);
1506
- if (segment.path === resolvedTranscriptPath) sessionMeta = segmentSessionMeta;
1507
- }
1508
- return {
1509
- sessionMeta,
1510
- hasPendingWork: accumulator.activeItems.size > 0 || Array.from(accumulator.agentStatuses.values()).some(isInProgressStatus),
1511
- initialUserTurnId: accumulator.initialUserTurnId
1512
- };
1513
- }
1514
- async function readCodexTranscriptMetrics(transcriptPath) {
1515
- const segments = await resolveTranscriptSegments((0, node_path.resolve)(getCliWorkflowRuntime().cwd, transcriptPath));
1516
- const metrics = { toolSamples: [] };
1517
- let pendingToolNames = [];
1518
- for (const segment of segments) for await (const line of readTranscriptLines(segment.path, segment.endByteOffset)) {
1519
- const parsed = parseRolloutLine(line.trim());
1520
- const payload = parsed ? getRecordAtPath(parsed, ["payload"]) ?? getRecordAtPath(parsed, ["item", "payload"]) : null;
1521
- if (!payload) continue;
1522
- if (parsed?.type === "turn_context" && !metrics.model) metrics.model = stringValue(payload.model);
1523
- if (isCodexToolCall(payload)) {
1524
- const toolName = stringValue(payload.name) ?? stringValue(payload.tool_name);
1525
- if (toolName) pendingToolNames.push(toolName);
1526
- continue;
1527
- }
1528
- if (payload.type !== "token_count") continue;
1529
- const info = getRecordAtPath(payload, ["info"]);
1530
- const totalUsage = parseCodexTokenUsage(getRecordAtPath(info, ["total_token_usage"]));
1531
- const lastUsage = parseCodexTokenUsage(getRecordAtPath(info, ["last_token_usage"]));
1532
- if (totalUsage) metrics.totalUsage = totalUsage;
1533
- if (lastUsage && pendingToolNames.length > 0) {
1534
- const dividedUsage = divideCodexTokenUsage(lastUsage, pendingToolNames.length);
1535
- metrics.toolSamples.push(...pendingToolNames.map((toolName) => ({
1536
- toolName,
1537
- usage: dividedUsage
1538
- })));
1539
- pendingToolNames = [];
1540
- }
1541
- }
1542
- return metrics;
1543
- }
1544
- function isCodexToolCall(payload) {
1545
- return payload.type === "custom_tool_call" || payload.type === "function_call" || payload.type === "mcp_tool_call" || payload.type === "dynamic_tool_call";
1546
- }
1547
- function parseCodexTokenUsage(value) {
1548
- if (!value) return;
1549
- const numberValue = (key) => {
1550
- const raw = value[key];
1551
- return typeof raw === "number" && Number.isFinite(raw) ? raw : 0;
1552
- };
1553
- const inputTokens = numberValue("input_tokens");
1554
- const outputTokens = numberValue("output_tokens");
1555
- return {
1556
- inputTokens,
1557
- outputTokens,
1558
- totalTokens: numberValue("total_tokens") || inputTokens + outputTokens,
1559
- cachedInputTokens: numberValue("cached_input_tokens"),
1560
- reasoningOutputTokens: numberValue("reasoning_output_tokens")
1561
- };
1562
- }
1563
- function divideCodexTokenUsage(usage, divisor) {
1564
- const divide = (value) => Math.round(value / Math.max(1, divisor));
1565
- return {
1566
- inputTokens: divide(usage.inputTokens),
1567
- outputTokens: divide(usage.outputTokens),
1568
- totalTokens: divide(usage.totalTokens),
1569
- cachedInputTokens: divide(usage.cachedInputTokens),
1570
- reasoningOutputTokens: divide(usage.reasoningOutputTokens)
1571
- };
1572
- }
1573
- async function emitCodexTranscriptMetrics(transcriptPath) {
1574
- const metrics = await readCodexTranscriptMetrics(transcriptPath);
1575
- if (!metrics.totalUsage && metrics.toolSamples.length === 0) return;
1576
- const runtime = getCliWorkflowRuntime();
1577
- const telemetry = await (0, _agimon_ai_po_logsink_telemetry_node.createNodeTelemetry)({
1578
- packageName: "@agimon-ai/po-workflow",
1579
- serviceName: "codex",
1580
- workspaceRoot: runtime.cwd,
1581
- cwd: runtime.cwd,
1582
- env: { ...runtime.baseEnvironment }
1583
- });
1584
- const attributesForUsage = (usage) => ({
1585
- provider: "codex",
1586
- model: metrics.model ?? "unknown",
1587
- "gen_ai.usage.input_tokens": usage.inputTokens,
1588
- "gen_ai.usage.output_tokens": usage.outputTokens,
1589
- "gen_ai.usage.total_tokens": usage.totalTokens,
1590
- "gen_ai.usage.cache_read.input_tokens": usage.cachedInputTokens,
1591
- "gen_ai.usage.reasoning.output_tokens": usage.reasoningOutputTokens
1592
- });
1593
- if (metrics.totalUsage) telemetry.logger.info("codex.llm_usage", { attributes: attributesForUsage(metrics.totalUsage) });
1594
- for (const sample of metrics.toolSamples) telemetry.logger.info("codex.tool_token_sample", { attributes: {
1595
- ...attributesForUsage(sample.usage),
1596
- "codex.tool.name": sample.toolName,
1597
- "codex.token_attribution": "toolCallTurn",
1598
- "tool.name": sample.toolName
1599
- } });
1600
- await telemetry.flush();
1601
- await telemetry.shutdown();
1602
- }
1603
- async function resolveTranscriptSegments(transcriptPath) {
1604
- return resolveTranscriptSegmentsInner(transcriptPath, /* @__PURE__ */ new Set());
1605
- }
1606
- async function resolveTranscriptSegmentsInner(transcriptPath, visitedPaths, endByteOffset) {
1607
- if (visitedPaths.has(transcriptPath)) return [{
1608
- path: transcriptPath,
1609
- endByteOffset
1610
- }];
1611
- visitedPaths.add(transcriptPath);
1612
- const historyBase = parseHistoryBasePayload((await readTranscriptHeadFromFile(transcriptPath))?.history_base);
1613
- if (!historyBase?.thread_id) return [{
1614
- path: transcriptPath,
1615
- endByteOffset
1616
- }];
1617
- const baseTranscriptPath = await findRelatedTranscriptPath(transcriptPath, historyBase.thread_id);
1618
- if (!baseTranscriptPath) return [{
1619
- path: transcriptPath,
1620
- endByteOffset
1621
- }];
1622
- return [...await resolveTranscriptSegmentsInner(baseTranscriptPath, visitedPaths, historyBase.end_byte_offset), {
1623
- path: transcriptPath,
1624
- endByteOffset
1625
- }];
1626
- }
1627
- async function readTranscriptHeadFromFile(transcriptPath) {
1628
- try {
1629
- for await (const line of readTranscriptLines(transcriptPath)) {
1630
- const trimmed = line.trim();
1631
- if (trimmed.length === 0) continue;
1632
- const parsed = parseRolloutLine(trimmed);
1633
- if (!parsed) continue;
1634
- const sessionMeta = parseSessionMetaPayload(parsed);
1635
- if (sessionMeta) return sessionMeta;
1636
- }
1637
- } catch {
1638
- return null;
1639
- }
1640
- return null;
1641
- }
1642
- async function scanTranscriptSegment(segment, accumulator) {
1643
- if (segment.endByteOffset !== void 0 && segment.endByteOffset <= 0) return null;
1644
- let sessionMeta = null;
1645
- try {
1646
- for await (const line of readTranscriptLines(segment.path, segment.endByteOffset)) {
1647
- const trimmed = line.trim();
1648
- if (trimmed.length === 0) continue;
1649
- const parsed = parseRolloutLine(trimmed);
1650
- if (!parsed) continue;
1651
- if (!sessionMeta) sessionMeta = parseSessionMetaPayload(parsed);
1652
- if (!accumulator.initialUserTurnId) accumulator.initialUserTurnId = parseUserTurnId(parsed);
1653
- recordInProgressItem(parsed, accumulator.activeItems);
1654
- recordAgentStatus(parsed, accumulator.agentStatuses);
1655
- }
1656
- } catch {
1657
- return null;
1658
- }
1659
- return sessionMeta;
1660
- }
1661
- function parseRolloutLine(line) {
1662
- try {
1663
- const parsed = JSON.parse(line);
1664
- return isRecord$1(parsed) ? parsed : null;
1665
- } catch {
1666
- return null;
1667
- }
1668
- }
1669
- function parseSessionMetaPayload(parsed) {
1670
- if (parsed.type === SESSION_META_ITEM_TYPE && isSessionMetaPayload(parsed.payload)) return parsed.payload;
1671
- if (parsed.item?.type === SESSION_META_ITEM_TYPE && isSessionMetaPayload(parsed.item.payload)) return parsed.item.payload;
1672
- return null;
1673
- }
1674
- function isSessionMetaPayload(value) {
1675
- return isRecord$1(value);
1676
- }
1677
- function parseHistoryBasePayload(value) {
1678
- if (!isRecord$1(value)) return null;
1679
- return {
1680
- end_byte_offset: typeof value.end_byte_offset === "number" ? value.end_byte_offset : void 0,
1681
- thread_id: typeof value.thread_id === "string" && value.thread_id.length > 0 ? value.thread_id : void 0
1682
- };
1683
- }
1684
- async function findRelatedTranscriptPath(currentTranscriptPath, threadId) {
1685
- const currentDir = (0, node_path.dirname)(currentTranscriptPath);
1686
- const currentDirMatch = await findTranscriptPathInDirectory(currentDir, threadId);
1687
- if (currentDirMatch) return currentDirMatch;
1688
- const sessionsRoot = findSessionsRoot(currentTranscriptPath) ?? currentDir;
1689
- if (sessionsRoot === currentDir) return null;
1690
- return findTranscriptPathUnderRoot(sessionsRoot, threadId);
1691
- }
1692
- async function findTranscriptPathInDirectory(directory, threadId) {
1693
- const { fs, ioContext } = getCliWorkflowRuntime();
1694
- try {
1695
- const match = (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.listDir(directory, ioContext)).find((entry) => entry.kind === "file" && isPlainTranscriptFileForThread(entry.name, threadId));
1696
- return match ? (0, node_path.join)(directory, match.name) : null;
1697
- } catch {
1698
- return null;
1699
- }
1700
- }
1701
- async function findTranscriptPathUnderRoot(root, threadId) {
1702
- const { fs, ioContext } = getCliWorkflowRuntime();
1703
- const queue = [root];
1704
- let visitedEntries = 0;
1705
- while (queue.length > 0 && visitedEntries < MAX_TRANSCRIPT_PATH_SEARCH_ENTRIES) {
1706
- const directory = queue.shift();
1707
- if (!directory) continue;
1708
- try {
1709
- const entries = (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.listDir(directory, ioContext));
1710
- for (const entry of entries) {
1711
- visitedEntries += 1;
1712
- if (visitedEntries > MAX_TRANSCRIPT_PATH_SEARCH_ENTRIES) return null;
1713
- const entryPath = (0, node_path.join)(directory, entry.name);
1714
- if (entry.kind === "file" && isPlainTranscriptFileForThread(entry.name, threadId)) return entryPath;
1715
- if (entry.kind === "directory") queue.push(entryPath);
1716
- }
1717
- } catch {
1718
- continue;
1719
- }
1720
- }
1721
- return null;
1722
- }
1723
- function findSessionsRoot(transcriptPath) {
1724
- let directory = (0, node_path.dirname)((0, node_path.resolve)(transcriptPath));
1725
- while ((0, node_path.dirname)(directory) !== directory) {
1726
- if ((0, node_path.basename)(directory) === "sessions") return directory;
1727
- directory = (0, node_path.dirname)(directory);
1728
- }
1729
- return null;
1730
- }
1731
- function isPlainTranscriptFileForThread(fileName, threadId) {
1732
- return fileName.endsWith(`-${threadId}.jsonl`);
1733
- }
1734
- function parseUserTurnId(parsed) {
1735
- const payload = getRecordAtPath(parsed, ["payload"]) ?? getRecordAtPath(parsed, ["item", "payload"]);
1736
- if (!payload) return;
1737
- const completedItemType = stringValue(getRecordAtPath(payload, ["item"])?.type);
1738
- if (payload.type === "item_completed" && completedItemType && USER_MESSAGE_ITEM_TYPES.has(completedItemType)) return stringValue(payload.turn_id);
1739
- if (payload.type !== "message" || payload.role !== "user") return;
1740
- return stringValue(getRecordAtPath(payload, ["internal_chat_message_metadata_passthrough"])?.turn_id);
1741
- }
1742
- function recordInProgressItem(parsed, activeItems) {
1743
- const item = getRecordAtPath(parsed, ["payload", "item"]) ?? getRecordAtPath(parsed, [
1744
- "item",
1745
- "payload",
1746
- "item"
1747
- ]);
1748
- if (!item) return;
1749
- const itemId = stringValue(item.id);
1750
- const itemType = stringValue(item.type);
1751
- if (!itemId || !itemType || !TRACKED_IN_PROGRESS_ITEM_TYPES.has(itemType)) return;
1752
- if (isInProgressStatus(item.status)) activeItems.add(itemId);
1753
- else activeItems.delete(itemId);
1754
- }
1755
- function recordAgentStatus(parsed, agentStatuses) {
1756
- const payload = getRecordAtPath(parsed, ["payload"]) ?? getRecordAtPath(parsed, ["item", "payload"]);
1757
- if (!payload) return;
1758
- const item = getRecordAtPath(payload, ["item"]) ?? getRecordAtPath(parsed, ["payload", "item"]);
1759
- const itemType = stringValue(item?.type);
1760
- if (itemType && COLLAB_AGENT_TOOL_CALL_ITEM_TYPES.has(itemType)) {
1761
- recordAgentStatusesObject(agentStatuses, getRecordAtPath(item, ["agents_states"]));
1762
- recordAgentStatusesObject(agentStatuses, getRecordAtPath(item, ["agentsStates"]));
1763
- }
1764
- if (!stringValue(payload.type)?.startsWith("collab_")) return;
1765
- recordSingleAgentStatus(agentStatuses, stringValue(payload.new_thread_id), payload.status);
1766
- recordSingleAgentStatus(agentStatuses, stringValue(payload.receiver_thread_id), payload.status);
1767
- const statuses = getRecordAtPath(payload, ["statuses"]);
1768
- if (statuses) for (const [agentId, status] of Object.entries(statuses)) recordSingleAgentStatus(agentStatuses, agentId, status);
1769
- }
1770
- function recordAgentStatusesObject(agentStatuses, statuses) {
1771
- if (!statuses) return;
1772
- for (const [agentId, status] of Object.entries(statuses)) recordSingleAgentStatus(agentStatuses, agentId, status);
1773
- }
1774
- function recordSingleAgentStatus(agentStatuses, agentId, status) {
1775
- const statusValue = agentStatusValue(status);
1776
- if (!agentId || !statusValue) return;
1777
- agentStatuses.set(agentId, statusValue);
1778
- }
1779
- function agentStatusValue(status) {
1780
- if (typeof status === "string") return status;
1781
- if (!isRecord$1(status)) return null;
1782
- const [variant] = Object.keys(status);
1783
- return variant ?? null;
1784
- }
1785
- function isInProgressStatus(status) {
1786
- const value = typeof status === "string" ? status : agentStatusValue(status);
1787
- return value !== null && IN_PROGRESS_STATUSES.has(value);
1788
- }
1789
- function getRecordAtPath(value, path) {
1790
- let current = value;
1791
- for (const key of path) {
1792
- if (!isRecord$1(current)) return null;
1793
- current = current[key];
330
+ //#region src/models/WorkflowCommandError.ts
331
+ /**
332
+ * Structured error raised by workflow CLI commands.
333
+ */
334
+ var WorkflowCommandError = class extends Error {
335
+ code;
336
+ context;
337
+ constructor(message, code, context = {}, options) {
338
+ super(message, options);
339
+ this.code = code;
340
+ this.context = context;
341
+ this.name = "WorkflowCommandError";
1794
342
  }
1795
- return isRecord$1(current) ? current : null;
1796
- }
1797
- function stringValue(value) {
1798
- return typeof value === "string" && value.length > 0 ? value : void 0;
1799
- }
1800
- const codexSessionStartHookCommand = new commander.Command("codex-session-start-hook").description(`Codex session-start hook: binds ${STATUS_FILE_ENV_KEY} to the first workflow Codex session id`).action(async () => {
1801
- await runCodexSessionStartHook();
1802
- });
1803
- const codexStopHookCommand = new commander.Command("codex-stop-hook").description(`Codex stop hook: reads stop-hook JSON on stdin and marks ${STATUS_FILE_ENV_KEY} when the root session ends`).action(async () => {
1804
- await runCodexStopHook();
1805
- });
343
+ };
1806
344
  //#endregion
1807
345
  //#region src/bin/workflowCommands/controlWorkflow.ts
1808
346
  function createControlCommand(action, name, description) {
@@ -2285,6 +823,7 @@ const KEEP_WORKTREE_OPTION = "--keep-worktree";
2285
823
  const RUNNER_OPTION = "--runner";
2286
824
  const COMMAND_OPTION = "--command";
2287
825
  const CHOICE_OPTION = "--choice";
826
+ const PROFILE_OPTION = "--profile";
2288
827
  const LAUNCHER_OPTION = "--launcher";
2289
828
  const STATUS_FILE_OPTION = "--status-file";
2290
829
  const BACKGROUND_OPTION_DESCRIPTION = "Run the workflow in a detached background process";
@@ -2303,12 +842,7 @@ function parseKeyValueEntries(entries) {
2303
842
  return Object.keys(values).length > 0 ? values : void 0;
2304
843
  }
2305
844
  function resolveRunnerOption(options) {
2306
- if (options.runner && options.cliAgent && options.runner !== options.cliAgent) throw new WorkflowCommandError("Conflicting runner selectors.", RUN_WORKFLOW_COMMAND_ERROR_CODE, {
2307
- cliAgent: options.cliAgent,
2308
- command: RUN_WORKFLOW_COMMAND_NAME,
2309
- runner: options.runner
2310
- });
2311
- return options.runner ?? options.cliAgent;
845
+ return options.runner;
2312
846
  }
2313
847
  function launchDetachedRun(workflow, options) {
2314
848
  const { baseEnvironment, cwd, workflowHost } = getCliWorkflowRuntime();
@@ -2333,6 +867,7 @@ function launchDetachedRun(workflow, options) {
2333
867
  if (runner) args.push(RUNNER_OPTION, runner);
2334
868
  if (options.command) args.push(COMMAND_OPTION, options.command);
2335
869
  if (options.choice) args.push(CHOICE_OPTION, options.choice);
870
+ if (options.profile) args.push(PROFILE_OPTION, options.profile);
2336
871
  if (options.prompt) args.push(PROMPT_OPTION, options.prompt);
2337
872
  if (options.launcher) args.push(LAUNCHER_OPTION, options.launcher);
2338
873
  if (options.name) args.push(NAME_OPTION, options.name);
@@ -2373,9 +908,10 @@ async function registerBackgroundChild(workflow, options) {
2373
908
  workspace: options.workspace,
2374
909
  job: options.job,
2375
910
  name: options.name,
2376
- runner: options.runner ?? options.cliAgent,
911
+ runner: options.runner,
2377
912
  command: options.command,
2378
913
  choice: options.choice,
914
+ profile: options.profile,
2379
915
  statusFile: options.statusFile
2380
916
  },
2381
917
  force: true
@@ -2401,7 +937,7 @@ function createRunWorkflowCommand(dependencies = {}) {
2401
937
  const registerBackgroundChildRelease = dependencies.registerBackgroundChild ?? registerBackgroundChild;
2402
938
  const logError = dependencies.logError ?? ((message, error) => console.error(message, error));
2403
939
  const logInfo = dependencies.logInfo ?? ((message) => process.stdout.write(`${message}\n`));
2404
- return new commander.Command(RUN_WORKFLOW_COMMAND_NAME).description(RUN_WORKFLOW_COMMAND_DESCRIPTION).argument("<workflow>", "Path to the workflow YAML file").option("-j, --job <name>", "Run only this job (and its dependencies)").option("-i, --input <key=value...>", "Set workflow_dispatch input (repeatable)").option("-e, --env <key=value...>", "Set extra environment variable (repeatable)").option("--secret-file <path>", "Load secrets from a dotenv-style file").option("--dry-run", "Print steps without executing").option("--continue-on-error", "Continue past step failures").option("--runner <runner>", "Preferred runner key for step command maps").option("--command <name>", "Command templated interactiveRun steps run through (default: each step's first)").option("--choice <name>", "Model choice for steps that do not pin one (default: the choice named \"default\")").addOption(new commander.Option("--launcher <launcher>", "Terminal launcher").choices(["cmux", "tmux"])).option("--cli-agent <agent>", "Deprecated alias for --runner").option("-p, --prompt <text>", "User prompt for user_prompt trigger workflows").option("-n, --name <name>", "Name for the workflow run context directory").option("-w, --workspace <name>", "Workspace for workflow registry storage").option("--keep-worktree", "Keep worktree on completion (skip merge and cleanup for retry)").option("--status-file <path>", "Write terminal workflow run JSON to this file after completion").option("--skip-launch", "Skip launch-command delegation (used by inner invocations)").option("-b, --background", BACKGROUND_OPTION_DESCRIPTION).action(async (workflow, options) => {
940
+ return new commander.Command(RUN_WORKFLOW_COMMAND_NAME).description(RUN_WORKFLOW_COMMAND_DESCRIPTION).argument("<workflow>", "Path to the workflow YAML file").option("-j, --job <name>", "Run only this job (and its dependencies)").option("-i, --input <key=value...>", "Set workflow_dispatch input (repeatable)").option("-e, --env <key=value...>", "Set extra environment variable (repeatable)").option("--secret-file <path>", "Load secrets from a dotenv-style file").option("--dry-run", "Print steps without executing").option("--continue-on-error", "Continue past step failures").option("--runner <runner>", "Preferred runner key for step command maps").option("--command <name>", "Command templated interactiveRun steps run through (default: each step's first)").option("--choice <name>", "Model choice for steps that do not pin one (default: the choice named \"default\")").option("--profile <name>", "Po profile whose secrets run steps declaring `secrets` receive").addOption(new commander.Option("--launcher <launcher>", "Terminal launcher").choices(["cmux", "tmux"])).option("-p, --prompt <text>", "User prompt for user_prompt trigger workflows").option("-n, --name <name>", "Name for the workflow run context directory").option("-w, --workspace <name>", "Workspace for workflow registry storage").option("--keep-worktree", "Keep worktree on completion (skip merge and cleanup for retry)").option("--status-file <path>", "Write terminal workflow run JSON to this file after completion").option("--skip-launch", "Skip launch-command delegation (used by inner invocations)").option("-b, --background", BACKGROUND_OPTION_DESCRIPTION).action(async (workflow, options) => {
2405
941
  try {
2406
942
  const normalizedOptions = {
2407
943
  ...options,
@@ -2419,10 +955,10 @@ function createRunWorkflowCommand(dependencies = {}) {
2419
955
  try {
2420
956
  const runner = resolveRunnerOption(normalizedOptions);
2421
957
  const result = await service.run({
2422
- cliAgent: normalizedOptions.cliAgent,
2423
958
  runner,
2424
959
  command: normalizedOptions.command,
2425
960
  choice: normalizedOptions.choice,
961
+ profile: normalizedOptions.profile,
2426
962
  workflowPath: workflow,
2427
963
  job: normalizedOptions.job,
2428
964
  inputs: parseKeyValueEntries(normalizedOptions.input),
@@ -2460,7 +996,6 @@ const runWorkflowCommand = createRunWorkflowCommand();
2460
996
  //#endregion
2461
997
  //#region src/bin/workflowCommands/step.ts
2462
998
  const DECISION_ERROR_EXIT_CODE = 1;
2463
- const STDIN_READ_TIMEOUT_MS = 1e3;
2464
999
  const DECISION_FILE_FLAGS = "--decision-file <path>";
2465
1000
  const DECISION_FILE_DESCRIPTION = `The step's decision file, named in its instructions (default: $${require_RecoverWorkflowService.WORKFLOW_DECISION_FILE_ENV})`;
2466
1001
  async function reasonFrom(runtime, options) {
@@ -2468,28 +1003,10 @@ async function reasonFrom(runtime, options) {
2468
1003
  if (!reason?.trim()) throw new Error("Give a reason with --reason <text> or --reason-file <path>.");
2469
1004
  return reason.trim();
2470
1005
  }
2471
- /** Hook runners write their payload on stdin; read it so they never hit a closed pipe. */
2472
- async function drainStdin() {
2473
- if (process.stdin.isTTY) return;
2474
- const drained = (async () => {
2475
- for await (const _chunk of process.stdin);
2476
- })();
2477
- drained.catch(() => {});
2478
- let timer;
2479
- await Promise.race([drained, new Promise((resolve) => {
2480
- timer = setTimeout(() => {
2481
- process.stdin.destroy();
2482
- resolve();
2483
- }, STDIN_READ_TIMEOUT_MS);
2484
- })]);
2485
- if (timer) clearTimeout(timer);
2486
- }
2487
1006
  function createStepCommand(dependencies = {}) {
2488
1007
  const runtime = dependencies.runtime ?? getCliWorkflowRuntime();
2489
1008
  const env = dependencies.env ?? runtime.baseEnvironment;
2490
1009
  const exit = dependencies.exit ?? ((code) => process.exit(code));
2491
- const readStdin = dependencies.readStdin ?? drainStdin;
2492
- const writeStdout = dependencies.writeStdout ?? ((message) => process.stdout.write(message));
2493
1010
  const writeStderr = dependencies.writeStderr ?? ((message) => process.stderr.write(message));
2494
1011
  const record = async (options, decision, done) => {
2495
1012
  try {
@@ -2522,14 +1039,6 @@ function createStepCommand(dependencies = {}) {
2522
1039
  reason: await reasonFrom(runtime, options)
2523
1040
  }), "Recorded: step failed. You can stop now.");
2524
1041
  });
2525
- command.command("stop-hook").description("Stop hook: refuse the stop while the step still needs a decision (prints a block decision)").action(async () => {
2526
- await readStdin();
2527
- const gate = await require_RecoverWorkflowService.gateStepDecision(runtime, env);
2528
- if (gate.action === "block") writeStdout(`${JSON.stringify({
2529
- decision: "block",
2530
- reason: gate.message
2531
- })}\n`);
2532
- });
2533
1042
  return command;
2534
1043
  }
2535
1044
  const stepCommand = createStepCommand();
@@ -2616,14 +1125,7 @@ async function main() {
2616
1125
  program.addCommand(launchProcessCommand);
2617
1126
  program.addCommand(hostRunCommand);
2618
1127
  program.addCommand(inspectWorkflowCommand);
2619
- program.addCommand(checkCodexQuotaCommand);
2620
1128
  program.addCommand(closeLauncherCommand);
2621
- program.addCommand(antigravityStopHookCommand);
2622
- program.addCommand(claudeSessionStartHookCommand);
2623
- program.addCommand(claudeStopHookCommand);
2624
- program.addCommand(claudeNotificationHookCommand);
2625
- program.addCommand(codexSessionStartHookCommand);
2626
- program.addCommand(codexStopHookCommand);
2627
1129
  program.addCommand(describeRunCommand);
2628
1130
  program.addCommand(doctorCommand);
2629
1131
  program.addCommand(pauseWorkflowCommand);