@operad-io/harness-process 0.1.1 → 0.2.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.
@@ -0,0 +1,133 @@
1
+ /**
2
+ * A question a harness's agent asked a person, as the kernel's form
3
+ * (ADR 0026 D6). Each harness reads its own protocol's question into
4
+ * `HarnessQuestion`; this module turns that into the one shape `ctx.ask`
5
+ * carries, and reads the person's answer back for the harness to send on.
6
+ *
7
+ * The one shape is the kernel's: a question has an id, its text, a short
8
+ * header, choices with a label and a description, whether more than one may be
9
+ * picked, and whether the person may answer in their own words. An answer names
10
+ * the question by its id and carries labels, text, or `skipped`.
11
+ */
12
+
13
+ import { cut, type AskQuestion, type AskQuestionAnswer, type AskQuestionChoice, type AskRequest } from "@operad-io/engine";
14
+
15
+ /** The kernel's longest question text, mirrored here so a long one is cut. */
16
+ const MAX_QUESTION_TEXT = 500;
17
+ /** The kernel's longest Markdown body, mirrored here. */
18
+ const MAX_QUESTION_BODY = 256 * 1024;
19
+ /** The kernel's longest header, mirrored here. */
20
+ const MAX_QUESTION_HEADER = 40;
21
+ /** The kernel's longest choice label, mirrored here. */
22
+ const MAX_QUESTION_CHOICE_LABEL = 80;
23
+ /** The kernel's longest choice description, mirrored here. */
24
+ const MAX_QUESTION_CHOICE_DESCRIPTION = 280;
25
+
26
+ /** One choice a harness's agent offered. */
27
+ export interface HarnessQuestionChoice {
28
+ readonly label: string;
29
+ readonly description?: string | undefined;
30
+ }
31
+
32
+ /** One question a harness's agent asked, in the harness's own words. */
33
+ export interface HarnessQuestion {
34
+ /** What the harness names this question by; empty for a harness without ids. */
35
+ readonly id: string;
36
+ readonly text: string;
37
+ readonly body?: string | undefined;
38
+ readonly header?: string | undefined;
39
+ readonly choices?: readonly HarnessQuestionChoice[] | undefined;
40
+ /** True when the person may pick more than one choice. */
41
+ readonly multiple?: boolean | undefined;
42
+ /** True when the person may type an answer of their own. */
43
+ readonly freeText?: boolean | undefined;
44
+ }
45
+
46
+ /** A leading `Other`-style label is the free text a harness adds itself. */
47
+ function isOther(label: string): boolean {
48
+ return label.trim().toLowerCase() === "other";
49
+ }
50
+
51
+ /**
52
+ * The kernel's form from a harness's questions. An empty id becomes `q<n>`, a
53
+ * duplicate id gets a suffix, and an empty choice label or question text is
54
+ * left out: the kernel refuses the shape otherwise, and no answer could be
55
+ * matched to it.
56
+ */
57
+ export function askQuestions(questions: readonly HarnessQuestion[]): AskQuestion[] {
58
+ const used = new Set<string>();
59
+ const form: AskQuestion[] = [];
60
+ for (const [index, question] of questions.entries()) {
61
+ const text = cut(question.text.trim(), MAX_QUESTION_TEXT);
62
+ if (text.length === 0) continue;
63
+ const base = question.id.trim().length > 0 ? question.id.trim() : `q${index + 1}`;
64
+ let id = base;
65
+ for (let n = 2; used.has(id); n += 1) id = `${base}-${n}`;
66
+ used.add(id);
67
+ const choices: AskQuestionChoice[] = [];
68
+ for (const choice of question.choices ?? []) {
69
+ const label = cut(choice.label.trim(), MAX_QUESTION_CHOICE_LABEL);
70
+ if (label.length === 0 || isOther(label)) continue;
71
+ if (choices.some((existing) => existing.label === label)) continue;
72
+ choices.push({
73
+ label,
74
+ ...(choice.description === undefined || choice.description.trim().length === 0
75
+ ? {}
76
+ : { description: cut(choice.description.trim(), MAX_QUESTION_CHOICE_DESCRIPTION) }),
77
+ });
78
+ }
79
+ form.push({
80
+ id,
81
+ text,
82
+ ...(question.body === undefined || question.body.length === 0
83
+ ? {}
84
+ : { body: cut(question.body, MAX_QUESTION_BODY) }),
85
+ ...(question.header === undefined || question.header.trim().length === 0
86
+ ? {}
87
+ : { header: cut(question.header.trim(), MAX_QUESTION_HEADER) }),
88
+ ...(choices.length === 0 ? {} : { choices }),
89
+ ...(question.multiple === true ? { multiple: true } : {}),
90
+ ...(question.freeText === true || (question.choices ?? []).some((choice) => isOther(choice.label))
91
+ ? { freeText: true }
92
+ : {}),
93
+ });
94
+ }
95
+ return form;
96
+ }
97
+
98
+ /** The request `ctx.ask` gets for a form: its text, and the answer's way back. */
99
+ export function formRequest(
100
+ form: readonly AskQuestion[],
101
+ resume: unknown,
102
+ options: {
103
+ readonly graceSecs?: number | undefined;
104
+ readonly onTimeout?: "waiting" | "reject_once" | undefined;
105
+ } = {},
106
+ ): AskRequest {
107
+ return {
108
+ prompt: form.map((question) => question.text).join("\n\n"),
109
+ questions: form,
110
+ ...(options.graceSecs === undefined ? {} : { graceSecs: options.graceSecs }),
111
+ ...(options.onTimeout === undefined ? {} : { onTimeout: options.onTimeout }),
112
+ resume: resume as AskRequest["resume"],
113
+ };
114
+ }
115
+
116
+ /** The person's answer to one question, or undefined when they gave none. */
117
+ export function answerFor(
118
+ answers: readonly AskQuestionAnswer[] | undefined,
119
+ id: string,
120
+ ): AskQuestionAnswer | undefined {
121
+ return answers?.find((answer) => answer.id === id);
122
+ }
123
+
124
+ /** The labels and free text of one answer, in one string; empty when skipped. */
125
+ export function answerText(answer: AskQuestionAnswer | undefined): string {
126
+ if (answer === undefined || answer.skipped === true) return "";
127
+ return [...(answer.choices ?? []), ...(answer.text === undefined ? [] : [answer.text])].join(", ");
128
+ }
129
+
130
+ /** True when the person left this question alone. */
131
+ export function isSkipped(answer: AskQuestionAnswer | undefined): boolean {
132
+ return answer === undefined || answer.skipped === true;
133
+ }
package/src/refusal.ts ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The early failed result of an agent step: the reason was found before the
3
+ * program ran, so there is no exit code, session or usage. Every harness writes
4
+ * it the same way, with its own reason and any field its plan adds.
5
+ */
6
+
7
+ import type { PluginStepResult } from "@operad-io/engine";
8
+ import { withTimings, type StepTimings } from "./timings.ts";
9
+ import { standardUsage, type UsageSource } from "./usage.ts";
10
+
11
+ /** What one early refusal writes. */
12
+ export interface RefusalInput {
13
+ /** Writes the message to the step's log and returns its path. */
14
+ readonly log: (message: string) => Promise<string>;
15
+ readonly timings: StepTimings;
16
+ /** The harness and the model known before the run, for the usage line. */
17
+ readonly who: UsageSource;
18
+ readonly reason: string;
19
+ readonly message: string;
20
+ /** A field this harness's result carries, such as codex's image call count. */
21
+ readonly extra?: Readonly<Record<string, unknown>> | undefined;
22
+ }
23
+
24
+ /** The `failed` result of a step that refused before it started its program. */
25
+ export async function refuseResult(input: RefusalInput): Promise<PluginStepResult> {
26
+ const log = await input.log(input.message);
27
+ const timing = input.timings.finish();
28
+ return withTimings(
29
+ {
30
+ result: "failed",
31
+ data: {
32
+ reason: input.reason,
33
+ message: input.message,
34
+ exitCode: null,
35
+ signal: null,
36
+ sessionId: null,
37
+ finalMessage: null,
38
+ usage: standardUsage(input.who, undefined, null),
39
+ log,
40
+ durationMs: timing.totalMs,
41
+ stderr: [input.message],
42
+ ...input.extra,
43
+ },
44
+ },
45
+ timing,
46
+ );
47
+ }
package/src/skills.ts ADDED
@@ -0,0 +1,232 @@
1
+ /**
2
+ * The skill directories a harness step is given. Both reference harnesses read
3
+ * the same `SKILL.md` format (ADR 0011 D2), so they read the name here the same
4
+ * way: a skill without a readable file or a name is skipped by both.
5
+ *
6
+ * A harness that cannot load skills itself gets a short list of them in its
7
+ * prompt instead: name, description and the path of each `SKILL.md`, never its
8
+ * body (ADR 0022 D9).
9
+ */
10
+
11
+ import { readFileSync, statSync } from "node:fs";
12
+ import { basename, dirname, join } from "node:path";
13
+ import type { HarnessCapabilities } from "@operad-io/engine";
14
+
15
+ /** One skill directory that may be given to an agent. */
16
+ export interface GivenSkill {
17
+ /** The absolute directory with the `SKILL.md`. */
18
+ readonly path: string;
19
+ /** The skill's name, from the file's frontmatter. */
20
+ readonly name: string;
21
+ }
22
+
23
+ /** A given directory that is not a skill, and why. */
24
+ export interface SkippedSkill {
25
+ readonly path: string;
26
+ readonly reason: string;
27
+ }
28
+
29
+ export interface GivenSkills {
30
+ readonly skills: readonly GivenSkill[];
31
+ readonly skipped: readonly SkippedSkill[];
32
+ }
33
+
34
+ /** A name the Agent Skills format allows and a file name can hold. */
35
+ const SKILL_NAME = /^[a-z0-9][a-z0-9-]*$/;
36
+
37
+ /** A one-line frontmatter value, with its quotes and an inline comment read. */
38
+ function inlineValue(raw: string): string | undefined {
39
+ let value = raw.trim();
40
+ const quote = value[0];
41
+ if (quote === '"' || quote === "'") {
42
+ const close = value.lastIndexOf(quote);
43
+ const rest = close > 0 ? value.slice(close + 1).trim() : "";
44
+ if (close > 0 && (rest.length === 0 || rest.startsWith("#"))) {
45
+ value = value.slice(1, close);
46
+ return value.length === 0 ? undefined : value;
47
+ }
48
+ }
49
+ const comment = value.search(/\s#/);
50
+ if (comment !== -1) value = value.slice(0, comment).trimEnd();
51
+ if (
52
+ value.length >= 2 &&
53
+ ((value.startsWith('"') && value.endsWith('"')) ||
54
+ (value.startsWith("'") && value.endsWith("'")))
55
+ ) {
56
+ value = value.slice(1, -1);
57
+ }
58
+ return value.length === 0 ? undefined : value;
59
+ }
60
+
61
+ /** A block scalar's lines, ended by the frontmatter's closing `---` or an unindented line. */
62
+ function blockLines(lines: readonly string[], index: number): string[] {
63
+ const parts: string[] = [];
64
+ for (let next = index + 1; next < lines.length; next += 1) {
65
+ const entry = lines[next] ?? "";
66
+ if (entry.trim() === "---") break;
67
+ if (entry.trim().length === 0) {
68
+ parts.push("");
69
+ continue;
70
+ }
71
+ if (!/^\s/.test(entry)) break;
72
+ parts.push(entry.trim());
73
+ }
74
+ while (parts.at(-1) === "") parts.pop();
75
+ while (parts[0] === "") parts.shift();
76
+ return parts;
77
+ }
78
+
79
+ /** A block scalar as one value: `|` keeps its lines, `>` folds them. */
80
+ function blockValue(parts: readonly string[], indicator: string): string | undefined {
81
+ let value: string;
82
+ if (indicator.startsWith("|")) {
83
+ value = parts.join("\n").trim();
84
+ } else {
85
+ const folded: string[] = [];
86
+ let paragraph: string[] = [];
87
+ for (const part of parts) {
88
+ if (part.length === 0) {
89
+ if (paragraph.length > 0) folded.push(paragraph.join(" "));
90
+ paragraph = [];
91
+ } else {
92
+ paragraph.push(part);
93
+ }
94
+ }
95
+ if (paragraph.length > 0) folded.push(paragraph.join(" "));
96
+ value = folded.join("\n").trim();
97
+ }
98
+ return value.length === 0 ? undefined : value;
99
+ }
100
+
101
+ /** One field of a `SKILL.md` frontmatter, or undefined when it has none. */
102
+ function frontmatterValue(content: string, key: string): string | undefined {
103
+ const text = content.charCodeAt(0) === 0xfeff ? content.slice(1) : content;
104
+ const lines = text.split(/\r?\n/);
105
+ if (lines[0]?.trim() !== "---") return undefined;
106
+ const pattern = new RegExp(`^${key}\\s*:\\s*(.*)$`);
107
+ for (let index = 1; index < lines.length; index += 1) {
108
+ const line = lines[index] ?? "";
109
+ if (line.trim() === "---") return undefined;
110
+ const match = pattern.exec(line);
111
+ if (match === null) continue;
112
+ const raw = (match[1] ?? "").trim();
113
+ const block = /^([>|][+-]?)(?:\s+#.*)?$/.exec(raw);
114
+ if (block !== null) return blockValue(blockLines(lines, index), block[1] ?? "");
115
+ return inlineValue(raw);
116
+ }
117
+ return undefined;
118
+ }
119
+
120
+ /** The `name` of a `SKILL.md`, or undefined when its frontmatter has none. */
121
+ export function skillName(content: string): string | undefined {
122
+ return frontmatterValue(content, "name");
123
+ }
124
+
125
+ /** The `description` of a `SKILL.md`, or undefined when its frontmatter has none. */
126
+ export function skillDescription(content: string): string | undefined {
127
+ return frontmatterValue(content, "description");
128
+ }
129
+
130
+ /** Reads the directories the step gave: the skills that can be loaded, and the ones it skips. */
131
+ export function readGivenSkills(paths: readonly string[]): GivenSkills {
132
+ const skills: GivenSkill[] = [];
133
+ const skipped: SkippedSkill[] = [];
134
+ const names = new Set<string>();
135
+ for (const path of paths) {
136
+ let directory = path;
137
+ let file = join(path, "SKILL.md");
138
+ try {
139
+ if (statSync(path).isFile()) {
140
+ if (basename(path) !== "SKILL.md") {
141
+ skipped.push({ path, reason: "the given path is not a skill directory" });
142
+ continue;
143
+ }
144
+ directory = dirname(path);
145
+ file = path;
146
+ }
147
+ } catch {
148
+ skipped.push({ path, reason: "SKILL.md cannot be read" });
149
+ continue;
150
+ }
151
+ let content: string;
152
+ try {
153
+ content = readFileSync(file, "utf8");
154
+ } catch {
155
+ skipped.push({ path, reason: "SKILL.md cannot be read" });
156
+ continue;
157
+ }
158
+ const name = skillName(content);
159
+ if (name === undefined) {
160
+ skipped.push({ path, reason: "SKILL.md has no name" });
161
+ continue;
162
+ }
163
+ if (!SKILL_NAME.test(name) || name.length > 64) {
164
+ skipped.push({ path, reason: `the name "${name}" is not a skill name` });
165
+ continue;
166
+ }
167
+ if (names.has(name)) {
168
+ skipped.push({ path, reason: `the name "${name}" is already given` });
169
+ continue;
170
+ }
171
+ names.add(name);
172
+ skills.push({ path: directory, name });
173
+ }
174
+ return { skills, skipped };
175
+ }
176
+
177
+ /** The most skills the prompt lists; any beyond it are counted, not listed. */
178
+ export const MAX_PROMPT_SKILLS = 20;
179
+
180
+ /** The most characters of a description the prompt carries, then `...`. */
181
+ export const MAX_PROMPT_DESCRIPTION_CHARS = 160;
182
+
183
+ /** A description on one line, cut at the cap. */
184
+ function promptDescription(description: string): string {
185
+ const oneLine = description.replace(/\s+/g, " ").trim();
186
+ if (oneLine.length <= MAX_PROMPT_DESCRIPTION_CHARS) return oneLine;
187
+ return `${oneLine.slice(0, MAX_PROMPT_DESCRIPTION_CHARS).trimEnd()}...`;
188
+ }
189
+
190
+ /**
191
+ * The short skill list a harness that does not load skills itself gets in its
192
+ * prompt: each readable skill's name, its description and the path of its
193
+ * `SKILL.md`, and one sentence to read that file first. Empty when no skill can
194
+ * be read; a skill whose `SKILL.md` cannot be read is left out.
195
+ */
196
+ export function skillListText(paths: readonly string[]): string {
197
+ const given = readGivenSkills(paths);
198
+ const listed = given.skills.slice(0, MAX_PROMPT_SKILLS);
199
+ if (listed.length === 0) return "";
200
+ const lines = ["Read a skill's SKILL.md before doing what it describes."];
201
+ for (const skill of listed) {
202
+ const file = join(skill.path, "SKILL.md");
203
+ let description: string | undefined;
204
+ try {
205
+ description = skillDescription(readFileSync(file, "utf8"));
206
+ } catch {
207
+ description = undefined;
208
+ }
209
+ const head = description === undefined ? skill.name : `${skill.name}: ${promptDescription(description)}`;
210
+ lines.push(`- ${head} (SKILL.md at ${file})`);
211
+ }
212
+ const omitted = given.skills.length - listed.length;
213
+ if (omitted > 0) {
214
+ lines.push(`Only the first ${MAX_PROMPT_SKILLS} skills are listed; ${omitted} more are not.`);
215
+ }
216
+ return lines.join("\n");
217
+ }
218
+
219
+ /**
220
+ * The prompt a harness step runs: the step's prompt, plus the skill list when
221
+ * the harness does not declare that it loads skills itself. A harness that
222
+ * declares `loadsSkills` never gets the list.
223
+ */
224
+ export function promptWithSkills(
225
+ prompt: string,
226
+ paths: readonly string[],
227
+ capabilities?: HarnessCapabilities,
228
+ ): string {
229
+ if (capabilities?.loadsSkills === true || paths.length === 0) return prompt;
230
+ const list = skillListText(paths);
231
+ return list.length === 0 ? prompt : `${prompt}\n\n${list}`;
232
+ }
package/src/step.ts CHANGED
@@ -4,8 +4,8 @@
4
4
  * the run's outcome into a step result.
5
5
  */
6
6
 
7
- import { stat } from "node:fs/promises";
8
- import type { AgentResultData, PluginStepResult } from "@operad-io/engine";
7
+ import { directoryError } from "@operad-io/engine";
8
+ import type { AgentResultData, CostQuality, PluginStepResult } from "@operad-io/engine";
9
9
  import { MAX_LINE_CHARS, type AgentRunOutcome } from "./process.ts";
10
10
  import { standardUsage, type RawCounts, type UsageSource } from "./usage.ts";
11
11
  import { isRecord } from "@operad-io/engine";
@@ -22,16 +22,27 @@ export interface AgentWorkerResult {
22
22
  /** `quality` is `estimated` for an API-price figure; `incomplete` when some message had no price. */
23
23
  readonly cost: {
24
24
  readonly micros: number;
25
- readonly quality?: "estimated" | "exact";
25
+ readonly quality?: CostQuality;
26
26
  readonly incomplete?: true;
27
27
  } | null;
28
28
  readonly finalMessage: string | null;
29
29
  /** The model that did the work, when the worker reports it. */
30
30
  readonly model?: string | null;
31
+ /** The context at the end of a finished reply, when the worker can tell. */
32
+ readonly context?: {
33
+ readonly used: number;
34
+ readonly window?: number;
35
+ } | undefined;
31
36
  readonly reason?: string;
32
37
  readonly message?: string;
33
38
  /** Set when the worker saw a rate limit: it is a usage limit whatever the text says. */
34
- readonly modelError?: { readonly kind: string };
39
+ readonly modelError?: {
40
+ readonly kind: string;
41
+ readonly status?: number | null;
42
+ readonly retry_after_secs?: number | null;
43
+ /** When the model gave the error, in epoch milliseconds, when the worker can tell. */
44
+ readonly reported_at?: number | null;
45
+ };
35
46
  }
36
47
 
37
48
  export function text(value: unknown, at: string): string {
@@ -52,6 +63,15 @@ export function secs(value: unknown, at: string): number {
52
63
  return value;
53
64
  }
54
65
 
66
+ /** A positive number in a setting, or undefined when it is unset; names the field when it is not. */
67
+ export function optionalPositive(value: unknown, at: string, integer: boolean): number | undefined {
68
+ if (value === undefined) return undefined;
69
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || (integer && !Number.isInteger(value))) {
70
+ throw new Error(`${at}: must be a positive ${integer ? "integer" : "number"}`);
71
+ }
72
+ return value;
73
+ }
74
+
55
75
  export function stringListParam(value: unknown, at: string): readonly string[] {
56
76
  if (value === undefined) return [];
57
77
  if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
@@ -114,23 +134,10 @@ export function parseStepFlags<Level extends string>(
114
134
  };
115
135
  }
116
136
 
117
- export async function directoryError(cwd: string): Promise<string | undefined> {
118
- try {
119
- const info = await stat(cwd);
120
- return info.isDirectory() ? undefined : `cwd is not a directory: ${cwd}`;
121
- } catch {
122
- return `cwd does not exist: ${cwd}`;
123
- }
124
- }
137
+ export { directoryError };
125
138
 
126
- /** Reads a `result` line of the worker, or undefined for any other line. */
127
- export function parseResult<Result extends AgentWorkerResult>(line: string): Result | undefined {
128
- let value: unknown;
129
- try {
130
- value = JSON.parse(line);
131
- } catch {
132
- return undefined;
133
- }
139
+ /** Reads a worker's `result` value, or undefined when it is another line. */
140
+ export function resultValue<Result extends AgentWorkerResult>(value: unknown): Result | undefined {
134
141
  if (!isRecord(value) || value.type !== "result") return undefined;
135
142
  const name = value.result;
136
143
  if (name !== "done" && name !== "failed" && name !== "cancelled") return undefined;
@@ -139,12 +146,53 @@ export function parseResult<Result extends AgentWorkerResult>(line: string): Res
139
146
 
140
147
  const UNAVAILABLE = /\b429\b|\b(?:503|529)\b|overloaded|rate[ _-]?limit|too many requests/i;
141
148
  const USAGE_LIMIT = /usage[ _-]?limit|quota|exceeded your (?:current )?(?:usage|plan|quota)|insufficient[ _-]credit|out of credits/i;
149
+ /** A provider's own retry-after or reset wait: the number and its unit. */
150
+ const RETRY_AFTER = /\b(?:retry[- ]after|try again (?:in|after)|retry in|available(?: again)? in|resets? in)\s*[:=]?\s*(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|secs?|seconds?|m|mins?|minutes?|h|hrs?|hours?|d|days?|w|weeks?|mo(?:nths?)?)?(?![a-z])/i;
151
+
152
+ /**
153
+ * The seconds a model's message says to wait, from a retry-after or reset
154
+ * phrase. A bare number after such a phrase is seconds. Undefined when the
155
+ * message gives no such wait; a date or a time of day is not read, because its
156
+ * day is unknown.
157
+ */
158
+ export function retryAfterSecsOf(message: string): number | undefined {
159
+ const found = RETRY_AFTER.exec(message);
160
+ if (found === null) return undefined;
161
+ const unit = found[2];
162
+ // A word after the number is a unit this parser does not know, not seconds.
163
+ if (
164
+ unit === undefined &&
165
+ /^\s*[a-z]/i.test(message.slice(found.index + found[0].length))
166
+ ) {
167
+ return undefined;
168
+ }
169
+ const value = Number(found[1]);
170
+ if (!Number.isFinite(value) || value <= 0) return undefined;
171
+ const unitName = (unit ?? "s").toLowerCase();
172
+ const factor =
173
+ unitName.startsWith("millisecond") || unitName === "ms"
174
+ ? 1 / 1000
175
+ : unitName.startsWith("min") || unitName === "m"
176
+ ? 60
177
+ : unitName.startsWith("h")
178
+ ? 60 * 60
179
+ : unitName.startsWith("mo")
180
+ ? 30 * 24 * 60 * 60
181
+ : unitName.startsWith("w")
182
+ ? 7 * 24 * 60 * 60
183
+ : unitName.startsWith("d")
184
+ ? 24 * 60 * 60
185
+ : 1;
186
+ const seconds = Math.ceil(value * factor);
187
+ return seconds > 0 ? seconds : undefined;
188
+ }
142
189
 
143
190
  /**
144
191
  * The `modelError` of a worker failure with reason `model_error`, in the shape
145
192
  * `radian` gives. `kind` comes from the message: a usage limit is
146
193
  * `usage_limit`, a 429 or an overloaded provider is `unavailable`, anything else
147
- * is `protocol`. A usage-limit message wins over a 429 in the same text.
194
+ * is `protocol`. A usage-limit message wins over a 429 in the same text. A wait
195
+ * the message names is `retry_after_secs`; without one it is null.
148
196
  */
149
197
  export function modelErrorOf(message: string): Record<string, unknown> {
150
198
  const status = /\b(429|503|529)\b/.exec(message);
@@ -154,11 +202,21 @@ export function modelErrorOf(message: string): Record<string, unknown> {
154
202
  return {
155
203
  kind,
156
204
  status: status === null ? null : Number(status[1]),
157
- retry_after_secs: null,
205
+ retry_after_secs: retryAfterSecsOf(message) ?? null,
158
206
  message,
159
207
  };
160
208
  }
161
209
 
210
+ /** A worker's end-of-reply context, when it has a whole token count. */
211
+ export function contextOf(value: unknown): { readonly used: number; readonly window?: number } | undefined {
212
+ if (!isRecord(value)) return undefined;
213
+ const used = value.used;
214
+ if (typeof used !== "number" || !Number.isInteger(used) || used < 0) return undefined;
215
+ const window = value.window;
216
+ const known = typeof window === "number" && Number.isInteger(window) && window > 0 ? window : undefined;
217
+ return { used, ...(known === undefined ? {} : { window: known }) };
218
+ }
219
+
162
220
  export function agentData(
163
221
  who: UsageSource,
164
222
  outcome: AgentRunOutcome,
@@ -174,12 +232,15 @@ export function agentData(
174
232
  incomplete: result.cost.incomplete === true,
175
233
  estimated: result.cost.quality === "estimated",
176
234
  };
235
+ const context = contextOf(result?.context);
177
236
  return {
178
237
  exitCode: outcome.exitCode,
179
238
  signal: outcome.signal,
180
239
  sessionId: result?.sessionId ?? null,
181
240
  finalMessage: result?.finalMessage ?? null,
241
+ ...(result?.message === undefined ? {} : { message: result.message }),
182
242
  usage: standardUsage(who, result?.usage, cost),
243
+ ...(context === undefined ? {} : { context }),
183
244
  log,
184
245
  durationMs,
185
246
  stderr: outcome.stderrTail,
@@ -270,10 +331,31 @@ export function resultFor(
270
331
  if (result.result === "failed") {
271
332
  const message = result.message ?? "the harness failed";
272
333
  // A rate limit the worker saw is a usage limit whatever the text says.
334
+ const byText = modelErrorOf(message);
335
+ const given = result.modelError;
336
+ const positive = (value: unknown): number | undefined =>
337
+ typeof value === "number" && Number.isFinite(value) && value > 0
338
+ ? value
339
+ : undefined;
340
+ const retryAfterSecs =
341
+ positive(given?.retry_after_secs) ?? positive(byText["retry_after_secs"]);
273
342
  const modelError =
274
- result.modelError !== undefined
275
- ? { kind: result.modelError.kind, status: null, retry_after_secs: null, message }
276
- : modelErrorOf(message);
343
+ given !== undefined
344
+ ? {
345
+ kind: given.kind,
346
+ status: positive(given.status) ?? positive(byText["status"]) ?? null,
347
+ retry_after_secs: retryAfterSecs ?? null,
348
+ ...(retryAfterSecs === undefined
349
+ ? {}
350
+ : { reported_at: positive(given.reported_at) ?? Date.now() }),
351
+ message,
352
+ }
353
+ : {
354
+ ...byText,
355
+ ...(retryAfterSecs === undefined
356
+ ? {}
357
+ : { reported_at: Date.now() }),
358
+ };
277
359
  return fail({
278
360
  reason: result.reason ?? "exit",
279
361
  message,