@a-dray/aglib 0.3.4 → 0.4.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.
package/dist/agent.d.ts CHANGED
@@ -101,7 +101,7 @@ interface RunAgentBase {
101
101
  key?: string;
102
102
  context?: {
103
103
  run?: string;
104
- turn?: string;
104
+ turn?: string | (() => string);
105
105
  };
106
106
  signal?: AbortSignal;
107
107
  }
package/dist/agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"","sourcesContent":["import type { Content } from \"./content.js\";\nimport type { Harness, LifecycleHook } from \"./harness/harness.js\";\nimport type { Decide, Tool } from \"./tools/tool.js\";\nimport type { Runnable, Store } from \"./store/store.js\";\nimport type { Update } from \"./harness/harness.js\";\nimport type { Failure } from \"./result.js\";\nimport type { From, Usage } from \"./session/entry.js\";\n\n/** An inert declaration. Nothing here opens a connection or holds state. */\nexport interface Agent {\n id: string;\n /** Bump when instructions, tools or configuration stop being compatible with an existing session. */\n version: string;\n instructions: Content;\n harness: Harness;\n tools?: readonly Tool[];\n /** Per-call policy over parsed arguments. Absent means every call executes. */\n decide?: Decide;\n /**\n * Name each arrival's sender in the turn the model reads, as `[from kind id]`.\n *\n * Off by default, because two separate things were one: `from` is provenance\n * the log holds whatever this says, and this is text in a prompt. An\n * application that renders its own attribution into the input it delivers —\n * most do, since only they can name a sender in words their agent knows —\n * would otherwise have the model read two names for one sender, one of them a\n * session id that means nothing to it. Turn it on where nothing else says who\n * wrote.\n */\n attribution?: boolean;\n /** Ordered, uniquely named lifecycle callbacks. Continuations share this run's durable log. */\n hooks?: readonly LifecycleHook[];\n /**\n * Ceilings on one activation, over the facts this library holds: turns and\n * tool calls are on the log, and a deadline is the clock.\n *\n * There is no ceiling on money, and the asymmetry is the point. A spend limit\n * would have to read a rate table the library does not have and should not\n * carry, so it would take a function from the caller and then need defending\n * against it — a code for \"you declared a ceiling nothing can hold\", a rule\n * for a generation the function could not price, a check for a price that is\n * negative or not a number. All of that is the cost of enforcing something\n * from a fact we do not own, and enforcing it is policy besides: the two\n * applications that wanted one wanted it to stop at different moments.\n *\n * `RunResult.usage` is what a caller needs from here, and it is solid. What\n * that costs, and what to do about it, is priced by whoever holds the rates.\n */\n limits?: { maxTurns?: number; maxToolCalls?: number; deadline?: string };\n}\n\n/**\n * How an activation ended, and what it consumed on the way.\n *\n * `usage` is on every outcome, not only a completed one: a run that burned four\n * dollars of tokens and then failed burned them, and a caller that has to ask\n * the log to find that out has been handed a result missing the expensive half\n * of what happened.\n *\n * Summed from the `assistant` entries this activation committed, which is why a\n * harness does not report it — the log already holds every generation, and a\n * second total is a second answer. Money is not here: the counts are the fact,\n * and the rates that turn them into money belong to the deployment.\n */\nexport type RunResult =\n | { status: \"completed\"; output: Content; usage: Usage; seq: number }\n | { status: \"cancelled\"; usage: Usage; seq: number }\n | { status: \"failed\"; error: Failure; usage: Usage; seq: number };\n\nexport interface AgentRun extends AsyncIterable<Update> {\n readonly result: Promise<RunResult>;\n cancel(): void;\n}\n\n/**\n * One piece of input for an activation, and where it came from.\n *\n * Always the object form, because `Content` may itself be an array of parts and\n * a bare array therefore cannot say whether it is one multi-part message or\n * several messages. `RunAgentOptions.input` still takes plain content for the\n * common case; only the *many* form is required to name each arrival.\n */\nexport interface Arrival { input: Content; from?: From }\n\ninterface RunAgentBase {\n agent: Agent;\n /** Opaque application index key, used only when this run creates the session. */\n key?: string;\n context?: { run?: string; turn?: string };\n signal?: AbortSignal;\n}\n\n/**\n * An activation is working one of two things, and never both.\n *\n * A caller is **sending** — a person typed, a webhook fired, a test asked a\n * question. Or a worker is running **what the store handed it**, which carries\n * the session, the position to write from, and the deliveries to consume, all\n * as one value that arrived together and cannot be recombined wrongly.\n *\n * That second form replaced three fields a worker had to line up by hand:\n * `sessionId`, the position, and how many deliveries to take. Every one of them\n * was only ever a field of the claim, so each was a value another field already\n * determined — and the one that mattered, taking the deliveries, silently\n * left the input queued for ever when it was forgotten. Both applications\n * written on this wrote the same eight lines to get it right.\n */\nexport type RunAgentOptions = RunAgentBase & (\n | {\n /** One message as plain content, one named arrival, or several named arrivals. */\n input: Content | Arrival | readonly Arrival[];\n /**\n * Which session it goes to, as a UUID. A new one is opened when this is\n * omitted. An application's own naming for a conversation goes in `key`,\n * which is opaque to the library; a store is entitled to keep a session\n * id in a `uuid` column and refuse anything else.\n */\n sessionId?: string;\n /** Omit for an ephemeral run: the log lives in memory and nothing is persisted. */\n store?: Store;\n claim?: never;\n }\n | {\n /**\n * What `store.next()` or `store.interrupted()` handed this worker.\n *\n * Its deliveries become this activation's input and are consumed by the\n * write that commits them, in the same compare-and-swap that checks the\n * position — so a worker that loses the race loses its turn and never the\n * messages. A claim with an empty queue is a **resumption**: nothing opens\n * it, the loop continues the committed log, and the effect that already\n * happened is read there rather than asked for again. Only a harness\n * declaring `recovery: \"history\"` is given one.\n */\n claim: Runnable;\n /**\n * Required here, unlike a caller sending. A claim is a position in a log\n * and a queue to consume, and both of those are the store's — without one\n * the deliveries would be replayed into memory and left queued for ever.\n */\n store: Store;\n /**\n * Something the worker is adding of its own, ahead of what was waiting.\n *\n * One real use: orientation for a harness whose protocol has no system\n * prompt, which has nowhere else to go and must lead. Adding nothing is\n * the ordinary case.\n */\n input?: Content | Arrival | readonly Arrival[];\n sessionId?: never;\n }\n);\n"]}
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"","sourcesContent":["import type { Content } from \"./content.js\";\nimport type { Harness, LifecycleHook } from \"./harness/harness.js\";\nimport type { Decide, Tool } from \"./tools/tool.js\";\nimport type { Runnable, Store } from \"./store/store.js\";\nimport type { Update } from \"./harness/harness.js\";\nimport type { Failure } from \"./result.js\";\nimport type { From, Usage } from \"./session/entry.js\";\n\n/** An inert declaration. Nothing here opens a connection or holds state. */\nexport interface Agent {\n id: string;\n /** Bump when instructions, tools or configuration stop being compatible with an existing session. */\n version: string;\n instructions: Content;\n harness: Harness;\n tools?: readonly Tool[];\n /** Per-call policy over parsed arguments. Absent means every call executes. */\n decide?: Decide;\n /**\n * Name each arrival's sender in the turn the model reads, as `[from kind id]`.\n *\n * Off by default, because two separate things were one: `from` is provenance\n * the log holds whatever this says, and this is text in a prompt. An\n * application that renders its own attribution into the input it delivers —\n * most do, since only they can name a sender in words their agent knows —\n * would otherwise have the model read two names for one sender, one of them a\n * session id that means nothing to it. Turn it on where nothing else says who\n * wrote.\n */\n attribution?: boolean;\n /** Ordered, uniquely named lifecycle callbacks. Continuations share this run's durable log. */\n hooks?: readonly LifecycleHook[];\n /**\n * Ceilings on one activation, over the facts this library holds: turns and\n * tool calls are on the log, and a deadline is the clock.\n *\n * There is no ceiling on money, and the asymmetry is the point. A spend limit\n * would have to read a rate table the library does not have and should not\n * carry, so it would take a function from the caller and then need defending\n * against it — a code for \"you declared a ceiling nothing can hold\", a rule\n * for a generation the function could not price, a check for a price that is\n * negative or not a number. All of that is the cost of enforcing something\n * from a fact we do not own, and enforcing it is policy besides: the two\n * applications that wanted one wanted it to stop at different moments.\n *\n * `RunResult.usage` is what a caller needs from here, and it is solid. What\n * that costs, and what to do about it, is priced by whoever holds the rates.\n */\n limits?: { maxTurns?: number; maxToolCalls?: number; deadline?: string };\n}\n\n/**\n * How an activation ended, and what it consumed on the way.\n *\n * `usage` is on every outcome, not only a completed one: a run that burned four\n * dollars of tokens and then failed burned them, and a caller that has to ask\n * the log to find that out has been handed a result missing the expensive half\n * of what happened.\n *\n * Summed from the `assistant` entries this activation committed, which is why a\n * harness does not report it — the log already holds every generation, and a\n * second total is a second answer. Money is not here: the counts are the fact,\n * and the rates that turn them into money belong to the deployment.\n */\nexport type RunResult =\n | { status: \"completed\"; output: Content; usage: Usage; seq: number }\n | { status: \"cancelled\"; usage: Usage; seq: number }\n | { status: \"failed\"; error: Failure; usage: Usage; seq: number };\n\nexport interface AgentRun extends AsyncIterable<Update> {\n readonly result: Promise<RunResult>;\n cancel(): void;\n}\n\n/**\n * One piece of input for an activation, and where it came from.\n *\n * Always the object form, because `Content` may itself be an array of parts and\n * a bare array therefore cannot say whether it is one multi-part message or\n * several messages. `RunAgentOptions.input` still takes plain content for the\n * common case; only the *many* form is required to name each arrival.\n */\nexport interface Arrival { input: Content; from?: From }\n\ninterface RunAgentBase {\n agent: Agent;\n /** Opaque application index key, used only when this run creates the session. */\n key?: string;\n context?: { run?: string; turn?: string | (() => string) };\n signal?: AbortSignal;\n}\n\n/**\n * An activation is working one of two things, and never both.\n *\n * A caller is **sending** — a person typed, a webhook fired, a test asked a\n * question. Or a worker is running **what the store handed it**, which carries\n * the session, the position to write from, and the deliveries to consume, all\n * as one value that arrived together and cannot be recombined wrongly.\n *\n * That second form replaced three fields a worker had to line up by hand:\n * `sessionId`, the position, and how many deliveries to take. Every one of them\n * was only ever a field of the claim, so each was a value another field already\n * determined — and the one that mattered, taking the deliveries, silently\n * left the input queued for ever when it was forgotten. Both applications\n * written on this wrote the same eight lines to get it right.\n */\nexport type RunAgentOptions = RunAgentBase & (\n | {\n /** One message as plain content, one named arrival, or several named arrivals. */\n input: Content | Arrival | readonly Arrival[];\n /**\n * Which session it goes to, as a UUID. A new one is opened when this is\n * omitted. An application's own naming for a conversation goes in `key`,\n * which is opaque to the library; a store is entitled to keep a session\n * id in a `uuid` column and refuse anything else.\n */\n sessionId?: string;\n /** Omit for an ephemeral run: the log lives in memory and nothing is persisted. */\n store?: Store;\n claim?: never;\n }\n | {\n /**\n * What `store.next()` or `store.interrupted()` handed this worker.\n *\n * Its deliveries become this activation's input and are consumed by the\n * write that commits them, in the same compare-and-swap that checks the\n * position — so a worker that loses the race loses its turn and never the\n * messages. A claim with an empty queue is a **resumption**: nothing opens\n * it, the loop continues the committed log, and the effect that already\n * happened is read there rather than asked for again. Only a harness\n * declaring `recovery: \"history\"` is given one.\n */\n claim: Runnable;\n /**\n * Required here, unlike a caller sending. A claim is a position in a log\n * and a queue to consume, and both of those are the store's — without one\n * the deliveries would be replayed into memory and left queued for ever.\n */\n store: Store;\n /**\n * Something the worker is adding of its own, ahead of what was waiting.\n *\n * One real use: orientation for a harness whose protocol has no system\n * prompt, which has nowhere else to go and must lead. Adding nothing is\n * the ordinary case.\n */\n input?: Content | Arrival | readonly Arrival[];\n sessionId?: never;\n }\n);\n"]}
@@ -1,3 +1,29 @@
1
+ /** Ask one tool call through the executor whose validation and policy own it. */
2
+ async function executeOne(context, call) {
3
+ if (!context.tools) {
4
+ return {
5
+ callId: call.callId,
6
+ result: { content: `No tool named '${call.name}' is available.`, isError: true },
7
+ deliveries: [],
8
+ };
9
+ }
10
+ for await (const completion of context.tools.execute({ calls: [call], signal: context.signal })) {
11
+ return completion;
12
+ }
13
+ return {
14
+ callId: call.callId,
15
+ result: { content: "Tool use cancelled", isError: true },
16
+ deliveries: [],
17
+ };
18
+ }
19
+ /** Calls left open by a process that died are never re-executed automatically. */
20
+ function unresolved(context) {
21
+ const answered = new Set(context.entries().filter((entry) => entry.type === "tool.finished")
22
+ .map((entry) => `${entry.runId}\u0000${entry.callId}`));
23
+ return context.entries().flatMap((entry) => entry.type === "assistant" && entry.runId === context.runId
24
+ ? (entry.calls ?? []).filter((call) => !answered.has(`${entry.runId}\u0000${call.callId}`))
25
+ : []);
26
+ }
1
27
  /**
2
28
  * Ask the model, run what it asks for, repeat.
3
29
  *
@@ -12,6 +38,92 @@ export function createNativeHarness(options) {
12
38
  recovery: "history",
13
39
  async run(context) {
14
40
  const { runId } = context;
41
+ const pending = new Map();
42
+ const asyncTools = new Set(context.tools?.list().filter((tool) => tool.async === true).map((tool) => tool.name) ?? []);
43
+ const canRunAsync = (call) => options.model.asyncTools === true && call.async === true && asyncTools.has(call.name);
44
+ let resultsForNextRequest = false;
45
+ // This function begins with unresolved calls only on recovery. Calls
46
+ // started below stay in `pending` until they have reported back.
47
+ const abandoned = unresolved(context);
48
+ if (abandoned.length) {
49
+ await context.commit(abandoned.map((call) => ({
50
+ type: "tool.finished", runId, callId: call.callId,
51
+ result: {
52
+ content: "This call did not report back: the activation ended before its result was committed.",
53
+ isError: true,
54
+ },
55
+ })));
56
+ }
57
+ const finish = async (completion) => {
58
+ pending.delete(completion.callId);
59
+ await context.commit([{
60
+ type: "tool.finished", runId, callId: completion.callId, result: completion.result,
61
+ }], completion.deliveries);
62
+ resultsForNextRequest = true;
63
+ };
64
+ const firstPending = () => Promise.race([...pending.entries()].map(async ([callId, completion]) => ({ callId, completion: await completion })));
65
+ const settlePending = async () => {
66
+ while (pending.size) {
67
+ const event = await firstPending();
68
+ if (pending.has(event.callId))
69
+ await finish(event.completion);
70
+ }
71
+ };
72
+ const startAsync = async (call) => {
73
+ if (pending.has(call.callId))
74
+ return;
75
+ if (!context.tools) {
76
+ await finish(await executeOne(context, call));
77
+ return;
78
+ }
79
+ await context.commit([{ type: "tool.started", runId, callId: call.callId }]);
80
+ pending.set(call.callId, executeOne(context, call));
81
+ };
82
+ /** Commit foreground and background completions through the same writer. */
83
+ const executeBatch = async (calls) => {
84
+ if (!context.tools)
85
+ return;
86
+ const iterator = context.tools.execute({ calls, signal: context.signal })[Symbol.asyncIterator]();
87
+ let next = iterator.next();
88
+ for (;;) {
89
+ const event = await Promise.race([
90
+ next.then((value) => ({ type: "batch", value })),
91
+ ...([...pending.entries()].map(async ([callId, completion]) => ({
92
+ type: "tool", value: { callId, completion: await completion },
93
+ }))),
94
+ ]);
95
+ if (event.type === "tool") {
96
+ if (pending.has(event.value.callId))
97
+ await finish(event.value.completion);
98
+ continue;
99
+ }
100
+ if (event.value.done)
101
+ return;
102
+ await finish(event.value.value);
103
+ await context.drain?.();
104
+ next = iterator.next();
105
+ }
106
+ };
107
+ /** Wait for one background result or newly delivered input. */
108
+ const waitForWork = async () => {
109
+ for (;;) {
110
+ const event = await Promise.race([
111
+ firstPending().then((value) => ({ type: "tool", value })),
112
+ ...(context.waitForInput
113
+ ? [context.waitForInput().then(() => ({ type: "input" }))]
114
+ : []),
115
+ ]);
116
+ if (event.type === "tool") {
117
+ if (pending.has(event.value.callId))
118
+ await finish(event.value.completion);
119
+ return;
120
+ }
121
+ if (await context.drain?.())
122
+ return;
123
+ if (context.signal.aborted)
124
+ return;
125
+ }
126
+ };
15
127
  for (;;) {
16
128
  if (context.signal.aborted)
17
129
  return { status: "cancelled" };
@@ -23,9 +135,13 @@ export function createNativeHarness(options) {
23
135
  if (context.signal.aborted)
24
136
  return { status: "cancelled" };
25
137
  const history = context.history();
138
+ // Results committed after this snapshot need a later request even if
139
+ // the active generation can continue independently of them.
140
+ resultsForNextRequest = false;
26
141
  // One cache mark, at the end of the system prefix: instructions plus
27
142
  // run-scoped context, which are fixed for the life of the run.
28
143
  const cacheAfter = history.findIndex((message) => message.role !== "system");
144
+ const generationId = crypto.randomUUID();
29
145
  const startedAt = new Date().toISOString();
30
146
  const generation = options.model.generate({
31
147
  messages: history,
@@ -36,87 +152,160 @@ export function createNativeHarness(options) {
36
152
  ...(cacheAfter > 0 ? { cacheAfter } : {}),
37
153
  signal: context.signal,
38
154
  });
39
- let step = await generation.next();
40
- while (!step.done) {
41
- const delta = step.value;
42
- if (delta.type === "text.delta")
43
- context.emit({ type: "text.delta", text: delta.text });
44
- if (delta.type === "reasoning.delta")
45
- context.emit({ type: "reasoning.delta", text: delta.text });
155
+ const launched = new Set();
156
+ const steering = new Set();
157
+ let inputForNext = false;
158
+ let next = generation.next();
159
+ let step;
160
+ for (;;) {
161
+ const event = await Promise.race([
162
+ next.then((value) => ({ type: "model", value })),
163
+ ...([...pending.entries()].map(async ([callId, completion]) => ({
164
+ type: "tool", value: { callId, completion: await completion },
165
+ }))),
166
+ ...(context.waitForInput
167
+ ? [context.waitForInput().then(() => ({ type: "input" }))]
168
+ : []),
169
+ ...([...steering].map(async (promise) => ({
170
+ type: "steer", promise, value: await promise,
171
+ }))),
172
+ ]);
173
+ if (event.type === "tool") {
174
+ if (pending.has(event.value.callId))
175
+ await finish(event.value.completion);
176
+ continue;
177
+ }
178
+ if (event.type === "steer") {
179
+ steering.delete(event.promise);
180
+ if (event.value.status === "rejected")
181
+ inputForNext = true;
182
+ continue;
183
+ }
184
+ if (event.type === "input") {
185
+ const arrived = await context.drain?.() ?? 0;
186
+ if (!arrived)
187
+ continue;
188
+ const fresh = context.history().filter((message) => message.role === "user").slice(-arrived);
189
+ if (!generation.steer || !fresh.length) {
190
+ inputForNext = true;
191
+ continue;
192
+ }
193
+ const attempt = generation.steer(fresh).catch((error) => ({
194
+ status: "rejected",
195
+ error: {
196
+ code: "failed", retryable: true,
197
+ message: error instanceof Error ? error.message : String(error),
198
+ },
199
+ }));
200
+ steering.add(attempt);
201
+ continue;
202
+ }
203
+ const current = event.value;
204
+ if (current.done) {
205
+ step = current;
206
+ break;
207
+ }
208
+ const delta = current.value;
209
+ if (delta.type === "text.delta") {
210
+ context.emit({ ...delta, runId, generationId });
211
+ }
212
+ if (delta.type === "reasoning.delta") {
213
+ context.emit({ type: "reasoning.delta", text: delta.text, runId, generationId });
214
+ }
46
215
  if (delta.type === "tool-call.delta") {
47
- context.emit({ type: "tool-call.delta", callId: delta.callId, arguments: delta.arguments });
216
+ context.emit({
217
+ type: "tool-call.delta", callId: delta.callId, arguments: delta.arguments, runId, generationId,
218
+ });
48
219
  }
49
- step = await generation.next();
220
+ if (delta.type === "tool-call.done" && canRunAsync(delta.call) && !launched.has(delta.call.callId)) {
221
+ launched.add(delta.call.callId);
222
+ await context.commit([{
223
+ type: "assistant", runId, content: "", calls: [delta.call],
224
+ generation: { id: generationId, startedAt },
225
+ }]);
226
+ await startAsync(delta.call);
227
+ }
228
+ next = generation.next();
229
+ }
230
+ for (const result of await Promise.all(steering)) {
231
+ if (result.status === "rejected")
232
+ inputForNext = true;
50
233
  }
51
234
  for (const hook of context.hooks ?? [])
52
235
  await hook.afterModel?.(context, step.value);
53
236
  if (!step.value.ok) {
237
+ await settlePending();
238
+ if ((inputForNext || resultsForNextRequest) && step.value.error.retryable &&
239
+ step.value.error.code !== "cancelled" && !context.signal.aborted)
240
+ continue;
54
241
  return step.value.error.code === "cancelled"
55
242
  ? { status: "cancelled" }
56
243
  : { status: "failed", error: step.value.error };
57
244
  }
58
245
  const endedAt = new Date().toISOString();
59
246
  const response = step.value.value;
60
- const calls = response.message.calls ?? [];
247
+ const calls = (response.message.calls ?? []).filter((call) => !launched.has(call.callId));
61
248
  await context.commit([{
62
249
  type: "assistant", runId, content: response.message.content,
63
250
  ...(calls.length ? { calls } : {}),
64
251
  usage: response.usage,
65
252
  ...(response.providerState ? { providerState: response.providerState } : {}),
66
- generation: { ...(response.model ? { model: response.model } : {}), startedAt, endedAt },
253
+ generation: {
254
+ id: generationId, ...(response.model ? { model: response.model } : {}), startedAt, endedAt,
255
+ },
67
256
  }]);
68
- if (!calls.length) {
69
- // The reason the model stopped decides the outcome, and it decides it
70
- // before the absence of tool calls does. A turn cut off by the output
71
- // ceiling or declined by a safety classifier is not an answer, and
72
- // reporting either as `completed` hands the caller a truncated or
73
- // refused response dressed as a finished one.
74
- if (response.finishReason === "length") {
75
- return { status: "failed", error: {
76
- code: "output-truncated",
77
- message: "The response stopped at the output limit before it was finished.",
78
- retryable: false,
79
- } };
80
- }
81
- if (response.finishReason === "refusal") {
82
- return { status: "failed", error: {
83
- code: "refused",
84
- message: "The provider declined to answer.",
85
- retryable: false,
86
- } };
87
- }
88
- return { status: "completed", output: response.message.content };
89
- }
90
257
  if (response.finishReason === "length") {
91
258
  // A truncated response can carry half-parsed arguments that happen to
92
- // be valid JSON. None of the batch runs; the model is told why and
93
- // can reissue.
259
+ // be valid JSON. Calls already completed and launched by the provider
260
+ // remain real; the incomplete remainder is refused.
94
261
  await context.commit(calls.map((call) => ({
95
262
  type: "tool.finished", runId, callId: call.callId,
96
- result: { content: "Not executed: the response was truncated. Reissue the call if it is still needed.", isError: true },
263
+ result: {
264
+ content: "Not executed: the response was truncated. Reissue the call if it is still needed.",
265
+ isError: true,
266
+ },
97
267
  })));
98
- continue;
268
+ await settlePending();
269
+ if ((calls.length || resultsForNextRequest) && !context.signal.aborted)
270
+ continue;
271
+ return { status: "failed", error: {
272
+ code: "output-truncated",
273
+ message: "The response stopped at the output limit before it was finished.",
274
+ retryable: false,
275
+ } };
99
276
  }
100
- if (!context.tools) {
277
+ if (response.finishReason === "refusal" && !calls.length) {
278
+ await settlePending();
279
+ if ((inputForNext || resultsForNextRequest) && !context.signal.aborted)
280
+ continue;
281
+ return { status: "failed", error: {
282
+ code: "refused", message: "The provider declined to answer.", retryable: false,
283
+ } };
284
+ }
285
+ const asyncCalls = calls.filter(canRunAsync);
286
+ const synchronous = calls.filter((call) => !canRunAsync(call));
287
+ if (calls.length && context.tools) {
101
288
  await context.commit(calls.map((call) => ({
102
- type: "tool.finished", runId, callId: call.callId,
103
- result: { content: `No tool named '${call.name}' is available.`, isError: true },
289
+ type: "tool.started", runId, callId: call.callId,
104
290
  })));
291
+ for (const call of asyncCalls) {
292
+ pending.set(call.callId, executeOne(context, call));
293
+ }
294
+ if (synchronous.length)
295
+ await executeBatch(synchronous);
296
+ }
297
+ if (calls.length && !context.tools) {
298
+ for (const call of calls)
299
+ await finish(await executeOne(context, call));
300
+ }
301
+ const arrived = await context.drain?.() ?? 0;
302
+ if (synchronous.length || arrived || inputForNext || resultsForNextRequest || (calls.length && !context.tools))
303
+ continue;
304
+ if (pending.size) {
305
+ await waitForWork();
105
306
  continue;
106
307
  }
107
- // Recorded before anything runs. On restart an unmatched `tool.started`
108
- // is how we know the process died mid-effect — and why nothing is
109
- // re-executed automatically.
110
- await context.commit(calls.map((call) => ({ type: "tool.started", runId, callId: call.callId })));
111
- const outcome = await context.tools.execute({ calls, signal: context.signal });
112
- await context.commit(outcome.results.map(({ callId, result }) => ({
113
- type: "tool.finished", runId, callId, result,
114
- })));
115
- // Nothing is half-done here: every call asked for has been answered and
116
- // committed. Anything waiting is folded in before the next request is
117
- // built, so a message delivered to a busy session is read without the
118
- // activation having to be ended and its work thrown away.
119
- await context.drain?.();
308
+ return { status: "completed", output: response.message.content };
120
309
  }
121
310
  },
122
311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{ Entry } from \"../../../session/entry.js\";\nimport type { Model } from \"../../../model/model.js\";\n\nexport interface NativeHarnessOptions {\n model: Model;\n maxOutputTokens?: number;\n temperature?: number;\n /** How hard the model should think, where the provider supports it. */\n effort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n}\n\n/**\n * Ask the model, run what it asks for, repeat.\n *\n * The loop holds no transcript. Every turn it re-reads `context.history()`,\n * which projects the committed log, and every result it produces goes back\n * through `context.commit` before the next turn is built. There is exactly one\n * representation of the conversation and it is the log.\n */\nexport function createNativeHarness(options: NativeHarnessOptions): Harness {\n return {\n id: \"native\",\n recovery: \"history\",\n\n async run(context: HarnessContext): Promise<HarnessResult> {\n const { runId } = context;\n\n for (;;) {\n if (context.signal.aborted) return { status: \"cancelled\" };\n\n for (const hook of context.hooks ?? []) {\n const failure = await hook.beforeModel?.(context);\n if (failure) return { status: \"failed\", error: failure };\n }\n if (context.signal.aborted) return { status: \"cancelled\" };\n const history = context.history();\n\n // One cache mark, at the end of the system prefix: instructions plus\n // run-scoped context, which are fixed for the life of the run.\n const cacheAfter = history.findIndex((message) => message.role !== \"system\");\n\n const startedAt = new Date().toISOString();\n const generation = options.model.generate({\n messages: history,\n ...(context.tools ? { tools: context.tools.list() } : {}),\n ...(options.maxOutputTokens !== undefined ? { maxOutputTokens: options.maxOutputTokens } : {}),\n ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n ...(options.effort ? { effort: options.effort } : {}),\n ...(cacheAfter > 0 ? { cacheAfter } : {}),\n signal: context.signal,\n });\n\n let step = await generation.next();\n while (!step.done) {\n const delta = step.value;\n if (delta.type === \"text.delta\") context.emit({ type: \"text.delta\", text: delta.text });\n if (delta.type === \"reasoning.delta\") context.emit({ type: \"reasoning.delta\", text: delta.text });\n if (delta.type === \"tool-call.delta\") {\n context.emit({ type: \"tool-call.delta\", callId: delta.callId, arguments: delta.arguments });\n }\n step = await generation.next();\n }\n for (const hook of context.hooks ?? []) await hook.afterModel?.(context, step.value);\n if (!step.value.ok) {\n return step.value.error.code === \"cancelled\"\n ? { status: \"cancelled\" }\n : { status: \"failed\", error: step.value.error };\n }\n\n const endedAt = new Date().toISOString();\n const response = step.value.value;\n const calls = response.message.calls ?? [];\n\n await context.commit([{\n type: \"assistant\", runId, content: response.message.content,\n ...(calls.length ? { calls } : {}),\n usage: response.usage,\n ...(response.providerState ? { providerState: response.providerState } : {}),\n generation: { ...(response.model ? { model: response.model } : {}), startedAt, endedAt },\n }]);\n\n if (!calls.length) {\n // The reason the model stopped decides the outcome, and it decides it\n // before the absence of tool calls does. A turn cut off by the output\n // ceiling or declined by a safety classifier is not an answer, and\n // reporting either as `completed` hands the caller a truncated or\n // refused response dressed as a finished one.\n if (response.finishReason === \"length\") {\n return { status: \"failed\", error: {\n code: \"output-truncated\",\n message: \"The response stopped at the output limit before it was finished.\",\n retryable: false,\n } };\n }\n if (response.finishReason === \"refusal\") {\n return { status: \"failed\", error: {\n code: \"refused\",\n message: \"The provider declined to answer.\",\n retryable: false,\n } };\n }\n return { status: \"completed\", output: response.message.content };\n }\n\n if (response.finishReason === \"length\") {\n // A truncated response can carry half-parsed arguments that happen to\n // be valid JSON. None of the batch runs; the model is told why and\n // can reissue.\n await context.commit(calls.map((call): Entry => ({\n type: \"tool.finished\", runId, callId: call.callId,\n result: { content: \"Not executed: the response was truncated. Reissue the call if it is still needed.\", isError: true },\n })));\n continue;\n }\n\n if (!context.tools) {\n await context.commit(calls.map((call): Entry => ({\n type: \"tool.finished\", runId, callId: call.callId,\n result: { content: `No tool named '${call.name}' is available.`, isError: true },\n })));\n continue;\n }\n\n // Recorded before anything runs. On restart an unmatched `tool.started`\n // is how we know the process died mid-effect — and why nothing is\n // re-executed automatically.\n await context.commit(calls.map((call): Entry => ({ type: \"tool.started\", runId, callId: call.callId })));\n\n const outcome = await context.tools.execute({ calls, signal: context.signal });\n await context.commit(outcome.results.map(({ callId, result }): Entry => ({\n type: \"tool.finished\", runId, callId, result,\n })));\n\n // Nothing is half-done here: every call asked for has been answered and\n // committed. Anything waiting is folded in before the next request is\n // built, so a message delivered to a busy session is read without the\n // activation having to be ended and its work thrown away.\n await context.drain?.();\n }\n },\n };\n}\n"]}
1
+ {"version":3,"file":"loop.js","sourceRoot":"","sources":["../../../../src/harness/adapters/native/loop.ts"],"names":[],"mappings":"AAmBA,iFAAiF;AACjF,KAAK,UAAU,UAAU,CAAC,OAAuB,EAAE,IAAc;IAC/D,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACnB,OAAO;YACL,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,MAAM,EAAE,EAAE,OAAO,EAAE,kBAAkB,IAAI,CAAC,IAAI,iBAAiB,EAAE,OAAO,EAAE,IAAI,EAAE;YAChF,UAAU,EAAE,EAAE;SACf,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,EAAE,MAAM,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC;QAChG,OAAO,UAAU,CAAC;IACpB,CAAC;IACD,OAAO;QACL,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,MAAM,EAAE,EAAE,OAAO,EAAE,oBAAoB,EAAE,OAAO,EAAE,IAAI,EAAE;QACxD,UAAU,EAAE,EAAE;KACf,CAAC;AACJ,CAAC;AAED,kFAAkF;AAClF,SAAS,UAAU,CAAC,OAAuB;IACzC,MAAM,QAAQ,GAAG,IAAI,GAAG,CACtB,OAAO,CAAC,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,eAAe,CAAC;SAChE,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,KAAK,SAAS,KAAK,CAAC,MAAM,EAAE,CAAC,CACzD,CAAC;IACF,OAAO,OAAO,CAAC,OAAO,EA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K,CAAC;oBAAE,SAAS;gBAEzH,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;oBACjB,MAAM,WAAW,EAAE,CAAC;oBACpB,SAAS;gBACX,CAAC;gBAED,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;YACnE,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { Harness, HarnessContext, HarnessResult } from \"../../harness.js\";\nimport type { Entry, ToolCall, ToolResult } from \"../../../session/entry.js\";\nimport type { Message, Model, ModelSteerResult } from \"../../../model/model.js\";\nimport type { Delivery } from \"../../../store/store.js\";\n\nexport interface NativeHarnessOptions {\n model: Model;\n maxOutputTokens?: number;\n temperature?: number;\n /** How hard the model should think, where the provider supports it. */\n effort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n}\n\ninterface Completion {\n callId: string;\n result: ToolResult;\n deliveries: readonly Delivery[];\n}\n\n/** Ask one tool call through the executor whose validation and policy own it. */\nasync function executeOne(context: HarnessContext, call: ToolCall): Promise<Completion> {\n if (!context.tools) {\n return {\n callId: call.callId,\n result: { content: `No tool named '${call.name}' is available.`, isError: true },\n deliveries: [],\n };\n }\n for await (const completion of context.tools.execute({ calls: [call], signal: context.signal })) {\n return completion;\n }\n return {\n callId: call.callId,\n result: { content: \"Tool use cancelled\", isError: true },\n deliveries: [],\n };\n}\n\n/** Calls left open by a process that died are never re-executed automatically. */\nfunction unresolved(context: HarnessContext): ToolCall[] {\n const answered = new Set(\n context.entries().filter((entry) => entry.type === \"tool.finished\")\n .map((entry) => `${entry.runId}\\u0000${entry.callId}`),\n );\n return context.entries().flatMap((entry) => entry.type === \"assistant\" && entry.runId === context.runId\n ? (entry.calls ?? []).filter((call) => !answered.has(`${entry.runId}\\u0000${call.callId}`))\n : []);\n}\n\n/**\n * Ask the model, run what it asks for, repeat.\n *\n * The loop holds no transcript. Every turn it re-reads `context.history()`,\n * which projects the committed log, and every result it produces goes back\n * through `context.commit` before the next turn is built. There is exactly one\n * representation of the conversation and it is the log.\n */\nexport function createNativeHarness(options: NativeHarnessOptions): Harness {\n return {\n id: \"native\",\n recovery: \"history\",\n\n async run(context: HarnessContext): Promise<HarnessResult> {\n const { runId } = context;\n const pending = new Map<string, Promise<Completion>>();\n const asyncTools = new Set(\n context.tools?.list().filter((tool) => tool.async === true).map((tool) => tool.name) ?? [],\n );\n const canRunAsync = (call: ToolCall) =>\n options.model.asyncTools === true && call.async === true && asyncTools.has(call.name);\n let resultsForNextRequest = false;\n\n // This function begins with unresolved calls only on recovery. Calls\n // started below stay in `pending` until they have reported back.\n const abandoned = unresolved(context);\n if (abandoned.length) {\n await context.commit(abandoned.map((call): Entry => ({\n type: \"tool.finished\", runId, callId: call.callId,\n result: {\n content: \"This call did not report back: the activation ended before its result was committed.\",\n isError: true,\n },\n })));\n }\n\n const finish = async (completion: Completion) => {\n pending.delete(completion.callId);\n await context.commit([{\n type: \"tool.finished\", runId, callId: completion.callId, result: completion.result,\n }], completion.deliveries);\n resultsForNextRequest = true;\n };\n\n const firstPending = () => Promise.race(\n [...pending.entries()].map(async ([callId, completion]) => ({ callId, completion: await completion })),\n );\n\n const settlePending = async () => {\n while (pending.size) {\n const event = await firstPending();\n if (pending.has(event.callId)) await finish(event.completion);\n }\n };\n\n const startAsync = async (call: ToolCall) => {\n if (pending.has(call.callId)) return;\n if (!context.tools) {\n await finish(await executeOne(context, call));\n return;\n }\n await context.commit([{ type: \"tool.started\", runId, callId: call.callId }]);\n pending.set(call.callId, executeOne(context, call));\n };\n\n /** Commit foreground and background completions through the same writer. */\n const executeBatch = async (calls: readonly ToolCall[]) => {\n if (!context.tools) return;\n const iterator = context.tools.execute({ calls, signal: context.signal })[Symbol.asyncIterator]();\n let next = iterator.next();\n for (;;) {\n const event = await Promise.race([\n next.then((value) => ({ type: \"batch\" as const, value })),\n ...([...pending.entries()].map(async ([callId, completion]) => ({\n type: \"tool\" as const, value: { callId, completion: await completion },\n }))),\n ]);\n if (event.type === \"tool\") {\n if (pending.has(event.value.callId)) await finish(event.value.completion);\n continue;\n }\n if (event.value.done) return;\n await finish(event.value.value);\n await context.drain?.();\n next = iterator.next();\n }\n };\n\n /** Wait for one background result or newly delivered input. */\n const waitForWork = async (): Promise<void> => {\n for (;;) {\n const event = await Promise.race([\n firstPending().then((value) => ({ type: \"tool\" as const, value })),\n ...(context.waitForInput\n ? [context.waitForInput().then(() => ({ type: \"input\" as const }))]\n : []),\n ]);\n if (event.type === \"tool\") {\n if (pending.has(event.value.callId)) await finish(event.value.completion);\n return;\n }\n if (await context.drain?.()) return;\n if (context.signal.aborted) return;\n }\n };\n\n for (;;) {\n if (context.signal.aborted) return { status: \"cancelled\" };\n\n for (const hook of context.hooks ?? []) {\n const failure = await hook.beforeModel?.(context);\n if (failure) return { status: \"failed\", error: failure };\n }\n if (context.signal.aborted) return { status: \"cancelled\" };\n const history = context.history();\n // Results committed after this snapshot need a later request even if\n // the active generation can continue independently of them.\n resultsForNextRequest = false;\n\n // One cache mark, at the end of the system prefix: instructions plus\n // run-scoped context, which are fixed for the life of the run.\n const cacheAfter = history.findIndex((message) => message.role !== \"system\");\n const generationId = crypto.randomUUID();\n const startedAt = new Date().toISOString();\n const generation = options.model.generate({\n messages: history,\n ...(context.tools ? { tools: context.tools.list() } : {}),\n ...(options.maxOutputTokens !== undefined ? { maxOutputTokens: options.maxOutputTokens } : {}),\n ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n ...(options.effort ? { effort: options.effort } : {}),\n ...(cacheAfter > 0 ? { cacheAfter } : {}),\n signal: context.signal,\n });\n\n const launched = new Set<string>();\n const steering = new Set<Promise<ModelSteerResult>>();\n let inputForNext = false;\n let next = generation.next();\n let step;\n\n for (;;) {\n const event = await Promise.race([\n next.then((value) => ({ type: \"model\" as const, value })),\n ...([...pending.entries()].map(async ([callId, completion]) => ({\n type: \"tool\" as const, value: { callId, completion: await completion },\n }))),\n ...(context.waitForInput\n ? [context.waitForInput().then(() => ({ type: \"input\" as const }))]\n : []),\n ...([...steering].map(async (promise) => ({\n type: \"steer\" as const, promise, value: await promise,\n }))),\n ]);\n if (event.type === \"tool\") {\n if (pending.has(event.value.callId)) await finish(event.value.completion);\n continue;\n }\n if (event.type === \"steer\") {\n steering.delete(event.promise);\n if (event.value.status === \"rejected\") inputForNext = true;\n continue;\n }\n if (event.type === \"input\") {\n const arrived = await context.drain?.() ?? 0;\n if (!arrived) continue;\n const fresh = context.history().filter((message): message is Extract<Message, { role: \"user\" }> =>\n message.role === \"user\").slice(-arrived);\n if (!generation.steer || !fresh.length) {\n inputForNext = true;\n continue;\n }\n const attempt = generation.steer(fresh).catch((error): ModelSteerResult => ({\n status: \"rejected\",\n error: {\n code: \"failed\", retryable: true,\n message: error instanceof Error ? error.message : String(error),\n },\n }));\n steering.add(attempt);\n continue;\n }\n\n const current = event.value;\n if (current.done) { step = current; break; }\n const delta = current.value;\n if (delta.type === \"text.delta\") {\n context.emit({ ...delta, runId, generationId });\n }\n if (delta.type === \"reasoning.delta\") {\n context.emit({ type: \"reasoning.delta\", text: delta.text, runId, generationId });\n }\n if (delta.type === \"tool-call.delta\") {\n context.emit({\n type: \"tool-call.delta\", callId: delta.callId, arguments: delta.arguments, runId, generationId,\n });\n }\n if (delta.type === \"tool-call.done\" && canRunAsync(delta.call) && !launched.has(delta.call.callId)) {\n launched.add(delta.call.callId);\n await context.commit([{\n type: \"assistant\", runId, content: \"\", calls: [delta.call],\n generation: { id: generationId, startedAt },\n }]);\n await startAsync(delta.call);\n }\n next = generation.next();\n }\n\n for (const result of await Promise.all(steering)) {\n if (result.status === \"rejected\") inputForNext = true;\n }\n\n for (const hook of context.hooks ?? []) await hook.afterModel?.(context, step.value);\n if (!step.value.ok) {\n await settlePending();\n if ((inputForNext || resultsForNextRequest) && step.value.error.retryable &&\n step.value.error.code !== \"cancelled\" && !context.signal.aborted) continue;\n return step.value.error.code === \"cancelled\"\n ? { status: \"cancelled\" }\n : { status: \"failed\", error: step.value.error };\n }\n\n const endedAt = new Date().toISOString();\n const response = step.value.value;\n const calls = (response.message.calls ?? []).filter((call) => !launched.has(call.callId));\n\n await context.commit([{\n type: \"assistant\", runId, content: response.message.content,\n ...(calls.length ? { calls } : {}),\n usage: response.usage,\n ...(response.providerState ? { providerState: response.providerState } : {}),\n generation: {\n id: generationId, ...(response.model ? { model: response.model } : {}), startedAt, endedAt,\n },\n }]);\n\n if (response.finishReason === \"length\") {\n // A truncated response can carry half-parsed arguments that happen to\n // be valid JSON. Calls already completed and launched by the provider\n // remain real; the incomplete remainder is refused.\n await context.commit(calls.map((call): Entry => ({\n type: \"tool.finished\", runId, callId: call.callId,\n result: {\n content: \"Not executed: the response was truncated. Reissue the call if it is still needed.\",\n isError: true,\n },\n })));\n await settlePending();\n if ((calls.length || resultsForNextRequest) && !context.signal.aborted) continue;\n return { status: \"failed\", error: {\n code: \"output-truncated\",\n message: \"The response stopped at the output limit before it was finished.\",\n retryable: false,\n } };\n }\n\n if (response.finishReason === \"refusal\" && !calls.length) {\n await settlePending();\n if ((inputForNext || resultsForNextRequest) && !context.signal.aborted) continue;\n return { status: \"failed\", error: {\n code: \"refused\", message: \"The provider declined to answer.\", retryable: false,\n } };\n }\n\n const asyncCalls = calls.filter(canRunAsync);\n const synchronous = calls.filter((call) => !canRunAsync(call));\n\n if (calls.length && context.tools) {\n await context.commit(calls.map((call): Entry => ({\n type: \"tool.started\", runId, callId: call.callId,\n })));\n\n for (const call of asyncCalls) {\n pending.set(call.callId, executeOne(context, call));\n }\n\n if (synchronous.length) await executeBatch(synchronous);\n }\n\n if (calls.length && !context.tools) {\n for (const call of calls) await finish(await executeOne(context, call));\n }\n\n const arrived = await context.drain?.() ?? 0;\n if (synchronous.length || arrived || inputForNext || resultsForNextRequest || (calls.length && !context.tools)) continue;\n\n if (pending.size) {\n await waitForWork();\n continue;\n }\n\n return { status: \"completed\", output: response.message.content };\n }\n },\n };\n}\n"]}
@@ -20,9 +20,14 @@ export type Update = {
20
20
  } | {
21
21
  type: "text.delta";
22
22
  text: string;
23
+ phase?: "commentary" | "final_answer";
24
+ runId?: string;
25
+ generationId?: string;
23
26
  } | {
24
27
  type: "reasoning.delta";
25
28
  text: string;
29
+ runId?: string;
30
+ generationId?: string;
26
31
  } | {
27
32
  type: "tool.progress";
28
33
  callId: string;
@@ -33,6 +38,8 @@ export type Update = {
33
38
  type: "tool-call.delta";
34
39
  callId: string;
35
40
  arguments: string;
41
+ runId?: string;
42
+ generationId?: string;
36
43
  } | {
37
44
  type: "entry";
38
45
  entry: Stored;
@@ -74,7 +81,7 @@ export interface HarnessContext {
74
81
  * compare-and-swap means another writer is at this position, and the run is
75
82
  * over. Anything the agent was sending with that write goes with it.
76
83
  */
77
- commit(entries: readonly Entry[]): Promise<void>;
84
+ commit(entries: readonly Entry[], deliveries?: readonly Delivery[]): Promise<void>;
78
85
  /**
79
86
  * Fold any waiting input into this activation, and say how much arrived.
80
87
  *
@@ -97,6 +104,8 @@ export interface HarnessContext {
97
104
  * for long, because the next commit meets it.
98
105
  */
99
106
  drain?(): Promise<number>;
107
+ /** Wait until input may be available. A wake is a reason to drain, never the input itself. */
108
+ waitForInput?(): Promise<void>;
100
109
  emit(update: Update): void;
101
110
  signal: AbortSignal;
102
111
  }
@@ -1 +1 @@
1
- {"version":3,"file":"harness.js","sourceRoot":"","sources":["../../src/harness/harness.ts"],"names":[],"mappings":"","sourcesContent":["import type { Content } from \"../content.js\";\nimport type { Delivery, Entry, Stored, Usage } from \"../session/entry.js\";\nimport type { Message, ModelResponse, ModelError } from \"../model/model.js\";\nimport type { Result } from \"../result.js\";\nimport type { ToolExecutor } from \"../tools/tool.js\";\nimport type { Failure } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\n\n/**\n * Ephemeral output for a live viewer. Only committed entries are recovery state.\n *\n * An `entry` update carries the whole `Stored` shape — sequence and commit time\n * both. Anything building a live projection off this stream needs the timestamp\n * the log already has, and inventing one at receipt would put a second answer\n * to the same question into the world.\n */\nexport type Update =\n | { type: \"hook.error\"; hook: string; message: string }\n | { type: \"text.delta\"; text: string }\n | { type: \"reasoning.delta\"; text: string }\n | { type: \"tool.progress\"; callId: string; data: JsonValue }\n /** Arguments arriving a fragment at a time, so a viewer can show a call forming. */\n | { type: \"tool-call.delta\"; callId: string; arguments: string }\n | { type: \"entry\"; entry: Stored };\n\nexport interface HarnessContext {\n /** The same callbacks used by the run; a harness invokes model boundaries it owns. */\n hooks?: readonly LifecycleHook[];\n sessionId: string;\n runId: string;\n instructions: Content;\n /**\n * The log projected for this turn. A function, not a snapshot: it is rebuilt\n * from committed entries every time it is read, so a harness cannot hold a\n * transcript that drifts from the log.\n */\n history(): readonly Message[];\n /**\n * The committed log itself. A harness needs it to reason in sequence numbers\n * — where a compaction may cut, which call has no result yet — which the\n * projection deliberately does not carry.\n */\n entries(): readonly Stored[];\n /**\n * Application context placed around the cache boundary. `run` is stable for\n * the whole run and sits inside the cached prefix; `turn` is for this request\n * only and sits after it. Getting that split right is the loop's job because\n * only the loop knows where the prefix ends.\n */\n context?: { run?: string; turn?: string };\n tools?: ToolExecutor;\n /**\n * Commit to the log. Returns when durable — a harness never holds\n * uncommitted state.\n *\n * A refused write **rejects**, and a harness must not catch it: a lost\n * compare-and-swap means another writer is at this position, and the run is\n * over. Anything the agent was sending with that write goes with it.\n */\n commit(entries: readonly Entry[]): Promise<void>;\n /**\n * Fold any waiting input into this activation, and say how much arrived.\n *\n * Called at a boundary the harness picks — ours takes it after each batch of\n * tool results, which is the last point at which nothing is half-done. This\n * is the whole of `priority: \"turn\"`: a message reaching a busy session\n * without the turn's work being thrown away to get its attention.\n *\n * A harness with no such point does not offer this, and a `\"turn\"` delivery\n * to it waits for the next activation instead. It is never promoted to\n * ending the one that is running — the sender asked for the place that costs\n * nothing, and the answer to \"I cannot\" is later, not more destructive.\n *\n * Absent when there is no store, because then nothing can be waiting.\n *\n * Two things it will not do. It folds nothing into an activation that has\n * been cancelled — a message taken off the queue by a run that is ending is a\n * message nobody answers and nothing can find again. And a store it cannot\n * read answers zero, the same as an empty queue: the failure is not hidden\n * for long, because the next commit meets it.\n */\n drain?(): Promise<number>;\n emit(update: Update): void;\n signal: AbortSignal;\n}\n\n/**\n * How one activation ended, and nothing about what it consumed.\n *\n * A harness used to report usage too, and that was a second answer to a\n * question the log already answers: every generation's counts are on the\n * `assistant` entry that carried it. `runAgent` sums those, so accounting is\n * the same fact for a harness that owns its own loop as for ours, and a\n * cancelled or failed activation still says what it spent.\n */\nexport type HarnessResult =\n | { status: \"completed\"; output: Content }\n | { status: \"cancelled\" }\n | { status: \"failed\"; error: Failure };\n\n/** One application extension, configured alongside other lifecycle work. */\nexport interface LifecycleHook {\n name: string;\n beforeRun?(context: HarnessContext): void | Promise<void>;\n beforeModel?(context: HarnessContext): void | Failure | Promise<void | Failure>;\n afterModel?(context: HarnessContext, result: Result<ModelResponse, ModelError>): void | Promise<void>;\n /** Only a completed, non-cancelled run may continue, once per hook name and run id. */\n beforeStop?(context: HarnessContext, result: HarnessResult):\n void | { input: Content } | { deliveries: readonly Delivery[] } |\n Promise<void | { input: Content } | { deliveries: readonly Delivery[] }>;\n /** After the terminal write; exceptions are observable but cannot change the outcome or skip other hooks. */\n afterRun?(context: HarnessContext, result: HarnessResult & { seq: number; usage: Usage }): void | Promise<void>;\n}\n\n/**\n * Executes one activation of an agent.\n *\n * One fact, not eight. Everything the old capability matrix carried was either\n * optional output, a different subsystem, or something no consumer asked about.\n *\n * `toolUse` went the same way, one release later. It claimed to say whose tools\n * ran — \"application\" through the executor, \"harness\" its own — and three\n * things were wrong with it. Nothing branched on it; no document owned the\n * claim; and the word did not survive contact with the adapters. A harness can\n * run a *vendor's* tools through our executor, validated and authorized, and a\n * harness can run tools *we wrote* inside its own process. Whose tools, whose\n * code and whose authority are three questions, and one enum answered none of\n * them reliably.\n *\n * The question it was reaching for — did anyone authorize this call — is a fact\n * about a call, not about a harness, and belongs on the tool entry if and when\n * something needs to read it. `recipes/vendored-agent` and\n * `docs/ARCHITECTURE.md` carry the per-adapter comparison in prose, which is\n * where a fact about adapters belongs and where it can be accurate.\n */\nexport interface Harness {\n readonly id: string;\n /** \"history\": committed entries are enough to restart. \"none\": an interrupted run is over. */\n readonly recovery: \"history\" | \"none\";\n run(context: HarnessContext): Promise<HarnessResult>;\n}\n"]}
1
+ {"version":3,"file":"harness.js","sourceRoot":"","sources":["../../src/harness/harness.ts"],"names":[],"mappings":"","sourcesContent":["import type { Content } from \"../content.js\";\nimport type { Delivery, Entry, Stored, Usage } from \"../session/entry.js\";\nimport type { Message, ModelResponse, ModelError } from \"../model/model.js\";\nimport type { Result } from \"../result.js\";\nimport type { ToolExecutor } from \"../tools/tool.js\";\nimport type { Failure } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\n\n/**\n * Ephemeral output for a live viewer. Only committed entries are recovery state.\n *\n * An `entry` update carries the whole `Stored` shape — sequence and commit time\n * both. Anything building a live projection off this stream needs the timestamp\n * the log already has, and inventing one at receipt would put a second answer\n * to the same question into the world.\n */\nexport type Update =\n | { type: \"hook.error\"; hook: string; message: string }\n | { type: \"text.delta\"; text: string; phase?: \"commentary\" | \"final_answer\"; runId?: string; generationId?: string }\n | { type: \"reasoning.delta\"; text: string; runId?: string; generationId?: string }\n | { type: \"tool.progress\"; callId: string; data: JsonValue }\n /** Arguments arriving a fragment at a time, so a viewer can show a call forming. */\n | { type: \"tool-call.delta\"; callId: string; arguments: string; runId?: string; generationId?: string }\n | { type: \"entry\"; entry: Stored };\n\nexport interface HarnessContext {\n /** The same callbacks used by the run; a harness invokes model boundaries it owns. */\n hooks?: readonly LifecycleHook[];\n sessionId: string;\n runId: string;\n instructions: Content;\n /**\n * The log projected for this turn. A function, not a snapshot: it is rebuilt\n * from committed entries every time it is read, so a harness cannot hold a\n * transcript that drifts from the log.\n */\n history(): readonly Message[];\n /**\n * The committed log itself. A harness needs it to reason in sequence numbers\n * — where a compaction may cut, which call has no result yet — which the\n * projection deliberately does not carry.\n */\n entries(): readonly Stored[];\n /**\n * Application context placed around the cache boundary. `run` is stable for\n * the whole run and sits inside the cached prefix; `turn` is for this request\n * only and sits after it. Getting that split right is the loop's job because\n * only the loop knows where the prefix ends.\n */\n context?: { run?: string; turn?: string };\n tools?: ToolExecutor;\n /**\n * Commit to the log. Returns when durable — a harness never holds\n * uncommitted state.\n *\n * A refused write **rejects**, and a harness must not catch it: a lost\n * compare-and-swap means another writer is at this position, and the run is\n * over. Anything the agent was sending with that write goes with it.\n */\n commit(entries: readonly Entry[], deliveries?: readonly Delivery[]): Promise<void>;\n /**\n * Fold any waiting input into this activation, and say how much arrived.\n *\n * Called at a boundary the harness picks — ours takes it after each batch of\n * tool results, which is the last point at which nothing is half-done. This\n * is the whole of `priority: \"turn\"`: a message reaching a busy session\n * without the turn's work being thrown away to get its attention.\n *\n * A harness with no such point does not offer this, and a `\"turn\"` delivery\n * to it waits for the next activation instead. It is never promoted to\n * ending the one that is running — the sender asked for the place that costs\n * nothing, and the answer to \"I cannot\" is later, not more destructive.\n *\n * Absent when there is no store, because then nothing can be waiting.\n *\n * Two things it will not do. It folds nothing into an activation that has\n * been cancelled — a message taken off the queue by a run that is ending is a\n * message nobody answers and nothing can find again. And a store it cannot\n * read answers zero, the same as an empty queue: the failure is not hidden\n * for long, because the next commit meets it.\n */\n drain?(): Promise<number>;\n /** Wait until input may be available. A wake is a reason to drain, never the input itself. */\n waitForInput?(): Promise<void>;\n emit(update: Update): void;\n signal: AbortSignal;\n}\n\n/**\n * How one activation ended, and nothing about what it consumed.\n *\n * A harness used to report usage too, and that was a second answer to a\n * question the log already answers: every generation's counts are on the\n * `assistant` entry that carried it. `runAgent` sums those, so accounting is\n * the same fact for a harness that owns its own loop as for ours, and a\n * cancelled or failed activation still says what it spent.\n */\nexport type HarnessResult =\n | { status: \"completed\"; output: Content }\n | { status: \"cancelled\" }\n | { status: \"failed\"; error: Failure };\n\n/** One application extension, configured alongside other lifecycle work. */\nexport interface LifecycleHook {\n name: string;\n beforeRun?(context: HarnessContext): void | Promise<void>;\n beforeModel?(context: HarnessContext): void | Failure | Promise<void | Failure>;\n afterModel?(context: HarnessContext, result: Result<ModelResponse, ModelError>): void | Promise<void>;\n /** Only a completed, non-cancelled run may continue, once per hook name and run id. */\n beforeStop?(context: HarnessContext, result: HarnessResult):\n void | { input: Content } | { deliveries: readonly Delivery[] } |\n Promise<void | { input: Content } | { deliveries: readonly Delivery[] }>;\n /** After the terminal write; exceptions are observable but cannot change the outcome or skip other hooks. */\n afterRun?(context: HarnessContext, result: HarnessResult & { seq: number; usage: Usage }): void | Promise<void>;\n}\n\n/**\n * Executes one activation of an agent.\n *\n * One fact, not eight. Everything the old capability matrix carried was either\n * optional output, a different subsystem, or something no consumer asked about.\n *\n * `toolUse` went the same way, one release later. It claimed to say whose tools\n * ran — \"application\" through the executor, \"harness\" its own — and three\n * things were wrong with it. Nothing branched on it; no document owned the\n * claim; and the word did not survive contact with the adapters. A harness can\n * run a *vendor's* tools through our executor, validated and authorized, and a\n * harness can run tools *we wrote* inside its own process. Whose tools, whose\n * code and whose authority are three questions, and one enum answered none of\n * them reliably.\n *\n * The question it was reaching for — did anyone authorize this call — is a fact\n * about a call, not about a harness, and belongs on the tool entry if and when\n * something needs to read it. `recipes/vendored-agent` and\n * `docs/ARCHITECTURE.md` carry the per-adapter comparison in prose, which is\n * where a fact about adapters belongs and where it can be accurate.\n */\nexport interface Harness {\n readonly id: string;\n /** \"history\": committed entries are enough to restart. \"none\": an interrupted run is over. */\n readonly recovery: \"history\" | \"none\";\n run(context: HarnessContext): Promise<HarnessResult>;\n}\n"]}
@@ -0,0 +1,33 @@
1
+ import type { Model } from "../../model.js";
2
+ interface StreamEnvelope {
3
+ type: string;
4
+ message?: unknown;
5
+ error?: unknown;
6
+ code?: number;
7
+ reason?: string;
8
+ }
9
+ /** The small part of ResponsesWS used here, injectable so the wire can be tested without a model call. */
10
+ export interface OpenAiResponsesConnection {
11
+ send(event: unknown): void;
12
+ close(): void;
13
+ [Symbol.asyncIterator](): AsyncIterableIterator<StreamEnvelope>;
14
+ }
15
+ export interface OpenAiResponsesOptions {
16
+ apiKey: string;
17
+ model: string;
18
+ baseURL?: string;
19
+ headers?: Readonly<Record<string, string>>;
20
+ /** Declare function tools with OpenAI's asynchronous execution extension. */
21
+ asyncTools?: boolean;
22
+ /** Expose mid-generation steering. The provider remains the capability authority. */
23
+ steering?: boolean;
24
+ /** Injectable for tests; the default is the official SDK's ResponsesWS. */
25
+ connect?: () => OpenAiResponsesConnection;
26
+ }
27
+ export interface OpenAiResponsesModel extends Model {
28
+ /** Close the reusable WebSocket and fail any generations still using it. */
29
+ close(): void;
30
+ }
31
+ /** OpenAI's Responses wire, including completed output items, async tools and optional steering. */
32
+ export declare function createOpenAiResponsesModel(options: OpenAiResponsesOptions): OpenAiResponsesModel;
33
+ export {};