@moo.md/hum 0.0.0-stage → 0.1.0

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 (150) hide show
  1. package/defaults/hum.json +321 -0
  2. package/defaults/kinds/check.json +183 -0
  3. package/defaults/kinds/docs.json +151 -0
  4. package/defaults/kinds/feature.json +202 -0
  5. package/defaults/kinds/fix.json +183 -0
  6. package/defaults/kinds/hotfix.json +164 -0
  7. package/defaults/roles/build.md +3 -0
  8. package/defaults/roles/fix.md +1 -0
  9. package/defaults/roles/plan.md +3 -0
  10. package/defaults/roles/review.md +3 -0
  11. package/evals/alignment/RESULTS.md +8 -0
  12. package/evals/alignment/cases.jsonl +128 -0
  13. package/evals/alignment/sample.jsonl +20 -0
  14. package/evals/kind/RESULTS.md +5 -0
  15. package/evals/kind/cases.jsonl +24 -0
  16. package/evals/plan-outcome/RESULTS.md +4 -0
  17. package/evals/plan-outcome/cases.jsonl +12 -0
  18. package/evals/repeat-pair/RESULTS.md +4 -0
  19. package/evals/repeat-pair/cases.jsonl +51 -0
  20. package/evals/reply-option/RESULTS.md +3 -0
  21. package/evals/reply-option/cases.jsonl +45 -0
  22. package/evals/review-verdict/RESULTS.md +4 -0
  23. package/evals/review-verdict/cases.jsonl +12 -0
  24. package/package.json +88 -4
  25. package/schema/hum.schema.json +1355 -0
  26. package/scripts/eval.ts +244 -0
  27. package/src/adapter-api.ts +134 -0
  28. package/src/adapters/admit.ts +111 -0
  29. package/src/adapters/argument.ts +11 -0
  30. package/src/adapters/claim.ts +93 -0
  31. package/src/adapters/claude-bg.ts +392 -0
  32. package/src/adapters/claude-p.ts +599 -0
  33. package/src/adapters/contract.ts +231 -0
  34. package/src/adapters/fake.ts +157 -0
  35. package/src/adapters/git.ts +156 -0
  36. package/src/adapters/github.ts +479 -0
  37. package/src/adapters/guard.ts +152 -0
  38. package/src/adapters/history.ts +215 -0
  39. package/src/adapters/item-file.ts +102 -0
  40. package/src/adapters/limit.ts +67 -0
  41. package/src/adapters/markdown.ts +365 -0
  42. package/src/adapters/marked.ts +127 -0
  43. package/src/adapters/model-call.ts +75 -0
  44. package/src/adapters/once.ts +45 -0
  45. package/src/adapters/owner-commit.ts +60 -0
  46. package/src/adapters/pull-requests.ts +253 -0
  47. package/src/adapters/registry.ts +156 -0
  48. package/src/adapters/roundup.ts +293 -0
  49. package/src/adapters/serial.ts +22 -0
  50. package/src/adapters/transcript.ts +99 -0
  51. package/src/cli/commands.ts +46 -0
  52. package/src/cli/main.ts +8 -0
  53. package/src/cli/ops.ts +224 -0
  54. package/src/cli/service.ts +156 -0
  55. package/src/cli/setup.ts +141 -0
  56. package/src/cli/shared-watch.ts +127 -0
  57. package/src/config/change.ts +54 -0
  58. package/src/config/checks.ts +217 -0
  59. package/src/config/git-ref-name.d.ts +3 -0
  60. package/src/config/hash.ts +6 -0
  61. package/src/config/json.ts +6 -0
  62. package/src/config/load.ts +88 -0
  63. package/src/config/machine.ts +20 -0
  64. package/src/config/migrate.ts +61 -0
  65. package/src/config/refusal.ts +58 -0
  66. package/src/config/schema.ts +465 -0
  67. package/src/config/settings.ts +6 -0
  68. package/src/config/state-map.ts +76 -0
  69. package/src/decide/alignment.ts +79 -0
  70. package/src/decide/answer.ts +131 -0
  71. package/src/decide/kind.ts +39 -0
  72. package/src/decide/labels.ts +137 -0
  73. package/src/decide/merge.ts +102 -0
  74. package/src/decide/prose.ts +109 -0
  75. package/src/decide/question.ts +159 -0
  76. package/src/decide/review.ts +10 -0
  77. package/src/decide/risk.ts +216 -0
  78. package/src/decide/taste.ts +37 -0
  79. package/src/exec.ts +85 -0
  80. package/src/index.ts +200 -0
  81. package/src/loop/breaks.ts +8 -0
  82. package/src/loop/check-item.ts +76 -0
  83. package/src/loop/ci.ts +8 -0
  84. package/src/loop/github.ts +81 -0
  85. package/src/loop/groups.ts +108 -0
  86. package/src/loop/memory.ts +70 -0
  87. package/src/loop/notes.ts +76 -0
  88. package/src/loop/pair.ts +39 -0
  89. package/src/loop/pass.ts +99 -0
  90. package/src/loop/proof.ts +85 -0
  91. package/src/loop/prove-item.ts +33 -0
  92. package/src/loop/records.ts +75 -0
  93. package/src/loop/signals.ts +130 -0
  94. package/src/measure/inputs.ts +28 -0
  95. package/src/measure/measure.ts +68 -0
  96. package/src/service/cards.ts +24 -0
  97. package/src/service/ci-tick.ts +28 -0
  98. package/src/service/launchd.ts +16 -0
  99. package/src/service/supervise.ts +145 -0
  100. package/src/service/systemd.ts +44 -0
  101. package/src/service/token.ts +21 -0
  102. package/src/service/unit.ts +29 -0
  103. package/src/service/wake.ts +30 -0
  104. package/src/service/workflows.ts +97 -0
  105. package/src/setup/propose.ts +120 -0
  106. package/src/setup/prove.ts +216 -0
  107. package/src/setup/scan.ts +186 -0
  108. package/src/setup/scratch.ts +81 -0
  109. package/src/setup/shipped.ts +15 -0
  110. package/src/setup/tables.ts +101 -0
  111. package/src/setup/waits.ts +58 -0
  112. package/src/setup/write.ts +161 -0
  113. package/src/slots/env.ts +42 -0
  114. package/src/slots/pool.ts +329 -0
  115. package/src/slots/scan.ts +26 -0
  116. package/src/slots/worktree.ts +17 -0
  117. package/src/state/events.ts +52 -0
  118. package/src/state/faults.ts +73 -0
  119. package/src/state/format.ts +50 -0
  120. package/src/state/fs.ts +100 -0
  121. package/src/state/items.ts +195 -0
  122. package/src/state/open.ts +80 -0
  123. package/src/state/ops.ts +76 -0
  124. package/src/state/records.ts +35 -0
  125. package/src/state/runs.ts +99 -0
  126. package/src/state/saved.ts +119 -0
  127. package/src/status/file.ts +49 -0
  128. package/src/status/format.ts +132 -0
  129. package/src/status/sections.ts +14 -0
  130. package/src/status/version.ts +2 -0
  131. package/src/time.ts +7 -0
  132. package/src/worker/alignment-report.ts +18 -0
  133. package/src/worker/answers.ts +153 -0
  134. package/src/worker/base-check.ts +45 -0
  135. package/src/worker/checks.ts +40 -0
  136. package/src/worker/kind.ts +68 -0
  137. package/src/worker/land.ts +509 -0
  138. package/src/worker/lifecycle.ts +97 -0
  139. package/src/worker/merged.ts +29 -0
  140. package/src/worker/open.ts +100 -0
  141. package/src/worker/prose-run.ts +56 -0
  142. package/src/worker/questions.ts +89 -0
  143. package/src/worker/scheduler.ts +135 -0
  144. package/src/worker/signature.ts +41 -0
  145. package/src/worker/tally.ts +25 -0
  146. package/src/worker/taste.ts +38 -0
  147. package/src/worker/thin-path.ts +886 -0
  148. package/src/worker/worker.ts +750 -0
  149. package/surface.json +8787 -0
  150. package/README.md +0 -3
@@ -0,0 +1,599 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { closeSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import pMemoize, { pMemoizeClear } from "p-memoize";
6
+ import pRetry from "p-retry";
7
+ import semver from "semver";
8
+ import { x } from "tinyexec";
9
+ import { z } from "zod";
10
+ import type { EFFORTS } from "../config/schema.ts";
11
+ import { CommandTimedOut, exec, SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
12
+ import { rejectedToken, UNAUTHORIZED } from "../service/token.ts";
13
+ import { atomicWrite, isMissing } from "../state/fs.ts";
14
+ import type { State } from "../state/open.ts";
15
+ import { SECOND_MS } from "../time.ts";
16
+ import { CARD_EXCERPT, type Card } from "../status/format.ts";
17
+ import { LIMIT_TEXT, LIMIT_UNPARSED, type LimitEnded, limitOf, savedLimitUntil, settleLimit } from "./limit.ts";
18
+ import { billed } from "./transcript.ts";
19
+
20
+ export type Effort = (typeof EFFORTS)[number];
21
+
22
+ /** The oldest Claude Code the runner was proven on. */
23
+ export const CLAUDE_FLOOR = "2.1.316";
24
+
25
+ /** No approval prompt in a headless run, and nothing else: no sandbox and no deny rules. */
26
+ export const RUN_SETTINGS = JSON.stringify({
27
+ permissions: { defaultMode: "bypassPermissions" },
28
+ });
29
+
30
+ /**
31
+ * The two kinds of `claude -p` call. An agent run keeps its session. A model call runs as hope's judge does: no
32
+ * session kept, no hooks, and the default output style, so the owner's style cannot reshape its answer. It also loads
33
+ * no settings source (plugins, MCP servers, memory files) and no built-in tool: a question needs neither, and each
34
+ * one bills on every call.
35
+ */
36
+ export const CALLS = {
37
+ run: { settings: RUN_SETTINGS, flags: [] },
38
+ judgment: {
39
+ settings: JSON.stringify({ permissions: { defaultMode: "bypassPermissions" }, disableAllHooks: true, outputStyle: "default" }),
40
+ flags: ["--no-session-persistence", "--setting-sources", "", "--tools", ""],
41
+ },
42
+ } as const satisfies Record<string, { settings: string; flags: readonly string[] }>;
43
+
44
+ export type Call = keyof typeof CALLS;
45
+
46
+ const REQUIRED_PLUGIN = "hope";
47
+
48
+ const CREDENTIALS = "credentials.json";
49
+
50
+ const STDERR_TAIL = 500;
51
+
52
+ const LOCK_TRIES = 3;
53
+
54
+ const LOCK_BACKOFF_MS = 2000;
55
+
56
+ export type RunSpec = {
57
+ readonly model: string;
58
+ readonly effort: Effort;
59
+ /** The JSON Schema of the run's structured result. */
60
+ readonly schema: object;
61
+ readonly sessionId: string;
62
+ readonly call?: Call;
63
+ /** The run's name in agent view and in `claude agents`. */
64
+ readonly name?: string;
65
+ };
66
+
67
+ /**
68
+ * The one flag set for every `claude -p` call, the start check included, so the check proves the flags a run uses.
69
+ * The prompt goes on stdin, never in argv. Never `--bare`, `--resume` or `--continue`: bare mode reads neither the
70
+ * login nor the plan token, and a run never resumes a session.
71
+ */
72
+ export const runArgs = ({ model, effort, schema, sessionId, call = "run", name }: RunSpec): string[] => [
73
+ "-p",
74
+ "--output-format",
75
+ "stream-json",
76
+ "--verbose",
77
+ "--model",
78
+ model,
79
+ "--effort",
80
+ effort,
81
+ "--json-schema",
82
+ JSON.stringify(schema),
83
+ "--settings",
84
+ CALLS[call].settings,
85
+ "--session-id",
86
+ sessionId,
87
+ ...CALLS[call].flags,
88
+ ...(name === undefined ? [] : ["-n", name]),
89
+ ];
90
+
91
+ const Usage = z.looseObject({
92
+ input_tokens: z.number().default(0),
93
+ output_tokens: z.number().default(0),
94
+ cache_creation_input_tokens: z.number().default(0),
95
+ });
96
+
97
+ const ModelUsage = z.looseObject({
98
+ inputTokens: z.number().default(0),
99
+ outputTokens: z.number().default(0),
100
+ cacheCreationInputTokens: z.number().default(0),
101
+ cacheReadInputTokens: z.number().default(0),
102
+ });
103
+
104
+ const Init = z.looseObject({
105
+ type: z.literal("system"),
106
+ subtype: z.literal("init"),
107
+ apiKeySource: z.string().optional(),
108
+ plugins: z.array(z.looseObject({ name: z.string() })).default([]),
109
+ });
110
+
111
+ const Assistant = z.looseObject({
112
+ type: z.literal("assistant"),
113
+ message: z.looseObject({ id: z.string(), usage: Usage }),
114
+ });
115
+
116
+ const RateLimit = z.looseObject({
117
+ type: z.literal("rate_limit_event"),
118
+ rate_limit_info: z.looseObject({
119
+ status: z.string(),
120
+ resetsAt: z.number().optional(),
121
+ }),
122
+ });
123
+
124
+ const Result = z.looseObject({
125
+ type: z.literal("result"),
126
+ subtype: z.string(),
127
+ is_error: z.boolean(),
128
+ session_id: z.string().optional(),
129
+ result: z.string().default(""),
130
+ structured_output: z.unknown().optional(),
131
+ modelUsage: z.record(z.string(), ModelUsage).default({}),
132
+ });
133
+
134
+ type Result = z.infer<typeof Result>;
135
+
136
+ const StreamEvent = z.discriminatedUnion("type", [Init, Assistant, RateLimit, Result]);
137
+
138
+ type StreamEvent = z.infer<typeof StreamEvent>;
139
+
140
+ /** What the stream has said so far. */
141
+ type Transcript = {
142
+ readonly plugins: readonly string[];
143
+ readonly keySource: string | undefined;
144
+ /** One message streams several events, and the last carries its final usage; so billed tokens are kept per message id. */
145
+ readonly messages: Readonly<Record<string, number>>;
146
+ readonly rejectedUntil: number | undefined;
147
+ readonly result: Result | undefined;
148
+ };
149
+
150
+ const EMPTY_TRANSCRIPT: Transcript = {
151
+ plugins: [],
152
+ keySource: undefined,
153
+ messages: {},
154
+ rejectedUntil: undefined,
155
+ result: undefined,
156
+ };
157
+
158
+ const isRejection = (info: z.infer<typeof RateLimit>["rate_limit_info"]): info is { status: "rejected"; resetsAt: number } =>
159
+ info.status === "rejected" && info.resetsAt !== undefined;
160
+
161
+ const readEvent = {
162
+ system: (t, { plugins, apiKeySource }) => ({
163
+ ...t,
164
+ plugins: plugins.map((plugin) => plugin.name),
165
+ keySource: apiKeySource,
166
+ }),
167
+ assistant: (t, { message: { id, usage } }) => ({
168
+ ...t,
169
+ messages: {
170
+ ...t.messages,
171
+ [id]: billed(usage.input_tokens, usage.output_tokens, usage.cache_creation_input_tokens),
172
+ },
173
+ }),
174
+ rate_limit_event: (t, { rate_limit_info }) => (isRejection(rate_limit_info) ? { ...t, rejectedUntil: rate_limit_info.resetsAt * SECOND_MS } : t),
175
+ result: (t, result) => ({ ...t, result }),
176
+ } satisfies { readonly [K in StreamEvent["type"]]: (t: Transcript, event: Extract<StreamEvent, { type: K }>) => Transcript };
177
+
178
+ /** The event a stdout line holds; undefined for a line that is no JSON or no event this reader knows. */
179
+ const parseEvent = (line: string): StreamEvent | undefined => {
180
+ try {
181
+ return StreamEvent.safeParse(JSON.parse(line)).data;
182
+ } catch {
183
+ return undefined;
184
+ }
185
+ };
186
+
187
+ /** The transcript after one stdout line. A line that is no event this reader knows changes nothing. */
188
+ const readLine = (t: Transcript, line: string): Transcript => {
189
+ const event = parseEvent(line);
190
+
191
+ // SAFETY: the table holds one reader per member of the union, keyed by its `type`.
192
+ return event ? (readEvent[event.type] as (t: Transcript, event: StreamEvent) => Transcript)(t, event) : t;
193
+ };
194
+
195
+ const spentSoFar = (t: Transcript): number => Object.values(t.messages).reduce((sum, tokens) => sum + tokens, 0);
196
+
197
+ const hasFirstToken = (t: Transcript): boolean => Object.keys(t.messages).length > 0;
198
+
199
+ const isOverCap = (tokens: number, cap: number | undefined): boolean => cap !== undefined && tokens > cap;
200
+
201
+ /** What a finished `claude -p` process reported. Done is `succeeded`, and for an item also an artifact on its branch. */
202
+ export type Finished = {
203
+ readonly kind: "finished";
204
+ readonly subtype: string;
205
+ readonly isError: boolean;
206
+ readonly sessionId: string | undefined;
207
+ readonly text: string;
208
+ readonly structured: unknown;
209
+ readonly tokens: number;
210
+ /** Tokens read from the prompt cache, which the bill does not count. */
211
+ readonly cacheReadTokens: number;
212
+ readonly plugins: readonly string[];
213
+ readonly keySource: string | undefined;
214
+ /** The model ids that answered, as the result names them. */
215
+ readonly models: readonly string[];
216
+ };
217
+
218
+ export type RunOutcome =
219
+ | Finished
220
+ /** Zero calls until `until` (epoch ms). */
221
+ | { readonly kind: "limited"; readonly until: number }
222
+ /** No run started or no verdict could be read; `card` says why. */
223
+ | { readonly kind: "held"; readonly card: Card }
224
+ /** The run was stopped at the item's token cap. */
225
+ | { readonly kind: "over-cap"; readonly tokens: number }
226
+ /** The caller's signal stopped the run. */
227
+ | { readonly kind: "stopped" };
228
+
229
+ /** What one process ended as, before the runner acts on a limit it could not read. */
230
+ type Ended = RunOutcome | LimitEnded;
231
+
232
+ export const succeeded = (outcome: Finished): boolean => outcome.subtype === "success" && !outcome.isError;
233
+
234
+ const LOCK_TEXT = /refresh[^\n]*lock|lock[^\n]*refresh/i;
235
+
236
+ const isLimitRefusal = (t: Transcript, result: Result): boolean => result.is_error && (t.rejectedUntil !== undefined || LIMIT_TEXT.test(result.result));
237
+
238
+ const isLockError = (outcome: RunOutcome): boolean => outcome.kind === "finished" && outcome.isError && LOCK_TEXT.test(outcome.text);
239
+
240
+ const isUnauthorized = (finished: Finished): boolean => finished.isError && UNAUTHORIZED.test(finished.text);
241
+
242
+ const sumUsage = (result: Result, tokensOf: (usage: z.infer<typeof ModelUsage>) => number): number =>
243
+ Object.values(result.modelUsage).reduce((sum, usage) => sum + tokensOf(usage), 0);
244
+
245
+ /** What the whole stream amounts to, once the process has ended. */
246
+ const endedAs = (t: Transcript, { sessionId, tokenCap, stderr }: { sessionId: string; tokenCap: number | undefined; stderr: string }): Ended => {
247
+ const { result } = t;
248
+
249
+ if (result === undefined) {
250
+ return {
251
+ kind: "finished",
252
+ subtype: "no-result",
253
+ isError: true,
254
+ sessionId,
255
+ text: stderr.trim().slice(-STDERR_TAIL),
256
+ structured: undefined,
257
+ tokens: 0,
258
+ cacheReadTokens: 0,
259
+ plugins: t.plugins,
260
+ keySource: t.keySource,
261
+ models: [],
262
+ };
263
+ }
264
+
265
+ if (isLimitRefusal(t, result)) {
266
+ return limitOf(result.result, t.rejectedUntil);
267
+ }
268
+
269
+ const tokens = sumUsage(result, (usage) => billed(usage.inputTokens, usage.outputTokens, usage.cacheCreationInputTokens));
270
+
271
+ if (isOverCap(tokens, tokenCap)) return { kind: "over-cap", tokens };
272
+
273
+ return {
274
+ kind: "finished",
275
+ subtype: result.subtype,
276
+ isError: result.is_error,
277
+ sessionId: result.session_id ?? sessionId,
278
+ text: result.result,
279
+ structured: result.structured_output,
280
+ tokens,
281
+ cacheReadTokens: sumUsage(result, (usage) => usage.cacheReadInputTokens),
282
+ plugins: t.plugins,
283
+ keySource: t.keySource,
284
+ models: Object.keys(result.modelUsage),
285
+ };
286
+ };
287
+
288
+ export type RunRequest = {
289
+ readonly prompt: string;
290
+ readonly cwd: string;
291
+ readonly model: string;
292
+ readonly effort: Effort;
293
+ readonly schema: object;
294
+ readonly call?: Call;
295
+ /** Saved before the run launches. A background run is found by it after a crash, and agent view lists it under it. */
296
+ readonly name?: string;
297
+ /** Tokens the item may still spend. */
298
+ readonly tokenCap?: number;
299
+ readonly sessionId?: string;
300
+ /** Added to the run's environment on top of the runner's own. */
301
+ readonly env?: Readonly<Record<string, string>>;
302
+ readonly signal?: AbortSignal;
303
+ /** Called with the session id of each attempt, before its process starts. */
304
+ readonly onSession?: (sessionId: string) => void;
305
+ /** Called once, when the first model message arrives. */
306
+ readonly onFirstToken?: () => void;
307
+ };
308
+
309
+ /** A runner whose start check has run. A runner that failed it holds every run with the card that says why. */
310
+ export type Runner = {
311
+ readonly run: (request: RunRequest) => Promise<RunOutcome>;
312
+ /** Epoch ms until which every run is held, or 0. */
313
+ readonly limitedUntil: () => number;
314
+ /** The names of the runs alive outside this process: a background runner lists them, a `claude -p` runner has none. */
315
+ readonly liveRuns?: () => Promise<ReadonlySet<string>>;
316
+ };
317
+
318
+ export type RunnerOptions = {
319
+ readonly state: Pick<State, "dir" | "faults" | "limit">;
320
+ /** The model the start check runs on. */
321
+ readonly model: string;
322
+ readonly binary?: string;
323
+ /** The limit of `claude --version`, which the version floor reads, and of the start check; the owner's `commandTimeoutSeconds` in milliseconds. */
324
+ readonly timeoutMs?: number;
325
+ /** Added to the process environment. An API key in the environment is passed on untouched. */
326
+ readonly env?: Readonly<Record<string, string>>;
327
+ readonly now?: () => number;
328
+ /** The first wait before a run that hit the refresh-lock error runs again; later waits grow from it. */
329
+ readonly lockBackoffMs?: number;
330
+ };
331
+
332
+ /** A run that ended on the refresh-lock error, thrown so the retry runs it again. */
333
+ class LockHeld extends Error {
334
+ override name = "LockHeld";
335
+
336
+ constructor(readonly outcome: RunOutcome) {
337
+ super("claude could not take the credentials refresh lock");
338
+ }
339
+ }
340
+
341
+ const credentialOf = (keySource: string | undefined, env: Readonly<Record<string, string | undefined>>): string => {
342
+ if (keySource !== undefined && keySource !== "none") return `api-key:${keySource}`;
343
+
344
+ return env.CLAUDE_CODE_OAUTH_TOKEN ? "oauth-token" : "login";
345
+ };
346
+
347
+ const Credential = z.object({ credential: z.string() });
348
+
349
+ const readCredential = (file: string): string | undefined => {
350
+ try {
351
+ return Credential.parse(JSON.parse(readFileSync(file, "utf8"))).credential;
352
+ } catch (error) {
353
+ if (error instanceof Error && isMissing(error)) return undefined;
354
+
355
+ throw error;
356
+ }
357
+ };
358
+
359
+ /** The credential is recorded at the first start. A different one later shows one card, and runs go on. */
360
+ const recordCredential = (state: RunnerOptions["state"], credential: string): void => {
361
+ const file = join(state.dir, CREDENTIALS);
362
+ const recorded = readCredential(file);
363
+
364
+ if (recorded === undefined) {
365
+ mkdirSync(state.dir, { recursive: true });
366
+ atomicWrite(file, `${JSON.stringify({ credential })}\n`);
367
+
368
+ return;
369
+ }
370
+
371
+ if (recorded === credential) return state.faults.clear("credential-changed");
372
+
373
+ state.faults.raise({
374
+ code: "credential-changed",
375
+ cause: `claude now runs on ${credential}; it was recorded as ${recorded}.`,
376
+ fix: `Runs go on. Delete ${file} to record ${credential} as the choice.`,
377
+ });
378
+ };
379
+
380
+ const START_TIMED_OUT = "start-check-timed-out";
381
+
382
+ export const START_PROMPT = 'Reply with the JSON {"ok":true}.';
383
+
384
+ export const START_SCHEMA = {
385
+ type: "object",
386
+ properties: { ok: { type: "boolean" } },
387
+ required: ["ok"],
388
+ };
389
+
390
+ /** What the start check's run must answer. */
391
+ export const START_ANSWER = z.object({ ok: z.literal(true) });
392
+
393
+ const VERSION = /\d+\.\d+\.\d+/;
394
+
395
+ /** A version that is missing, unreadable or older than the floor starts no run. */
396
+ const isBelowFloor = (version: string | undefined): boolean => version === undefined || semver.valid(version) === null || semver.lt(version, CLAUDE_FLOOR);
397
+
398
+ type Started = { readonly check: RunOutcome; readonly runner: Runner };
399
+
400
+ /**
401
+ * Runs `claude -p` as the owner's own unmodified `claude` binary, on their login, their plan token or an API key.
402
+ * No run starts until the version floor and the start check pass; until then every run is held with one card.
403
+ */
404
+ const startChecked = async (options: RunnerOptions): Promise<Started> => {
405
+ const { state, binary = "claude", now = Date.now, lockBackoffMs = LOCK_BACKOFF_MS, timeoutMs = SHIPPED_COMMAND_TIMEOUT_MS } = options;
406
+ const env = { ...process.env, ...options.env };
407
+ const limitedUntil = () => savedLimitUntil(state);
408
+
409
+ const hold = (code: string, cause: string, fix: string): Extract<RunOutcome, { kind: "held" }> => ({
410
+ kind: "held",
411
+ card: state.faults.raise({ code, cause, fix }),
412
+ });
413
+
414
+ const held = (outcome: Extract<RunOutcome, { kind: "held" }>) => ({
415
+ check: outcome,
416
+ runner: { run: async () => outcome, limitedUntil },
417
+ });
418
+
419
+ /** One process, read line by line. The cap is checked on every streamed message, and the process is killed the moment it is passed. */
420
+ const spawnRun = async ({ prompt, cwd, model, effort, schema, call, name, tokenCap, signal, onFirstToken, env: runEnv }: RunRequest, sessionId: string): Promise<Ended> => {
421
+ const stop = new AbortController();
422
+ const logs = mkdtempSync(join(tmpdir(), "hum-claude-"));
423
+ const stderrFile = join(logs, "stderr");
424
+ const stderrFd = openSync(stderrFile, "w");
425
+
426
+ try {
427
+ const proc = x(binary, runArgs({ model, effort, schema, sessionId, call, name }), {
428
+ stdin: prompt,
429
+ signal: AbortSignal.any(signal ? [stop.signal, signal] : [stop.signal]),
430
+ nodePath: false,
431
+ // stderr goes to a file, so the line reader sees stdout alone: one stream cannot split another's line.
432
+ nodeOptions: {
433
+ cwd,
434
+ env: { ...env, ...runEnv },
435
+ killSignal: "SIGKILL",
436
+ stdio: ["pipe", "pipe", stderrFd],
437
+ },
438
+ });
439
+
440
+ // A process that ends before it reads its stdin breaks the pipe; what it said is read from its result.
441
+ proc.process?.stdin?.on("error", () => {});
442
+
443
+ let transcript = EMPTY_TRANSCRIPT;
444
+
445
+ for await (const line of proc) {
446
+ const next = readLine(transcript, line);
447
+
448
+ if (hasFirstToken(next) && !hasFirstToken(transcript)) onFirstToken?.();
449
+
450
+ transcript = next;
451
+
452
+ if (isOverCap(spentSoFar(transcript), tokenCap)) {
453
+ stop.abort();
454
+
455
+ return { kind: "over-cap", tokens: spentSoFar(transcript) };
456
+ }
457
+ }
458
+
459
+ return endedAs(transcript, {
460
+ sessionId,
461
+ tokenCap,
462
+ stderr: readFileSync(stderrFile, "utf8"),
463
+ });
464
+ } catch (error) {
465
+ if (signal?.aborted) return { kind: "stopped" };
466
+
467
+ return hold("claude-not-found", `claude could not start: ${error instanceof Error ? error.message : String(error)}`, "Install Claude Code and sign in.");
468
+ } finally {
469
+ closeSync(stderrFd);
470
+ rmSync(logs, { recursive: true, force: true });
471
+ }
472
+ };
473
+
474
+ /** The ended run, with a limit saved so no call is made before it ends, and an unreadable limit held with one card. */
475
+ const settle = (ended: Ended): RunOutcome => (ended.kind === "limited" || ended.kind === "limit-unparsed" ? settleLimit(state, ended) : ended);
476
+
477
+ /** A refresh-lock error is retried with growing, jittered waits, each try on a new session id. */
478
+ const attempt = (request: RunRequest): Promise<RunOutcome> =>
479
+ pRetry(
480
+ async (attemptNumber) => {
481
+ const sessionId = attemptNumber === 1 ? (request.sessionId ?? randomUUID()) : randomUUID();
482
+
483
+ request.onSession?.(sessionId);
484
+
485
+ const outcome = settle(await spawnRun(request, sessionId));
486
+
487
+ if (isLockError(outcome)) throw new LockHeld(outcome);
488
+
489
+ return outcome;
490
+ },
491
+ {
492
+ retries: LOCK_TRIES - 1,
493
+ minTimeout: lockBackoffMs,
494
+ randomize: true,
495
+ shouldRetry: ({ error }) => error instanceof LockHeld,
496
+ },
497
+ ).catch((error: Error) => {
498
+ if (error instanceof LockHeld) return error.outcome;
499
+
500
+ throw error;
501
+ });
502
+
503
+ const run = async (request: RunRequest): Promise<RunOutcome> => {
504
+ if (now() < limitedUntil()) return { kind: "limited", until: limitedUntil() };
505
+
506
+ const outcome = await attempt(request);
507
+
508
+ if (outcome.kind !== "finished") return outcome;
509
+
510
+ if (isUnauthorized(outcome)) return { kind: "held", card: rejectedToken(state.faults, outcome.text) };
511
+
512
+ state.faults.clear("token-rejected");
513
+
514
+ return outcome;
515
+ };
516
+
517
+ const version = await exec(binary, ["--version"], {
518
+ nodePath: false,
519
+ timeoutMs,
520
+ nodeOptions: { env },
521
+ }).then(
522
+ ({ stdout }) => VERSION.exec(stdout)?.[0],
523
+ (error: Error) => {
524
+ if (error instanceof CommandTimedOut) throw error;
525
+
526
+ return undefined;
527
+ },
528
+ );
529
+
530
+ if (isBelowFloor(version)) {
531
+ return held(hold("claude-too-old", `Claude Code ${version ?? "was not found"}; hum was proven on ${CLAUDE_FLOOR} or later.`, "Update Claude Code: claude update."));
532
+ }
533
+
534
+ const check = await attempt({
535
+ prompt: START_PROMPT,
536
+ cwd: tmpdir(),
537
+ model: options.model,
538
+ effort: "low",
539
+ schema: START_SCHEMA,
540
+ signal: AbortSignal.timeout(timeoutMs),
541
+ });
542
+
543
+ if (check.kind === "stopped") return held(hold(START_TIMED_OUT, `The start check got no answer within ${timeoutMs / SECOND_MS} seconds and was stopped.`, "hum makes the check again on the next run; if this card stays, check that claude -p answers in a terminal."));
544
+
545
+ if (check.kind === "held") return held(check);
546
+
547
+ if (check.kind === "limited") return { check, runner: { run: async () => check, limitedUntil } };
548
+
549
+ if (check.kind !== "finished") return held(hold("start-check-failed", `The start check ended as ${check.kind}.`, "Run it again once the limit resets."));
550
+
551
+ const hasPlugin = check.plugins.includes(REQUIRED_PLUGIN);
552
+
553
+ if (!succeeded(check) || !hasPlugin) {
554
+ return held(
555
+ hold(
556
+ "start-check-failed",
557
+ `The start check returned ${check.subtype}${check.isError ? " with an error" : ""}${hasPlugin ? "" : ` and no ${REQUIRED_PLUGIN} plugin`}: ${check.text.slice(0, CARD_EXCERPT)}`,
558
+ `Check that claude runs signed in (not in bare mode) and that the ${REQUIRED_PLUGIN} plugin is installed.`,
559
+ ),
560
+ );
561
+ }
562
+
563
+ recordCredential(state, credentialOf(check.keySource, env));
564
+
565
+ state.faults.clear(LIMIT_UNPARSED);
566
+ state.faults.clear(START_TIMED_OUT);
567
+
568
+ return { check, runner: { run, limitedUntil } };
569
+ };
570
+
571
+ /** A start check that a usage limit refused or that got no answer says nothing about the install: it is made again on the next run. */
572
+ const isUnsettled = ({ check }: Started): boolean => check.kind === "limited" || (check.kind === "held" && (check.card.code === LIMIT_UNPARSED || check.card.code === START_TIMED_OUT));
573
+
574
+ /**
575
+ * A runner. Its start check is made again on the next run for as long as a usage limit refuses it, and a saved
576
+ * limit that still stands defers the check, so no call is made before the limit ends and no restart is needed.
577
+ */
578
+ export const startRunner = async (options: RunnerOptions): Promise<Started> => {
579
+ const { state, now = Date.now } = options;
580
+ const started = pMemoize(() => startChecked(options));
581
+
582
+ const settle = async (): Promise<Started> => {
583
+ const result = await started();
584
+
585
+ if (isUnsettled(result)) pMemoizeClear(started);
586
+
587
+ return result;
588
+ };
589
+
590
+ const isLimited = (): boolean => now() < savedLimitUntil(state);
591
+ const limited = (): RunOutcome => ({ kind: "limited", until: savedLimitUntil(state) });
592
+
593
+ const runner: Runner = {
594
+ run: async (request) => (isLimited() ? limited() : (await settle()).runner.run(request)),
595
+ limitedUntil: () => savedLimitUntil(state),
596
+ };
597
+
598
+ return { check: isLimited() ? limited() : (await settle()).check, runner };
599
+ };