@autumnsgrove/lyra 0.1.0 → 0.3.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 (173) hide show
  1. package/dist/adapters/cloudflare/index.d.ts +1 -0
  2. package/dist/adapters/cloudflare/index.d.ts.map +1 -1
  3. package/dist/adapters/cloudflare/index.js +1 -0
  4. package/dist/adapters/cloudflare/index.js.map +1 -1
  5. package/dist/adapters/cloudflare/session.d.ts +102 -0
  6. package/dist/adapters/cloudflare/session.d.ts.map +1 -0
  7. package/dist/adapters/cloudflare/session.js +595 -0
  8. package/dist/adapters/cloudflare/session.js.map +1 -0
  9. package/dist/adapters/openai/errors.d.ts +36 -0
  10. package/dist/adapters/openai/errors.d.ts.map +1 -0
  11. package/dist/adapters/openai/errors.js +117 -0
  12. package/dist/adapters/openai/errors.js.map +1 -0
  13. package/dist/adapters/openai/index.d.ts +18 -0
  14. package/dist/adapters/openai/index.d.ts.map +1 -0
  15. package/dist/adapters/openai/index.js +18 -0
  16. package/dist/adapters/openai/index.js.map +1 -0
  17. package/dist/adapters/openai/model.d.ts +50 -0
  18. package/dist/adapters/openai/model.d.ts.map +1 -0
  19. package/dist/adapters/openai/model.js +169 -0
  20. package/dist/adapters/openai/model.js.map +1 -0
  21. package/dist/adapters/openai/presets.d.ts +36 -0
  22. package/dist/adapters/openai/presets.d.ts.map +1 -0
  23. package/dist/adapters/openai/presets.js +43 -0
  24. package/dist/adapters/openai/presets.js.map +1 -0
  25. package/dist/adapters/openai/request.d.ts +47 -0
  26. package/dist/adapters/openai/request.d.ts.map +1 -0
  27. package/dist/adapters/openai/request.js +93 -0
  28. package/dist/adapters/openai/request.js.map +1 -0
  29. package/dist/adapters/openai/sse.d.ts +44 -0
  30. package/dist/adapters/openai/sse.d.ts.map +1 -0
  31. package/dist/adapters/openai/sse.js +410 -0
  32. package/dist/adapters/openai/sse.js.map +1 -0
  33. package/dist/core/approval.d.ts +38 -0
  34. package/dist/core/approval.d.ts.map +1 -0
  35. package/dist/core/approval.js +47 -0
  36. package/dist/core/approval.js.map +1 -0
  37. package/dist/core/compaction.d.ts +193 -0
  38. package/dist/core/compaction.d.ts.map +1 -0
  39. package/dist/core/compaction.js +460 -0
  40. package/dist/core/compaction.js.map +1 -0
  41. package/dist/core/define-recipe.d.ts +8 -1
  42. package/dist/core/define-recipe.d.ts.map +1 -1
  43. package/dist/core/define-recipe.js +13 -0
  44. package/dist/core/define-recipe.js.map +1 -1
  45. package/dist/core/events.d.ts +32 -2
  46. package/dist/core/events.d.ts.map +1 -1
  47. package/dist/core/events.js +16 -1
  48. package/dist/core/events.js.map +1 -1
  49. package/dist/core/execute-tools.d.ts +7 -0
  50. package/dist/core/execute-tools.d.ts.map +1 -1
  51. package/dist/core/execute-tools.js +6 -0
  52. package/dist/core/execute-tools.js.map +1 -1
  53. package/dist/core/hash.d.ts +10 -0
  54. package/dist/core/hash.d.ts.map +1 -0
  55. package/dist/core/hash.js +14 -0
  56. package/dist/core/hash.js.map +1 -0
  57. package/dist/core/model.d.ts +12 -0
  58. package/dist/core/model.d.ts.map +1 -1
  59. package/dist/core/propose.d.ts +29 -0
  60. package/dist/core/propose.d.ts.map +1 -0
  61. package/dist/core/propose.js +75 -0
  62. package/dist/core/propose.js.map +1 -0
  63. package/dist/core/recipe.d.ts +2 -0
  64. package/dist/core/recipe.d.ts.map +1 -1
  65. package/dist/core/recipe.js +5 -8
  66. package/dist/core/recipe.js.map +1 -1
  67. package/dist/core/resume.d.ts +19 -1
  68. package/dist/core/resume.d.ts.map +1 -1
  69. package/dist/core/resume.js +64 -6
  70. package/dist/core/resume.js.map +1 -1
  71. package/dist/core/retry.d.ts +9 -0
  72. package/dist/core/retry.d.ts.map +1 -0
  73. package/dist/core/retry.js +9 -0
  74. package/dist/core/retry.js.map +1 -0
  75. package/dist/core/run-handle.d.ts +5 -0
  76. package/dist/core/run-handle.d.ts.map +1 -1
  77. package/dist/core/run-handle.js +1 -0
  78. package/dist/core/run-handle.js.map +1 -1
  79. package/dist/core/run.d.ts +29 -2
  80. package/dist/core/run.d.ts.map +1 -1
  81. package/dist/core/run.js +526 -132
  82. package/dist/core/run.js.map +1 -1
  83. package/dist/core/runtime.d.ts +12 -0
  84. package/dist/core/runtime.d.ts.map +1 -1
  85. package/dist/core/runtime.js +34 -2
  86. package/dist/core/runtime.js.map +1 -1
  87. package/dist/core/system-clock.d.ts.map +1 -1
  88. package/dist/core/system-clock.js +5 -1
  89. package/dist/core/system-clock.js.map +1 -1
  90. package/dist/core/tool.d.ts +55 -0
  91. package/dist/core/tool.d.ts.map +1 -1
  92. package/dist/core/tool.js +16 -0
  93. package/dist/core/tool.js.map +1 -1
  94. package/dist/core/usage.d.ts +27 -0
  95. package/dist/core/usage.d.ts.map +1 -0
  96. package/dist/core/usage.js +67 -0
  97. package/dist/core/usage.js.map +1 -0
  98. package/dist/index.d.ts +7 -0
  99. package/dist/index.d.ts.map +1 -1
  100. package/dist/index.js +7 -0
  101. package/dist/index.js.map +1 -1
  102. package/dist/protocol/answers.d.ts +33 -0
  103. package/dist/protocol/answers.d.ts.map +1 -0
  104. package/dist/protocol/answers.js +86 -0
  105. package/dist/protocol/answers.js.map +1 -0
  106. package/dist/protocol/commands.d.ts +84 -0
  107. package/dist/protocol/commands.d.ts.map +1 -0
  108. package/dist/protocol/commands.js +232 -0
  109. package/dist/protocol/commands.js.map +1 -0
  110. package/dist/protocol/events.d.ts +145 -0
  111. package/dist/protocol/events.d.ts.map +1 -0
  112. package/dist/protocol/events.js +195 -0
  113. package/dist/protocol/events.js.map +1 -0
  114. package/dist/protocol/frames.d.ts +72 -0
  115. package/dist/protocol/frames.d.ts.map +1 -0
  116. package/dist/protocol/frames.js +134 -0
  117. package/dist/protocol/frames.js.map +1 -0
  118. package/dist/protocol/http.d.ts +52 -0
  119. package/dist/protocol/http.d.ts.map +1 -0
  120. package/dist/protocol/http.js +357 -0
  121. package/dist/protocol/http.js.map +1 -0
  122. package/dist/protocol/reader.d.ts +35 -0
  123. package/dist/protocol/reader.d.ts.map +1 -0
  124. package/dist/protocol/reader.js +71 -0
  125. package/dist/protocol/reader.js.map +1 -0
  126. package/dist/protocol/session.d.ts +85 -0
  127. package/dist/protocol/session.d.ts.map +1 -0
  128. package/dist/protocol/session.js +801 -0
  129. package/dist/protocol/session.js.map +1 -0
  130. package/dist/record/entries.d.ts +110 -2
  131. package/dist/record/entries.d.ts.map +1 -1
  132. package/dist/record/entries.js +337 -10
  133. package/dist/record/entries.js.map +1 -1
  134. package/dist/record/replay.d.ts +6 -0
  135. package/dist/record/replay.d.ts.map +1 -1
  136. package/dist/record/replay.js +11 -3
  137. package/dist/record/replay.js.map +1 -1
  138. package/dist/record/truncate.d.ts +12 -0
  139. package/dist/record/truncate.d.ts.map +1 -1
  140. package/dist/record/truncate.js +72 -1
  141. package/dist/record/truncate.js.map +1 -1
  142. package/dist/testkit/cassette.d.ts +91 -0
  143. package/dist/testkit/cassette.d.ts.map +1 -0
  144. package/dist/testkit/cassette.js +250 -0
  145. package/dist/testkit/cassette.js.map +1 -0
  146. package/dist/testkit/fake-model-server.d.ts +104 -0
  147. package/dist/testkit/fake-model-server.d.ts.map +1 -0
  148. package/dist/testkit/fake-model-server.js +251 -0
  149. package/dist/testkit/fake-model-server.js.map +1 -0
  150. package/dist/testkit/index.d.ts +5 -2
  151. package/dist/testkit/index.d.ts.map +1 -1
  152. package/dist/testkit/index.js +5 -2
  153. package/dist/testkit/index.js.map +1 -1
  154. package/dist/testkit/misbehaving-model.d.ts +40 -0
  155. package/dist/testkit/misbehaving-model.d.ts.map +1 -0
  156. package/dist/testkit/misbehaving-model.js +134 -0
  157. package/dist/testkit/misbehaving-model.js.map +1 -0
  158. package/dist/testkit/model.d.ts +20 -0
  159. package/dist/testkit/model.d.ts.map +1 -1
  160. package/dist/testkit/model.js +50 -3
  161. package/dist/testkit/model.js.map +1 -1
  162. package/dist/testkit/scenario.d.ts +36 -2
  163. package/dist/testkit/scenario.d.ts.map +1 -1
  164. package/dist/testkit/scenario.js +98 -13
  165. package/dist/testkit/scenario.js.map +1 -1
  166. package/dist/testkit/timeline-recipe.d.ts.map +1 -1
  167. package/dist/testkit/timeline-recipe.js +3 -0
  168. package/dist/testkit/timeline-recipe.js.map +1 -1
  169. package/dist/testkit/tools.d.ts +15 -1
  170. package/dist/testkit/tools.d.ts.map +1 -1
  171. package/dist/testkit/tools.js +19 -0
  172. package/dist/testkit/tools.js.map +1 -1
  173. package/package.json +5 -1
package/dist/core/run.js CHANGED
@@ -12,20 +12,33 @@
12
12
  * the run once, with `failed`, and `run_end` is still emitted: the record says how
13
13
  * far it got, and a client that was watching is not left waiting.
14
14
  */
15
- import { executeTools } from "./execute-tools.js";
15
+ import { deniedByRecipe, deniedOutcome, deniedWithoutAPerson, policyOf, } from "./approval.js";
16
+ import { buildView, chooseCut, currentStateTexts, DEFAULT_KEEP_TOKENS, DEFAULT_RESULT_CAP_BYTES, DEFAULT_SUMMARY_INSTRUCTIONS, defaultReserveTokens, estimateConversation, estimateSinceLastReply, shouldCompact, summarize, summaryMaterial, validateCompactionSettings, } from "./compaction.js";
17
+ import { executeTools, usableArguments } from "./execute-tools.js";
18
+ import { parkedReasonOf, } from "./events.js";
16
19
  import { reachedLimit, validateLimits } from "./limits.js";
20
+ import { createUsageTotal } from "./usage.js";
17
21
  import { compareTools, describeChange, pinRecipe } from "./recipe.js";
22
+ import { hashText } from "./hash.js";
23
+ import { RETRY_DELAYS_MS } from "./retry.js";
18
24
  import { formatErrors } from "./schema.js";
19
25
  import { readResumeSeed, reserveIds } from "./resume.js";
20
26
  import { replayState } from "./state.js";
21
- import { fitEntry, utf8Length } from "../record/truncate.js";
27
+ import { activePath, entryMessage } from "../record/replay.js";
28
+ import { cutText, fitEntry, utf8Length } from "../record/truncate.js";
22
29
  import { RECORD_VERSION, encodeEntry, encodeHeader, } from "../record/entries.js";
23
30
  /** Five minutes, per docs/implementation/01-core-with-fakes.md, "Judgment calls already made". */
24
31
  export const DEFAULT_TOOL_DEADLINE_MS = 300_000;
25
32
  /** One record entry is capped at 1 MiB (decision 90), because a row is 2 MB. */
26
33
  export const DEFAULT_ENTRY_CAP_BYTES = 1_048_576;
27
- /** Three retries with growing delays, per decision 26; a healthy run never waits. */
28
- const RETRY_DELAYS_MS = [1_000, 4_000, 16_000];
34
+ /**
35
+ * A byte cap a caller set, when it is one that says anything. A zero, a fraction
36
+ * or a negative has no meaning as a limit, so it is not one: the next cap out
37
+ * applies instead of the result being emptied.
38
+ */
39
+ function usableCap(value) {
40
+ return value !== undefined && Number.isSafeInteger(value) && value > 0 ? value : undefined;
41
+ }
29
42
  /** The cap an entry has: the record's own, lowered to the storage's when that is smaller. */
30
43
  export function entryCapBytes(storage, requested) {
31
44
  const own = requested ?? DEFAULT_ENTRY_CAP_BYTES;
@@ -82,81 +95,6 @@ function messageOf(error) {
82
95
  const text = error instanceof Error ? error.message : String(error);
83
96
  return text.slice(0, 500);
84
97
  }
85
- /**
86
- * Tokens always add up. A cost total only means something when every reply
87
- * reported one, from the same kind of billing (decision 15), so one reply without
88
- * a cost drops the total for the run instead of reporting a number that is too low.
89
- *
90
- * A cost *limit* is different: it compares against every amount reported, whatever
91
- * its source, and it is unenforceable as soon as one reply reports none, because
92
- * the total is then understated (LIM05).
93
- */
94
- function createUsageTotal() {
95
- let inputTokens = 0;
96
- let outputTokens = 0;
97
- let cost;
98
- let costKnown = true;
99
- let spent = 0;
100
- let everyCostReported = true;
101
- return {
102
- add(next) {
103
- inputTokens += next.inputTokens;
104
- outputTokens += next.outputTokens;
105
- if (next.cost === undefined) {
106
- everyCostReported = false;
107
- }
108
- else {
109
- spent += next.cost.amount;
110
- }
111
- if (!costKnown) {
112
- return;
113
- }
114
- if (next.cost === undefined) {
115
- costKnown = false;
116
- }
117
- else if (cost === undefined) {
118
- cost = next.cost;
119
- }
120
- else if (cost.source === next.cost.source) {
121
- cost = {
122
- amount: cost.amount + next.cost.amount,
123
- currency: "USD",
124
- source: cost.source,
125
- };
126
- }
127
- else {
128
- costKnown = false;
129
- }
130
- },
131
- total() {
132
- const sum = { inputTokens, outputTokens };
133
- if (costKnown && cost !== undefined) {
134
- sum.cost = cost;
135
- }
136
- return sum;
137
- },
138
- tokens() {
139
- return inputTokens + outputTokens;
140
- },
141
- costSpent() {
142
- return { amount: spent, known: everyCostReported };
143
- },
144
- };
145
- }
146
- /**
147
- * A parked reason as this build knows it. A record written by a newer Lyra may name
148
- * one that is not here, and guessing would overrule a person's decision, so an
149
- * unknown reason is reported as `stuck` with the raw reason kept in the detail.
150
- */
151
- const KNOWN_PARKED_REASONS = [
152
- "stopped",
153
- "stuck",
154
- "limit",
155
- "model_unavailable",
156
- ];
157
- function parkedReasonOf(reason) {
158
- return KNOWN_PARKED_REASONS.find((known) => known === reason) ?? "stuck";
159
- }
160
98
  export async function runTask(config) {
161
99
  const clock = config.clock;
162
100
  const runId = config.runId;
@@ -164,7 +102,18 @@ export async function runTask(config) {
164
102
  const entryCap = entryCapBytes(config.storage, config.entryCapBytes);
165
103
  const signal = config.signal ?? new AbortController().signal;
166
104
  const control = config.control;
167
- const messages = [];
105
+ /**
106
+ * The conversation as the model sees it: the latest summary, each tool's current
107
+ * state, and the entries the record's pointer keeps. It is rebuilt from the
108
+ * record at a compaction, so the live view and a resumed one cannot drift.
109
+ */
110
+ let messages = [];
111
+ /** The entries the view keeps, which is what a later cut is chosen from. */
112
+ let viewEntries = [];
113
+ /** The latest summary, which a new one updates rather than restarts (decision 40). */
114
+ let previousSummary;
115
+ /** The last request's reported input tokens, which the estimate starts from. */
116
+ let lastInputTokens;
168
117
  const tools = new Map(config.tools.map((tool) => [tool.spec.name, tool]));
169
118
  let live = true;
170
119
  /**
@@ -178,6 +127,14 @@ export async function runTask(config) {
178
127
  let turns = 0;
179
128
  /** The id of the entry before the next one, which is what `parent` records. */
180
129
  let parent = null;
130
+ /** Whether a person can be reached to answer a request (decision 35). */
131
+ const canAsk = config.canAsk === true;
132
+ /** The recipe's own default policy, for a tool that says nothing (decision 35). */
133
+ const approvalDefault = config.approvals?.policy;
134
+ /** After this, an unanswered request is denied (decision 37). */
135
+ const requestTimeoutMs = config.approvals?.timeoutMs;
136
+ /** Set when a call is waiting for a person, which parks the run after the batch. */
137
+ let waitingRequest;
181
138
  /** The clock time the run's latest `running` or `resumed` status was saved. */
182
139
  let activeSince = clock.now();
183
140
  /** Active milliseconds already spent before this segment began (LIM04, LIM06). */
@@ -234,6 +191,14 @@ export async function runTask(config) {
234
191
  }
235
192
  const seq = await save(line);
236
193
  parent = entry.id;
194
+ // One place keeps the conversation in step with the record: an entry the model
195
+ // would read becomes a message. A compaction is the caller's to handle, because
196
+ // it rebuilds the view rather than adding to it.
197
+ const message = entryMessage(entry);
198
+ if (message !== undefined) {
199
+ viewEntries.push(entry);
200
+ messages.push(message);
201
+ }
237
202
  return seq;
238
203
  };
239
204
  const saveStatus = async (state, reason, detail) => {
@@ -350,9 +315,7 @@ export async function runTask(config) {
350
315
  label,
351
316
  text: message.text,
352
317
  };
353
- const seq = await append(entry);
354
- messages.push({ role: "user", text: message.text });
355
- return seq;
318
+ return append(entry);
356
319
  };
357
320
  /**
358
321
  * Read what the run's owner queued, at a gap. Returns whether anything arrived,
@@ -368,7 +331,51 @@ export async function runTask(config) {
368
331
  }
369
332
  return queued.length > 0;
370
333
  };
334
+ /**
335
+ * Save a result, and hand back what was saved. The content is what the model
336
+ * saw, which is what the record and the event both carry.
337
+ */
338
+ /**
339
+ * A question's answer as the call's result. The same outcome a live tool would
340
+ * have returned, so `apply` and a replay see one shape (decision 112).
341
+ */
342
+ const saveAnsweredCall = async (call, decided) => {
343
+ const chosen = (decided.ids ?? []).join(", ");
344
+ const answer = {
345
+ isError: false,
346
+ content: decided.text ?? `the person chose ${chosen === "" ? "nothing" : chosen}`,
347
+ details: {
348
+ ...(decided.text === undefined ? {} : { answer: decided.text }),
349
+ ...(decided.ids === undefined ? {} : { ids: decided.ids }),
350
+ },
351
+ };
352
+ const saved = await saveToolResult(call, answer);
353
+ emit({
354
+ type: "tool_end",
355
+ run: runId,
356
+ ts: clock.now(),
357
+ seq: saved.seq,
358
+ callId: call.id,
359
+ name: call.name,
360
+ isError: false,
361
+ content: saved.content,
362
+ });
363
+ const tool = tools.get(call.name);
364
+ const args = tool === undefined ? undefined : usableArguments(tool, call.arguments);
365
+ if (tool?.apply !== undefined && args?.ok === true) {
366
+ state = tool.apply(state, args.value, answer);
367
+ }
368
+ };
371
369
  const saveToolResult = async (call, outcome) => {
370
+ // The model's view of a result is capped when it arrives, and the record keeps
371
+ // exactly what the model saw, so a resume replays the same text. Nothing older
372
+ // is rewritten, which is what keeps the stable prefix cacheable (decision 40).
373
+ const tool = tools.get(call.name);
374
+ const cap = usableCap(tool?.maxResultBytes) ??
375
+ usableCap(config.toolResultBytes) ??
376
+ DEFAULT_RESULT_CAP_BYTES;
377
+ const cut = cutText(outcome.content, cap, tool?.truncationHint);
378
+ const content = cut?.text ?? outcome.content;
372
379
  const entry = {
373
380
  type: "tool_message",
374
381
  id: config.ids.next("e"),
@@ -376,22 +383,18 @@ export async function runTask(config) {
376
383
  ts: clock.now(),
377
384
  toolCallId: call.id,
378
385
  isError: outcome.isError,
379
- content: outcome.content,
386
+ content,
380
387
  };
388
+ if (cut !== undefined) {
389
+ entry.truncated = { field: "content", droppedBytes: cut.droppedBytes };
390
+ }
381
391
  if (outcome.details !== undefined) {
382
392
  entry.details = outcome.details;
383
393
  }
384
394
  if (outcome.done === true) {
385
395
  entry.done = true;
386
396
  }
387
- const seq = await append(entry);
388
- messages.push({
389
- role: "tool",
390
- toolCallId: call.id,
391
- content: outcome.content,
392
- isError: outcome.isError,
393
- });
394
- return seq;
397
+ return { seq: await append(entry), content };
395
398
  };
396
399
  /** Ask the model once. A slot that throws is a failed run, not a crash. */
397
400
  const askOnce = async () => {
@@ -452,10 +455,94 @@ export async function runTask(config) {
452
455
  }
453
456
  }
454
457
  };
458
+ /**
459
+ * Ask a person about one call, and park the run until they answer (decisions 34
460
+ * and 85). The request is saved before anything is sent, so an answer can always
461
+ * be paired with it, and the record says what the run is waiting for.
462
+ */
463
+ const saveRequest = async (call, tool, ask) => {
464
+ const request = ask === undefined
465
+ ? {
466
+ type: "request",
467
+ id: config.ids.next("e"),
468
+ parent,
469
+ ts: clock.now(),
470
+ request: config.ids.next("auth"),
471
+ kind: "approve",
472
+ title: `May the run use ${call.name}?`,
473
+ message: `The model asked to run the ${call.name} tool.`,
474
+ callId: call.id,
475
+ tool: call.name,
476
+ args: call.arguments,
477
+ }
478
+ : {
479
+ type: "request",
480
+ id: config.ids.next("e"),
481
+ parent,
482
+ ts: clock.now(),
483
+ request: config.ids.next("auth"),
484
+ kind: ask.kind,
485
+ title: ask.title,
486
+ message: ask.message,
487
+ callId: call.id,
488
+ tool: call.name,
489
+ args: call.arguments,
490
+ ...(ask.preview === undefined ? {} : { preview: ask.preview }),
491
+ ...(ask.options === undefined ? {} : { options: ask.options }),
492
+ };
493
+ if (tool?.risk !== undefined) {
494
+ request.risk = tool.risk;
495
+ }
496
+ if (requestTimeoutMs !== undefined) {
497
+ request.timeoutMs = requestTimeoutMs;
498
+ }
499
+ const seq = await append(request);
500
+ emit({
501
+ type: "request",
502
+ run: runId,
503
+ ts: clock.now(),
504
+ seq,
505
+ request: request.request,
506
+ callId: call.id,
507
+ ...(request.timeoutMs === undefined ? {} : { timeoutMs: request.timeoutMs }),
508
+ });
509
+ return request.request;
510
+ };
511
+ /** Answer a call that will not run, so the batch stays paired (module 21's rule). */
512
+ const answerWithoutRunning = async (call, reason) => {
513
+ emit({ type: "tool_call", run: runId, ts: clock.now(), call });
514
+ const outcome = deniedOutcome(reason);
515
+ const saved = await saveToolResult(call, outcome);
516
+ emit({
517
+ type: "tool_end",
518
+ run: runId,
519
+ ts: clock.now(),
520
+ seq: saved.seq,
521
+ callId: call.id,
522
+ name: call.name,
523
+ isError: true,
524
+ content: saved.content,
525
+ });
526
+ noteFailure(call.name, saved.content);
527
+ };
528
+ /** The task's result, left for a person to decide on (decision 50). */
529
+ const saveProposal = async (proposal) => {
530
+ const entry = {
531
+ type: "proposal",
532
+ id: config.ids.next("e"),
533
+ parent,
534
+ ts: clock.now(),
535
+ proposal: config.ids.next("prop"),
536
+ payload: proposal.payload,
537
+ evidence: proposal.evidence,
538
+ state: "open",
539
+ };
540
+ await append(entry);
541
+ };
455
542
  /** Set when a tool's answer says the done-check passed (decision 25). */
456
543
  let finishedRun = false;
457
- /** Run one reply's calls, which is the same work on the first try and after a resume. */
458
- const runBatch = async (calls) => {
544
+ /** Run one call through the executor, which is what every allowed call gets. */
545
+ const runOne = async (calls) => {
459
546
  await executeTools({
460
547
  calls,
461
548
  tools: config.tools,
@@ -474,24 +561,35 @@ export async function runTask(config) {
474
561
  name: call.name,
475
562
  });
476
563
  },
564
+ onAsk: async (call, ask) => {
565
+ // A tool that needs an answer parks the run exactly as a policy does:
566
+ // one mechanism, one record entry (decision 34).
567
+ waitingRequest = await saveRequest(call, tools.get(call.name), ask);
568
+ },
477
569
  onFinish: async (call, outcome, args) => {
478
- const resultSeq = await saveToolResult(call, outcome);
570
+ const saved = await saveToolResult(call, outcome);
479
571
  emit({
480
572
  type: "tool_end",
481
573
  run: runId,
482
574
  ts: clock.now(),
483
- seq: resultSeq,
575
+ seq: saved.seq,
484
576
  callId: call.id,
485
577
  name: call.name,
486
578
  isError: outcome.isError,
487
- content: outcome.content,
579
+ content: saved.content,
488
580
  });
489
581
  if (outcome.isError) {
490
- noteFailure(call.name, outcome.content);
582
+ noteFailure(call.name, saved.content);
491
583
  }
492
584
  else {
493
585
  noteSuccess();
494
586
  }
587
+ if (outcome.propose !== undefined && !outcome.isError) {
588
+ // The run's result is a decision someone else makes, so it is saved and
589
+ // the run ends `done` (decisions 50, 52, 53).
590
+ await saveProposal(outcome.propose);
591
+ finishedRun = true;
592
+ }
495
593
  if (outcome.done === true && !outcome.isError) {
496
594
  finishedRun = true;
497
595
  }
@@ -504,14 +602,84 @@ export async function runTask(config) {
504
602
  },
505
603
  });
506
604
  };
605
+ /**
606
+ * Run one reply's calls, in order, asking a person where the recipe says so and
607
+ * refusing where it says no (decisions 34, 35). A call that needs an answer stops
608
+ * the batch: it has not run, so the calls after it have no result yet either, and
609
+ * a resume answers them from the person's decision rather than guessing.
610
+ */
611
+ const runBatch = async (calls) => {
612
+ for (const call of calls) {
613
+ const tool = tools.get(call.name);
614
+ const policy = tool === undefined ? "allow" : policyOf(tool, approvalDefault);
615
+ if (policy === "deny") {
616
+ await answerWithoutRunning(call, tool === undefined ? "no tool by that name" : deniedByRecipe(tool));
617
+ continue;
618
+ }
619
+ if (policy === "ask") {
620
+ if (!canAsk) {
621
+ // Decision 35: nothing can deliver the question, so it is denied
622
+ // rather than waiting forever on something nobody allowed.
623
+ await answerWithoutRunning(call, tool === undefined ? "no tool by that name" : deniedWithoutAPerson(tool));
624
+ continue;
625
+ }
626
+ waitingRequest = await saveRequest(call, tool);
627
+ return;
628
+ }
629
+ await runOne([call]);
630
+ if (waitingRequest !== undefined) {
631
+ // The call itself asked a person, so the ones behind it have to wait for
632
+ // the answer rather than run while someone is deciding (decision 34).
633
+ return;
634
+ }
635
+ }
636
+ };
507
637
  /**
508
638
  * Answer the calls the record has no result for, which is where a kill leaves a
509
639
  * run. A call that is safe to repeat runs now; one that is not is answered with
510
640
  * an unknown outcome and never repeated, because the record cannot tell a tool
511
641
  * that never started from one that changed something and then died (decision 24).
512
642
  */
513
- const answerUnanswered = async (seed) => {
514
- for (const call of seed.unansweredCalls) {
643
+ const answerUnanswered = async (seed, decided) => {
644
+ // The call a request named, and every call after it, never ran: the batch
645
+ // stopped there rather than guessing. A person's decision settles them, and an
646
+ // approval covers only the call it named, so the rest meet their own policy.
647
+ const asked = seed.pendingRequest?.callId;
648
+ const heldFrom = asked === undefined ? -1 : seed.unansweredCalls.findIndex((call) => call.id === asked);
649
+ for (const [index, call] of seed.unansweredCalls.entries()) {
650
+ if (heldFrom >= 0 && index >= heldFrom) {
651
+ if (decided === undefined) {
652
+ // Nothing has decided yet, which a resume should have caught before
653
+ // reaching here; answering nothing keeps the record honest.
654
+ continue;
655
+ }
656
+ if (decided.decision === "deny") {
657
+ const note = decided.note === undefined
658
+ ? ""
659
+ : `, and said: ${decided.note.slice(0, 500)}`;
660
+ await answerWithoutRunning(call, `a person denied this call${note === "" ? "" : note}`);
661
+ continue;
662
+ }
663
+ // A question's answer is the call's result: the tool never produced one,
664
+ // so the person's words (or the option they picked) are what the model
665
+ // reads and what the tool's own `apply` records (decision 34).
666
+ if (seed.pendingRequest?.kind !== "approve" &&
667
+ (decided.text !== undefined || decided.ids !== undefined)) {
668
+ await saveAnsweredCall(call, decided);
669
+ await runBatch(seed.unansweredCalls.slice(heldFrom + 1));
670
+ return;
671
+ }
672
+ // The person approved the call the request named: it runs, and everything
673
+ // the batch held behind it runs through the policy as usual — unless the
674
+ // call asked something of its own, which holds the rest again.
675
+ if (index === heldFrom) {
676
+ await runOne([call]);
677
+ if (waitingRequest === undefined) {
678
+ await runBatch(seed.unansweredCalls.slice(heldFrom + 1));
679
+ }
680
+ return;
681
+ }
682
+ }
515
683
  const tool = tools.get(call.name);
516
684
  if (tool !== undefined && tool.safeToRepeat === true) {
517
685
  await runBatch([call]);
@@ -522,16 +690,16 @@ export async function runTask(config) {
522
690
  isError: true,
523
691
  content: "outcome unknown: this call may or may not have run; check before repeating",
524
692
  };
525
- const resultSeq = await saveToolResult(call, unknown);
693
+ const saved = await saveToolResult(call, unknown);
526
694
  emit({
527
695
  type: "tool_end",
528
696
  run: runId,
529
697
  ts: clock.now(),
530
- seq: resultSeq,
698
+ seq: saved.seq,
531
699
  callId: call.id,
532
700
  name: call.name,
533
701
  isError: true,
534
- content: unknown.content,
702
+ content: saved.content,
535
703
  });
536
704
  }
537
705
  };
@@ -545,11 +713,14 @@ export async function runTask(config) {
545
713
  if (status === undefined) {
546
714
  return undefined;
547
715
  }
716
+ // A person who brings a follow-up is asking for more, so an ending already on
717
+ // the record no longer answers them: the run goes on from where it stopped.
718
+ const continues = by === "person" && config.resume?.followUp !== undefined;
548
719
  const total = usageTotal.total();
549
- if (status.state === "done") {
720
+ if (status.state === "done" && !continues) {
550
721
  return { reason: "done", usage: total, turns };
551
722
  }
552
- if (status.state === "failed") {
723
+ if (status.state === "failed" && !continues) {
553
724
  return {
554
725
  reason: "failed",
555
726
  error: { code: "internal", message: "the record says the run failed" },
@@ -572,9 +743,144 @@ export async function runTask(config) {
572
743
  const stopped = () => signal.aborted
573
744
  ? { reason: "parked", parkedReason: "stopped", usage: usageTotal.total(), turns }
574
745
  : undefined;
746
+ /** Why a failed run failed, when it has a reason worth keeping on the record. */
747
+ let failureDetail;
748
+ // A window is the model slot's unless the recipe overrides it. Without one, the
749
+ // run never compacts on its own: there is no number to compare against
750
+ // (decision 41), and the manual command is the only way to ask for a summary.
751
+ const contextWindow = config.compaction?.contextWindow ?? config.model.contextWindow;
752
+ const reserveTokens = config.compaction?.reserveTokens ??
753
+ (contextWindow === undefined ? 0 : defaultReserveTokens(contextWindow));
754
+ const keepTokens = config.compaction?.keepTokens ?? DEFAULT_KEEP_TOKENS;
755
+ const summaryInstructions = config.compaction?.instructions ?? DEFAULT_SUMMARY_INSTRUCTIONS;
756
+ const summaryModel = config.compaction?.model;
757
+ /** What each tool says its state is, which the view shows after a compaction. */
758
+ const stateTexts = () => currentStateTexts(config.tools, state);
759
+ /** The view as a summary call sees it: the summary it updates, and the steps since. */
760
+ const viewFor = () => ({
761
+ entries: viewEntries,
762
+ summary: previousSummary,
763
+ stateTexts: [],
764
+ messages,
765
+ });
766
+ /**
767
+ * Compact if the next request would come too close to the model's window.
768
+ *
769
+ * It runs before the request it makes room for, and it is the only place the
770
+ * record's view changes. A failure parks the run as `model_unavailable` with
771
+ * the detail `compaction_failed`: continuing without the summary would mean
772
+ * sending a request the model cannot read.
773
+ */
774
+ const compactIfNeeded = async () => {
775
+ if (contextWindow === undefined) {
776
+ return undefined;
777
+ }
778
+ // The provider's reported count is the authority while it still describes the
779
+ // request it was counted for, so it is the base plus what arrived since. With
780
+ // no base — a fresh run, or a resume whose record was cut after the last reply
781
+ // — the estimate is the whole view, because the summary and the kept steps are
782
+ // part of what the next request has to carry.
783
+ const estimate = lastInputTokens === undefined
784
+ ? estimateConversation(messages)
785
+ : lastInputTokens + estimateSinceLastReply(messages);
786
+ if (!shouldCompact(estimate, contextWindow, reserveTokens)) {
787
+ return undefined;
788
+ }
789
+ const cut = chooseCut(viewEntries, keepTokens);
790
+ if (cut === undefined) {
791
+ if (estimate <= contextWindow) {
792
+ // There is nothing older to summarize, and the request still fits.
793
+ return undefined;
794
+ }
795
+ // No summary can make a single step fit, so the run says so plainly rather
796
+ // than spending a call on it and failing differently (decision 6's limit).
797
+ const error = {
798
+ code: "bad_request",
799
+ message: `input_too_large: the conversation is about ${estimate} tokens and this model's context window is ${contextWindow}, so compacting cannot make it fit`,
800
+ };
801
+ emit({ type: "error", run: runId, ts: clock.now(), error });
802
+ failureDetail = "input_too_large";
803
+ return { reason: "failed", error, usage: usageTotal.total(), turns };
804
+ }
805
+ const summarized = await summarize({
806
+ summarizer: {
807
+ model: config.model,
808
+ instructions: summaryInstructions,
809
+ ...(summaryModel === undefined ? {} : { modelName: summaryModel }),
810
+ },
811
+ material: summaryMaterial(viewFor(), cut),
812
+ clock,
813
+ signal,
814
+ onRetry: (attempt, delayMs, error) => {
815
+ emit({ type: "retry", run: runId, ts: clock.now(), attempt, delayMs, error });
816
+ },
817
+ });
818
+ if (!summarized.ok) {
819
+ const stoppedWhileCompacting = stopped();
820
+ if (stoppedWhileCompacting !== undefined) {
821
+ return stoppedWhileCompacting;
822
+ }
823
+ emit({ type: "error", run: runId, ts: clock.now(), error: summarized.error });
824
+ return {
825
+ reason: "parked",
826
+ parkedReason: "model_unavailable",
827
+ parkedDetail: "compaction_failed",
828
+ usage: usageTotal.total(),
829
+ turns,
830
+ };
831
+ }
832
+ // The summary is a call like any other, so it counts toward what the run
833
+ // spent and toward its token limit (decision 40).
834
+ usageTotal.add(summarized.value.usage);
835
+ const entry = {
836
+ type: "compaction",
837
+ id: config.ids.next("e"),
838
+ parent,
839
+ ts: clock.now(),
840
+ summary: summarized.value.summary,
841
+ firstKept: cut.firstKept,
842
+ replaces: cut.replaces,
843
+ usage: summarized.value.usage,
844
+ model: summarized.value.model,
845
+ trigger: "auto",
846
+ instructionsHash: await hashText(summaryInstructions),
847
+ };
848
+ // The entry is fitted before it is saved, because the view has to show what
849
+ // the record will hold: a summary over the entry cap is cut like any other
850
+ // content, and the model must not read something a resume could not replay.
851
+ const fitted = fitEntry(entry, entryCap);
852
+ if (fitted.refused !== undefined) {
853
+ throw new SaveFailed({ code: "internal", message: fitted.refused });
854
+ }
855
+ const saved = fitted.entry.type === "compaction" ? fitted.entry : entry;
856
+ const seq = await appendLine(entry, fitted.line);
857
+ emit({
858
+ type: "compaction",
859
+ run: runId,
860
+ ts: clock.now(),
861
+ seq,
862
+ summary: saved.summary,
863
+ replaces: saved.replaces,
864
+ trigger: saved.trigger,
865
+ });
866
+ // The view is now the record's: the summary, the tools' state, and the
867
+ // entries the pointer keeps. Nothing before it left the record (decision 39).
868
+ const view = buildView([...viewEntries, saved], stateTexts());
869
+ viewEntries = view.entries;
870
+ messages = view.messages;
871
+ previousSummary = view.summary;
872
+ // The count from before the cut no longer describes the conversation. The next
873
+ // reply replaces it, but a retry that runs out and falls back comes back here
874
+ // without one, so the base is dropped here exactly as the resume seed drops it.
875
+ lastInputTokens = undefined;
876
+ return undefined;
877
+ };
575
878
  // A bad limit fails here rather than parking a run that cannot start (LIM03).
576
879
  const checkedLimits = config.limits === undefined ? undefined : validateLimits(config.limits);
577
880
  const limits = checkedLimits !== undefined && checkedLimits.ok ? checkedLimits.value : undefined;
881
+ // A compaction setting that cannot mean anything is a recipe's mistake, and it
882
+ // fails here rather than at the first compaction (the same rule as a limit).
883
+ const checkedCompaction = config.compaction === undefined ? undefined : validateCompactionSettings(config.compaction);
578
884
  const loop = async () => {
579
885
  for (;;) {
580
886
  const stoppedBeforeAsking = stopped();
@@ -602,6 +908,12 @@ export async function runTask(config) {
602
908
  turns,
603
909
  };
604
910
  }
911
+ // Compaction happens at the same gap a steer is read at, before the request
912
+ // it makes room for, so it never splits a call from its result.
913
+ const compacted = await compactIfNeeded();
914
+ if (compacted !== undefined) {
915
+ return compacted;
916
+ }
605
917
  // A turn is one step, however many times it is retried.
606
918
  turns += 1;
607
919
  emit({ type: "turn_start", run: runId, ts: clock.now(), turn: turns });
@@ -651,6 +963,9 @@ export async function runTask(config) {
651
963
  const reply = answered.reply;
652
964
  const calls = normalizeCalls(reply.toolCalls, config.ids);
653
965
  usageTotal.add(reply.usage);
966
+ // What this request actually cost the provider is the base the next
967
+ // compaction estimate starts from (decision 41).
968
+ lastInputTokens = reply.usage.inputTokens;
654
969
  emit(reply.usage.cost === undefined
655
970
  ? {
656
971
  type: "usage",
@@ -693,15 +1008,6 @@ export async function runTask(config) {
693
1008
  text: reply.text,
694
1009
  toolCalls: calls,
695
1010
  });
696
- const assistant = reply.reasoning === undefined
697
- ? { role: "assistant", text: reply.text, toolCalls: calls }
698
- : {
699
- role: "assistant",
700
- text: reply.text,
701
- reasoning: reply.reasoning,
702
- toolCalls: calls,
703
- };
704
- messages.push(assistant);
705
1011
  // A cost limit it cannot measure is not a limit, so the run says so once
706
1012
  // and carries on without enforcing it (decision 15, LIM05).
707
1013
  if (limits?.cost !== undefined && !costLimitNoted && !usageTotal.costSpent().known) {
@@ -718,16 +1024,16 @@ export async function runTask(config) {
718
1024
  isError: true,
719
1025
  content: "this call was not run: the reply was cut off by the token limit, so its arguments may be incomplete",
720
1026
  };
721
- const resultSeq = await saveToolResult(call, cutOff);
1027
+ const saved = await saveToolResult(call, cutOff);
722
1028
  emit({
723
1029
  type: "tool_end",
724
1030
  run: runId,
725
1031
  ts: clock.now(),
726
- seq: resultSeq,
1032
+ seq: saved.seq,
727
1033
  callId: call.id,
728
1034
  name: call.name,
729
1035
  isError: true,
730
- content: cutOff.content,
1036
+ content: saved.content,
731
1037
  });
732
1038
  }
733
1039
  emit({
@@ -778,7 +1084,6 @@ export async function runTask(config) {
778
1084
  text: REMINDER_TEXT,
779
1085
  };
780
1086
  await append(reminder);
781
- messages.push({ role: "user", text: REMINDER_TEXT });
782
1087
  continue;
783
1088
  }
784
1089
  if (!stuck.enabled) {
@@ -815,6 +1120,16 @@ export async function runTask(config) {
815
1120
  turn: turns,
816
1121
  finishReason: reply.finishReason,
817
1122
  });
1123
+ if (waitingRequest !== undefined) {
1124
+ // A call is waiting for a person, so the run stops here at no cost and
1125
+ // the calls after it are answered when they answer (decision 34).
1126
+ return {
1127
+ reason: "parked",
1128
+ parkedReason: "waiting_for_person",
1129
+ usage: usageTotal.total(),
1130
+ turns,
1131
+ };
1132
+ }
818
1133
  if (repeatedFailure !== undefined) {
819
1134
  // The same tool failed the same way often enough: park rather than
820
1135
  // spend the person's allowance on a loop that cannot progress (STK03).
@@ -863,7 +1178,11 @@ export async function runTask(config) {
863
1178
  };
864
1179
  const firstFits = (entry) => utf8Length(encodeEntry(entry)) <= entryCap;
865
1180
  emit({ type: "run_start", run: runId, ts: clock.now(), task: config.task });
866
- const refused = checkedLimits !== undefined && !checkedLimits.ok ? checkedLimits.error : undefined;
1181
+ const refused = checkedLimits !== undefined && !checkedLimits.ok
1182
+ ? checkedLimits.error
1183
+ : checkedCompaction !== undefined && !checkedCompaction.ok
1184
+ ? checkedCompaction.error
1185
+ : undefined;
867
1186
  if (refused !== undefined) {
868
1187
  emit({ type: "error", run: runId, ts: clock.now(), error: refused });
869
1188
  result = { reason: "failed", error: refused, usage: usageTotal.total(), turns };
@@ -896,8 +1215,15 @@ export async function runTask(config) {
896
1215
  for (const usage of seed.usages) {
897
1216
  usageTotal.add(usage);
898
1217
  }
899
- messages.push(...seed.messages);
1218
+ // A summary is a call like any other for a limit, so its cost is part of
1219
+ // what the run already spent (CMP14).
1220
+ for (const usage of seed.summaryUsages) {
1221
+ usageTotal.add(usage);
1222
+ }
900
1223
  turns = seed.turns;
1224
+ // The base the estimate starts from, which the seed drops when a cut came
1225
+ // after the last reply: that number then describes a longer conversation.
1226
+ lastInputTokens = seed.lastInputTokens;
901
1227
  parent = seed.parent;
902
1228
  closedActiveMs = seed.activeMs;
903
1229
  let prepared;
@@ -922,7 +1248,29 @@ export async function runTask(config) {
922
1248
  state = replayState(prepared.state, seed.record.entries, tools);
923
1249
  return undefined;
924
1250
  };
925
- const recorded = recordedOutcome(seed, config.resume.by);
1251
+ const waiting = seed.pendingRequest;
1252
+ let decided = seed.answer;
1253
+ if (waiting !== undefined &&
1254
+ decided === undefined &&
1255
+ waiting.timeoutMs !== undefined &&
1256
+ clock.now() >= waiting.ts + waiting.timeoutMs) {
1257
+ // Nobody answered before the request's timeout, so it resolves to deny
1258
+ // and the record says the clock decided, not a person (decision 37).
1259
+ decided = {
1260
+ type: "request_answered",
1261
+ id: config.ids.next("e"),
1262
+ parent,
1263
+ ts: clock.now(),
1264
+ request: waiting.request,
1265
+ decision: "deny",
1266
+ note: "no answer arrived before the request's timeout",
1267
+ timedOut: true,
1268
+ };
1269
+ await append(decided);
1270
+ }
1271
+ // A decision means the run goes on: a timeout's wake is not the accident
1272
+ // rule's business (decision 23), it is the clock answering.
1273
+ const recorded = decided === undefined ? recordedOutcome(seed, config.resume.by) : undefined;
926
1274
  const current = config.recipe === undefined
927
1275
  ? undefined
928
1276
  : await pinRecipe({
@@ -932,7 +1280,19 @@ export async function runTask(config) {
932
1280
  tools: config.tools.map((tool) => tool.spec),
933
1281
  });
934
1282
  const change = recipeChangeParked(seed, current);
935
- if (recorded !== undefined) {
1283
+ if (waiting !== undefined && decided === undefined) {
1284
+ // The run is waiting for a person, and there is no answer on the
1285
+ // record yet. Nothing is written and nothing is guessed: it parks
1286
+ // again, and stays parked until someone decides (decision 34).
1287
+ nothingWritten = true;
1288
+ result = {
1289
+ reason: "parked",
1290
+ parkedReason: "waiting_for_person",
1291
+ usage: usageTotal.total(),
1292
+ turns,
1293
+ };
1294
+ }
1295
+ else if (recorded !== undefined) {
936
1296
  // Nothing is written: the record already says how this run ended, or
937
1297
  // that it waits for a person. The state is only for the caller's
938
1298
  // benefit, so a rebuild that cannot happen loses it and not the ending.
@@ -945,7 +1305,7 @@ export async function runTask(config) {
945
1305
  }
946
1306
  result = recorded;
947
1307
  }
948
- else if (seed.finished) {
1308
+ else if (seed.finished && config.resume.followUp === undefined) {
949
1309
  // A kill landed between an accepted finish and the closing status. The
950
1310
  // record already knows the done-check passed, so the run ends done
951
1311
  // rather than asking the model for a turn it already gave.
@@ -976,25 +1336,59 @@ export async function runTask(config) {
976
1336
  if (refused !== undefined) {
977
1337
  throw new Error(refused);
978
1338
  }
1339
+ // The conversation is the record's view, up to the latest compaction's
1340
+ // pointer, so a resumed run sees what the compacted one saw (decision 39).
1341
+ // The active path, not every stored entry: a record whose chain is
1342
+ // damaged has entries the conversation does not contain, and the view
1343
+ // has to be the same conversation replay reports (CMP23).
1344
+ const seededView = buildView(activePath(seed.record.entries), stateTexts());
1345
+ viewEntries = seededView.entries;
1346
+ messages = seededView.messages;
1347
+ previousSummary = seededView.summary;
979
1348
  if (seed.messages.length === 0) {
980
1349
  // The kill landed after the header and before the task message, so the
981
1350
  // resume writes the job the caller is asking for. This comes after the
982
1351
  // seed sets `parent`, or the write would leave the message orphaned.
983
1352
  const first = makeFirst(prepared?.message ?? config.input, seed.input);
984
1353
  await append(first);
985
- messages.push({ role: "user", text: first.text });
986
1354
  }
987
1355
  if (current !== undefined) {
988
1356
  await noteRecipeChange(seed, current);
989
1357
  }
990
1358
  await saveStatus("resumed");
991
1359
  activeSince = clock.now();
992
- await answerUnanswered(seed);
993
- // A repeated safe call may itself have passed the done-check (a
994
- // finish is safe to repeat for exactly this reason).
995
- result = finishedRun
996
- ? { reason: "done", usage: usageTotal.total(), turns }
997
- : await loop();
1360
+ await answerUnanswered(seed, decided);
1361
+ // The follow-up comes after any unanswered call is answered, so the
1362
+ // conversation never puts a person's message between a call and its result.
1363
+ if (config.resume.followUp !== undefined) {
1364
+ const message = {
1365
+ type: "user_message",
1366
+ id: config.ids.next("e"),
1367
+ parent,
1368
+ ts: clock.now(),
1369
+ label: "follow_up",
1370
+ text: config.resume.followUp,
1371
+ };
1372
+ await append(message);
1373
+ }
1374
+ if (waitingRequest !== undefined) {
1375
+ // A call the batch held needs a person of its own, so the resume stops
1376
+ // there rather than asking the model for a turn it cannot act on.
1377
+ result = {
1378
+ reason: "parked",
1379
+ parkedReason: "waiting_for_person",
1380
+ usage: usageTotal.total(),
1381
+ turns,
1382
+ };
1383
+ }
1384
+ else if (finishedRun) {
1385
+ // A repeated safe call may itself have passed the done-check (a finish
1386
+ // is safe to repeat for exactly this reason).
1387
+ result = { reason: "done", usage: usageTotal.total(), turns };
1388
+ }
1389
+ else {
1390
+ result = await loop();
1391
+ }
998
1392
  }
999
1393
  }
1000
1394
  }
@@ -1021,6 +1415,7 @@ export async function runTask(config) {
1021
1415
  task: config.task,
1022
1416
  startedAt: clock.now(),
1023
1417
  host: config.host,
1418
+ ...(config.tenant === undefined ? {} : { tenant: config.tenant }),
1024
1419
  };
1025
1420
  if (config.recipe !== undefined) {
1026
1421
  // The pin is what a later resume is held to, so it is taken before the
@@ -1035,7 +1430,6 @@ export async function runTask(config) {
1035
1430
  await save(encodeHeader(header));
1036
1431
  recordStarted = true;
1037
1432
  await append(first);
1038
- messages.push({ role: "user", text: first.text });
1039
1433
  state = prepared?.state;
1040
1434
  await saveStatus("running");
1041
1435
  activeSince = clock.now();
@@ -1062,7 +1456,7 @@ export async function runTask(config) {
1062
1456
  ? "done"
1063
1457
  : result.reason === "parked"
1064
1458
  ? "parked"
1065
- : "failed", result.reason === "parked" ? result.parkedReason : undefined, result.reason === "parked" ? result.parkedDetail : undefined);
1459
+ : "failed", result.reason === "parked" ? result.parkedReason : undefined, result.reason === "parked" ? result.parkedDetail : failureDetail);
1066
1460
  }
1067
1461
  }
1068
1462
  catch (caught) {