@nylorun/harness 0.19.2-beta → 0.21.0-beta

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,288 @@
1
+ import { HarnessError, isModelFailureOutcome } from "@nylorun/core/define";
2
+ /** Characters per token for the heuristic estimate; the reserve absorbs its error. */
3
+ const CHARS_PER_TOKEN = 4;
4
+ /** The kept tail is at most this many tokens, and at most this share of the window. */
5
+ const KEEP_TOKENS = 20_000;
6
+ const KEEP_SHARE = 0.3;
7
+ /** Room held back for the reply when the adapter does not report an output limit. */
8
+ const DEFAULT_RESERVE = 8_192;
9
+ const MAX_RESERVE = 16_384;
10
+ /** Tool inputs and results are clipped to this many characters in the summarizer's input. */
11
+ const CLIP = 2_000;
12
+ /** Tokens the summary instructions, format and previous summary take in a summary call. */
13
+ const SUMMARY_OVERHEAD = 1_024;
14
+ /**
15
+ * The window and output limit the adapter reported on the latest candidate
16
+ * (`evidence.extras.contextWindow`, `maxOutputTokens`). Undefined until a model has answered.
17
+ */
18
+ export function contextBudget(transcript) {
19
+ for (let index = transcript.length - 1; index >= 0; index--) {
20
+ const entry = transcript[index];
21
+ if (entry.kind !== "candidate")
22
+ continue;
23
+ const extras = entry.candidate.evidence?.extras;
24
+ const window = extras?.contextWindow;
25
+ if (typeof window !== "number" || window <= 0)
26
+ continue;
27
+ const output = extras?.maxOutputTokens;
28
+ const reserve = Math.min(typeof output === "number" && output > 0 ? output : DEFAULT_RESERVE, MAX_RESERVE, Math.floor(window / 4));
29
+ return { contextWindow: window, reserve };
30
+ }
31
+ return undefined;
32
+ }
33
+ /**
34
+ * Tokens the next prompt needs: the last reported usage, which already counts the
35
+ * instructions, tools and everything before it, plus an estimate of what came after.
36
+ * Without usage, everything is estimated.
37
+ */
38
+ export function estimateTokens(transcript) {
39
+ for (let index = transcript.length - 1; index >= 0; index--) {
40
+ const entry = transcript[index];
41
+ if (entry.kind !== "candidate" || !entry.candidate.usage)
42
+ continue;
43
+ const usage = entry.candidate.usage;
44
+ const reported = usage.totalTokens ??
45
+ (usage.inputTokens ?? 0) +
46
+ (usage.cachedTokens ?? 0) +
47
+ (usage.cacheWriteTokens ?? 0) +
48
+ (usage.outputTokens ?? 0);
49
+ if (reported <= 0)
50
+ continue;
51
+ return reported + transcript.slice(index + 1).reduce((sum, item) => sum + entryTokens(item), 0);
52
+ }
53
+ return transcript.reduce((sum, item) => sum + entryTokens(item), 0);
54
+ }
55
+ /** A rough token count of what one entry contributes to a prompt. */
56
+ export function entryTokens(entry) {
57
+ return Math.ceil(entryText(entry, Number.POSITIVE_INFINITY).length / CHARS_PER_TOKEN);
58
+ }
59
+ /**
60
+ * Where the kept tail starts. It keeps about `keepTokens` of the newest entries, never
61
+ * starts with tool results (their call stays with them), and never keeps the previous
62
+ * summary. Returns 0 or 1 when there is nothing older to summarize.
63
+ */
64
+ export function findCut(transcript, keepTokens) {
65
+ const first = transcript[0]?.kind === "compaction" ? 1 : 0;
66
+ let kept = 0;
67
+ let cut = transcript.length;
68
+ while (cut > first) {
69
+ const tokens = entryTokens(transcript[cut - 1]);
70
+ if (kept + tokens > keepTokens && cut < transcript.length)
71
+ break;
72
+ kept += tokens;
73
+ cut--;
74
+ }
75
+ // Tool results belong with the call that asked for them.
76
+ while (cut > first && transcript[cut]?.kind === "tool-results")
77
+ cut--;
78
+ return cut;
79
+ }
80
+ /**
81
+ * Summarize everything before the cut with one model call and return the new transcript,
82
+ * or undefined when there is nothing older to summarize. The current turn's messages from
83
+ * the user stay verbatim even when the cut falls inside the turn.
84
+ */
85
+ export async function compact(input) {
86
+ const { transcript } = input;
87
+ const tokensBefore = estimateTokens(transcript);
88
+ const window = input.budget?.contextWindow ?? tokensBefore;
89
+ const keepTokens = Math.max(1, Math.min(KEEP_TOKENS, Math.floor(window * KEEP_SHARE)));
90
+ const cut = findCut(transcript, keepTokens);
91
+ const previous = transcript[0]?.kind === "compaction" ? transcript[0] : undefined;
92
+ const start = previous ? 1 : 0;
93
+ if (cut <= start)
94
+ return undefined;
95
+ const older = transcript.slice(start, cut);
96
+ // The user's request for the turn in progress is never summarized away.
97
+ const request = older.filter((entry) => entry.kind === "input" &&
98
+ entry.turnId === input.turnId &&
99
+ (entry.event.kind === "user-message" || entry.event.kind === "interrupt"));
100
+ const tail = [...request, ...transcript.slice(cut)];
101
+ const keptTokens = tail.reduce((sum, entry) => sum + entryTokens(entry), 0);
102
+ const reserve = input.budget?.reserve ?? DEFAULT_RESERVE;
103
+ const maxOutputTokens = Math.max(256, Math.floor(reserve * 0.8));
104
+ // The summarizer sees at most what fits its window: older history is summarized in
105
+ // chunks, each merged into the running summary. A single call would fail on a provider,
106
+ // or lose the start of the history on a server that truncates silently.
107
+ const chunkTokens = input.budget
108
+ ? Math.max(1_000, input.budget.contextWindow - reserve - SUMMARY_OVERHEAD)
109
+ : Number.POSITIVE_INFINITY;
110
+ const chunks = chunked(older, chunkTokens);
111
+ // A step can compact before its call and again after an overflow; each is its own effect.
112
+ const base = `compaction-${input.stepId}${input.trigger === "overflow" ? "-overflow" : ""}`;
113
+ let summary = previous?.summary;
114
+ for (const [index, chunk] of chunks.entries()) {
115
+ const last = index === chunks.length - 1;
116
+ const outcome = await input.invoke(summaryCall(input, chunk, summary, maxOutputTokens), {
117
+ request: summaryRequest(input),
118
+ invocationId: index === 0 ? base : `${base}-${index}`,
119
+ signal: input.signal,
120
+ compaction: {
121
+ trigger: input.trigger,
122
+ tokensBefore,
123
+ keptTokens,
124
+ ...(last ? {} : { partial: true }),
125
+ },
126
+ reportPreparedCall() { },
127
+ });
128
+ if (isModelFailureOutcome(outcome))
129
+ throw new HarnessError(`model.${outcome.code}`, `Compacting the conversation failed: ${outcome.message}`);
130
+ summary = summaryText(outcome).trim();
131
+ if (!summary)
132
+ throw new HarnessError("model.invalid_output", "Compacting the conversation failed: the model returned an empty summary.");
133
+ }
134
+ if (!summary)
135
+ throw new HarnessError("model.invalid_output", "Compacting the conversation failed: the model returned an empty summary.");
136
+ const entry = {
137
+ kind: "compaction",
138
+ turnId: input.turnId,
139
+ stepId: input.stepId,
140
+ summary,
141
+ trigger: input.trigger,
142
+ tokensBefore,
143
+ tokensAfter: keptTokens + Math.ceil(summary.length / CHARS_PER_TOKEN),
144
+ };
145
+ return Object.freeze([Object.freeze(entry), ...tail]);
146
+ }
147
+ /** How a compaction entry reaches the model: a user message ahead of the kept tail. */
148
+ export function summaryPrompt(entry) {
149
+ return [
150
+ "Earlier parts of this conversation were summarized to fit the context window.",
151
+ "<summary>",
152
+ entry.summary,
153
+ "</summary>",
154
+ ].join("\n");
155
+ }
156
+ const SYSTEM = [
157
+ "You summarize a conversation between a user and an AI agent that uses tools, so the agent",
158
+ "can continue the work with a shorter context. Write for the agent, not the user.",
159
+ "Keep facts exactly: names, identifiers, paths, numbers, decisions and open problems.",
160
+ "Do not invent anything and do not continue the task yourself.",
161
+ ].join(" ");
162
+ const FORMAT = [
163
+ "Write the summary with these sections, leaving out a section that has nothing:",
164
+ "## Goal",
165
+ "## Constraints and preferences",
166
+ "## Progress",
167
+ "## Key decisions",
168
+ "## Next steps",
169
+ "## Critical context",
170
+ "If a previous summary is given, merge it with the new conversation into one summary.",
171
+ ].join("\n");
172
+ /** Consecutive runs of entries whose summarizer input stays under `limit` tokens. */
173
+ function chunked(entries, limit) {
174
+ const chunks = [];
175
+ let current = [];
176
+ let size = 0;
177
+ for (const entry of entries) {
178
+ const tokens = Math.ceil(entryText(entry, CLIP).length / CHARS_PER_TOKEN);
179
+ if (current.length && size + tokens > limit) {
180
+ chunks.push(current);
181
+ current = [];
182
+ size = 0;
183
+ }
184
+ current.push(entry);
185
+ size += tokens;
186
+ }
187
+ if (current.length)
188
+ chunks.push(current);
189
+ return chunks;
190
+ }
191
+ function summaryCall(input, older, previous, maxOutputTokens) {
192
+ const conversation = older
193
+ .map((entry) => entryText(entry, CLIP))
194
+ .filter((text) => text !== "")
195
+ .join("\n\n");
196
+ const text = [
197
+ ...(previous ? ["<previous-summary>", previous, "</previous-summary>", ""] : []),
198
+ "<conversation>",
199
+ conversation,
200
+ "</conversation>",
201
+ "",
202
+ FORMAT,
203
+ ].join("\n");
204
+ const prompt = [
205
+ { kind: "instructions", role: "system", content: [{ type: "text", text: SYSTEM }] },
206
+ { kind: "message", role: "user", content: [{ type: "text", text }] },
207
+ ];
208
+ return {
209
+ prompt,
210
+ tools: [],
211
+ model: { controls: { maxOutputTokens } },
212
+ executionId: input.executionId,
213
+ };
214
+ }
215
+ function summaryRequest(input) {
216
+ return {
217
+ executionId: input.executionId,
218
+ turnId: input.turnId,
219
+ stepId: input.stepId,
220
+ configuration: {
221
+ version: 1,
222
+ instructions: [],
223
+ tools: [],
224
+ toolContracts: [],
225
+ contributors: [],
226
+ },
227
+ instructions: [SYSTEM],
228
+ context: { items: [], contributors: [] },
229
+ transcript: [],
230
+ arrivals: [],
231
+ toolResults: [],
232
+ tools: [],
233
+ };
234
+ }
235
+ function summaryText(outcome) {
236
+ if (typeof outcome === "string")
237
+ return outcome;
238
+ return outcome.output.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("");
239
+ }
240
+ /** The model-visible text of one entry, with tool payloads clipped to `clip` characters. */
241
+ function entryText(entry, clip) {
242
+ switch (entry.kind) {
243
+ case "input": {
244
+ const event = entry.event;
245
+ if (event.kind === "user-message" || event.kind === "interrupt")
246
+ return `[User]: ${"content" in event && event.content
247
+ ? event.content
248
+ .map((part) => (part.type === "text" ? part.text : `[${part.mediaType}]`))
249
+ .join(" ")
250
+ : (event.text ?? "")}`;
251
+ if (event.kind === "approve")
252
+ return `[User ${event.approved ? "approved" : "denied"} a request]`;
253
+ if (event.kind === "respond")
254
+ return `[User answered]: ${clipped(event.value, clip)}`;
255
+ return "";
256
+ }
257
+ case "candidate":
258
+ return entry.candidate.output
259
+ .flatMap((block) => {
260
+ if (block.type === "text")
261
+ return block.text ? [`[Assistant]: ${block.text}`] : [];
262
+ if (block.type === "json")
263
+ return [`[Assistant]: ${clipped(block.value, clip)}`];
264
+ if (block.type === "tool-call")
265
+ return [`[Assistant called ${block.name}]: ${clipped(block.args, clip)}`];
266
+ return [];
267
+ })
268
+ .join("\n");
269
+ case "tool-results":
270
+ return entry.results
271
+ .map((result) => result.kind === "completed"
272
+ ? `[Tool ${result.toolName} result]: ${clipped(result.output, clip)}`
273
+ : result.kind === "denied"
274
+ ? `[Tool ${result.toolName} denied]: ${result.reason ?? ""}`
275
+ : `[Tool ${result.toolName} failed]: ${result.message}`)
276
+ .join("\n");
277
+ case "final":
278
+ return "";
279
+ case "compaction":
280
+ return summaryPrompt(entry);
281
+ }
282
+ }
283
+ function clipped(value, clip) {
284
+ const text = typeof value === "string" ? value : JSON.stringify(value ?? null);
285
+ return text.length <= clip
286
+ ? text
287
+ : `${text.slice(0, clip)}… [${text.length - clip} more characters]`;
288
+ }
@@ -8,6 +8,12 @@ export interface DelegationHost {
8
8
  readonly definition: AgentDefinition;
9
9
  readonly onModelCall: ModelAdapter;
10
10
  };
11
+ /**
12
+ * Run a flow agent used as a tool: the host starts it in its own linked session and
13
+ * returns the settled value (the flow's output, or a `{ kind: "failed" }` value). Only
14
+ * durable hosts can; local runs have no flow engine.
15
+ */
16
+ flow?(delegate: Delegate, ref: AgentRef, task: string): Promise<JsonValue>;
11
17
  /**
12
18
  * Journal a lifecycle point exactly once. Local runs have nothing to journal. `callId` is
13
19
  * the parent model's tool call id, for display only; it is not part of the point's identity.
@@ -21,6 +27,14 @@ export interface ExecuteInternals {
21
27
  readonly delegation?: DelegationHost;
22
28
  /** Set when this invocation is an agent used as a tool. */
23
29
  readonly delegated?: AgentRef;
30
+ /**
31
+ * Segment rollover (Model Calls §10): end the invocation with `yielded` at the next step
32
+ * boundary once this many steps ran, or this much time passed, in this invocation.
33
+ */
34
+ readonly yieldAfter?: {
35
+ readonly steps?: number;
36
+ readonly ms?: number;
37
+ };
24
38
  }
25
39
  /** Codes are curated: a child's provider error bodies never reach the parent's context. */
26
40
  export declare const INTERACTION_UNSUPPORTED = "Agents used as tools can't ask for input, approval or a wait yet; do this work on the parent agent.";
@@ -1,4 +1,4 @@
1
- import { HarnessError, isHarnessError } from "@nylorun/core/define";
1
+ import { HarnessError, isFlowDelegate, isHarnessError } from "@nylorun/core/define";
2
2
  import { definitionFromBinding } from "../definition/agent-definition.js";
3
3
  import { withNestedIds } from "../utils/ids.js";
4
4
  import { initializeExecutionState } from "./initial-state.js";
@@ -40,20 +40,28 @@ export async function runDelegation(invocation, execute, call, delegate) {
40
40
  let outcome;
41
41
  let status = "failed";
42
42
  try {
43
- const child = host.child(delegate, ref);
44
- const listener = options.onEvent;
45
- const result = await withNestedIds(call.invocationId, () => execute(child.definition, {
46
- input: task,
47
- onModelCall: child.onModelCall,
48
- signal,
49
- ...(options.info === undefined ? {} : { info: options.info }),
50
- state: initializeExecutionState(child.definition, {
51
- executionId: `${invocation.state.executionId}/${call.invocationId}`,
52
- }),
53
- ...(listener ? { onEvent: (event) => listener({ ...event, agent: ref }) } : {}),
54
- }, { delegated: ref }));
55
- status = result.status;
56
- outcome = settle(result);
43
+ if (isFlowDelegate(delegate)) {
44
+ if (!host.flow)
45
+ throw new HarnessError("execution.invalid-input", `Agent '${ref.id}' is a flow agent; flow agents used as tools run on the Runtime`);
46
+ outcome = settleFlow(await host.flow(delegate, ref, task));
47
+ status = outcome.kind === "completed" ? "completed" : "failed";
48
+ }
49
+ else {
50
+ const child = host.child(delegate, ref);
51
+ const listener = options.onEvent;
52
+ const result = await withNestedIds(call.invocationId, () => execute(child.definition, {
53
+ input: task,
54
+ onModelCall: child.onModelCall,
55
+ signal,
56
+ ...(options.info === undefined ? {} : { info: options.info }),
57
+ state: initializeExecutionState(child.definition, {
58
+ executionId: `${invocation.state.executionId}/${call.invocationId}`,
59
+ }),
60
+ ...(listener ? { onEvent: (event) => listener({ ...event, agent: ref }) } : {}),
61
+ }, { delegated: ref }));
62
+ status = result.status;
63
+ outcome = settle(result);
64
+ }
57
65
  }
58
66
  catch (cause) {
59
67
  // Durable hosts suspend children mid-flight; that must escape to the parent journal.
@@ -110,6 +118,9 @@ function settle(result) {
110
118
  code: "delegation.interaction-unsupported",
111
119
  message: INTERACTION_UNSUPPORTED,
112
120
  };
121
+ // Agents used as tools run inside one step of their parent and never roll over.
122
+ if (result.status === "yielded")
123
+ return { kind: "failed", code: "delegation.failed", message: "The agent stopped early." };
113
124
  const reason = result.error.code;
114
125
  const curated = reason.startsWith("execution.") ? reason : `${reason}: ${result.error.message}`;
115
126
  const partial = lastText(result);
@@ -131,3 +142,16 @@ function lastText(result) {
131
142
  }
132
143
  return undefined;
133
144
  }
145
+ /** A flow's settled value: its output, or the `{ kind: "failed" }` value the host records. */
146
+ function settleFlow(value) {
147
+ if (value && typeof value === "object" && !Array.isArray(value)) {
148
+ const record = value;
149
+ if (record.kind === "failed" && typeof record.code === "string")
150
+ return {
151
+ kind: "failed",
152
+ code: "delegation.failed",
153
+ message: `The agent failed (${record.code}: ${typeof record.message === "string" ? record.message : record.code}).`,
154
+ };
155
+ }
156
+ return settle({ status: "completed", output: value });
157
+ }
@@ -12,6 +12,7 @@ const USAGE_TOKEN_KEYS = [
12
12
  "outputTokens",
13
13
  "totalTokens",
14
14
  "cachedTokens",
15
+ "cacheWriteTokens",
15
16
  "reasoningTokens",
16
17
  ];
17
18
  export function normalizeDirective(value) {
@@ -1,9 +1,10 @@
1
1
  import { copyJson, freezeGraph } from "@nylorun/core/define";
2
+ import { summaryPrompt } from "../compaction/index.js";
2
3
  export function projectModelCall(request) {
3
4
  return freezeGraph({
4
5
  prompt: Object.freeze([
5
6
  ...projectInstructions(request.instructions),
6
- ...request.transcript.flatMap(projectEntry),
7
+ ...request.transcript.flatMap((entry) => projectEntry(entry, request.turnId)),
7
8
  ...projectContext(request.context),
8
9
  ]),
9
10
  tools: Object.freeze(request.configuration.tools.map((tool) => Object.freeze({
@@ -42,7 +43,7 @@ function renderContext(items) {
42
43
  "</runtime-context>",
43
44
  ].join("\n");
44
45
  }
45
- function projectEntry(entry) {
46
+ function projectEntry(entry, turnId) {
46
47
  if (entry.kind === "input") {
47
48
  if (entry.event.kind !== "user-message" && entry.event.kind !== "interrupt")
48
49
  return [];
@@ -64,8 +65,12 @@ function projectEntry(entry) {
64
65
  }
65
66
  if (entry.kind === "candidate") {
66
67
  const content = entry.candidate.output.flatMap((block) => {
67
- if (block.type === "text" ||
68
- (block.type === "reasoning" && block.providerMetadata !== undefined))
68
+ if (block.type === "text")
69
+ return [Object.freeze({ ...block })];
70
+ // Reasoning an adapter marked `replay: "turn"` is sent back only within its own turn.
71
+ if (block.type === "reasoning" &&
72
+ block.providerMetadata !== undefined &&
73
+ (block.providerMetadata.replay !== "turn" || entry.turnId === turnId))
69
74
  return [Object.freeze({ ...block })];
70
75
  if (block.type === "json")
71
76
  return [textPart(JSON.stringify(block.value))];
@@ -85,10 +90,22 @@ function projectEntry(entry) {
85
90
  });
86
91
  if (content.length === 0)
87
92
  return [];
88
- return [freezeItem({ kind: "message", role: "assistant", content: Object.freeze(content) })];
93
+ const producer = producerOf(entry.candidate.evidence?.extras?.producer);
94
+ return [
95
+ freezeItem({
96
+ kind: "message",
97
+ role: "assistant",
98
+ content: Object.freeze(content),
99
+ ...(producer ? { producer } : {}),
100
+ }),
101
+ ];
89
102
  }
90
103
  if (entry.kind === "tool-results")
91
104
  return entry.results.map(projectToolResult);
105
+ if (entry.kind === "compaction")
106
+ return [
107
+ freezeItem({ kind: "message", role: "user", content: [textPart(summaryPrompt(entry))] }),
108
+ ];
92
109
  return [];
93
110
  }
94
111
  function projectToolResult(result) {
@@ -121,3 +138,15 @@ function freezeItem(item) {
121
138
  content: Object.freeze(item.content.map((part) => Object.freeze(part))),
122
139
  });
123
140
  }
141
+ function producerOf(value) {
142
+ if (!value || typeof value !== "object" || Array.isArray(value))
143
+ return undefined;
144
+ const producer = value;
145
+ if (typeof producer.provider !== "string" || typeof producer.model !== "string")
146
+ return undefined;
147
+ return Object.freeze({
148
+ provider: producer.provider,
149
+ model: producer.model,
150
+ ...(typeof producer.api === "string" ? { api: producer.api } : {}),
151
+ });
152
+ }
package/dist/loop/run.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { HostSuspension } from "./host-suspension.js";
2
2
  import { HarnessError, isHarnessError } from "@nylorun/core/define";
3
3
  import { runStep } from "./step/run.js";
4
+ import { compact, contextBudget, estimateTokens } from "./compaction/index.js";
4
5
  import { createId } from "../utils/ids.js";
5
6
  import { copyJson } from "@nylorun/core/define";
6
7
  import { dispatchPlan } from "./dispatch.js";
@@ -35,6 +36,29 @@ export async function execute(agent, options, internals = {}) {
35
36
  signal.throwIfAborted();
36
37
  let turnId;
37
38
  let stepNumber;
39
+ /** Steps run and when this invocation started, for segment rollover. */
40
+ let stepsRun = 0;
41
+ const started = Date.now();
42
+ /** One compaction and retry per overflow; reset once a step succeeds. */
43
+ let overflowCompacted = false;
44
+ /** Summarize older history into a compaction entry (Model Calls §8). */
45
+ const compactHistory = async (trigger, stepId) => {
46
+ const next = await compact({
47
+ transcript: invocation.state.transcript,
48
+ executionId: invocation.state.executionId,
49
+ turnId,
50
+ stepId,
51
+ trigger,
52
+ budget: contextBudget(invocation.state.transcript),
53
+ invoke: options.onModelCall,
54
+ signal,
55
+ });
56
+ if (!next)
57
+ return false;
58
+ invocation.state = { ...invocation.state, transcript: next };
59
+ await record();
60
+ return true;
61
+ };
38
62
  let arrivals = [];
39
63
  let toolResults = [];
40
64
  const hooked = hasAnyHooks(agent);
@@ -62,6 +86,7 @@ export async function execute(agent, options, internals = {}) {
62
86
  1 +
63
87
  invocation.state.transcript.filter((entry) => entry.kind === "candidate" && entry.turnId === turnId).length;
64
88
  invocation.state = { ...invocation.state, status: "active" };
89
+ toolResults = lastResults(invocation.state);
65
90
  await record();
66
91
  }
67
92
  else {
@@ -94,7 +119,24 @@ export async function execute(agent, options, internals = {}) {
94
119
  }
95
120
  for (;; stepNumber++) {
96
121
  signal.throwIfAborted();
122
+ // Segment rollover: end this segment between steps; the host continues the turn.
123
+ const yieldAfter = internals.yieldAfter;
124
+ if (yieldAfter &&
125
+ stepsRun > 0 &&
126
+ !invocation.state.plan &&
127
+ ((yieldAfter.steps !== undefined && stepsRun >= yieldAfter.steps) ||
128
+ (yieldAfter.ms !== undefined && Date.now() - started >= yieldAfter.ms))) {
129
+ if (!invocation.state.turn)
130
+ setTurn(() => ({ turnId, attempts: { afterStep: 0, afterTurn: 0 } }));
131
+ return finish({ status: "yielded" });
132
+ }
133
+ stepsRun++;
97
134
  const stepId = createId("step");
135
+ // Keep the next prompt inside the model's window, before it is sent.
136
+ const budget = contextBudget(invocation.state.transcript);
137
+ if (budget &&
138
+ estimateTokens(invocation.state.transcript) > budget.contextWindow - budget.reserve)
139
+ await compactHistory("threshold", stepId);
98
140
  const snapshot = {
99
141
  id: invocation.state.executionId,
100
142
  status: "running",
@@ -151,6 +193,16 @@ export async function execute(agent, options, internals = {}) {
151
193
  ...turn,
152
194
  attempts: { ...turn.attempts, afterStep: turn.attempts.afterStep + 1 },
153
195
  }));
196
+ // The prompt did not fit: compact once and ask again with the same inputs.
197
+ if (result.output.kind === "tripwire" &&
198
+ result.output.tripwire.code === "model.context_overflow" &&
199
+ !overflowCompacted) {
200
+ overflowCompacted = true;
201
+ if (await compactHistory("overflow", stepId))
202
+ continue;
203
+ }
204
+ if (result.output.kind !== "tripwire")
205
+ overflowCompacted = false;
154
206
  let candidate = result.candidate;
155
207
  let finalOutput = result.output.kind === "final" ? result.output.output : undefined;
156
208
  let turnDecision = {};
@@ -350,6 +402,12 @@ async function finishInvocation(invocation, result) {
350
402
  ],
351
403
  };
352
404
  }
405
+ if (result.status === "yielded") {
406
+ // Mid-turn: the state keeps its turn and stays active, so `continue` picks it up.
407
+ invocation.state = { ...invocation.state, status: "active" };
408
+ await invocation.record();
409
+ return { status: "yielded", state: invocation.state };
410
+ }
353
411
  if (result.status !== "paused" && invocation.state.turn) {
354
412
  const { turn: _turn, ...rest } = invocation.state;
355
413
  invocation.state = rest;
@@ -1,6 +1,6 @@
1
1
  import { HostSuspension } from "../host-suspension.js";
2
2
  import { normalizeCandidate } from "../model/normalize.js";
3
- import { HarnessError, isHarnessError } from "@nylorun/core/define";
3
+ import { HarnessError, isHarnessError, isModelFailureOutcome } from "@nylorun/core/define";
4
4
  import { copyJson } from "@nylorun/core/define";
5
5
  import { runMiddleware } from "./compose.js";
6
6
  import { ContextDraft } from "./context-draft.js";
@@ -149,6 +149,14 @@ export async function runStep(input) {
149
149
  });
150
150
  if (input.signal.aborted)
151
151
  throw input.signal.reason;
152
+ // A provider failure the adapter classified ends the step with `model.<code>`.
153
+ if (isModelFailureOutcome(outcome))
154
+ throw new HarnessError(`model.${outcome.code}`, outcome.message, {
155
+ details: {
156
+ retryable: outcome.retryable,
157
+ ...(outcome.retryAfterMs === undefined ? {} : { retryAfterMs: outcome.retryAfterMs }),
158
+ },
159
+ });
152
160
  const minted = context.mintFromModel(normalizeCandidate(outcome));
153
161
  const candidate = context.currentCandidate;
154
162
  if (!candidate)
@@ -60,6 +60,26 @@ function entryAt(value, index) {
60
60
  });
61
61
  return result;
62
62
  }
63
+ case "compaction": {
64
+ exactKeys(entry, ["kind", "turnId", "stepId", "summary", "trigger", "tokensBefore", "tokensAfter"], `Transcript entry ${index}`);
65
+ requiredString(entry.stepId, `Transcript entry ${index} stepId`);
66
+ if (typeof entry.summary !== "string")
67
+ fail(`Transcript entry ${index} summary`);
68
+ if (entry.trigger !== "threshold" && entry.trigger !== "overflow")
69
+ fail(`Transcript entry ${index} trigger`);
70
+ for (const key of ["tokensBefore", "tokensAfter"])
71
+ if (!Number.isInteger(entry[key]) || entry[key] < 0)
72
+ fail(`Transcript entry ${index} ${key}`);
73
+ return Object.freeze({
74
+ kind: "compaction",
75
+ turnId: entry.turnId,
76
+ stepId: entry.stepId,
77
+ summary: entry.summary,
78
+ trigger: entry.trigger,
79
+ tokensBefore: entry.tokensBefore,
80
+ tokensAfter: entry.tokensAfter,
81
+ });
82
+ }
63
83
  case "final":
64
84
  exactKeys(entry, ["kind", "turnId", "stepId", "output"], `Transcript entry ${index}`);
65
85
  requiredString(entry.stepId, `Transcript entry ${index} stepId`);
@@ -65,7 +65,7 @@ export type DurableResult = {
65
65
  readonly checkpoint: DurableCheckpoint;
66
66
  readonly effectIds: readonly string[];
67
67
  } | {
68
- readonly status: "completed" | "paused" | "cancelled" | "failed";
68
+ readonly status: "completed" | "paused" | "cancelled" | "failed" | "yielded";
69
69
  readonly checkpoint: DurableCheckpoint;
70
70
  readonly result: RunResult<unknown>;
71
71
  };
@@ -98,4 +98,9 @@ export declare function runDurable(options: {
98
98
  host: DurableHost;
99
99
  signal?: AbortSignal;
100
100
  sessionTools?: readonly DurableSessionTool[];
101
+ /** Segment rollover (Model Calls §10): yield after this many steps or milliseconds. */
102
+ yieldAfter?: {
103
+ readonly steps?: number;
104
+ readonly ms?: number;
105
+ };
101
106
  }): Promise<DurableResult>;