@thaodangspace/argos 0.1.2 → 0.1.5

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 (106) hide show
  1. package/README.md +4 -4
  2. package/dist/args.d.ts.map +1 -1
  3. package/dist/args.js +5 -1
  4. package/dist/args.js.map +1 -1
  5. package/dist/commands/chart.d.ts +21 -0
  6. package/dist/commands/chart.d.ts.map +1 -0
  7. package/dist/commands/chart.js +209 -0
  8. package/dist/commands/chart.js.map +1 -0
  9. package/dist/commands/doctor.d.ts +34 -1
  10. package/dist/commands/doctor.d.ts.map +1 -1
  11. package/dist/commands/doctor.js +181 -4
  12. package/dist/commands/doctor.js.map +1 -1
  13. package/dist/commands/hc.d.ts +16 -0
  14. package/dist/commands/hc.d.ts.map +1 -0
  15. package/dist/commands/hc.js +689 -0
  16. package/dist/commands/hc.js.map +1 -0
  17. package/dist/commands/rex-agents.d.ts +26 -0
  18. package/dist/commands/rex-agents.d.ts.map +1 -0
  19. package/dist/commands/rex-agents.js +505 -0
  20. package/dist/commands/rex-agents.js.map +1 -0
  21. package/dist/commands/runs.d.ts.map +1 -1
  22. package/dist/commands/runs.js +5 -1
  23. package/dist/commands/runs.js.map +1 -1
  24. package/dist/commands/schedule.d.ts.map +1 -1
  25. package/dist/commands/schedule.js +2 -1
  26. package/dist/commands/schedule.js.map +1 -1
  27. package/dist/commands/serve.d.ts +170 -10
  28. package/dist/commands/serve.d.ts.map +1 -1
  29. package/dist/commands/serve.js +291 -49
  30. package/dist/commands/serve.js.map +1 -1
  31. package/dist/main.d.ts.map +1 -1
  32. package/dist/main.js +9 -0
  33. package/dist/main.js.map +1 -1
  34. package/dist/output.d.ts +1 -1
  35. package/dist/output.d.ts.map +1 -1
  36. package/dist/output.js +14 -4
  37. package/dist/output.js.map +1 -1
  38. package/dist/packs/apply.d.ts +36 -0
  39. package/dist/packs/apply.d.ts.map +1 -0
  40. package/dist/packs/apply.js +103 -0
  41. package/dist/packs/apply.js.map +1 -0
  42. package/dist/packs/bundled.d.ts +27 -0
  43. package/dist/packs/bundled.d.ts.map +1 -0
  44. package/dist/packs/bundled.js +42 -0
  45. package/dist/packs/bundled.js.map +1 -0
  46. package/dist/packs/pack.d.ts +142 -0
  47. package/dist/packs/pack.d.ts.map +1 -0
  48. package/dist/packs/pack.js +204 -0
  49. package/dist/packs/pack.js.map +1 -0
  50. package/dist/packs/plan.d.ts +123 -0
  51. package/dist/packs/plan.d.ts.map +1 -0
  52. package/dist/packs/plan.js +307 -0
  53. package/dist/packs/plan.js.map +1 -0
  54. package/dist/packs/templates-dir.d.ts +29 -0
  55. package/dist/packs/templates-dir.d.ts.map +1 -0
  56. package/dist/packs/templates-dir.js +49 -0
  57. package/dist/packs/templates-dir.js.map +1 -0
  58. package/package.json +4 -2
  59. package/templates/packs/claude/claude-step.mjs +666 -0
  60. package/templates/packs/claude/pack.json +38 -0
  61. package/templates/packs/smoke/pack.json +20 -0
  62. package/templates/packs/smoke/smoke.mjs +104 -0
  63. package/ui/_app/immutable/assets/0.CUSoXXAe.css +1 -0
  64. package/ui/_app/immutable/chunks/7kS98abs.js +1 -0
  65. package/ui/_app/immutable/chunks/BQUxoyXx.js +1 -0
  66. package/ui/_app/immutable/chunks/BVvEKWUw.js +1 -0
  67. package/ui/_app/immutable/chunks/BcmE4Pmo.js +2 -0
  68. package/ui/_app/immutable/chunks/BeleWrn1.js +5 -0
  69. package/ui/_app/immutable/chunks/CJuNNExc.js +1 -0
  70. package/ui/_app/immutable/chunks/CSzwgvai.js +55 -0
  71. package/ui/_app/immutable/chunks/CrMz2YMe.js +1 -0
  72. package/ui/_app/immutable/chunks/DK3Fl9T5.js +1 -0
  73. package/ui/_app/immutable/chunks/DR13iyEP.js +3 -0
  74. package/ui/_app/immutable/chunks/DxF9htzl.js +1 -0
  75. package/ui/_app/immutable/chunks/KjnrVwp0.js +4 -0
  76. package/ui/_app/immutable/chunks/Ta9EVp1m.js +1 -0
  77. package/ui/_app/immutable/chunks/UEYpU5e_.js +1 -0
  78. package/ui/_app/immutable/chunks/XmWYLfMV.js +1 -0
  79. package/ui/_app/immutable/entry/app.fpTlr2bV.js +2 -0
  80. package/ui/_app/immutable/entry/start.CmdXdr1Q.js +2 -0
  81. package/ui/_app/immutable/nodes/0.CexwxgPf.js +1 -0
  82. package/ui/_app/immutable/nodes/1.CXvw6Lx4.js +1 -0
  83. package/ui/_app/immutable/nodes/2.CVRWg4vc.js +2 -0
  84. package/ui/_app/immutable/nodes/3.Te_SG5Lg.js +1 -0
  85. package/ui/_app/immutable/nodes/4.9tMyBzuY.js +3 -0
  86. package/ui/_app/immutable/nodes/5.G4bzLcKA.js +1 -0
  87. package/ui/_app/version.json +1 -1
  88. package/ui/build.json +3 -3
  89. package/ui/index.html +23 -18
  90. package/ui/_app/immutable/assets/0.Y-Ej83kR.css +0 -1
  91. package/ui/_app/immutable/assets/2.D2FEqQBh.css +0 -1
  92. package/ui/_app/immutable/assets/3.CI7aeD9i.css +0 -1
  93. package/ui/_app/immutable/assets/StartRunDialog.BbbZvJfB.css +0 -1
  94. package/ui/_app/immutable/assets/runs.CU5wtnW2.css +0 -1
  95. package/ui/_app/immutable/chunks/BKHbyffl.js +0 -3
  96. package/ui/_app/immutable/chunks/BeG5AxKI.js +0 -3
  97. package/ui/_app/immutable/chunks/Buwi_lQz.js +0 -2
  98. package/ui/_app/immutable/chunks/CV2Ptlrp.js +0 -1
  99. package/ui/_app/immutable/chunks/CtbaNJav.js +0 -1
  100. package/ui/_app/immutable/chunks/D8sQwgC_.js +0 -55
  101. package/ui/_app/immutable/entry/app.DPg5reEl.js +0 -2
  102. package/ui/_app/immutable/entry/start.iWBP-EvH.js +0 -2
  103. package/ui/_app/immutable/nodes/0.Cu8SyVzm.js +0 -1
  104. package/ui/_app/immutable/nodes/1.Bga_qdeZ.js +0 -1
  105. package/ui/_app/immutable/nodes/2.CKNrkmzJ.js +0 -1
  106. package/ui/_app/immutable/nodes/3.OrFQ8OoI.js +0 -1
@@ -0,0 +1,666 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * One argos agent step on herdr-core (`executor: hc`): a single headless Claude Code run.
4
+ *
5
+ * hc starts this program as a template command in a fresh terminal (the run's cwd) and, once the
6
+ * program reports `idle` through OSC 7501, types the step prompt in as the template's first
7
+ * message. Then:
8
+ *
9
+ * 1. Read the prompt. `--prompt-file` is the non-tty entry point (tests, `hc exec`, rehearsal);
10
+ * on a real terminal the read is raw + bracketed-paste, with a quiet-gap fallback for an hc
11
+ * that types the text raw. Nothing is echoed, so the prompt never lands on the screen argos
12
+ * reads later.
13
+ * 2. Run `claude -p` with the model / effort / permission mode given on the command line, printing
14
+ * one short line per tool call and per assistant text block, so `hc attach --observe <terminal>`
15
+ * shows progress.
16
+ * 3. Quota: argos's `providers.on_exhausted` only works on Paseo, and on hc a failed step is
17
+ * retried after 1s/2s/4s, which would end a long loop. So a Claude usage limit is waited out
18
+ * here (until the reset time when Claude gives one, else every --quota-retry, at most
19
+ * --quota-max-wait), then the prompt runs again in a new session. The terminal stays `working`
20
+ * while it waits.
21
+ * 4. Clear the screen and scrollback and print only Claude's final message: argos reads the step's
22
+ * declared outputs from that screen (one fenced ```json block). Report done, exit 0. Any
23
+ * failure exits non-zero (argos: step_failed, then the step's own `retries`).
24
+ *
25
+ * argos records no usage for hc steps, so each run appends one line to
26
+ * $XDG_STATE_HOME/argos-hc/claude-step.log (else ~/.local/state/argos-hc/claude-step.log): time,
27
+ * cwd, hc terminal, session, cost, how it ended.
28
+ *
29
+ * Standalone by contract (FR5): imports only `node:*`, reads no ARGOS_* name, and resolves the
30
+ * user's PATH itself because hc starts it from its own minimal environment. Node >= 22.13.
31
+ */
32
+
33
+ import { execFile, spawn } from "node:child_process";
34
+ import { appendFileSync, accessSync, constants, mkdirSync, readFileSync, writeSync } from "node:fs";
35
+ import { homedir } from "node:os";
36
+ import { delimiter, dirname, join } from "node:path";
37
+
38
+ /** ECMA-48 OSC: `ESC ] 7501 ; state=<word> ST`. hc parses the root record and reports the word. */
39
+ const OSC_END = "\u001b\\";
40
+ const PASTE_START = Buffer.from("\u001b[200~");
41
+ const PASTE_END = Buffer.from("\u001b[201~");
42
+ /** Without bracketed paste (an hc that types the text raw), the prompt ends after this much quiet. */
43
+ const QUIET_MS = 2_000;
44
+ const CLEAR = "\u001b[3J\u001b[H\u001b[2J";
45
+ const KILL_GRACE_MS = 10_000;
46
+ const PATH_PROBE_TIMEOUT_MS = 5_000;
47
+ const QUOTA_TEXT =
48
+ /usage limit|hit your limit|limit reached|rate.?limit|out of (extra )?usage|resets? at|resets \d/i;
49
+ const KNOWN_OPTIONS = new Set([
50
+ "model",
51
+ "effort",
52
+ "permission-mode",
53
+ "work-timeout",
54
+ "quota-retry",
55
+ "quota-max-wait",
56
+ "claude",
57
+ "prompt-file",
58
+ "log",
59
+ ]);
60
+
61
+ let currentChild = null;
62
+ let terminating = false;
63
+
64
+ // ------------------------------------------------------------------ screen
65
+
66
+ function write(text) {
67
+ writeSync(1, text);
68
+ }
69
+
70
+ function writeStderr(text) {
71
+ try {
72
+ writeSync(2, `${text}\n`);
73
+ } catch {
74
+ // A closed stderr must never abort the run.
75
+ }
76
+ }
77
+
78
+ function reportState(state) {
79
+ write(`\u001b]7501;state=${state}${OSC_END}`);
80
+ }
81
+
82
+ function say(line) {
83
+ write(`${line}\n`);
84
+ }
85
+
86
+ function oneLine(text, width = 180) {
87
+ // Fences are rewritten so a progress line can never look like the final result to argos.
88
+ const cleaned = String(text ?? "")
89
+ .replace(/[\u0000-\u001f\u007f]+/g, " ")
90
+ .replaceAll("```", "'''")
91
+ .trim();
92
+ return cleaned.length <= width ? cleaned : `${cleaned.slice(0, width - 1)}…`;
93
+ }
94
+
95
+ // ------------------------------------------------------------------ arguments
96
+
97
+ class UsageError extends Error {}
98
+
99
+ function parseArgs(argv) {
100
+ const values = new Map();
101
+ for (let index = 0; index < argv.length; index += 1) {
102
+ const item = argv[index];
103
+ if (!item.startsWith("--")) throw new UsageError(`unexpected argument ${JSON.stringify(item)}`);
104
+ let name = item.slice(2);
105
+ let value;
106
+ const equals = name.indexOf("=");
107
+ if (equals !== -1) {
108
+ value = name.slice(equals + 1);
109
+ name = name.slice(0, equals);
110
+ } else {
111
+ value = argv[index + 1];
112
+ if (value === undefined) throw new UsageError(`--${name} needs a value`);
113
+ index += 1;
114
+ }
115
+ if (!KNOWN_OPTIONS.has(name)) throw new UsageError(`unknown option --${name}`);
116
+ values.set(name, value);
117
+ }
118
+ return values;
119
+ }
120
+
121
+ /** Durations are `<n>[s|m|h]`, exactly as the Python program accepted them. */
122
+ function duration(text, name) {
123
+ const match = /^(\d+)([smh])?$/.exec(String(text).trim());
124
+ if (!match) throw new UsageError(`${name}: expected <n>[s|m|h], got ${JSON.stringify(text)}`);
125
+ const unit = match[2] ?? "s";
126
+ const scale = unit === "h" ? 3_600_000 : unit === "m" ? 60_000 : 1_000;
127
+ return Number(match[1]) * scale;
128
+ }
129
+
130
+ function parseOptions(argv) {
131
+ const values = parseArgs(argv);
132
+ const model = values.get("model");
133
+ if (!model) throw new UsageError("--model is required");
134
+ return {
135
+ model,
136
+ effort: values.get("effort"),
137
+ permissionMode: values.get("permission-mode") ?? "auto",
138
+ workTimeoutMs: duration(values.get("work-timeout") ?? "60m", "--work-timeout"),
139
+ quotaRetryMs: duration(values.get("quota-retry") ?? "30m", "--quota-retry"),
140
+ quotaMaxWaitMs: duration(values.get("quota-max-wait") ?? "8h", "--quota-max-wait"),
141
+ claude: values.get("claude"),
142
+ promptFile: values.get("prompt-file"),
143
+ log: values.get("log"),
144
+ };
145
+ }
146
+
147
+ // ------------------------------------------------------------------ prompt
148
+
149
+ function normalizePrompt(input) {
150
+ const text = Buffer.isBuffer(input) ? input.toString("utf8") : String(input);
151
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").trim();
152
+ }
153
+
154
+ async function readStdin() {
155
+ const chunks = [];
156
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
157
+ return normalizePrompt(Buffer.concat(chunks));
158
+ }
159
+
160
+ /**
161
+ * Raw-mode read for the real hc terminal: no echo (the prompt must never reach the screen argos
162
+ * parses later), bracketed paste when hc sends one, and a quiet-gap fallback when hc types raw.
163
+ */
164
+ function readTerminal() {
165
+ const stdin = process.stdin;
166
+ stdin.setRawMode(true);
167
+ stdin.resume();
168
+ return new Promise((resolve) => {
169
+ let buffer = Buffer.alloc(0);
170
+ let quiet = null;
171
+ const finish = (text) => {
172
+ if (quiet !== null) clearTimeout(quiet);
173
+ stdin.off("data", onData);
174
+ stdin.off("end", onEnd);
175
+ stdin.setRawMode(false);
176
+ stdin.pause();
177
+ write("\u001b[?2004l");
178
+ resolve(normalizePrompt(Buffer.from(text)));
179
+ };
180
+ const onEnd = () => finish(buffer);
181
+ const onData = (chunk) => {
182
+ buffer = Buffer.concat([buffer, chunk]);
183
+ const start = buffer.indexOf(PASTE_START);
184
+ if (start !== -1) {
185
+ // A paste has begun, so only its end marker finishes the read: a quiet gap armed before the
186
+ // marker arrived must never fire on the raw buffer, or the prompt is truncated at the gap
187
+ // and keeps the `ESC[200~` framing bytes.
188
+ if (quiet !== null) {
189
+ clearTimeout(quiet);
190
+ quiet = null;
191
+ }
192
+ const end = buffer.indexOf(PASTE_END, start + PASTE_START.length);
193
+ if (end !== -1) {
194
+ finish(buffer.subarray(start + PASTE_START.length, end));
195
+ return;
196
+ }
197
+ } else {
198
+ if (quiet !== null) clearTimeout(quiet);
199
+ quiet = setTimeout(() => finish(buffer), QUIET_MS);
200
+ }
201
+ };
202
+ stdin.on("data", onData);
203
+ stdin.on("end", onEnd);
204
+ });
205
+ }
206
+
207
+ /**
208
+ * Report `idle` **before** the first read: hc delivers a template's first message only after the
209
+ * program says it is ready, so the idle report is what makes the prompt arrive at all. Bracketed
210
+ * paste is enabled first so that message is framed for {@link readTerminal}.
211
+ */
212
+ async function readPrompt(promptFile) {
213
+ if (promptFile !== undefined) {
214
+ reportState("idle");
215
+ if (promptFile === "-") return readStdin();
216
+ return normalizePrompt(readFileSync(promptFile, "utf8"));
217
+ }
218
+ if (process.stdin.isTTY) {
219
+ write("\u001b[?2004h");
220
+ reportState("idle");
221
+ return readTerminal();
222
+ }
223
+ reportState("idle");
224
+ return readStdin();
225
+ }
226
+
227
+ // ------------------------------------------------------------------ environment
228
+
229
+ /**
230
+ * The core runs under launchd (PATH=/usr/bin:/bin:…), and argos passes no env: take the PATH of
231
+ * the user's interactive login shell so claude, its Bash tool and the step scripts find node, gh,
232
+ * … as in a normal terminal. The probe runs detached so an rc file cannot draw on this screen.
233
+ */
234
+ function userPath(inheritedPath) {
235
+ const shell = process.env["SHELL"] || "/bin/sh";
236
+ return new Promise((resolve) => {
237
+ const fallback = () => resolve(inheritedPath);
238
+ try {
239
+ execFile(
240
+ shell,
241
+ ["-lic", 'printf __ARGOS_PATH__=%s "$PATH"'],
242
+ {
243
+ detached: true,
244
+ timeout: PATH_PROBE_TIMEOUT_MS,
245
+ stdio: ["ignore", "pipe", "ignore"],
246
+ encoding: "utf8",
247
+ maxBuffer: 1 << 20,
248
+ },
249
+ (error, stdout) => {
250
+ if (error) {
251
+ fallback();
252
+ return;
253
+ }
254
+ const match = /__ARGOS_PATH__=([^\n]*)\s*$/.exec(String(stdout).trimEnd());
255
+ const probed = (match?.[1] ?? "").trim();
256
+ if (!probed) {
257
+ fallback();
258
+ return;
259
+ }
260
+ const parts = [];
261
+ for (const entry of [...probed.split(delimiter), ...inheritedPath.split(delimiter)]) {
262
+ if (entry && !parts.includes(entry)) parts.push(entry);
263
+ }
264
+ resolve(parts.join(delimiter));
265
+ },
266
+ );
267
+ } catch {
268
+ fallback();
269
+ }
270
+ });
271
+ }
272
+
273
+ function findClaude(explicit, path) {
274
+ if (explicit) return explicit;
275
+ for (const folder of path.split(delimiter)) {
276
+ if (!folder) continue;
277
+ const candidate = join(folder, "claude");
278
+ try {
279
+ accessSync(candidate, constants.X_OK);
280
+ return candidate;
281
+ } catch {
282
+ // not here; keep looking
283
+ }
284
+ }
285
+ return join(homedir(), ".local", "bin", "claude");
286
+ }
287
+
288
+ // ------------------------------------------------------------------ one claude run
289
+
290
+ function killGroup(child, signal) {
291
+ if (!child || child.pid === undefined) return;
292
+ try {
293
+ process.kill(-child.pid, signal);
294
+ } catch {
295
+ try {
296
+ child.kill(signal);
297
+ } catch {
298
+ // Already gone: nothing to kill.
299
+ }
300
+ }
301
+ }
302
+
303
+ function toolDetail(input) {
304
+ const args = input ?? {};
305
+ return (
306
+ args["command"] ??
307
+ args["file_path"] ??
308
+ args["pattern"] ??
309
+ args["description"] ??
310
+ args["url"] ??
311
+ ""
312
+ );
313
+ }
314
+
315
+ function handleEvent(run, line) {
316
+ const text = line.trim();
317
+ if (!text) return;
318
+ let event;
319
+ try {
320
+ event = JSON.parse(text);
321
+ } catch {
322
+ say(oneLine(text));
323
+ return;
324
+ }
325
+ if (event === null || typeof event !== "object") {
326
+ say(oneLine(text));
327
+ return;
328
+ }
329
+ switch (event["type"]) {
330
+ case "system":
331
+ if (event["subtype"] === "init") {
332
+ run.session = event["session_id"] ?? run.session;
333
+ say(
334
+ `claude ${event["claude_code_version"] ?? "?"} · ${event["model"] ?? "?"} · session ${run.session}`,
335
+ );
336
+ }
337
+ return;
338
+ case "assistant": {
339
+ if (event["error"] === "rate_limit") run.quota = true;
340
+ const content = event["message"]?.["content"];
341
+ for (const block of Array.isArray(content) ? content : []) {
342
+ if (block?.["type"] === "tool_use") {
343
+ say(` → ${oneLine(`${block["name"] ?? "?"} ${toolDetail(block["input"])}`)}`);
344
+ } else if (block?.["type"] === "text" && String(block["text"] ?? "").trim()) {
345
+ say(` · ${oneLine(block["text"])}`);
346
+ }
347
+ }
348
+ return;
349
+ }
350
+ case "rate_limit_event": {
351
+ const info = event["rate_limit_info"] ?? {};
352
+ if (info["status"] === "rejected") {
353
+ run.quota = true;
354
+ const resets = info["resetsAt"];
355
+ if (typeof resets === "number" && Number.isFinite(resets)) {
356
+ run.resetsAt = resets > 1e12 ? resets : resets * 1_000;
357
+ }
358
+ }
359
+ return;
360
+ }
361
+ case "result":
362
+ run.result = event;
363
+ run.session = event["session_id"] ?? run.session;
364
+ return;
365
+ default:
366
+ say(oneLine(text));
367
+ }
368
+ }
369
+
370
+ function runClaude({ command, args, prompt, env, workTimeoutMs }) {
371
+ return new Promise((resolve) => {
372
+ const run = {
373
+ session: null,
374
+ result: null,
375
+ quota: false,
376
+ resetsAt: null,
377
+ timedOut: false,
378
+ exitCode: null,
379
+ failed: true,
380
+ spawnError: null,
381
+ };
382
+ let child;
383
+ try {
384
+ child = spawn(command, args, {
385
+ detached: true,
386
+ stdio: ["pipe", "pipe", "inherit"],
387
+ env,
388
+ });
389
+ } catch (error) {
390
+ run.spawnError = error;
391
+ resolve(run);
392
+ return;
393
+ }
394
+ currentChild = child;
395
+ let settled = false;
396
+ let buffer = "";
397
+ let killTimer = null;
398
+ const finish = () => {
399
+ if (settled) return;
400
+ settled = true;
401
+ clearTimeout(watchdog);
402
+ if (killTimer !== null) clearTimeout(killTimer);
403
+ currentChild = null;
404
+ if (buffer) handleEvent(run, buffer);
405
+ resolve(run);
406
+ };
407
+ const watchdog = setTimeout(() => {
408
+ run.timedOut = true;
409
+ killGroup(child, "SIGTERM");
410
+ killTimer = setTimeout(() => killGroup(child, "SIGKILL"), KILL_GRACE_MS);
411
+ }, workTimeoutMs);
412
+
413
+ child.stdout?.setEncoding("utf8");
414
+ child.stdout?.on("data", (chunk) => {
415
+ buffer += chunk;
416
+ let index = buffer.indexOf("\n");
417
+ while (index !== -1) {
418
+ handleEvent(run, buffer.slice(0, index));
419
+ buffer = buffer.slice(index + 1);
420
+ index = buffer.indexOf("\n");
421
+ }
422
+ });
423
+ child.on("error", (error) => {
424
+ run.spawnError = error;
425
+ finish();
426
+ });
427
+ child.on("close", (code) => {
428
+ run.exitCode = code;
429
+ finish();
430
+ });
431
+ child.stdin?.on("error", () => {
432
+ // claude exited before reading its prompt; the exit code is the signal.
433
+ });
434
+ child.stdin?.end(prompt);
435
+ });
436
+ }
437
+
438
+ /** Classify one run exactly as the Python program did. */
439
+ function classify(run) {
440
+ const result = run.result ?? {};
441
+ const failed =
442
+ run.result === null ||
443
+ Boolean(result["is_error"]) ||
444
+ result["subtype"] !== "success";
445
+ if (
446
+ failed &&
447
+ (result["api_error_status"] === 429 || QUOTA_TEXT.test(String(result["result"] ?? "")))
448
+ ) {
449
+ run.quota = true;
450
+ }
451
+ // A limit seen mid-run that Claude got past is not a quota failure.
452
+ run.quota = run.quota && failed;
453
+ run.failed = failed;
454
+ return run;
455
+ }
456
+
457
+ // ------------------------------------------------------------------ log
458
+
459
+ function localTimestamp(epoch) {
460
+ const date = new Date(epoch);
461
+ const pad = (value) => String(Math.trunc(Math.abs(value))).padStart(2, "0");
462
+ const offset = -date.getTimezoneOffset();
463
+ const sign = offset >= 0 ? "+" : "-";
464
+ const hours = pad(Math.floor(Math.abs(offset) / 60));
465
+ const minutes = pad(Math.abs(offset) % 60);
466
+ return (
467
+ `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` +
468
+ `T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}${sign}${hours}${minutes}`
469
+ );
470
+ }
471
+
472
+ function logPath(explicit) {
473
+ if (explicit) return explicit;
474
+ const stateHome = process.env["XDG_STATE_HOME"];
475
+ const base = stateHome ? stateHome : join(homedir(), ".local", "state");
476
+ return join(base, "argos-hc", "claude-step.log");
477
+ }
478
+
479
+ /** One JSON line per outcome. Never the prompt, never a path outside the run cwd; never fatal. */
480
+ function log({ startedAt, cwd, run, status, explicitPath }) {
481
+ const result = run?.result ?? {};
482
+ const entry = {
483
+ at: localTimestamp(startedAt),
484
+ cwd,
485
+ terminal: process.env["HC_TERMINAL_ID"] ?? null,
486
+ session: run?.session ?? null,
487
+ status,
488
+ cost_usd: result["total_cost_usd"] ?? null,
489
+ turns: result["num_turns"] ?? null,
490
+ seconds: Math.round((Date.now() - startedAt) / 1000),
491
+ };
492
+ try {
493
+ const file = logPath(explicitPath);
494
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
495
+ appendFileSync(file, `${JSON.stringify(entry)}\n`);
496
+ } catch {
497
+ // The log is diagnostic: a read-only home must never fail a step.
498
+ }
499
+ }
500
+
501
+ // ------------------------------------------------------------------ signals
502
+
503
+ function waitForExit(child, timeoutMs) {
504
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
505
+ return new Promise((resolve) => {
506
+ const timer = setTimeout(() => resolve(false), timeoutMs);
507
+ child.once("close", () => {
508
+ clearTimeout(timer);
509
+ resolve(true);
510
+ });
511
+ });
512
+ }
513
+
514
+ async function terminate(code) {
515
+ if (terminating) return;
516
+ terminating = true;
517
+ const child = currentChild;
518
+ if (child) {
519
+ killGroup(child, "SIGTERM");
520
+ if (!(await waitForExit(child, 5_000))) {
521
+ killGroup(child, "SIGKILL");
522
+ await waitForExit(child, 5_000);
523
+ }
524
+ }
525
+ reportState("done");
526
+ process.exit(code);
527
+ }
528
+
529
+ function installSignalHandlers() {
530
+ for (const [signal, code] of [
531
+ ["SIGTERM", 143],
532
+ ["SIGHUP", 129],
533
+ ["SIGINT", 130],
534
+ ]) {
535
+ process.on(signal, () => {
536
+ void terminate(code);
537
+ });
538
+ }
539
+ }
540
+
541
+ function exit(code) {
542
+ if (!terminating) process.exit(code);
543
+ }
544
+
545
+ function sleep(ms) {
546
+ return new Promise((resolve) => setTimeout(resolve, ms));
547
+ }
548
+
549
+ // ------------------------------------------------------------------ main
550
+
551
+ function usage(error) {
552
+ writeStderr(`claude-step: ${error instanceof Error ? error.message : String(error)}`);
553
+ return 2;
554
+ }
555
+
556
+ async function main() {
557
+ const argv = process.argv.slice(2);
558
+ let options;
559
+ try {
560
+ options = parseOptions(argv);
561
+ } catch (error) {
562
+ return usage(error);
563
+ }
564
+ installSignalHandlers();
565
+
566
+ let prompt;
567
+ try {
568
+ prompt = await readPrompt(options.promptFile);
569
+ } catch (error) {
570
+ return usage(error);
571
+ }
572
+ reportState("working");
573
+
574
+ const startedAt = Date.now();
575
+ const cwd = process.cwd();
576
+ if (!prompt) {
577
+ writeStderr("claude-step: no prompt arrived");
578
+ log({ startedAt, cwd, run: null, status: "no_prompt", explicitPath: options.log });
579
+ reportState("done");
580
+ return 2;
581
+ }
582
+
583
+ const env = { ...process.env, PATH: await userPath(process.env["PATH"] ?? "/usr/bin:/bin") };
584
+ if (!env["LANG"]) env["LANG"] = "en_US.UTF-8";
585
+ const command = findClaude(options.claude, env["PATH"]);
586
+ const args = [
587
+ "-p",
588
+ "--output-format",
589
+ "stream-json",
590
+ "--verbose",
591
+ "--model",
592
+ options.model,
593
+ "--permission-mode",
594
+ options.permissionMode,
595
+ ];
596
+ if (options.effort) args.push("--effort", options.effort);
597
+
598
+ let giveUpAt = null;
599
+ for (;;) {
600
+ const run = classify(
601
+ await runClaude({
602
+ command,
603
+ args,
604
+ prompt,
605
+ env,
606
+ workTimeoutMs: options.workTimeoutMs,
607
+ }),
608
+ );
609
+ const result = run.result ?? {};
610
+
611
+ if (run.timedOut) {
612
+ writeStderr(
613
+ `claude-step: the claude run passed --work-timeout (${options.workTimeoutMs}ms) and was stopped`,
614
+ );
615
+ log({ startedAt, cwd, run, status: "timeout", explicitPath: options.log });
616
+ reportState("done");
617
+ return 124;
618
+ }
619
+
620
+ if (run.quota) {
621
+ const now = Date.now();
622
+ if (giveUpAt === null) giveUpAt = now + options.quotaMaxWaitMs;
623
+ if (now >= giveUpAt) {
624
+ writeStderr(
625
+ `claude-step: Claude quota still exhausted after ${options.quotaMaxWaitMs}ms, giving up`,
626
+ );
627
+ log({ startedAt, cwd, run, status: "quota_exhausted", explicitPath: options.log });
628
+ reportState("done");
629
+ return 75;
630
+ }
631
+ // Nothing is written to the screen while waiting: the terminal stays `working` and argos
632
+ // keeps polling. One sleep, no polling loop.
633
+ const wake =
634
+ run.resetsAt !== null && run.resetsAt > now
635
+ ? Math.min(run.resetsAt + 60_000, giveUpAt)
636
+ : Math.min(now + options.quotaRetryMs, giveUpAt);
637
+ log({ startedAt, cwd, run, status: "quota_wait", explicitPath: options.log });
638
+ await sleep(Math.max(0, wake - Date.now()));
639
+ continue;
640
+ }
641
+
642
+ if (run.failed) {
643
+ const detail = run.spawnError
644
+ ? `could not run ${command}: ${run.spawnError.message}`
645
+ : `claude failed (exit ${run.exitCode}, ${result["subtype"] ?? "no result"}): ${oneLine(result["result"] ?? "", 400)}`;
646
+ writeStderr(`claude-step: ${detail}`);
647
+ log({ startedAt, cwd, run, status: "error", explicitPath: options.log });
648
+ reportState("done");
649
+ // A run that reported no result is a failure even when claude exited 0 (parity with the
650
+ // Python program's `exit_code or 1`): a zero exit must never read as a settled step.
651
+ return run.exitCode === null || run.exitCode === 0 ? 1 : run.exitCode;
652
+ }
653
+
654
+ // Only the final message stays on the screen: that is what argos parses.
655
+ write(CLEAR);
656
+ write(`${String(result["result"] ?? "").trimEnd()}\n`);
657
+ log({ startedAt, cwd, run, status: "success", explicitPath: options.log });
658
+ reportState("done");
659
+ return 0;
660
+ }
661
+ }
662
+
663
+ main().then(exit, (error) => {
664
+ writeStderr(`claude-step: ${error instanceof Error ? error.message : String(error)}`);
665
+ exit(1);
666
+ });
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "claude",
3
+ "version": 1,
4
+ "description": "Headless Claude Code (claude -p) as one argos hc step: login-shell PATH, OSC 7501 status, quota wait, one fenced JSON block on screen",
5
+ "requires": {
6
+ "node": ">=22.13",
7
+ "hcProtocol": 1
8
+ },
9
+ "program": {
10
+ "file": "claude-step.mjs"
11
+ },
12
+ "templates": [
13
+ {
14
+ "name": "claude-opus-high",
15
+ "args": "--model claude-opus-5-5 --effort high --permission-mode auto --work-timeout 150m --quota-retry 30m --quota-max-wait 4h",
16
+ "minStepTimeoutMs": 19800000,
17
+ "description": "Headless Claude Code (Opus 5.5, effort high, auto mode) for one argos step; work 150m, waits out quota up to 4h"
18
+ },
19
+ {
20
+ "name": "claude-opus-xhigh",
21
+ "args": "--model claude-opus-5-5 --effort xhigh --permission-mode auto --work-timeout 60m --quota-retry 30m --quota-max-wait 8h",
22
+ "minStepTimeoutMs": 33300000,
23
+ "description": "Headless Claude Code (Opus 5.5, effort xhigh, auto mode) for one argos step; waits out quota limits"
24
+ },
25
+ {
26
+ "name": "claude-sonnet-medium",
27
+ "args": "--model claude-sonnet-5-5 --effort medium --permission-mode auto --work-timeout 150m --quota-retry 30m --quota-max-wait 4h",
28
+ "minStepTimeoutMs": 19800000,
29
+ "description": "Headless Claude Code (Sonnet 5.5, effort medium, auto mode) for one argos step; work 150m, waits out quota up to 4h"
30
+ },
31
+ {
32
+ "name": "claude-fable-high",
33
+ "args": "--model claude-fable-5-2 --effort high --permission-mode auto --work-timeout 180m --quota-retry 30m --quota-max-wait 4h",
34
+ "minStepTimeoutMs": 26100000,
35
+ "description": "Headless Claude Code (Fable 5.2, effort high, auto mode) for one argos step; work 180m, waits out quota up to 4h"
36
+ }
37
+ ]
38
+ }