@parcha/agentrun-kernel 0.1.0-beta.34 → 0.1.0-beta.36

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 (45) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +0 -7
  3. package/dist/host/box.d.ts +0 -14
  4. package/dist/host/index.d.ts +4 -4
  5. package/dist/host/index.js +2 -2
  6. package/dist/host/overhead.d.ts +75 -4
  7. package/dist/host/overhead.js +220 -10
  8. package/dist/host/proxy.d.ts +40 -4
  9. package/dist/host/proxy.js +87 -3
  10. package/dist/index.d.ts +0 -2
  11. package/dist/index.js +0 -1
  12. package/dist/kernel/cap/index.d.ts +1 -1
  13. package/dist/kernel/cap/index.js +1 -1
  14. package/dist/kernel/cap/port.d.ts +3 -2
  15. package/dist/kernel/cap/port.js +2 -2
  16. package/dist/kernel/cap/price.js +5 -2
  17. package/dist/kernel/cap/run-cap.d.ts +2 -2
  18. package/dist/kernel/cap/run-cap.js +1 -1
  19. package/dist/kernel/cap/types.d.ts +7 -0
  20. package/dist/kernel/cap/words.d.ts +3 -0
  21. package/dist/kernel/cap/words.js +5 -2
  22. package/dist/kernel/index.d.ts +0 -2
  23. package/dist/kernel/index.js +0 -1
  24. package/dist/kernel/registry/index.d.ts +1 -1
  25. package/dist/kernel/registry/index.js +1 -1
  26. package/dist/kernel/registry/limits.d.ts +0 -1
  27. package/dist/kernel/registry/limits.js +0 -1
  28. package/dist/process/records.d.ts +0 -16
  29. package/dist/process/records.js +0 -41
  30. package/dist/process/settle.d.ts +1 -1
  31. package/dist/process/settle.js +2 -2
  32. package/dist/process/tools.d.ts +9 -0
  33. package/dist/process/tools.js +19 -6
  34. package/dist/process/zod.d.ts +0 -2
  35. package/dist/process/zod.js +0 -4
  36. package/dist/runner.d.ts +8 -0
  37. package/dist/runner.js +3 -3
  38. package/dist/testing.d.ts +17 -5
  39. package/dist/testing.js +72 -21
  40. package/dist/types.d.ts +15 -5
  41. package/package.json +3 -3
  42. package/dist/delegate.d.ts +0 -87
  43. package/dist/delegate.js +0 -143
  44. package/dist/kernel/follow-up.d.ts +0 -67
  45. package/dist/kernel/follow-up.js +0 -146
@@ -410,6 +410,9 @@ const FILTERED_DRAIN_MS = 5_000;
410
410
  * and the first fields of its data, which a stop can be read from when the event's line is longer than either window. */
411
411
  const LINE_START = 16 * 1024;
412
412
  const LINE_STARTS = 4;
413
+ /** The provider's word on asking again that an error answer passes on to the client (pi-ai's provider retry reads them,
414
+ * as the OpenAI and Anthropic SDKs do): how long to wait, and whether to retry at all. */
415
+ const RETRY_HEADERS = ["retry-after", "retry-after-ms", "x-should-retry"];
413
416
  /** A response header that names the request: the provider's `request-id` (`x-request-id`), or a gateway's own call id
414
417
  * (LiteLLM's `x-litellm-call-id`, the id its spend log records; `llm_provider-request-id`, the provider's passed on). */
415
418
  const ID_HEADER = /^(?:[a-z0-9]+[-_])*(?:request|call)[-_]id$/;
@@ -582,6 +585,41 @@ function baseOf(base) {
582
585
  throw new Error("agentrun-kernel: a model proxy's base is an origin and a path, with no userinfo, query, fragment or backslash");
583
586
  return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
584
587
  }
588
+ /** How long a count may take before the request goes on its byte bound: a count never holds a request up for long. */
589
+ export const COUNT_TIMEOUT_MS = 3_000;
590
+ /**
591
+ * The exact input tokens of a request with body `body`, by its provider's own count (`policy.countInput`), plus its
592
+ * margin; undefined (the request keeps its byte bound) when the policy has no counter, the upstream `origin` is not
593
+ * the counter's own, or the count fails, times out or says no count. Never throws: a count is only ever a tighter bound.
594
+ */
595
+ export async function countedInputOf(policy, origin, body, headers, fetch, say = () => { }, timeoutMs = COUNT_TIMEOUT_MS, signal) {
596
+ const counter = policy.countInput;
597
+ if (!counter)
598
+ return undefined;
599
+ try {
600
+ if (baseOf(counter.origin) !== origin)
601
+ return undefined;
602
+ // Cut at its timeout, or when `signal` aborts (its client went).
603
+ const cut = signal ? AbortSignal.any([AbortSignal.timeout(timeoutMs), signal]) : AbortSignal.timeout(timeoutMs);
604
+ const response = await fetch(`${origin}${counter.path}`, { method: "POST", headers: { ...counter.headers(headers), "content-type": "application/json" }, body: JSON.stringify(counter.body(body)), signal: cut });
605
+ if (!response.ok) {
606
+ await response.body?.cancel().catch(() => undefined);
607
+ say(`model proxy (${policy.id}): the provider's token count answered ${response.status}; the request keeps its byte bound`);
608
+ return undefined;
609
+ }
610
+ const tokens = counter.tokensOf(await response.json());
611
+ const margin = counter.margin ? counter.margin(body) : 0;
612
+ if (!Number.isSafeInteger(tokens) || tokens < 0 || !Number.isSafeInteger(margin) || margin < 0) {
613
+ say(`model proxy (${policy.id}): the provider's token count said no count; the request keeps its byte bound`);
614
+ return undefined;
615
+ }
616
+ return tokens + margin;
617
+ }
618
+ catch (error) {
619
+ say(`model proxy (${policy.id}): the provider's token count failed; the request keeps its byte bound`, { error: String(error?.message ?? error).slice(0, 200) });
620
+ return undefined;
621
+ }
622
+ }
585
623
  /** Start a session's model proxy on the loopback interface, admitting `key`. */
586
624
  /**
587
625
  * The most input tokens a request with body `sent` (the body `apply` returned, as it is sent) can be billed for: its UTF-8
@@ -598,9 +636,13 @@ export function inputTokensMaxOf(policy, body, sent, say = () => { }) {
598
636
  const overhead = policy.serverInputOverhead ? policy.serverInputOverhead(body) : 0;
599
637
  if (overhead === undefined)
600
638
  return undefined;
601
- if (typeof overhead !== "number" || !Number.isSafeInteger(overhead) || overhead < 0)
639
+ if (typeof overhead !== "number" || !Number.isSafeInteger(overhead))
602
640
  throw new Error(`not a token count: ${String(overhead).slice(0, 40)}`);
603
- return Buffer.byteLength(sent, "utf8") + overhead;
641
+ // Below 0 only by images' data the body carries (counted at what they are billed as instead): never past the bytes.
642
+ const bound = Buffer.byteLength(sent, "utf8") + overhead;
643
+ if (bound < 0)
644
+ throw new Error(`the policy counted ${-overhead} more bytes as billed apart than the body's ${Buffer.byteLength(sent, "utf8")}`);
645
+ return bound;
604
646
  }
605
647
  catch (error) {
606
648
  say(`model proxy (${policy.id}): the policy could not say what the provider adds to the body's input; its input is unmeasured`, { error: String(error?.message ?? error).slice(0, 200) });
@@ -856,6 +898,36 @@ export async function startModelProxy(options, key) {
856
898
  // admitted or booked, until the harness opens its next turn.
857
899
  if (answering && !route.free && stopTold !== undefined)
858
900
  return refuse(res, refusedStatus, `refused: the turn's answer was ${stopTold}, and the turn ends there`, req);
901
+ // An answer request on an upstream that is its provider's own (policy.countInput): its input bound is the provider's
902
+ // exact count when that is below its bytes, so a small cap admits a first turn its bytes would not. Each answer request
903
+ // is counted, not only the first: the cap prices a step by the last one's tokens plus how far its bound grew, so a
904
+ // counted bound beside a byte bound would read the bytes as growth. A count that fails or times out leaves the byte
905
+ // bound, and never holds the request up for long. A noted request is counted with its note, which bounds it without
906
+ // the note too (the note only adds).
907
+ // Only a bound that is a number is lowered: an unmeasured one (a fee with no bound, a hosted tool's reads) stays so.
908
+ let inputTokensCounted = false;
909
+ if (answering && !route.free && host === undefined && inputTokensMax !== undefined && policy.countInput) {
910
+ // A client that goes while its request is counted is gone before anything is admitted: the count is cut, and the
911
+ // request is neither admitted nor sent (nothing is booked, and no paid answer starts for no one).
912
+ const gone = new AbortController();
913
+ const onGone = () => gone.abort(new Error("the client went while its request was counted"));
914
+ res.once("close", onGone);
915
+ let counted;
916
+ try {
917
+ counted = await countedInputOf(policy, origin, body, headers, forward, say, COUNT_TIMEOUT_MS, gone.signal);
918
+ }
919
+ finally {
920
+ res.off("close", onGone);
921
+ }
922
+ if (gone.signal.aborted || res.destroyed)
923
+ return;
924
+ if (counted !== undefined && inputTokensMax !== undefined && counted < inputTokensMax) {
925
+ inputTokensMax = counted;
926
+ inputTokensCounted = true;
927
+ if (inputTokensMaxWithoutNote !== undefined)
928
+ inputTokensMaxWithoutNote = Math.min(inputTokensMaxWithoutNote, counted);
929
+ }
930
+ }
859
931
  // This request's own admission, handed back to its booking (requests may be in flight together).
860
932
  let ticket;
861
933
  try {
@@ -867,6 +939,8 @@ export async function startModelProxy(options, key) {
867
939
  ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }),
868
940
  ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }),
869
941
  ...(host === undefined ? {} : { host }),
942
+ ...(inputTokensCounted ? { inputTokensCounted: true } : {}),
943
+ ...(options.route === undefined ? {} : { route: options.route }),
870
944
  });
871
945
  }
872
946
  catch (error) {
@@ -1055,7 +1129,17 @@ export async function startModelProxy(options, key) {
1055
1129
  }
1056
1130
  began = { ok: upstream.ok, status: upstream.status };
1057
1131
  const contentType = upstream.headers.get("content-type") ?? "application/json";
1058
- res.writeHead(upstream.status, { "content-type": contentType });
1132
+ const sentHeaders = { "content-type": contentType };
1133
+ // An error answer keeps the provider's word on asking again (RETRY_HEADERS): the client's own retry of a 429 or a
1134
+ // 5xx waits as long as the provider asked, not its own guess.
1135
+ if (!upstream.ok) {
1136
+ for (const name of RETRY_HEADERS) {
1137
+ const value = upstream.headers.get(name);
1138
+ if (value !== null)
1139
+ sentHeaders[name] = value;
1140
+ }
1141
+ }
1142
+ res.writeHead(upstream.status, sentHeaders);
1059
1143
  const decoder = new TextDecoder();
1060
1144
  // The provider's own words in an error reach the harness with the credential this proxy sent, and the values of the
1061
1145
  // headers it added, cut out, then the host's redactor (errorCut): an error answer, or an error event in a stream. The
package/dist/index.d.ts CHANGED
@@ -1,8 +1,6 @@
1
1
  export { answeredUnpriced, createHarnessRunner, modelPortFor, sessionSpendOf, SUBMIT_TOOL, RUNNER_RECORDS } from "./runner.js";
2
2
  export { runBooking, type RunSessions } from "./run-booking.js";
3
3
  export type { Admission, BeforeRequest, Refusal, HarnessRunner, HarnessRunnerOptions, InFlight, ModelBooking, ModelPortEvent, ModelPortOptions, SessionCost } from "./runner.js";
4
- export { DELEGATE_RESULT_SCHEMA, DELEGATE_TOOL, delegateProblems, delegateTool } from "./delegate.js";
5
- export type { DelegateAgent, DelegateEvent, DelegateOptions } from "./delegate.js";
6
4
  export { HarnessRunError, SessionFenced, TurnParked } from "./errors.js";
7
5
  export { toolSchemaProblems } from "./schema-check.js";
8
6
  export { READ_SKILL_FILE, readSkillFileTool, SKILL_BYTES, skillProblems } from "./skill-files.js";
package/dist/index.js CHANGED
@@ -1,6 +1,5 @@
1
1
  export { answeredUnpriced, createHarnessRunner, modelPortFor, sessionSpendOf, SUBMIT_TOOL, RUNNER_RECORDS } from "./runner.js";
2
2
  export { runBooking } from "./run-booking.js";
3
- export { DELEGATE_RESULT_SCHEMA, DELEGATE_TOOL, delegateProblems, delegateTool } from "./delegate.js";
4
3
  export { HarnessRunError, SessionFenced, TurnParked } from "./errors.js";
5
4
  export { toolSchemaProblems } from "./schema-check.js";
6
5
  export { READ_SKILL_FILE, readSkillFileTool, SKILL_BYTES, skillProblems } from "./skill-files.js";
@@ -3,7 +3,7 @@ export { capRule, noteFor, type Judged, type JudgeState, type NoteState } from "
3
3
  export { beforeRequestOf, type BeforeRequestOptions } from "./port.js";
4
4
  export { DECISION_SESSION, overCapOf, paidCalls, runCap, TOOL_SESSION, type RunCap, type RunCapOptions, type RunDecisions, type RunTools } from "./run-cap.js";
5
5
  export { ANSWER_TOKENS_LEAST, CACHE_WARM_MS, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, expectedInput, inputBound, mostOutput, pricingOf, ratesFor, requestPrice } from "./price.js";
6
- export { CAP_REFUSAL_CODE, SPEND_CAP_REACHED, SUGGESTED_RAISE_FACTOR, centsMoney, leastMoney, money, OVER_CAP_END, overCapEnd, overCapMessage, overCapWords, raiseFigure, raiseTo, suggestedRaise } from "./words.js";
6
+ export { CAP_REFUSAL_CODE, SPEND_CAP_REACHED, SUGGESTED_RAISE_FACTOR, centsMoney, leastMoney, money, OVER_CAP_END, overCapEnd, overCapMessage, overCapWords, paidRefusal, raiseFigure, raiseTo, spentMoney, suggestedRaise } from "./words.js";
7
7
  export { checkRaise, followUpOf, parkOf, takeRaises, type BudgetPending, type Park, type RaiseCheck, type RaiseState } from "./park.js";
8
8
  export { WRAP_UP_FACTOR, WRAP_UP_LEAST_FACTOR, WRAP_UP_STEP0_ANSWER_TOKENS, typicalCost, wrapUpDue, wrapUpWords } from "./wrap-up.js";
9
9
  export { CapStop, createStepWaits, type StepWaits } from "./steps.js";
@@ -5,7 +5,7 @@ export { capRule, noteFor } from "./rule.js";
5
5
  export { beforeRequestOf } from "./port.js";
6
6
  export { DECISION_SESSION, overCapOf, paidCalls, runCap, TOOL_SESSION } from "./run-cap.js";
7
7
  export { ANSWER_TOKENS_LEAST, CACHE_WARM_MS, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, expectedInput, inputBound, mostOutput, pricingOf, ratesFor, requestPrice } from "./price.js";
8
- export { CAP_REFUSAL_CODE, SPEND_CAP_REACHED, SUGGESTED_RAISE_FACTOR, centsMoney, leastMoney, money, OVER_CAP_END, overCapEnd, overCapMessage, overCapWords, raiseFigure, raiseTo, suggestedRaise } from "./words.js";
8
+ export { CAP_REFUSAL_CODE, SPEND_CAP_REACHED, SUGGESTED_RAISE_FACTOR, centsMoney, leastMoney, money, OVER_CAP_END, overCapEnd, overCapMessage, overCapWords, paidRefusal, raiseFigure, raiseTo, spentMoney, suggestedRaise } from "./words.js";
9
9
  export { checkRaise, followUpOf, parkOf, takeRaises } from "./park.js";
10
10
  export { WRAP_UP_FACTOR, WRAP_UP_LEAST_FACTOR, WRAP_UP_STEP0_ANSWER_TOKENS, typicalCost, wrapUpDue, wrapUpWords } from "./wrap-up.js";
11
11
  export { CapStop, createStepWaits } from "./steps.js";
@@ -3,8 +3,9 @@ import type { CapMode, CapModel, Previous } from "./types.js";
3
3
  export interface BeforeRequestOptions {
4
4
  /** The run's cap, read before every request. Undefined: no cap, nothing refused. */
5
5
  capUsd(): number | undefined;
6
- /** A model as the cap prices it, by its id; undefined: a model with no price here. */
7
- modelOf(id: string): CapModel | undefined;
6
+ /** A model as the cap prices it, by its id and the route its request came by (ModelRequest.route; absent, the
7
+ * session's own): one id two routes price apart is priced as its route books it. Undefined: a model with no price here. */
8
+ modelOf(id: string, route?: string): CapModel | undefined;
8
9
  /** The session's previous request on a model, as its usage reported it: none prices the input uncached. */
9
10
  previousOf?(model: string): Previous | undefined;
10
11
  /** What the run spent beside the session's model requests, which the runner's booking does not hold: its priced tools'
@@ -20,7 +20,7 @@ export function beforeRequestOf(options) {
20
20
  // any paid step, so every refusable step after it sees it. Only a figure is money: one that is not goes to the rule.
21
21
  if (request.paid?.owed && isFigure(request.feeUsd ?? 0))
22
22
  return { holdUsd: request.feeUsd ?? 0 };
23
- const model = options.modelOf(request.model) ?? unpriced(request.model);
23
+ const model = options.modelOf(request.model, request.route) ?? unpriced(request.model);
24
24
  // A request the host sends beside the harness's own (its host label: a learned workflow's node) is another
25
25
  // conversation's prompt: nothing of the session's cache is read for it, so it is priced as a cache miss.
26
26
  const previous = request.host === undefined ? options.previousOf?.(request.model) : undefined;
@@ -39,7 +39,7 @@ export function beforeRequestOf(options) {
39
39
  // neither (no hold, no price or no measure) cannot be kept within the cap: refused for good, as an unmeasured input.
40
40
  let inFlight = 0;
41
41
  for (const flight of request.inFlight) {
42
- const figure = isFigure(flight.holdUsd) ? flight.holdUsd : worstOf(options.modelOf(flight.model), flight.inputTokensMax, flight.outputTokensMax);
42
+ const figure = isFigure(flight.holdUsd) ? flight.holdUsd : worstOf(options.modelOf(flight.model, flight.route), flight.inputTokensMax, flight.outputTokensMax);
43
43
  if (figure === undefined)
44
44
  return { refuse: unmeasured(capUsd), code: SPEND_CAP_REACHED };
45
45
  inFlight += figure;
@@ -70,8 +70,11 @@ export function inputBound(request) {
70
70
  const measured = request.inputTokens;
71
71
  if (typeof measured !== "number" || !Number.isFinite(measured) || measured < 0)
72
72
  return undefined;
73
- const added = request.shape ? providerInputOverhead(request.model.api, request.shape) : 0;
74
- return measured + added + (request.extraInputTokens ?? 0);
73
+ // Below 0 only by images' data counted at their billed size instead; a shape that says more such bytes than were
74
+ // measured is no bound.
75
+ const added = request.shape ? providerInputOverhead(request.model.api, { model: request.model.id, ...request.shape }) : 0;
76
+ const bound = measured + added + (request.extraInputTokens ?? 0);
77
+ return bound < 0 ? undefined : bound;
75
78
  }
76
79
  /** The output a request is sent with at most: what it asks (its model's ceiling when it says none), and its thinking budget
77
80
  * on an API whose thinking takes one, within the ceiling. Undefined: no ceiling and none asked. */
@@ -11,8 +11,8 @@ export interface RunCapOptions {
11
11
  capUsd(): number | undefined;
12
12
  readonly mode?: CapMode;
13
13
  readonly now?: () => number;
14
- /** The run's model requests' models (its decisions' are the cap's own). */
15
- modelOf(id: string): CapModel | undefined;
14
+ /** The run's model requests' models, by id and route (BeforeRequestOptions.modelOf; its decisions' are the cap's own). */
15
+ modelOf(id: string, route?: string): CapModel | undefined;
16
16
  previousOf?(model: string): Previous | undefined;
17
17
  /** The run's priced tools' charges and holds beside its requests (beforeRequestOf's), when it has any. */
18
18
  spentUsd?(): number | null;
@@ -40,7 +40,7 @@ export function runCap(options) {
40
40
  capUsd: options.capUsd,
41
41
  mode,
42
42
  ...(options.now ? { now: options.now } : {}),
43
- modelOf: (id) => deciding.get(id) ?? options.modelOf(id),
43
+ modelOf: (id, route) => deciding.get(id) ?? options.modelOf(id, route),
44
44
  ...(options.previousOf ? { previousOf: (model) => (deciding.has(model) ? undefined : options.previousOf(model)) } : {}),
45
45
  ...(options.spentUsd ? { spentUsd: options.spentUsd } : {}),
46
46
  ...(options.heldUsd ? { heldUsd: options.heldUsd } : {}),
@@ -111,6 +111,13 @@ export interface RefusalFigures {
111
111
  readonly needsUsd: number;
112
112
  readonly leastCapUsd: number;
113
113
  readonly boundUsd?: number;
114
+ /** A paid call's refusal: the call (its name, hold and basis), so a pause that lands after the refusal can say it again
115
+ * with the run's spend as it is then (paidRefusal). */
116
+ readonly step?: {
117
+ readonly name: string;
118
+ readonly holdUsd: number;
119
+ readonly basis: string;
120
+ };
114
121
  }
115
122
  /** How a step ended, for settle: a model request's as booking.ts reads it; a paid call's charge (null: it did not say). */
116
123
  export type Settled = Ended | {
@@ -17,6 +17,9 @@ export declare const raiseTo: (cap: number, total: number) => string;
17
17
  /** The raise a run parked at its cap is offered: what was taken plus 10 times the refused step's least, rounded up to a
18
18
  * whole dollar (a hair under, so a float just past a dollar stays that dollar), and above the cap past a float's tail. */
19
19
  export declare const suggestedRaise: (cap: number, spentUsd: number, needsUsd: number) => number;
20
+ /** A spend in words, to the nearest cent; one above $0 that rounds to it is "less than a cent", never "$0", which would
21
+ * say the run spent nothing. */
22
+ export declare const spentMoney: (usd: number) => string;
20
23
  /** A model request what is left cannot buy the least of. */
21
24
  export declare function roomRefusal(cap: number, spent: number, held: number, least: number, boundUsd?: number): {
22
25
  text: string;
@@ -34,10 +34,13 @@ export const suggestedRaise = (cap, spentUsd, needsUsd) => {
34
34
  const up = Math.ceil(spentUsd + SUGGESTED_RAISE_FACTOR * needsUsd - 1e-9);
35
35
  return up > cap + CAP_TOLERANCE ? up : Math.floor(cap + CAP_TOLERANCE) + 1;
36
36
  };
37
+ /** A spend in words, to the nearest cent; one above $0 that rounds to it is "less than a cent", never "$0", which would
38
+ * say the run spent nothing. */
39
+ export const spentMoney = (usd) => (usd > 0 && centsMoney(usd) === "$0" ? "less than a cent" : centsMoney(usd));
37
40
  /** What a run has spent of its cap: and what it holds for steps still running, when that is a cent or more. */
38
41
  const spentOf = (spent, held, cap) => {
39
42
  const holds = centsMoney(held);
40
- return holds !== "$0" ? `spent ${centsMoney(spent)} and holds ${holds} for steps still running, of its ${money(cap)} cap` : `spent ${centsMoney(spent)} of its ${money(cap)} cap`;
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`;
41
44
  };
42
45
  /** A model request what is left cannot buy the least of. */
43
46
  export function roomRefusal(cap, spent, held, least, boundUsd) {
@@ -53,7 +56,7 @@ export function paidRefusal(cap, spent, held, name, holdUsd, basis) {
53
56
  const leastCapUsd = raiseFigure(cap, spent + held + holdUsd);
54
57
  return {
55
58
  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.`,
56
- figures: { spentUsd: spent + held, needsUsd: holdUsd, leastCapUsd },
59
+ figures: { spentUsd: spent + held, needsUsd: holdUsd, leastCapUsd, step: { name, holdUsd, basis } },
57
60
  };
58
61
  }
59
62
  /** An amount rounded up to the cent, so "at most" holds. */
@@ -4,6 +4,4 @@ export { abortedOutcome, SessionHalt } from "./halt.js";
4
4
  export { BLOB_PIECE_CHARS, BLOB_RECORD, blobStreamName, readBlobs, sha256Hex, writeBlob } from "./blobs.js";
5
5
  export { foldSession, hostToolIO, INTERRUPTED_TEXT, KERNEL_RECORDS, openDrive, pendingSubmissions } from "./drive.js";
6
6
  export type { Drive, OpenDriveOptions } from "./drive.js";
7
- export { FOLLOW_UP_BUDGET_REACHED, FOLLOW_UP_CANCELLED, FOLLOW_UP_EFFECT, followUpKey, followUpOnce, followUpState } from "./follow-up.js";
8
- export type { FollowUp, FollowUpOptions, FollowUpResult, FollowUpState, FollowUpTarget } from "./follow-up.js";
9
7
  export * from "./registry/index.js";
@@ -2,5 +2,4 @@ export { EffectFailure, EffectInterrupted, Fatal, Restart, Unavailable } from ".
2
2
  export { abortedOutcome, SessionHalt } from "./halt.js";
3
3
  export { BLOB_PIECE_CHARS, BLOB_RECORD, blobStreamName, readBlobs, sha256Hex, writeBlob } from "./blobs.js";
4
4
  export { foldSession, hostToolIO, INTERRUPTED_TEXT, KERNEL_RECORDS, openDrive, pendingSubmissions } from "./drive.js";
5
- export { FOLLOW_UP_BUDGET_REACHED, FOLLOW_UP_CANCELLED, FOLLOW_UP_EFFECT, followUpKey, followUpOnce, followUpState } from "./follow-up.js";
6
5
  export * from "./registry/index.js";
@@ -10,6 +10,6 @@ export type { CapabilityKind, ExecResult, Executor, Hands, HostExecutors, Input,
10
10
  export { PHONE_EXECUTORS, PHONE_KEYS, PHONE_SWIPE_MAX_MS, PHONE_SWIPE_MS, PHONE_TOOL_DEFS, PHONE_TREE_MAX_CHARS, PHONE_TREE_MAX_NODES } from "./phone.js";
11
11
  export { HANDOFF_DEFAULT_S, HANDOFF_MAX_S, HANDOFF_MIN_S, HANDOFF_TOOL } from "./handoff.js";
12
12
  export type { Handoff } from "./hands.js";
13
- export { BACKGROUND_DIR, BACKGROUND_INPUT_BYTES, BACKGROUND_LIST_MAX, BACKGROUND_LOG_BYTES, BACKGROUND_MAX, BACKGROUND_PAGE_BYTES, BACKGROUND_SIGNALS, BACKGROUND_TOOLS, BASH_DEFAULT_TIMEOUT_S, BASH_MAX_TIMEOUT_S, READ_IMAGE_MAX_BYTES, SHELL_TOOLS, } from "./limits.js";
13
+ export { BACKGROUND_DIR, BACKGROUND_INPUT_BYTES, BACKGROUND_LIST_MAX, BACKGROUND_LOG_BYTES, BACKGROUND_MAX, BACKGROUND_PAGE_BYTES, BACKGROUND_SIGNALS, BACKGROUND_TOOLS, BASH_DEFAULT_TIMEOUT_S, READ_IMAGE_MAX_BYTES, SHELL_TOOLS, } from "./limits.js";
14
14
  export { createRegistry } from "./registry.js";
15
15
  export type { Registry } from "./registry.js";
@@ -10,5 +10,5 @@ export { defaultPermissionOf, SHELL_FAMILY, SHELL_WATCHERS, shellPermission, she
10
10
  export { answerOf, exitCodeOf, needsKindWords } from "./hands.js";
11
11
  export { PHONE_EXECUTORS, PHONE_KEYS, PHONE_SWIPE_MAX_MS, PHONE_SWIPE_MS, PHONE_TOOL_DEFS, PHONE_TREE_MAX_CHARS, PHONE_TREE_MAX_NODES } from "./phone.js";
12
12
  export { HANDOFF_DEFAULT_S, HANDOFF_MAX_S, HANDOFF_MIN_S, HANDOFF_TOOL } from "./handoff.js";
13
- export { BACKGROUND_DIR, BACKGROUND_INPUT_BYTES, BACKGROUND_LIST_MAX, BACKGROUND_LOG_BYTES, BACKGROUND_MAX, BACKGROUND_PAGE_BYTES, BACKGROUND_SIGNALS, BACKGROUND_TOOLS, BASH_DEFAULT_TIMEOUT_S, BASH_MAX_TIMEOUT_S, READ_IMAGE_MAX_BYTES, SHELL_TOOLS, } from "./limits.js";
13
+ export { BACKGROUND_DIR, BACKGROUND_INPUT_BYTES, BACKGROUND_LIST_MAX, BACKGROUND_LOG_BYTES, BACKGROUND_MAX, BACKGROUND_PAGE_BYTES, BACKGROUND_SIGNALS, BACKGROUND_TOOLS, BASH_DEFAULT_TIMEOUT_S, READ_IMAGE_MAX_BYTES, SHELL_TOOLS, } from "./limits.js";
14
14
  export { createRegistry } from "./registry.js";
@@ -2,7 +2,6 @@
2
2
  * (Claude Code's own 120 s and 600 s). A command that needs longer is a background process (bash_background). The
3
3
  * ceiling a run gets is its hands' `maxExecS`: 600 s locally and on a computer, less where the hands' exec is bounded. */
4
4
  export declare const BASH_DEFAULT_TIMEOUT_S = 120;
5
- export declare const BASH_MAX_TIMEOUT_S = 600;
6
5
  /** The largest image read hands the model, in bytes: 3.75 MiB, whose base64 is the 5 MiB the strictest platform a
7
6
  * harness sends images to takes (the claude-agent adapter's CLAUDE_AGENT_MAX_IMAGE_BYTES, Amazon Bedrock's). */
8
7
  export declare const READ_IMAGE_MAX_BYTES = 3932160;
@@ -4,7 +4,6 @@
4
4
  * (Claude Code's own 120 s and 600 s). A command that needs longer is a background process (bash_background). The
5
5
  * ceiling a run gets is its hands' `maxExecS`: 600 s locally and on a computer, less where the hands' exec is bounded. */
6
6
  export const BASH_DEFAULT_TIMEOUT_S = 120;
7
- export const BASH_MAX_TIMEOUT_S = 600;
8
7
  /** The largest image read hands the model, in bytes: 3.75 MiB, whose base64 is the 5 MiB the strictest platform a
9
8
  * harness sends images to takes (the claude-agent adapter's CLAUDE_AGENT_MAX_IMAGE_BYTES, Amazon Bedrock's). */
10
9
  export const READ_IMAGE_MAX_BYTES = 3_932_160;
@@ -109,22 +109,6 @@ export declare function journalBatches(state: SessionState): BatchRef[];
109
109
  export declare function journalRecords<T = unknown>(state: SessionState, stream?: string): JournalRecord<T>[];
110
110
  /** The normalized transcript, in log order. */
111
111
  export declare function transcriptOf(state: SessionState): JournalRecord<TranscriptEntry>[];
112
- /**
113
- * Where the last turn ended: the `effectOrder` index of the batch holding
114
- * the last `turn` entry, or of the last `unavailable` fact (a turn the
115
- * harness could not run: it is over, with an error, and nothing in it is
116
- * recovered), or -1 if no turn has ended yet. Everything after it belongs to
117
- * the current (or an interrupted) turn.
118
- */
119
- export declare function lastTurnEnd(state: SessionState): number;
120
- /**
121
- * A batch input for UIs: the transcript entries as they are, every other
122
- * stream as a count (native records can be large, and a page polling a
123
- * session should not carry them).
124
- */
125
- export declare function summarizeBatch(input: unknown): unknown;
126
- /** The transcript entries of one batch input (inline only; transcript entries are never offloaded). */
127
- export declare function batchTranscript(input: unknown): TranscriptEntry[];
128
112
  export interface OpenTurn {
129
113
  /** `effectOrder` index of the batch that ended the previous turn (-1: none ended yet). */
130
114
  since: number;
@@ -80,47 +80,6 @@ function lastUnavailable(state) {
80
80
  return i;
81
81
  return -1;
82
82
  }
83
- /**
84
- * Where the last turn ended: the `effectOrder` index of the batch holding
85
- * the last `turn` entry, or of the last `unavailable` fact (a turn the
86
- * harness could not run: it is over, with an error, and nothing in it is
87
- * recovered), or -1 if no turn has ended yet. Everything after it belongs to
88
- * the current (or an interrupted) turn.
89
- */
90
- export function lastTurnEnd(state) {
91
- let at = -1;
92
- for (const r of transcriptOf(state))
93
- if (r.data?.type === 'turn')
94
- at = r.at;
95
- return Math.max(at, lastUnavailable(state));
96
- }
97
- /**
98
- * A batch input for UIs: the transcript entries as they are, every other
99
- * stream as a count (native records can be large, and a page polling a
100
- * session should not carry them).
101
- */
102
- export function summarizeBatch(input) {
103
- const batch = input;
104
- if (!batch || typeof batch !== 'object' || !batch.streams)
105
- return input;
106
- const streams = {};
107
- for (const [name, part] of Object.entries(batch.streams)) {
108
- streams[name] =
109
- name === TRANSCRIPT
110
- ? part
111
- : {
112
- from: part.from,
113
- count: part.entries.length,
114
- blobs: part.entries.filter((e) => e.blob).length,
115
- };
116
- }
117
- return { v: batch.v, n: batch.n, streams };
118
- }
119
- /** The transcript entries of one batch input (inline only; transcript entries are never offloaded). */
120
- export function batchTranscript(input) {
121
- const part = input?.streams?.[TRANSCRIPT];
122
- return (part?.entries ?? []).map((e) => e.data).filter(Boolean);
123
- }
124
83
  /**
125
84
  * The turn that has not ended: everything after the last `turn` entry of
126
85
  * the transcript. `undefined` when the last turn ended and nothing happened
@@ -4,7 +4,7 @@ export interface SettleOptions {
4
4
  /** Placed prompts and follow-ups the harness's CLI never recorded (its own record, as the session keeps it): carried,
5
5
  * as a pending one is. */
6
6
  readonly unsent?: readonly string[];
7
- /** The submission of a host's own prompt (a follow-up's, `FollowUpTarget.settleOpenTurn`'s `opening`): withdrawn
7
+ /** The submission of a host's own prompt (`AdapterSession.settleOpenTurn`'s `opening`): withdrawn
8
8
  * while pending, never carried, and the only one withdrawn. */
9
9
  readonly host?: string;
10
10
  }
@@ -22,8 +22,8 @@ export async function settleTurn(drive, options = {}) {
22
22
  continue;
23
23
  await drive.submit({ id: `withdraw:${id}`, kind: "withdraw", target: id, carry: true, unsent: true });
24
24
  }
25
- // A follow-up's settle names its own prompt (`host`): that one is withdrawn and never carried, and the rest is left
26
- // as it is (kernel/follow-up.ts). A person's stop withdraws every prompt pending.
25
+ // A host's settle of its own prompt names it (`host`): that one is withdrawn and never carried, and the rest is left
26
+ // as it is. A person's stop withdraws every prompt pending.
27
27
  const pending = pendingSubmissions(drive.state()).filter((s) => options.host === undefined || s.id === options.host);
28
28
  for (const submission of pending) {
29
29
  // A prompt or follow-up the person stopped stays in the conversation: its text is carried into the next one
@@ -82,6 +82,15 @@ export declare class Mutex {
82
82
  }
83
83
  /** The memo key of a tool call. */
84
84
  export declare const toolKey: (callId: string) => string;
85
+ /**
86
+ * The host's gate, asked about a call before anything of it is written: the first step of every harness's tool bridge
87
+ * (this one's, and the faux harness's, run-adapters/testing). Undefined when it allows the call; the refusal for a deny,
88
+ * whose words are the call's answer; a park holds the call until `signal` is aborted (the run parked and this process
89
+ * lets go of it), then rejects, so the harness is never handed a result for it.
90
+ */
91
+ export declare function askGate(gate: (call: GateCall) => Promise<GateAnswer>, call: GateCall, signal: AbortSignal): Promise<{
92
+ deny: string;
93
+ } | undefined>;
85
94
  /**
86
95
  * Build the bridge for one drive. The calls' effects are this drive's: build
87
96
  * a new bridge per `drive(ctx)`.
@@ -24,6 +24,20 @@ function parkedUntilAborted(signal, tool) {
24
24
  signal.addEventListener('abort', parked, { once: true });
25
25
  });
26
26
  }
27
+ /**
28
+ * The host's gate, asked about a call before anything of it is written: the first step of every harness's tool bridge
29
+ * (this one's, and the faux harness's, run-adapters/testing). Undefined when it allows the call; the refusal for a deny,
30
+ * whose words are the call's answer; a park holds the call until `signal` is aborted (the run parked and this process
31
+ * lets go of it), then rejects, so the harness is never handed a result for it.
32
+ */
33
+ export async function askGate(gate, call, signal) {
34
+ const answer = await gate(call);
35
+ if (answer === 'allow')
36
+ return undefined;
37
+ if ('deny' in answer)
38
+ return answer;
39
+ return parkedUntilAborted(signal, call.tool);
40
+ }
27
41
  /**
28
42
  * Build the bridge for one drive. The calls' effects are this drive's: build
29
43
  * a new bridge per `drive(ctx)`.
@@ -45,12 +59,11 @@ export function toolBridge(ctx, tools, options = {}) {
45
59
  const fresh = !ctx.isMemoized(key);
46
60
  // The gate first: before the flush and the intent, so a refused or parked call leaves nothing in the log.
47
61
  if (fresh && options.gate) {
48
- const answer = await options.gate({ callId, tool: tool.name, args: (args ?? {}) });
49
- if (answer !== 'allow') {
50
- if ('deny' in answer)
51
- return { text: answer.deny, isError: true };
52
- await parkedUntilAborted(signal ? AbortSignal.any([signal, ctx.signal]) : ctx.signal, tool.name);
53
- }
62
+ // An earlier attempt's start in the log (a replay-safe call a crash cut): it may have been sent, and the gate says so.
63
+ const replayed = ctx.state().effects.has(key);
64
+ const refused = await askGate(options.gate, { callId, tool: tool.name, args: (args ?? {}), ...(replayed ? { replayed: true } : {}) }, signal ? AbortSignal.any([signal, ctx.signal]) : ctx.signal);
65
+ if (refused)
66
+ return { text: refused.deny, isError: true };
54
67
  }
55
68
  if (fresh && tool.replay === 'never')
56
69
  await options.beforeNever?.({ name: tool.name, callId, args });
@@ -25,8 +25,6 @@ export interface JsonSchemaObject {
25
25
  anyOf?: JsonSchemaObject[];
26
26
  nullable?: boolean;
27
27
  }
28
- /** A zod object for a JSON Schema object (extra properties allowed unless `additionalProperties: false`). */
29
- export declare function zodFromJsonSchema(schema: unknown, z: Z): ZodType;
30
28
  /** The raw shape (`{ key: zodType }`) of a JSON Schema object, for APIs that take a shape. */
31
29
  export declare function zodShapeFromJsonSchema(schema: unknown, z: Z): Record<string, ZodType>;
32
30
  export {};
@@ -13,10 +13,6 @@
13
13
  * `packages/harness-claude-code/src/bridge/json-schema-to-zod.ts`,
14
14
  * Apache-2.0); changed to take `z` as a parameter and to export the shape.
15
15
  */
16
- /** A zod object for a JSON Schema object (extra properties allowed unless `additionalProperties: false`). */
17
- export function zodFromJsonSchema(schema, z) {
18
- return toZodObject(isSchema(schema) ? schema : {}, z);
19
- }
20
16
  /** The raw shape (`{ key: zodType }`) of a JSON Schema object, for APIs that take a shape. */
21
17
  export function zodShapeFromJsonSchema(schema, z) {
22
18
  return toZodShape(isSchema(schema) ? schema : undefined, z);
package/dist/runner.d.ts CHANGED
@@ -71,6 +71,8 @@ export type BeforeRequest = (request: {
71
71
  /** The label of a request the host sent beside the harness's own (ModelRequest.host): a learned workflow's model node,
72
72
  * under the same check as the harness's own. */
73
73
  host?: string;
74
+ /** The route it came by (ModelRequest.route), absent for the session's own: the host prices it by model and route. */
75
+ route?: string;
74
76
  /** This session's paid requests admitted and not yet answered (in this process), oldest first, each with its own
75
77
  * `inputTokensMax`, the output limit it was admitted with (`outputTokensMax`) and what its host held for it
76
78
  * (`holdUsd`): a budget holds each one until it answers, since `spentUsd` counts answered requests only. Requests are
@@ -88,6 +90,11 @@ export type Refusal = {
88
90
  needsUsd: number;
89
91
  leastCapUsd: number;
90
92
  boundUsd?: number;
93
+ step?: {
94
+ name: string;
95
+ holdUsd: number;
96
+ basis: string;
97
+ };
91
98
  };
92
99
  /** The refusal's code, from a host that gives one (a spend cap's: `spend_cap_reached`): carried on the error that ends
93
100
  * the node (HarnessRunError.refusal), so a reader knows the refusal by it, never by its words. */
@@ -102,6 +109,7 @@ export type InFlight = {
102
109
  outputTokensMax?: number;
103
110
  holdUsd?: number;
104
111
  host?: string;
112
+ route?: string;
105
113
  };
106
114
  /** A host's admission: what it holds for the request (`holdUsd`), and the most output tokens, thinking included, it may
107
115
  * be sent with (`outputTokensMax`, what is left of a cap can buy), which its ticket carries to the model proxy. A
package/dist/runner.js CHANGED
@@ -179,7 +179,7 @@ function bookingFor(writer, options) {
179
179
  // A paid request whose cost couldn't be recorded stops the booking itself, whether or not the host gave it a stop.
180
180
  let failed;
181
181
  const end = (reason, message, code) => options.stop ? options.stop(reason, message, code) : new HarnessRunError(reason, turns, 0, { maxTurns: limit, ...(message === undefined ? {} : { message }), ...(code === undefined ? {} : { refusal: code }) });
182
- const admit = async ({ model, inputTokensMax: measured, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, noted, inputTokensMaxWithoutNote, host }) => {
182
+ const admit = async ({ model, inputTokensMax: measured, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, noted, inputTokensMaxWithoutNote, host, route }) => {
183
183
  let inputTokensMax = measured;
184
184
  const stopped = options.stopped?.(host === undefined ? {} : { host }) ?? failed;
185
185
  if (stopped)
@@ -190,7 +190,7 @@ function bookingFor(writer, options) {
190
190
  if (limit !== null && turns >= limit)
191
191
  throw end("turn_limit");
192
192
  const verdict = await options.beforeRequest?.({ ...node, model, turn: turns + 1, maxTurns: limit, ...(options.budgetUsd === undefined ? {} : { budgetUsd: options.budgetUsd }), spentUsd, inFlight: open.map((f) => ({ ...f })), inputTokensMax,
193
- ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }), ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }), ...(feeUsd === undefined ? {} : { feeUsd }), ...(paid ? { paid } : {}), ...(side ? { side } : {}), ...(noted ? { noted, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}), ...(host === undefined ? {} : { host }) });
193
+ ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }), ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }), ...(feeUsd === undefined ? {} : { feeUsd }), ...(paid ? { paid } : {}), ...(side ? { side } : {}), ...(noted ? { noted, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
194
194
  if (verdict && "refuse" in verdict)
195
195
  throw end("refused", verdict.refuse, typeof verdict.code === "string" ? verdict.code : undefined);
196
196
  const hold = verdict && "holdUsd" in verdict ? heldFigure(verdict.holdUsd) : undefined;
@@ -257,7 +257,7 @@ function bookingFor(writer, options) {
257
257
  emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: 0 }, ...(host === undefined ? {} : { host }), ended: { end: "nothing", label: "never_left" } });
258
258
  throw stoppedLate;
259
259
  }
260
- open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(host === undefined ? {} : { host }) });
260
+ open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
261
261
  return { turn, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(withoutNote ? { noteDropped: true } : {}) };
262
262
  };
263
263
  const models = {