@parcha/agentrun-kernel 0.1.0-beta.38 → 0.1.0-beta.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/NOTICE +2 -0
  3. package/dist/booking.d.ts +25 -6
  4. package/dist/booking.js +15 -4
  5. package/dist/host/index.d.ts +4 -3
  6. package/dist/host/index.js +3 -2
  7. package/dist/host/o200k.d.ts +11 -0
  8. package/dist/host/o200k.js +185 -0
  9. package/dist/host/overhead.d.ts +72 -12
  10. package/dist/host/overhead.js +220 -38
  11. package/dist/host/proxy.d.ts +85 -7
  12. package/dist/host/proxy.js +374 -87
  13. package/dist/index.d.ts +6 -6
  14. package/dist/index.js +4 -4
  15. package/dist/kernel/cap/admit.d.ts +5 -8
  16. package/dist/kernel/cap/admit.js +13 -19
  17. package/dist/kernel/cap/free.d.ts +43 -0
  18. package/dist/kernel/cap/free.js +71 -0
  19. package/dist/kernel/cap/index.d.ts +6 -5
  20. package/dist/kernel/cap/index.js +5 -4
  21. package/dist/kernel/cap/marks.d.ts +2 -3
  22. package/dist/kernel/cap/park.d.ts +3 -4
  23. package/dist/kernel/cap/park.js +4 -5
  24. package/dist/kernel/cap/port.d.ts +8 -13
  25. package/dist/kernel/cap/port.js +10 -18
  26. package/dist/kernel/cap/price.d.ts +10 -49
  27. package/dist/kernel/cap/price.js +15 -68
  28. package/dist/kernel/cap/recover.d.ts +1 -2
  29. package/dist/kernel/cap/recover.js +2 -4
  30. package/dist/kernel/cap/rule.d.ts +8 -16
  31. package/dist/kernel/cap/rule.js +35 -35
  32. package/dist/kernel/cap/run-cap.d.ts +21 -13
  33. package/dist/kernel/cap/run-cap.js +74 -36
  34. package/dist/kernel/cap/types.d.ts +11 -31
  35. package/dist/kernel/cap/words.d.ts +13 -8
  36. package/dist/kernel/cap/words.js +23 -14
  37. package/dist/kernel/cap/wrap-up.d.ts +4 -0
  38. package/dist/kernel/cap/wrap-up.js +5 -1
  39. package/dist/kernel/registry/computer-surface.generated.d.ts +1 -1
  40. package/dist/kernel/registry/computer-surface.generated.js +9 -25
  41. package/dist/kernel/registry/computer.d.ts +14 -7
  42. package/dist/kernel/registry/computer.js +52 -12
  43. package/dist/kernel/registry/gate.d.ts +2 -2
  44. package/dist/kernel/registry/gate.js +4 -7
  45. package/dist/kernel/registry/hands.d.ts +3 -4
  46. package/dist/kernel/registry/index.d.ts +1 -1
  47. package/dist/kernel/registry/index.js +1 -1
  48. package/dist/kernel/registry/registry.js +6 -9
  49. package/dist/process/recovery.d.ts +4 -1
  50. package/dist/process/recovery.js +15 -3
  51. package/dist/process/resume.d.ts +5 -2
  52. package/dist/process/resume.js +15 -3
  53. package/dist/process/tools.d.ts +26 -1
  54. package/dist/process/tools.js +47 -4
  55. package/dist/run-booking.d.ts +21 -2
  56. package/dist/run-booking.js +215 -18
  57. package/dist/runner.d.ts +82 -21
  58. package/dist/runner.js +176 -59
  59. package/dist/testing.d.ts +4 -2
  60. package/dist/testing.js +2 -2
  61. package/dist/tool-deferral.d.ts +3 -3
  62. package/dist/tool-deferral.js +4 -4
  63. package/dist/types.d.ts +70 -14
  64. package/dist/types.js +8 -0
  65. package/package.json +5 -3
  66. package/vendor/o200k/LICENSE +61 -0
  67. package/vendor/o200k/o200k_base.tiktoken +199998 -0
@@ -3,11 +3,12 @@
3
3
  // (modelPortFor: runner.request with what it holds before it leaves, runner.turn with what it cost once it answers). So
4
4
  // a decision is judged on the run's model spend beside its own and a model request on the run's decisions, a refusal's
5
5
  // figures are the run's (main's holdPaid reads the whole run), and a claim taken again after a lost one rebuilds the
6
- // spend of both from the journal: a decision held and never answered counts at its hold and its bound, as any request.
7
- // Decisions book under their own session (DECISION_SESSION), priced as main holds them (decisionAsk).
6
+ // spend of both from the journal: a decision held and never answered counts at its hold, as any request.
7
+ // Decisions book under their own session (DECISION_SESSION), held at their worst case (decisionAsk).
8
8
  import { runBooking } from "../../run-booking.js";
9
9
  import { modelPortFor, RUNNER_RECORDS, sessionSpendOf } from "../../runner.js";
10
- import { overCapEnd } from "./words.js";
10
+ import { aloneRefusal, overCapEnd, SPEND_CAP_REACHED } from "./words.js";
11
+ import { freeCeilingEnd, freeRequest } from "./free.js";
11
12
  import { decisionAsk } from "./admit.js";
12
13
  import { CapRefused, DecisionPriceUnreadable } from "./errors.js";
13
14
  import { beforeRequestOf, capRequestOf } from "./port.js";
@@ -15,45 +16,77 @@ import { beforeRequestOf, capRequestOf } from "./port.js";
15
16
  export const DECISION_SESSION = "decisions";
16
17
  /** The session a run's paid tool calls book under. */
17
18
  export const TOOL_SESSION = "paid-tools";
18
- /** How a run ends once its booked spend passed its cap (overCapEnd), read from its model session's `records` and what
19
- * its other sessions spent (`othersUsd`): each request at the figure the cap counts it at (sessionSpendOf's figures: one
20
- * cut by a crash at its hold plus its bound), and the bound of the requests since the spend last fit, so a cache miss
21
- * within that bound (a cut request's possible one included) pauses the run instead. Undefined while it fits, by such a
22
- * miss, or with a spend unknown. */
19
+ /** How a run ends once its booked spend passed its cap (overCapEnd), read from its model session's `records` (each
20
+ * request at the figure the cap counts it at, sessionSpendOf's: one cut by a crash at its hold) and what its other
21
+ * sessions spent (`othersUsd`). Undefined while it fits, or with a spend unknown. */
23
22
  export function overCapOf(records, othersUsd, capUsd) {
24
23
  const read = sessionSpendOf(records);
25
24
  if (read.spentUsd === null)
26
25
  return undefined;
27
- let running = othersUsd;
28
- let bound = 0;
29
- for (const { turn, usd } of read.figures) {
30
- running += usd ?? 0;
31
- bound = running <= capUsd ? 0 : bound + (read.bounds.get(turn) ?? 0);
32
- }
33
- return overCapEnd(othersUsd + read.spentUsd, capUsd, bound);
26
+ return overCapEnd(othersUsd + read.spentUsd, capUsd);
34
27
  }
35
28
  export function runCap(options) {
36
- const mode = options.mode ?? "expected";
37
29
  /** Each decision under way's model, as the rule prices it (decisionAsk), by the model key its request books under. */
38
30
  const deciding = new Map();
39
- const pricing = {
40
- modelOf: (id, route) => deciding.get(id) ?? options.modelOf(id, route),
41
- ...(options.recentOf ? { recentOf: (model) => (deciding.has(model) ? [] : options.recentOf(model)) } : {}),
42
- };
31
+ const pricing = { modelOf: (id, route) => deciding.get(id) ?? options.modelOf(id, route) };
43
32
  const rule = beforeRequestOf({
44
33
  capUsd: options.capUsd,
45
- mode,
46
- ...(options.now ? { now: options.now } : {}),
47
34
  ...pricing,
48
35
  ...(options.spentUsd ? { spentUsd: options.spentUsd } : {}),
49
36
  ...(options.heldUsd ? { heldUsd: options.heldUsd } : {}),
50
37
  ...(options.keepBackUsd ? { keepBackUsd: options.keepBackUsd } : {}),
51
38
  });
52
- const before = runBooking(options.sessions, options.judged ? async (request) => {
39
+ // A request on a free model (freeRequest), under a cap or none. The dollar cap cannot stop such requests, so a model
40
+ // request of the run's own sessions past the run's limit of them (`freeRequests`) is refused for good, before the
41
+ // dollar rule; one within it goes to the rule, and its admission says it counts (`freeRequest`, written on its
42
+ // runner.request, so the next count holds it in any process). A paid tool call and a decision book under their own
43
+ // sessions and never count; nor does a ChatGPT plan's request (no free model). A free model's request is also admitted
44
+ // `free`: the runner books it a known $0 however it ends (runner.ts Admitted), never unknown. One on a person's plan
45
+ // (CapModel.plan) is admitted `plan`: $0 to the run however it ends, cut by a crash included. A request is never both:
46
+ // freeModel refuses a plan model (its listing's price is no price), so `free` is false for every plan request, and the
47
+ // plan mark is returned before the free one is looked at. One the rule refused stays refused.
48
+ const limit = options.freeRequests;
49
+ const judge = async (request) => {
50
+ const free = freeRequest(request, pricing.modelOf);
51
+ const counted = free && request.key !== DECISION_SESSION && request.key !== TOOL_SESSION;
52
+ if (counted && limit !== undefined && (request.freeRequestsMade ?? 0) >= limit)
53
+ return { refuse: freeCeilingEnd(limit), forGood: true, code: SPEND_CAP_REACHED };
53
54
  const answer = await rule(request);
54
- options.judged(request, answer);
55
+ if (answer && "refuse" in answer)
56
+ return await roomOf(request, answer);
57
+ if (!request.paid && pricing.modelOf(request.model, request.route)?.plan)
58
+ return { ...answer, plan: true };
59
+ if (!free)
60
+ return answer;
61
+ return { ...(answer ?? {}), ...(counted ? { freeRequest: true } : {}), free: true };
62
+ };
63
+ // A step (a model request, a decision, a paid tool call) refused for room while steps in flight hold some of it: judged
64
+ // again by the same rule as if none of the steps that settle on their own were out (a hold-only step, one the booking
65
+ // no longer waits on, and a paid call's own session's requests in flight, one of which may have asked for it, still
66
+ // count: runBooking marks them `stays`). Fits so: it `waits` (runBooking asks again once they settle, and never passes the
67
+ // cap: every admission is the rule's over the holds as they are then). Refused even so: refused now, its figures that
68
+ // refusal's (the least cap that sends it once they settle), its words saying what is spent and what is held apart
69
+ // (aloneRefusal), never holds as spent. A step in flight that holds $0 (a free model's request) frees no room when it
70
+ // settles, so with only such steps beside the ones that stay, the refusal is the rule's own.
71
+ const roomOf = async (request, refused) => {
72
+ if (refused.forGood !== false || !refused.figures || !request.inFlight.some((flight) => !flight.stays && flight.holdUsd !== 0))
73
+ return refused;
74
+ const alone = await rule({ ...request, inFlight: request.inFlight.filter((flight) => flight.stays) });
75
+ if (!(alone && "refuse" in alone))
76
+ return { ...refused, waits: true };
77
+ const capUsd = options.capUsd();
78
+ if (alone.forGood !== false || !alone.figures || capUsd === undefined)
79
+ return alone;
80
+ const figures = { ...alone.figures, heldUsd: refused.figures.heldUsd ?? 0 };
81
+ return { ...alone, refuse: aloneRefusal(capUsd, figures), figures };
82
+ };
83
+ const before = runBooking(options.sessions, options.judged ? async (request) => {
84
+ const answer = await judge(request);
85
+ // An observer sees each verdict the run goes by: a refusal that waits is asked again, its verdict told then.
86
+ if (!(answer && "refuse" in answer && answer.waits))
87
+ options.judged(request, answer);
55
88
  return answer;
56
- } : rule);
89
+ } : judge, { ...(options.parked ? { parked: options.parked } : {}), ...(options.waitStallMs === undefined ? {} : { stallMs: options.waitStallMs }), ...(options.stopped ? { stopped: options.stopped } : {}) });
57
90
  const forget = (key) => void deciding.delete(key);
58
91
  return {
59
92
  before,
@@ -66,7 +99,7 @@ export function runCap(options) {
66
99
  // Under no cap a decision is not priced: nothing is read, nothing refused (its model may be "unreadable").
67
100
  if (capUsd !== undefined && request.model === "unreadable")
68
101
  throw new DecisionPriceUnreadable();
69
- const asked = capUsd === undefined || request.model === "unreadable" ? undefined : decisionAsk(request, mode);
102
+ const asked = capUsd === undefined || request.model === "unreadable" ? undefined : decisionAsk(request);
70
103
  const key = `decision:${request.id}`;
71
104
  if (asked)
72
105
  deciding.set(key, { ...asked.model, id: key });
@@ -91,14 +124,14 @@ export async function paidCalls(writer, before, options = {}) {
91
124
  const refsOf = () => (refs ??= writer.read().then((records) => new Set(records.filter((r) => r.kind === RUNNER_RECORDS.request).map((r) => r.data?.ref).filter((ref) => typeof ref === "string"))));
92
125
  const book = (request) =>
93
126
  // A hold that is no figure (an unpriced browser provider's) goes to the rule as given, which refuses it for good.
94
- steps.book(request.id, { model: `paid:${request.name}`, inputTokensMax: 0, ...(request.holdUsd !== 0 ? { feeUsd: request.holdUsd } : {}), paid: { name: request.name, basis: request.basis, ...(request.call === undefined ? {} : { call: request.call }), ...(request.chargedBy === undefined ? {} : { charged_by: request.chargedBy }), ...(request.tool === undefined ? {} : { tool: request.tool }), ...(request.tag === undefined ? {} : { tag: request.tag }), ...(request.owed ? { owed: true } : {}), ...(request.hold ? { hold: true } : {}), ...(request.ref === undefined ? {} : { ref: request.ref }) } });
127
+ steps.book(request.id, { model: `paid:${request.name}`, inputTokensMax: 0, ...(request.holdUsd !== 0 ? { feeUsd: request.holdUsd } : {}), paid: { name: request.name, basis: request.basis, ...(request.call === undefined ? {} : { call: request.call }), ...(request.chargedBy === undefined ? {} : { charged_by: request.chargedBy }), ...(request.tool === undefined ? {} : { tool: request.tool }), ...(request.tag === undefined ? {} : { tag: request.tag }), ...(request.owed ? { owed: true } : {}), ...(request.hold ? { hold: true } : {}), ...(request.ref === undefined ? {} : { ref: request.ref }), ...(request.under === undefined ? {} : { under: request.under }) } });
95
128
  return {
96
129
  admit: async (request) => {
97
130
  if (request.ref === undefined)
98
131
  return book(request);
99
132
  const booked = await refsOf();
100
133
  if (booked.has(request.ref))
101
- return { id: request.id, heldUsd: 0, boundUsd: 0, worstUsd: 0, stoppedUsd: () => 0, booked: true };
134
+ return { id: request.id, heldUsd: 0, stoppedUsd: () => 0, booked: true };
102
135
  booked.add(request.ref);
103
136
  try {
104
137
  return await book(request);
@@ -117,13 +150,20 @@ export async function paidCalls(writer, before, options = {}) {
117
150
  * each a runner.request before it is sent (flushed when `flush` is given) and a runner.turn once settled. */
118
151
  async function stepsOn(writer, before, flush, what, forget) {
119
152
  {
120
- /** The verdict of the step being admitted (admissions run one at a time on the booking), for its refusal. */
153
+ /** The verdict of the step being admitted (admissions run one at a time on the booking), for its hold or refusal: set
154
+ * as its check begins and ends, and taken by its book once its admission ends, before the next one's check begins. A
155
+ * step booked while another waits for room sets nothing, so it never wipes the verdict of the one before it. */
121
156
  let verdict;
122
- const lastVerdict = () => verdict;
157
+ const takeVerdict = () => {
158
+ const taken = verdict;
159
+ verdict = undefined;
160
+ return taken;
161
+ };
123
162
  const booking = await modelPortFor(writer, {
124
163
  key: writer.key,
125
164
  label: writer.key,
126
165
  beforeRequest: async (request) => {
166
+ verdict = undefined;
127
167
  const answer = await before(request);
128
168
  verdict = (answer ?? undefined);
129
169
  return answer;
@@ -132,32 +172,30 @@ async function stepsOn(writer, before, flush, what, forget) {
132
172
  ...(flush ? { onEvent: async (event) => { if (event.type === "request_start")
133
173
  await flush(); } } : {}),
134
174
  });
135
- // A step an earlier claim admitted and that never answered: booked cut, counted at its hold and its bound.
175
+ // A step an earlier claim admitted and that never answered: booked cut, counted at its hold.
136
176
  await booking.bookCut();
137
177
  const open = new Map();
138
178
  return {
139
179
  /** Books step `id`, asked as `asked` (its model key a decision's priced model, or a paid call's name). */
140
180
  async book(id, asked) {
141
181
  const key = asked.model;
142
- verdict = undefined;
143
182
  let ticket;
144
183
  try {
145
184
  ticket = await booking.models.beforeRequest(asked);
146
185
  }
147
186
  catch (error) {
148
187
  forget(key);
149
- const refused = lastVerdict();
188
+ const refused = takeVerdict();
150
189
  if (refused?.refuse !== undefined)
151
190
  throw new CapRefused(refused.refuse, { forGood: refused.forGood ?? true, spentUsd: refused.figures?.spentUsd ?? null, ...(refused.figures ? { figures: refused.figures } : {}) });
152
191
  throw error;
153
192
  }
154
193
  if (!ticket)
155
194
  throw new Error(`${what} ${id}: its booking gave it no ticket`);
156
- const admitted = lastVerdict();
195
+ const admitted = takeVerdict();
157
196
  const held = typeof admitted?.holdUsd === "number" ? admitted.holdUsd : 0;
158
- const bound = typeof admitted?.boundUsd === "number" ? admitted.boundUsd : 0;
159
197
  open.set(id, { ticket, key, heldUsd: held });
160
- return { id, heldUsd: held, boundUsd: bound, worstUsd: held + bound, stoppedUsd: () => held };
198
+ return { id, heldUsd: held, stoppedUsd: () => held };
161
199
  },
162
200
  async settle(id, usd, options) {
163
201
  const step = open.get(id);
@@ -19,26 +19,16 @@ export interface ModelPrice extends PriceRates {
19
19
  readonly tiers?: readonly PriceTier[];
20
20
  }
21
21
  /** A model as the cap prices it: its API (what its provider adds server-side, and whether its thinking takes a budget),
22
- * its price (null: none known), and its output ceiling (null: none). */
22
+ * its price (null: none known), and its output ceiling (null: none). `plan`: billed to a person's subscription plan (a
23
+ * ChatGPT plan's model), never by the token: a request on it costs the run no dollars, so the cap holds it at $0 and
24
+ * never limits its output, whatever its price says. */
23
25
  export interface CapModel {
24
26
  readonly id: string;
25
27
  readonly api: string;
26
28
  readonly price: ModelPrice | null;
27
29
  readonly outputCeiling: number | null;
28
30
  readonly reasoning?: boolean;
29
- }
30
- /** One of the session's recent requests (price.ts recentAfter), as its usage reported it: what of its input was read from
31
- * or written to the cache, the rest, its input bound (the unit a later request's is in) and when it ended (ms), on which
32
- * model. A later request reads its cache from one of them (price.ts warmFrom). */
33
- export interface RecentRequest {
34
- /** Its model as the cap prices it (CapModel.id), whatever id its client named it by. */
35
- readonly model: string;
36
- readonly cachedTokens: number;
37
- readonly inputTokens: number;
38
- readonly boundTokens: number;
39
- /** Its bound was its provider's count, not its bytes: used only for a next request bounded the same way. */
40
- readonly counted?: boolean;
41
- readonly endedAt: number;
31
+ readonly plan?: boolean;
42
32
  }
43
33
  /** A model request about to be sent, from any harness (pi in process, a CLI's through the model proxy). */
44
34
  export interface ModelCapRequest {
@@ -61,9 +51,6 @@ export interface ModelCapRequest {
61
51
  readonly outputTokensLeast?: number;
62
52
  /** Its thinking budget, on an API whose thinking takes one beside the answer's output. */
63
53
  readonly thinkingBudget?: number;
64
- /** The session's recent requests on its model, their bounds measured as this one's is: its input is expected to read
65
- * the cache of the one warmFrom picks, else none (priced uncached). */
66
- readonly recent?: readonly RecentRequest[];
67
54
  /** A side call (a title, a summary), never its turn's own. */
68
55
  readonly side?: boolean;
69
56
  /** It carries the cap's wrap-up note (Cap.note) in its body, its bytes in `inputTokens`: told once it is answered. */
@@ -71,7 +58,7 @@ export interface ModelCapRequest {
71
58
  }
72
59
  /** A workflow decision about to be judged, held as main holds it (serve decision-cap.ts holdOf): its model at its
73
60
  * catalog's price (`outputCeiling`: the catalog's most completion tokens), "unreadable" when the catalog could not be
74
- * read for one. Its output is DECISION_OUTPUT_TOKENS a question (expected), or its model's most (strict); its input its
61
+ * read for one. Its output is its model's most (no answer can take more); its input its
75
62
  * state and questions' bytes plus DECISION_IMAGE_TOKENS an image; its fees the catalog's per request and per image. With
76
63
  * no cap it is not priced at all. */
77
64
  export interface DecisionCapRequest {
@@ -80,8 +67,6 @@ export interface DecisionCapRequest {
80
67
  readonly model: CapModel | "unreadable";
81
68
  /** The UTF-8 bytes of its state and questions as JSON, one token a byte. */
82
69
  readonly inputTokens: number;
83
- /** How many questions it asks. */
84
- readonly questions: number;
85
70
  /** How many images it sends. */
86
71
  readonly images?: number;
87
72
  /** The catalog's price per request and per image, in USD. */
@@ -98,25 +83,23 @@ export interface ToolCapRequest {
98
83
  readonly basis: string;
99
84
  }
100
85
  export type CapRequest = ModelCapRequest | ToolCapRequest | DecisionCapRequest;
101
- /** A step the cap let go: what it is held at until it settles (a model request's expected cost at the output it may be
102
- * sent with, its worst case under strict), the most a cache miss can add (`boundUsd`), its worst case, and for a model
103
- * request the output it is limited to and what it counts at if stopped having streamed that many tokens. */
86
+ /** A step the cap let go: what it is held at until it settles (a model request's worst case at the output it may be sent
87
+ * with: its whole input bound uncached), and for a model request the output it is limited to and what it counts at if
88
+ * stopped having streamed that many tokens. */
104
89
  export interface Admission {
105
90
  readonly id: string;
106
91
  readonly heldUsd: number;
107
- readonly boundUsd: number;
108
- readonly worstUsd: number;
109
92
  readonly outputTokensMax?: number;
110
93
  readonly thinkingBudget?: number;
111
94
  stoppedUsd(streamedTokens: number): number;
112
95
  }
113
- /** A refusal for room's figures, beside its words: what the cap counted as taken, the least the step needs, and the least
114
- * cap that sends it (the figure its words name). */
96
+ /** A refusal for room's figures, beside its words: what the run had spent (never a hold), what its steps in flight held,
97
+ * the least the step needs, and the least cap that sends it (the figure its words name). */
115
98
  export interface RefusalFigures {
116
99
  readonly spentUsd: number;
100
+ readonly heldUsd?: number;
117
101
  readonly needsUsd: number;
118
102
  readonly leastCapUsd: number;
119
- readonly boundUsd?: number;
120
103
  /** A paid call's refusal: the call (its name, hold and basis), so a pause that lands after the refusal can say it again
121
104
  * with the run's spend as it is then (paidRefusal). */
122
105
  readonly step?: {
@@ -133,7 +116,6 @@ export type Settled = Ended | {
133
116
  export interface CapOptions {
134
117
  /** The run's cap, read before every paid check, so a raise holds from the next one. Undefined: no cap. */
135
118
  capUsd(): number | undefined;
136
- mode?: CapMode;
137
119
  /** What the run has spent when the cap opens (null: unknown). openCap reads it from `marks`. */
138
120
  spentUsd?: number | null;
139
121
  now?: () => number;
@@ -142,8 +124,6 @@ export interface CapOptions {
142
124
  /** How long settle waits for a step's end mark before it fails loudly. Default 10 s. */
143
125
  endMarkWaitMs?: number;
144
126
  }
145
- /** How the cap prices a request's input: "expected" from a recent request's cache; "strict" every token uncached. */
146
- export type CapMode = "expected" | "strict";
147
127
  export interface Cap {
148
128
  admit(request: CapRequest): Promise<Admission>;
149
129
  /** Books a step that ended, its hold let go: a model request by how it ended, a paid call at its charge (its hold when
@@ -21,23 +21,28 @@ export declare const suggestedRaise: (cap: number, spentUsd: number, needsUsd: n
21
21
  * say the run spent nothing. */
22
22
  export declare const spentMoney: (usd: number) => string;
23
23
  /** A model request what is left cannot buy the least of. */
24
- export declare function roomRefusal(cap: number, spent: number, held: number, least: number, boundUsd?: number): {
24
+ export declare function roomRefusal(cap: number, spent: number, held: number, least: number): {
25
25
  text: string;
26
26
  figures: RefusalFigures;
27
27
  };
28
+ /** A step that does not fit even once the steps in flight settle, so no wait sends it (`figures`, the refusal's as if none
29
+ * were in flight, with what they hold, `heldUsd`): what the run has spent, what it is holding for steps still running
30
+ * (never called spent: they settle at what they cost), and what the step needs, more than the cap leaves beside what is
31
+ * spent. A model request's least; a paid call's hold, by name (figures.step). Raise to `leastCapUsd`, the least cap that
32
+ * sends it once they settle. */
33
+ export declare function aloneRefusal(cap: number, figures: RefusalFigures): string;
28
34
  /** A paid call what is left cannot hold. */
29
35
  export declare function paidRefusal(cap: number, spent: number, held: number, name: string, holdUsd: number, basis: string): {
30
36
  text: string;
31
37
  figures: RefusalFigures;
32
38
  };
33
- /** The over-cap row's words, after the usage row whose booked cost `spentUsd` passed `capUsd`: by how much; when it passed
34
- * by no more than `boundUsd` (the bound of the requests since the cost last fit), a cache miss did it, and the most it
35
- * could have. None at or under the cap, with no cap, or with no known cost. */
36
- export declare function overCapWords(spentUsd: number | null, capUsd: number | undefined, boundUsd?: number): string | undefined;
39
+ /** The over-cap row's words, after the usage row whose booked cost `spentUsd` passed `capUsd`: by how much. A request is
40
+ * held at its worst case, so only a cost its admission never priced passes the cap (an owed charge, a provider that bills
41
+ * past its list price). None at or under the cap, with no cap, or with no known cost. */
42
+ export declare function overCapWords(spentUsd: number | null, capUsd: number | undefined): string | undefined;
37
43
  /** How a run ends whose booked cost `spentUsd` passed `capUsd`: failed, in these words (main's run end), the answer that
38
- * crossed it booked. None at or under the cap, with no cap, with no known cost, or when it passed by no more than
39
- * `boundUsd` (a cache miss within the bound it was admitted at: the run pauses at its next request instead). */
40
- export declare function overCapEnd(spentUsd: number | null, capUsd: number | undefined, boundUsd?: number): string | undefined;
44
+ * crossed it booked. None at or under the cap, with no cap, or with no known cost. */
45
+ export declare function overCapEnd(spentUsd: number | null, capUsd: number | undefined): string | undefined;
41
46
  /** How overCapEnd's words begin, and only theirs: a reader of a run's summary serves one that does as the error
42
47
  * spend_cap_reached, its message the words after `spend_cap_reached: ` (overCapMessage). */
43
48
  export declare const OVER_CAP_END = "spend_cap_reached: The run cost ";
@@ -43,41 +43,50 @@ const spentOf = (spent, held, cap) => {
43
43
  return holds !== "$0" ? `spent ${spentMoney(spent)} and holds ${holds} for steps still running, of its ${money(cap)} cap` : `spent ${spentMoney(spent)} of its ${money(cap)} cap`;
44
44
  };
45
45
  /** A model request what is left cannot buy the least of. */
46
- export function roomRefusal(cap, spent, held, least, boundUsd) {
46
+ export function roomRefusal(cap, spent, held, least) {
47
47
  const leastCapUsd = raiseFigure(cap, spent + held + least);
48
- const figures = { spentUsd: spent + held, needsUsd: least, leastCapUsd, ...(boundUsd && boundUsd > 0 ? { boundUsd } : {}) };
48
+ const figures = { spentUsd: spent, heldUsd: held, needsUsd: least, leastCapUsd };
49
49
  const [need, raise] = [leastMoney(least), `$${leastCapUsd.toFixed(2)}`];
50
50
  if (spent === 0 && held === 0)
51
51
  return { text: `${CAP_REFUSAL_CODE}Not sent: the next step needs at least ${need}, and this run's cap is ${money(cap)}. Raise the cap to at least ${raise} to continue.`, figures };
52
52
  return { text: `${CAP_REFUSAL_CODE}Not sent: this run has ${spentOf(spent, held, cap)}, and the next step needs at least ${need}. Raise the cap to at least ${raise} to continue.`, figures };
53
53
  }
54
+ /** A step that does not fit even once the steps in flight settle, so no wait sends it (`figures`, the refusal's as if none
55
+ * were in flight, with what they hold, `heldUsd`): what the run has spent, what it is holding for steps still running
56
+ * (never called spent: they settle at what they cost), and what the step needs, more than the cap leaves beside what is
57
+ * spent. A model request's least; a paid call's hold, by name (figures.step). Raise to `leastCapUsd`, the least cap that
58
+ * sends it once they settle. */
59
+ export function aloneRefusal(cap, figures) {
60
+ const holds = centsMoney(figures.heldUsd ?? 0);
61
+ const holding = holds !== "$0" ? ` and is holding ${holds} for steps still running` : "";
62
+ const [code, needs] = figures.step
63
+ ? [`${SPEND_CAP_REACHED}: `, `the next step, ${figures.step.name}, could cost up to ${money(figures.step.holdUsd)} (${figures.step.basis})`]
64
+ : [CAP_REFUSAL_CODE, `the next step needs at least ${leastMoney(figures.needsUsd)}`];
65
+ return `${code}Not sent: this run has spent ${spentMoney(figures.spentUsd)} of its ${money(cap)} cap${holding}; ${needs}, more than the cap leaves even once the steps still running settle. Raise the cap to at least $${figures.leastCapUsd.toFixed(2)} to continue.`;
66
+ }
54
67
  /** A paid call what is left cannot hold. */
55
68
  export function paidRefusal(cap, spent, held, name, holdUsd, basis) {
56
69
  const leastCapUsd = raiseFigure(cap, spent + held + holdUsd);
57
70
  return {
58
71
  text: `${SPEND_CAP_REACHED}: Not sent: this run has ${spentOf(spent, held, cap)}, and the next step, ${name}, could cost up to ${money(holdUsd)} (${basis}). Raise the cap to at least $${leastCapUsd.toFixed(2)} to continue.`,
59
- figures: { spentUsd: spent + held, needsUsd: holdUsd, leastCapUsd, step: { name, holdUsd, basis } },
72
+ figures: { spentUsd: spent, heldUsd: held, needsUsd: holdUsd, leastCapUsd, step: { name, holdUsd, basis } },
60
73
  };
61
74
  }
62
75
  /** An amount rounded up to the cent, so "at most" holds. */
63
76
  const centsUp = (usd) => money(Math.ceil(usd * 100 - 1e-9) / 100);
64
- /** The over-cap row's words, after the usage row whose booked cost `spentUsd` passed `capUsd`: by how much; when it passed
65
- * by no more than `boundUsd` (the bound of the requests since the cost last fit), a cache miss did it, and the most it
66
- * could have. None at or under the cap, with no cap, or with no known cost. */
67
- export function overCapWords(spentUsd, capUsd, boundUsd = 0) {
77
+ /** The over-cap row's words, after the usage row whose booked cost `spentUsd` passed `capUsd`: by how much. A request is
78
+ * held at its worst case, so only a cost its admission never priced passes the cap (an owed charge, a provider that bills
79
+ * past its list price). None at or under the cap, with no cap, or with no known cost. */
80
+ export function overCapWords(spentUsd, capUsd) {
68
81
  if (capUsd === undefined || typeof spentUsd !== "number" || spentUsd <= capUsd + FIT_TOLERANCE)
69
82
  return undefined;
70
- const byMiss = boundUsd > 0 && spentUsd - capUsd <= boundUsd + FIT_TOLERANCE;
71
- return byMiss ? `Went ${centsUp(spentUsd - capUsd)} over its cap on a cache miss (at most ${centsUp(boundUsd)}).` : `Spent ${centsMoney(spentUsd)}, ${centsUp(spentUsd - capUsd)} over the run's cap of ${centsMoney(capUsd)}`;
83
+ return `Spent ${centsMoney(spentUsd)}, ${centsUp(spentUsd - capUsd)} over the run's cap of ${centsMoney(capUsd)}`;
72
84
  }
73
85
  /** How a run ends whose booked cost `spentUsd` passed `capUsd`: failed, in these words (main's run end), the answer that
74
- * crossed it booked. None at or under the cap, with no cap, with no known cost, or when it passed by no more than
75
- * `boundUsd` (a cache miss within the bound it was admitted at: the run pauses at its next request instead). */
76
- export function overCapEnd(spentUsd, capUsd, boundUsd = 0) {
86
+ * crossed it booked. None at or under the cap, with no cap, or with no known cost. */
87
+ export function overCapEnd(spentUsd, capUsd) {
77
88
  if (capUsd === undefined || typeof spentUsd !== "number" || spentUsd <= capUsd + FIT_TOLERANCE)
78
89
  return undefined;
79
- if (boundUsd > 0 && spentUsd - capUsd <= boundUsd + FIT_TOLERANCE)
80
- return undefined;
81
90
  return `${OVER_CAP_END}${centsMoney(spentUsd)}, ${centsUp(spentUsd - capUsd)} over its cap of ${centsMoney(capUsd)}.`;
82
91
  }
83
92
  /** How overCapEnd's words begin, and only theirs: a reader of a run's summary serves one that does as the error
@@ -13,5 +13,9 @@ export declare function typicalCost(costs: readonly unknown[], nextExpected: num
13
13
  export declare function wrapUpDue(cap: number, spent: number, held: number, typical: number, leastUsd?: number): {
14
14
  leftUsd: number;
15
15
  } | undefined;
16
+ /** What every note the run's model is told by the server begins with (this wrap-up, and serve's note that its computer
17
+ * was replaced), so the model names it as the server's, never as an error of its own conversation. The server's row
18
+ * for such a note (serve's timeline, "AgentRun: …") is labelled already, and says the words after it. */
19
+ export declare const SERVER_NOTE_LABEL = "AgentRun server note: ";
16
20
  /** The note's words, what is left to the cent; before any priced request, the budget and a short answer. */
17
21
  export declare const wrapUpWords: (leftUsd: number, nonePriced?: boolean) => string;
@@ -30,8 +30,12 @@ export function wrapUpDue(cap, spent, held, typical, leastUsd) {
30
30
  const byLeast = leastUsd !== undefined && Number.isFinite(leastUsd) && leftUsd < WRAP_UP_LEAST_FACTOR * leastUsd;
31
31
  return byTypical || byLeast ? { leftUsd } : undefined;
32
32
  }
33
+ /** What every note the run's model is told by the server begins with (this wrap-up, and serve's note that its computer
34
+ * was replaced), so the model names it as the server's, never as an error of its own conversation. The server's row
35
+ * for such a note (serve's timeline, "AgentRun: …") is labelled already, and says the words after it. */
36
+ export const SERVER_NOTE_LABEL = "AgentRun server note: ";
33
37
  /** The note's words, what is left to the cent; before any priced request, the budget and a short answer. */
34
38
  export const wrapUpWords = (leftUsd, nonePriced = false) => {
35
39
  const left = centsMoney(Math.max(0, leftUsd));
36
- return nonePriced ? `This run's budget is about ${left}, enough for little work: answer as soon as you can.` : `About ${left} left of this run's budget: finish now with your answer.`;
40
+ return `${SERVER_NOTE_LABEL}${nonePriced ? `This run's budget is about ${left}, enough for little work: answer as soon as you can.` : `About ${left} left of this run's budget: finish now with your answer.`}`;
37
41
  };
@@ -1,6 +1,6 @@
1
1
  /** Each per-step tool's parameters, as JSON Schema. */
2
2
  export declare const COMPUTER_TOOL_SCHEMAS: {
3
- readonly [tool in "computer_observe" | "computer_act" | "computer_screenshot" | "computer_script"]: object;
3
+ readonly [tool in "computer_observe" | "computer_act" | "computer_screenshot"]: object;
4
4
  };
5
5
  /** computer_act's steps as TypeScript, for its description: its schema types them, with no words. */
6
6
  export declare const ACT_STEPS = "type UiStep = { press: UiRef; } | { set: UiRef; value: string; } | { perform: UiRef; action: string; } | { click: UiRef | Point; button?: \"left\" | \"right\"; count?: 1 | 2 | 3; } | { type: string; into?: UiRef; } | { key: string; } | { nav: \"back\" | \"home\" | \"app_switch\"; } | { scroll: UiRef | Point; dx?: number; dy?: number; } | { drag: Point[]; ms?: number; }; type UiRef = string; type Point = [ x: number, y: number ];";
@@ -308,27 +308,6 @@ export const COMPUTER_TOOL_SCHEMAS = {
308
308
  }
309
309
  },
310
310
  "additionalProperties": false
311
- },
312
- "computer_script": {
313
- "type": "object",
314
- "properties": {
315
- "code": {
316
- "description": "An async function's body; `return` what you need.",
317
- "type": "string"
318
- },
319
- "title": {
320
- "description": "For the run's timeline.",
321
- "type": "string"
322
- },
323
- "timeoutMs": {
324
- "description": "Default 120000, at most 600000.",
325
- "type": "number"
326
- }
327
- },
328
- "additionalProperties": false,
329
- "required": [
330
- "code"
331
- ]
332
311
  }
333
312
  };
334
313
  /** computer_act's steps as TypeScript, for its description: its schema types them, with no words. */
@@ -416,13 +395,18 @@ const TYPES = [
416
395
  },
417
396
  {
418
397
  "name": "UiStep",
419
- "uses": [],
420
- "text": "type UiStep = object; // computer_act's steps"
398
+ "uses": [
399
+ "UiRef",
400
+ "Point"
401
+ ],
402
+ "text": "type UiStep = { press: UiRef; } | { set: UiRef; value: string; } | { perform: UiRef; action: string; } | { click: UiRef | Point; button?: \"left\" | \"right\"; count?: 1 | 2 | 3; } | { type: string; into?: UiRef; } | { key: string; } | { nav: \"back\" | \"home\" | \"app_switch\"; } | { scroll: UiRef | Point; dx?: number; dy?: number; } | { drag: Point[]; ms?: number; };"
421
403
  },
422
404
  {
423
405
  "name": "UiExpect",
424
- "uses": [],
425
- "text": "type UiExpect = object; // computer_act's expect"
406
+ "uses": [
407
+ "UiRef"
408
+ ],
409
+ "text": "interface UiExpect { text?: string; ref?: UiRef; window?: { title?: string; role?: string; }; gone?: boolean; timeoutMs?: number; }"
426
410
  },
427
411
  {
428
412
  "name": "Image",
@@ -1,14 +1,21 @@
1
1
  import type { ToolDef } from "./defs.js";
2
2
  import { type CapabilityKind, type Executor } from "./hands.js";
3
+ /** The tool a script's `computer` runs every op through that no step tool runs. */
4
+ export declare const COMPUTER_OP_TOOL = "computer_op";
3
5
  /** The computer's tools, in the order a run lists them (the hand-over last). */
4
- export declare const COMPUTER_TOOLS: readonly ["computer_observe", "computer_act", "computer_screenshot", "computer_script", "computer_request_handoff"];
5
- /** The tool a host runs itself: a script runs in the host's isolate, over the same port. */
6
- export declare const SCRIPT_TOOL = "computer_script";
6
+ export declare const COMPUTER_TOOLS: readonly ["computer_observe", "computer_act", "computer_screenshot", "computer_op", "computer_request_handoff"];
7
+ /** The ops computer_op runs, each with the groups that offer it (one of them): the surface's ops (SURFACE_OPS) but the
8
+ * three the step tools run. */
9
+ export declare const COMPUTER_OPS: Readonly<Record<string, readonly string[]>>;
10
+ /** The op of each step tool, as a script's `computer` names it. */
11
+ export declare const STEP_TOOL_OPS: Readonly<Record<string, string>>;
12
+ /** The ops computer_op runs on a computer with `groups`. */
13
+ export declare function computerOpsFor(groups: readonly string[]): readonly string[];
7
14
  /** The tools a computer with `groups` offers: observe and act with the ui group, or a screen (observe) and input (act)
8
- * without it; the screenshot with a screen; the script with any of them. */
15
+ * without it; the screenshot with a screen; computer_op with any op past those (computerOpsFor). */
9
16
  export declare function computerToolsFor(groups: readonly string[]): readonly string[];
10
- /** The computer's tools in `kind`, under its settings key, for a computer with `groups` (the script's declarations
11
- * hold only what they offer). A script and an act change the computer: never replayed. */
17
+ /** The computer's tools in `kind`, under its settings key, for a computer with `groups`. An act or an op changes the
18
+ * computer: never replayed. */
12
19
  export declare function computerToolDefs(kind: CapabilityKind, groups: readonly string[]): readonly ToolDef[];
13
- /** The kernel's own executors of the computer's tools in `kind`: all but the script, which the host runs. */
20
+ /** The kernel's own executors of the computer's tools in `kind`. */
14
21
  export declare const computerExecutors: (kind: CapabilityKind) => Readonly<Record<string, Executor>>;