@parcha/agentrun-kernel 0.1.0-beta.37 → 0.1.0-beta.38
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/CHANGELOG.md +53 -0
- package/dist/host/index.d.ts +2 -4
- package/dist/host/index.js +2 -3
- package/dist/host/overhead.d.ts +42 -0
- package/dist/host/overhead.js +84 -10
- package/dist/host/proxy.d.ts +14 -11
- package/dist/host/proxy.js +46 -21
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/kernel/cap/index.d.ts +3 -3
- package/dist/kernel/cap/index.js +2 -2
- package/dist/kernel/cap/port.d.ts +14 -3
- package/dist/kernel/cap/port.js +29 -19
- package/dist/kernel/cap/price.d.ts +31 -12
- package/dist/kernel/cap/price.js +48 -28
- package/dist/kernel/cap/rule.d.ts +3 -1
- package/dist/kernel/cap/rule.js +21 -3
- package/dist/kernel/cap/run-cap.d.ts +9 -2
- package/dist/kernel/cap/run-cap.js +8 -3
- package/dist/kernel/cap/types.d.ts +9 -5
- package/dist/kernel/registry/computer-surface.generated.js +9 -2
- package/dist/kernel/registry/computer.js +12 -4
- package/dist/kernel/registry/hands.d.ts +1 -1
- package/dist/kernel/types.d.ts +8 -1
- package/dist/process/tools.d.ts +2 -0
- package/dist/process/tools.js +59 -5
- package/dist/runner.d.ts +1 -1
- package/dist/runner.js +100 -2
- package/dist/testing.d.ts +6 -2
- package/dist/testing.js +5 -3
- package/dist/tool-deferral.d.ts +12 -0
- package/dist/tool-deferral.js +17 -0
- package/dist/types.d.ts +68 -39
- package/package.json +2 -2
- package/dist/host/mcp-route.d.ts +0 -14
- package/dist/host/mcp-route.js +0 -125
package/dist/kernel/cap/port.js
CHANGED
|
@@ -7,6 +7,31 @@ import { SPEND_CAP_REACHED, unmeasured } from "./words.js";
|
|
|
7
7
|
const refusalOf = (error) => ({ refuse: error.message, code: error.code, forGood: error.forGood, ...(error.figures ? { figures: error.figures } : {}) });
|
|
8
8
|
/** A model the host has no price for: refused under a cap, by the rule. */
|
|
9
9
|
const unpriced = (id) => ({ id, api: "unknown", price: null, outputCeiling: null });
|
|
10
|
+
/** `request` as the rule prices it: the one place a request's model and the session's recent requests are chosen for it,
|
|
11
|
+
* so its admission, the wrap-up's note and what the run keeps back to answer (requestFigures) price it alike: its input
|
|
12
|
+
* read from the cache a recent request left warm (price.ts warmFrom), else uncached. */
|
|
13
|
+
export function capRequestOf(id, request, options) {
|
|
14
|
+
const model = options.modelOf(request.model, request.route) ?? unpriced(request.model);
|
|
15
|
+
// A request the host sends beside the harness's own (its host label: a learned workflow's node), a side call, or one
|
|
16
|
+
// that is no answer of the turn (a title, a summary, a child's) is another conversation's prompt: nothing of the
|
|
17
|
+
// session's cache is read for it, so it is priced as a cache miss.
|
|
18
|
+
// Its bound must be measured as the next request's is (a provider's count, or bytes): their difference is no growth.
|
|
19
|
+
// Asked by the model the cap prices it as: a CLI's request names its model as its provider does (openai/gpt-6.1-sol
|
|
20
|
+
// for gpt-6.1-sol), and its recent requests are the same model's whatever the name.
|
|
21
|
+
const mine = request.host === undefined && !request.side && !request.unanswered ? options.recentOf?.(model.id) : undefined;
|
|
22
|
+
const recent = mine?.filter((one) => (one.counted === true) === (request.inputTokensCounted === true));
|
|
23
|
+
return {
|
|
24
|
+
kind: "model",
|
|
25
|
+
id,
|
|
26
|
+
model,
|
|
27
|
+
inputTokens: request.inputTokensMax,
|
|
28
|
+
...(request.outputTokensAsked === undefined ? {} : { outputAsked: request.outputTokensAsked }),
|
|
29
|
+
...(request.outputTokensLeast === undefined ? {} : { outputTokensLeast: request.outputTokensLeast }),
|
|
30
|
+
...(recent?.length ? { recent } : {}),
|
|
31
|
+
...(isFigure(request.feeUsd) && request.feeUsd > 0 ? { feeUsd: request.feeUsd } : {}),
|
|
32
|
+
...(request.side ? { side: true } : {}),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
10
35
|
/** The host's beforeRequest for a CLI harness's session: the runner's spend and holds, judged by the one rule. */
|
|
11
36
|
export function beforeRequestOf(options) {
|
|
12
37
|
const mode = options.mode ?? "expected";
|
|
@@ -20,24 +45,7 @@ export function beforeRequestOf(options) {
|
|
|
20
45
|
// 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
46
|
if (request.paid?.owed && isFigure(request.feeUsd ?? 0))
|
|
22
47
|
return { holdUsd: request.feeUsd ?? 0 };
|
|
23
|
-
const
|
|
24
|
-
// A request the host sends beside the harness's own (its host label: a learned workflow's node), a side call, or one
|
|
25
|
-
// that is no answer of the turn (a title, a summary, a child's) is another conversation's prompt: nothing of the
|
|
26
|
-
// session's cache is read for it, so it is priced as a cache miss.
|
|
27
|
-
// Its bound must be measured as the next request's is (a provider's count, or bytes): their difference is no growth.
|
|
28
|
-
const before = request.host === undefined && !request.side && !request.unanswered ? options.previousOf?.(request.model) : undefined;
|
|
29
|
-
const previous = before && (before.counted === true) === (request.inputTokensCounted === true) ? before : undefined;
|
|
30
|
-
const asked = {
|
|
31
|
-
kind: "model",
|
|
32
|
-
id: `turn-${request.turn}`,
|
|
33
|
-
model,
|
|
34
|
-
inputTokens: request.inputTokensMax,
|
|
35
|
-
...(request.outputTokensAsked === undefined ? {} : { outputAsked: request.outputTokensAsked }),
|
|
36
|
-
...(request.outputTokensLeast === undefined ? {} : { outputTokensLeast: request.outputTokensLeast }),
|
|
37
|
-
...(previous ? { previous } : {}),
|
|
38
|
-
...(isFigure(request.feeUsd) && request.feeUsd > 0 ? { feeUsd: request.feeUsd } : {}),
|
|
39
|
-
...(request.side ? { side: true } : {}),
|
|
40
|
-
};
|
|
48
|
+
const asked = capRequestOf(`turn-${request.turn}`, request, options);
|
|
41
49
|
// Each request in flight at what the host held for it, else its worst case at the limit it was admitted with; one with
|
|
42
50
|
// neither (no hold, no price or no measure) cannot be kept within the cap: refused for good, as an unmeasured input.
|
|
43
51
|
let inFlight = 0;
|
|
@@ -70,7 +78,9 @@ export function beforeRequestOf(options) {
|
|
|
70
78
|
}
|
|
71
79
|
const judge = (input) => {
|
|
72
80
|
try {
|
|
73
|
-
const
|
|
81
|
+
const sized = { ...asked, inputTokens: input };
|
|
82
|
+
const keepUsd = options.keepBackUsd?.(request, sized);
|
|
83
|
+
const judged = capRule.judge(sized, { capUsd, spentUsd, heldUsd, mode, now: now(), ...(keepUsd === undefined ? {} : { keepUsd }) });
|
|
74
84
|
return { holdUsd: judged.heldUsd, boundUsd: judged.boundUsd, ...(judged.outputTokensMax === undefined ? {} : { outputTokensMax: judged.outputTokensMax }), stoppedUsd: judged.stoppedUsd };
|
|
75
85
|
}
|
|
76
86
|
catch (error) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CapMode, ModelCapRequest, ModelPrice, PriceRates,
|
|
1
|
+
import type { CapMode, ModelCapRequest, ModelPrice, PriceRates, RecentRequest } from "./types.js";
|
|
2
2
|
/** How long after a request ended the next one in its conversation is expected to read its cache: 4 minutes, inside
|
|
3
3
|
* Anthropic's 5. */
|
|
4
4
|
export declare const CACHE_WARM_MS: number;
|
|
@@ -27,19 +27,38 @@ export declare function ratesFor(price: ModelPrice, inputTokens: number): PriceR
|
|
|
27
27
|
* the input and cache-write rates, and its output at the output rate, each at the rates of the tier its whole input
|
|
28
28
|
* passes (ratesFor). A hold, a worst case and a booking the cap prices are so never under what the provider bills. */
|
|
29
29
|
export declare function pricingOf(price: ModelPrice): Pricing;
|
|
30
|
-
/**
|
|
31
|
-
*
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
export declare function
|
|
30
|
+
/** How many of a session's recent requests it keeps (recentAfter), the newest: enough for a conversation's last request
|
|
31
|
+
* to outlast the smaller requests a CLI sends between two of its own. Fewer only prices a request colder, never under. */
|
|
32
|
+
export declare const RECENT_REQUESTS_KEPT = 16;
|
|
33
|
+
/** The recent request whose cache a request of `bound` tokens on `model` is expected to read at `now`: of `recent`, those
|
|
34
|
+
* on its model that ended under CACHE_WARM_MS ago (by a clock that does not read before their end) with a bound no bigger
|
|
35
|
+
* than its own (a conversation only grows between its own requests), the biggest, the newest of equal ones. So a smaller
|
|
36
|
+
* request between two of a conversation's own (a CLI's side request while a tool runs, a child's, a summary) leaves the
|
|
37
|
+
* conversation's next request warm from its last, and a conversation that compacted is warm again from its first request
|
|
38
|
+
* after the compaction. None: priced uncached. */
|
|
39
|
+
export declare function warmFrom(bound: number, recent: readonly RecentRequest[] | undefined, now: number, model: string): RecentRequest | undefined;
|
|
40
|
+
/** The input of a request of `bound` tokens on `model` expected at `now` after `recent`: the cache of the request warmFrom
|
|
41
|
+
* picks at the cache-read price, and that request's input after the cache plus what the body grew by since at full
|
|
42
|
+
* price. Undefined (all of it uncached) when it picks none.
|
|
43
|
+
*
|
|
44
|
+
* Why a warm price opens no way past the cap. It is a guess: the request picked may be another conversation's whose
|
|
45
|
+
* bound happened to fit, or its cache may be gone. The guess lowers only what the request is held at (requestPrice's
|
|
46
|
+
* cost, never above its worst), never its worst: the whole bound uncached at the dearer of the input and cache-write
|
|
47
|
+
* prices whichever request was picked, the output limited to what it was admitted at. So a request's real cost is at
|
|
48
|
+
* most its hold plus its bound (Judged.boundUsd): a guess too low adds that much at most, the cache miss "expected" has
|
|
49
|
+
* always allowed and serve reports as the run's overshoot bound. The bound is counted wherever the run's room is read
|
|
50
|
+
* while the request is out (the wrap-up's gate and note count it at hold + bound, sessionSpendOf; a claim lost with it
|
|
51
|
+
* open books it cut at both); a CLI's own request admitted with its host's keep-back is limited so its worst leaves the
|
|
52
|
+
* keep-back free (rule.ts judgeModel), so even a miss stays under the cap; and once a request answers, its real cost
|
|
53
|
+
* is booked and the next admission reads it. "strict" reads no cache: every request held at its worst. */
|
|
54
|
+
export declare function expectedInput(bound: number, recent: readonly RecentRequest[] | undefined, now: number, model: string): InputParts | undefined;
|
|
55
|
+
/** The session's recent requests once `ended` has answered: `ended`, and those that ended under CACHE_WARM_MS before it
|
|
56
|
+
* but one on its model, measured its way and of its bound (`ended` is the newer of the two); the newest
|
|
57
|
+
* RECENT_REQUESTS_KEPT. None is dropped for being smaller or bigger than `ended`: warmFrom picks for each request. */
|
|
58
|
+
export declare function recentAfter(recent: readonly RecentRequest[], ended: RecentRequest): RecentRequest[];
|
|
40
59
|
/** A request priced under `mode`: `cost(output)`, what it is held at (its expected input, never more than uncached), and
|
|
41
60
|
* `worst(output)`, its input uncached; each with its hosted tools' most fee. */
|
|
42
|
-
export declare function requestPrice(pricing: Pricing, bound: number,
|
|
61
|
+
export declare function requestPrice(pricing: Pricing, bound: number, recent: readonly RecentRequest[] | undefined, now: number, mode: CapMode, model: string, feeUsd?: number): {
|
|
43
62
|
cost(output: number): number;
|
|
44
63
|
worst(output: number): number;
|
|
45
64
|
};
|
package/dist/kernel/cap/price.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// The kernel cap's one pricing rule, the same for every harness. A request's input bound (its measured bytes, what its
|
|
2
2
|
// provider adds, what its hosted tools read) is priced at the dearer of the input and cache-write prices; under "expected"
|
|
3
|
-
// the
|
|
4
|
-
//
|
|
5
|
-
//
|
|
3
|
+
// the cache of one of the session's recent requests (warmFrom) counts at the cache-read price, so only a cache miss can
|
|
4
|
+
// pass the cap, by at most the request's bound; under "strict" every token uncached. Its output is held at what it is
|
|
5
|
+
// sent with, its thinking budget included.
|
|
6
6
|
import { providerInputOverhead } from "../../host/overhead.js";
|
|
7
7
|
/** How long after a request ended the next one in its conversation is expected to read its cache: 4 minutes, inside
|
|
8
8
|
* Anthropic's 5. */
|
|
@@ -44,36 +44,56 @@ export function pricingOf(price) {
|
|
|
44
44
|
return (parts.cached * read + parts.fresh * fresh + output * rates.output) / 1e6;
|
|
45
45
|
};
|
|
46
46
|
}
|
|
47
|
-
/**
|
|
48
|
-
*
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
47
|
+
/** How many of a session's recent requests it keeps (recentAfter), the newest: enough for a conversation's last request
|
|
48
|
+
* to outlast the smaller requests a CLI sends between two of its own. Fewer only prices a request colder, never under. */
|
|
49
|
+
export const RECENT_REQUESTS_KEPT = 16;
|
|
50
|
+
/** The recent request whose cache a request of `bound` tokens on `model` is expected to read at `now`: of `recent`, those
|
|
51
|
+
* on its model that ended under CACHE_WARM_MS ago (by a clock that does not read before their end) with a bound no bigger
|
|
52
|
+
* than its own (a conversation only grows between its own requests), the biggest, the newest of equal ones. So a smaller
|
|
53
|
+
* request between two of a conversation's own (a CLI's side request while a tool runs, a child's, a summary) leaves the
|
|
54
|
+
* conversation's next request warm from its last, and a conversation that compacted is warm again from its first request
|
|
55
|
+
* after the compaction. None: priced uncached. */
|
|
56
|
+
export function warmFrom(bound, recent, now, model) {
|
|
57
|
+
let best;
|
|
58
|
+
for (const one of recent ?? []) {
|
|
59
|
+
const gap = now - one.endedAt;
|
|
60
|
+
if (one.model !== model || !(gap >= 0 && gap < CACHE_WARM_MS) || !(one.boundTokens <= bound))
|
|
61
|
+
continue;
|
|
62
|
+
if (!best || one.boundTokens > best.boundTokens || (one.boundTokens === best.boundTokens && one.endedAt >= best.endedAt))
|
|
63
|
+
best = one;
|
|
64
|
+
}
|
|
65
|
+
return best;
|
|
61
66
|
}
|
|
62
|
-
/** The
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
67
|
+
/** The input of a request of `bound` tokens on `model` expected at `now` after `recent`: the cache of the request warmFrom
|
|
68
|
+
* picks at the cache-read price, and that request's input after the cache plus what the body grew by since at full
|
|
69
|
+
* price. Undefined (all of it uncached) when it picks none.
|
|
70
|
+
*
|
|
71
|
+
* Why a warm price opens no way past the cap. It is a guess: the request picked may be another conversation's whose
|
|
72
|
+
* bound happened to fit, or its cache may be gone. The guess lowers only what the request is held at (requestPrice's
|
|
73
|
+
* cost, never above its worst), never its worst: the whole bound uncached at the dearer of the input and cache-write
|
|
74
|
+
* prices whichever request was picked, the output limited to what it was admitted at. So a request's real cost is at
|
|
75
|
+
* most its hold plus its bound (Judged.boundUsd): a guess too low adds that much at most, the cache miss "expected" has
|
|
76
|
+
* always allowed and serve reports as the run's overshoot bound. The bound is counted wherever the run's room is read
|
|
77
|
+
* while the request is out (the wrap-up's gate and note count it at hold + bound, sessionSpendOf; a claim lost with it
|
|
78
|
+
* open books it cut at both); a CLI's own request admitted with its host's keep-back is limited so its worst leaves the
|
|
79
|
+
* keep-back free (rule.ts judgeModel), so even a miss stays under the cap; and once a request answers, its real cost
|
|
80
|
+
* is booked and the next admission reads it. "strict" reads no cache: every request held at its worst. */
|
|
81
|
+
export function expectedInput(bound, recent, now, model) {
|
|
82
|
+
const from = warmFrom(bound, recent, now, model);
|
|
83
|
+
return from && { cached: from.cachedTokens, fresh: from.inputTokens + (bound - from.boundTokens) };
|
|
84
|
+
}
|
|
85
|
+
/** The session's recent requests once `ended` has answered: `ended`, and those that ended under CACHE_WARM_MS before it
|
|
86
|
+
* but one on its model, measured its way and of its bound (`ended` is the newer of the two); the newest
|
|
87
|
+
* RECENT_REQUESTS_KEPT. None is dropped for being smaller or bigger than `ended`: warmFrom picks for each request. */
|
|
88
|
+
export function recentAfter(recent, ended) {
|
|
89
|
+
const same = (one) => one.model === ended.model && (one.counted === true) === (ended.counted === true) && one.boundTokens === ended.boundTokens;
|
|
90
|
+
return [...recent.filter((one) => ended.endedAt - one.endedAt < CACHE_WARM_MS && !same(one)), ended].slice(-RECENT_REQUESTS_KEPT);
|
|
71
91
|
}
|
|
72
92
|
/** A request priced under `mode`: `cost(output)`, what it is held at (its expected input, never more than uncached), and
|
|
73
93
|
* `worst(output)`, its input uncached; each with its hosted tools' most fee. */
|
|
74
|
-
export function requestPrice(pricing, bound,
|
|
94
|
+
export function requestPrice(pricing, bound, recent, now, mode, model, feeUsd = 0) {
|
|
75
95
|
const worst = (output) => pricing({ cached: 0, fresh: bound }, output) + feeUsd;
|
|
76
|
-
const parts = mode === "strict" ? undefined : expectedInput(bound,
|
|
96
|
+
const parts = mode === "strict" ? undefined : expectedInput(bound, recent, now, model);
|
|
77
97
|
if (!parts)
|
|
78
98
|
return { cost: worst, worst };
|
|
79
99
|
return { cost: (output) => Math.min(pricing(parts, output) + feeUsd, worst(output)), worst };
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import type { CapMode, ModelCapRequest, ToolCapRequest } from "./types.js";
|
|
2
2
|
/** What a judgement reads: the cap (read before this check), the run's spend (null: unknown) and its holds (null:
|
|
3
|
-
* unknown).
|
|
3
|
+
* unknown). `keepUsd`: what the host keeps back beside a model request for the steps it may still ask for while it
|
|
4
|
+
* streams (serve's wrap-up reserve: one typical step and one least answer); judgeModel says how it limits the output. */
|
|
4
5
|
export type JudgeState = {
|
|
5
6
|
capUsd: number;
|
|
6
7
|
spentUsd: number | null;
|
|
7
8
|
heldUsd: number | null;
|
|
8
9
|
mode: CapMode;
|
|
9
10
|
now: number;
|
|
11
|
+
keepUsd?: number;
|
|
10
12
|
};
|
|
11
13
|
/** A money figure the cap can count: a finite number of 0 or more. Anything else (null, NaN, Infinity, below 0) is
|
|
12
14
|
* unknown: it never reads as $0 and never frees room. */
|
package/dist/kernel/cap/rule.js
CHANGED
|
@@ -17,10 +17,10 @@ export function priced(request, mode, now) {
|
|
|
17
17
|
if (bound === undefined || price === null)
|
|
18
18
|
return undefined;
|
|
19
19
|
const asked = outputAsked(request);
|
|
20
|
-
const { cost, worst } = requestPrice(pricingOf(price), bound, request.
|
|
20
|
+
const { cost, worst } = requestPrice(pricingOf(price), bound, request.recent, now, mode, request.model.id, request.feeUsd ?? 0);
|
|
21
21
|
return { asked, cost, worst, least: asked === undefined ? 0 : outputLeast(request, asked) };
|
|
22
22
|
}
|
|
23
|
-
function judgeModel(request, { capUsd, spentUsd: spent, heldUsd: held, mode, now }) {
|
|
23
|
+
function judgeModel(request, { capUsd, spentUsd: spent, heldUsd: held, mode, now, keepUsd }) {
|
|
24
24
|
if (inputBound(request) === undefined)
|
|
25
25
|
throw new CapRefused(unmeasured(capUsd), { forGood: true, spentUsd: spent });
|
|
26
26
|
const price = request.model.price;
|
|
@@ -29,7 +29,25 @@ function judgeModel(request, { capUsd, spentUsd: spent, heldUsd: held, mode, now
|
|
|
29
29
|
if (request.model.outputCeiling === null && price.output > 0)
|
|
30
30
|
throw new CapRefused(noCeiling(capUsd), { forGood: true, spentUsd: spent });
|
|
31
31
|
const p = priced(request, mode, now);
|
|
32
|
-
const
|
|
32
|
+
const left = capUsd - spent - held;
|
|
33
|
+
// The output it is sent with. With a keep-back from its host, first the most whose WORST case (its hold and the cache
|
|
34
|
+
// miss its bound covers, as a request in flight counts in the run's records) leaves `keepUsd` free: a tool call the
|
|
35
|
+
// request makes while it streams then finds room for the steps after it (serve's wrap-up, which counts the request
|
|
36
|
+
// at its worst until it is booked). When even its least and the keep-back do not fit, the run is wrapping up and this
|
|
37
|
+
// request may be its answer: it gets the most what is left buys, as with no keep-back.
|
|
38
|
+
// Why the cap still holds: the first branch only lowers the output, never below the least: cost(out) <= worst(out) <=
|
|
39
|
+
// left - keepUsd <= left. The second is the rule as it was. So every hold is at most what is left, as before; the
|
|
40
|
+
// hold, its bound, what a stop counts and what is booked are priced by the same p at the output sent, unchanged.
|
|
41
|
+
// (The keep-back is kept with a float's tail to spare, so the host's sum of the same figures never reads it as passed.)
|
|
42
|
+
// When the warm guess is wrong (expected mode prices the bound's head as cached from a recent request, and the cache
|
|
43
|
+
// is gone): the hold is too low, and three things still bound the spend. The output is limited to what is sent
|
|
44
|
+
// here, so the request's real cost is at most its worst: its whole bound uncached at the dearer input price plus
|
|
45
|
+
// that output. The first branch admits only a worst that leaves the keep-back free, so a full miss still lands under
|
|
46
|
+
// the cap. Its real cost is then booked at the turn, so the next request is judged on what this one cost, never on
|
|
47
|
+
// its hold. Only the second branch (no keep-back, or a run wrapping up) admits on the hold, and there a miss passes
|
|
48
|
+
// the cap by at most its bound, the overshoot expected mode states; strict mode reads no cache and has none.
|
|
49
|
+
const kept = isFigure(keepUsd) && keepUsd > 0 ? mostOutput(p.worst, p.least, p.asked ?? 0, left - keepUsd - 2 * FIT_TOLERANCE) : undefined;
|
|
50
|
+
const output = kept ?? mostOutput(p.cost, p.least, p.asked ?? 0, left);
|
|
33
51
|
if (output === undefined) {
|
|
34
52
|
const { text, figures } = roomRefusal(capUsd, spent, held, p.cost(p.least), p.worst(p.least) - p.cost(p.least));
|
|
35
53
|
throw new CapRefused(text, { forGood: false, spentUsd: spent, figures });
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { type RunSessions } from "../../run-booking.js";
|
|
2
2
|
import { type BeforeRequest } from "../../runner.js";
|
|
3
3
|
import type { SessionRecord, SessionWriter } from "../../types.js";
|
|
4
|
-
import
|
|
4
|
+
import { type PricedRequest } from "./port.js";
|
|
5
|
+
import type { Admission, CapMode, CapModel, DecisionCapRequest, ModelCapRequest, RecentRequest, Settled } from "./types.js";
|
|
5
6
|
/** The session a run's workflow decisions book under. */
|
|
6
7
|
export declare const DECISION_SESSION = "decisions";
|
|
7
8
|
export interface RunCapOptions {
|
|
@@ -13,10 +14,13 @@ export interface RunCapOptions {
|
|
|
13
14
|
readonly now?: () => number;
|
|
14
15
|
/** The run's model requests' models, by id and route (BeforeRequestOptions.modelOf; its decisions' are the cap's own). */
|
|
15
16
|
modelOf(id: string, route?: string): CapModel | undefined;
|
|
16
|
-
|
|
17
|
+
/** The session's recent requests, by the id their model is priced under (BeforeRequestOptions.recentOf). */
|
|
18
|
+
recentOf?(model: string): readonly RecentRequest[];
|
|
17
19
|
/** The run's priced tools' charges and holds beside its requests (beforeRequestOf's), when it has any. */
|
|
18
20
|
spentUsd?(): number | null;
|
|
19
21
|
heldUsd?(): number | null;
|
|
22
|
+
/** What the host keeps back beside a model request while it streams (BeforeRequestOptions.keepBackUsd). */
|
|
23
|
+
keepBackUsd?(request: Parameters<BeforeRequest>[0], asked: ModelCapRequest): number | undefined;
|
|
20
24
|
/** Told each request the rule judged, with the run's totals it was asked with, and its answer (an observer: a live
|
|
21
25
|
* view of the cap, a test's record). */
|
|
22
26
|
judged?(request: Parameters<BeforeRequest>[0], answer: Awaited<ReturnType<BeforeRequest>>): void;
|
|
@@ -35,6 +39,9 @@ export interface RunDecisions {
|
|
|
35
39
|
export interface RunCap {
|
|
36
40
|
/** The run's one rule for every model request (a model booking's beforeRequest), its decisions' models known to it. */
|
|
37
41
|
readonly before: BeforeRequest;
|
|
42
|
+
/** A model request as `before` prices it (port.ts capRequestOf, with the same models and the session's recent
|
|
43
|
+
* requests): what the wrap-up's note and the reserve (requestFigures) price, so they read a warm cache as admission does. */
|
|
44
|
+
asked(request: PricedRequest): ModelCapRequest;
|
|
38
45
|
/** The run's decisions, booked on `writer` (the run's DECISION_SESSION) under the same rule. `flush`: makes what the
|
|
39
46
|
* journal holds survive a lost box, awaited once a decision's hold is written and before it is sent, as a model
|
|
40
47
|
* request's is (request_start), so a decision sent and then lost with its box still counts after the next claim. */
|
|
@@ -10,7 +10,7 @@ import { modelPortFor, RUNNER_RECORDS, sessionSpendOf } from "../../runner.js";
|
|
|
10
10
|
import { overCapEnd } from "./words.js";
|
|
11
11
|
import { decisionAsk } from "./admit.js";
|
|
12
12
|
import { CapRefused, DecisionPriceUnreadable } from "./errors.js";
|
|
13
|
-
import { beforeRequestOf } from "./port.js";
|
|
13
|
+
import { beforeRequestOf, capRequestOf } from "./port.js";
|
|
14
14
|
/** The session a run's workflow decisions book under. */
|
|
15
15
|
export const DECISION_SESSION = "decisions";
|
|
16
16
|
/** The session a run's paid tool calls book under. */
|
|
@@ -36,14 +36,18 @@ export function runCap(options) {
|
|
|
36
36
|
const mode = options.mode ?? "expected";
|
|
37
37
|
/** Each decision under way's model, as the rule prices it (decisionAsk), by the model key its request books under. */
|
|
38
38
|
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
|
+
};
|
|
39
43
|
const rule = beforeRequestOf({
|
|
40
44
|
capUsd: options.capUsd,
|
|
41
45
|
mode,
|
|
42
46
|
...(options.now ? { now: options.now } : {}),
|
|
43
|
-
|
|
44
|
-
...(options.previousOf ? { previousOf: (model) => (deciding.has(model) ? undefined : options.previousOf(model)) } : {}),
|
|
47
|
+
...pricing,
|
|
45
48
|
...(options.spentUsd ? { spentUsd: options.spentUsd } : {}),
|
|
46
49
|
...(options.heldUsd ? { heldUsd: options.heldUsd } : {}),
|
|
50
|
+
...(options.keepBackUsd ? { keepBackUsd: options.keepBackUsd } : {}),
|
|
47
51
|
});
|
|
48
52
|
const before = runBooking(options.sessions, options.judged ? async (request) => {
|
|
49
53
|
const answer = await rule(request);
|
|
@@ -53,6 +57,7 @@ export function runCap(options) {
|
|
|
53
57
|
const forget = (key) => void deciding.delete(key);
|
|
54
58
|
return {
|
|
55
59
|
before,
|
|
60
|
+
asked: (request) => capRequestOf("asked", request, pricing),
|
|
56
61
|
async decisions(writer, decisionOptions = {}) {
|
|
57
62
|
const steps = await stepsOn(writer, before, decisionOptions.flush, "decision", forget);
|
|
58
63
|
return {
|
|
@@ -27,9 +27,11 @@ export interface CapModel {
|
|
|
27
27
|
readonly outputCeiling: number | null;
|
|
28
28
|
readonly reasoning?: boolean;
|
|
29
29
|
}
|
|
30
|
-
/**
|
|
31
|
-
* the cache, the rest, its input bound (the unit
|
|
32
|
-
|
|
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. */
|
|
33
35
|
readonly model: string;
|
|
34
36
|
readonly cachedTokens: number;
|
|
35
37
|
readonly inputTokens: number;
|
|
@@ -59,7 +61,9 @@ export interface ModelCapRequest {
|
|
|
59
61
|
readonly outputTokensLeast?: number;
|
|
60
62
|
/** Its thinking budget, on an API whose thinking takes one beside the answer's output. */
|
|
61
63
|
readonly thinkingBudget?: number;
|
|
62
|
-
|
|
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[];
|
|
63
67
|
/** A side call (a title, a summary), never its turn's own. */
|
|
64
68
|
readonly side?: boolean;
|
|
65
69
|
/** It carries the cap's wrap-up note (Cap.note) in its body, its bytes in `inputTokens`: told once it is answered. */
|
|
@@ -138,7 +142,7 @@ export interface CapOptions {
|
|
|
138
142
|
/** How long settle waits for a step's end mark before it fails loudly. Default 10 s. */
|
|
139
143
|
endMarkWaitMs?: number;
|
|
140
144
|
}
|
|
141
|
-
/** How the cap prices a request's input: "expected" from
|
|
145
|
+
/** How the cap prices a request's input: "expected" from a recent request's cache; "strict" every token uncached. */
|
|
142
146
|
export type CapMode = "expected" | "strict";
|
|
143
147
|
export interface Cap {
|
|
144
148
|
admit(request: CapRequest): Promise<Admission>;
|
|
@@ -6,7 +6,7 @@ export const COMPUTER_TOOL_SCHEMAS = {
|
|
|
6
6
|
"type": "object",
|
|
7
7
|
"properties": {
|
|
8
8
|
"app": {
|
|
9
|
-
"description": "Default: the app in front.",
|
|
9
|
+
"description": "Default: the app in front. With no ui group, opened or brought in front first.",
|
|
10
10
|
"type": "string"
|
|
11
11
|
},
|
|
12
12
|
"image": {
|
|
@@ -24,7 +24,7 @@ export const COMPUTER_TOOL_SCHEMAS = {
|
|
|
24
24
|
"type": "object",
|
|
25
25
|
"properties": {
|
|
26
26
|
"app": {
|
|
27
|
-
"description": "Default: the state's app, else the app in front.",
|
|
27
|
+
"description": "Default: the state's app, else the app in front. With no ui group, opened or brought in front first.",
|
|
28
28
|
"type": "string"
|
|
29
29
|
},
|
|
30
30
|
"state": {
|
|
@@ -577,6 +577,13 @@ const MEMBERS = [
|
|
|
577
577
|
],
|
|
578
578
|
"text": "readonly shell: { run(command: string | string[], options?: { cwd?: string; timeoutMs?: number; env?: Record<string, string>; }): Promise<RunResult>; };"
|
|
579
579
|
},
|
|
580
|
+
{
|
|
581
|
+
"groups": [
|
|
582
|
+
"processes"
|
|
583
|
+
],
|
|
584
|
+
"uses": [],
|
|
585
|
+
"text": "readonly processes: { start(command: string | string[], options?: { cwd?: string; env?: Record<string, string>; }): Promise<{ pid: number; }>; };"
|
|
586
|
+
},
|
|
580
587
|
{
|
|
581
588
|
"groups": [
|
|
582
589
|
"files"
|
|
@@ -21,21 +21,29 @@ export function computerToolsFor(groups) {
|
|
|
21
21
|
const act = has("ui") || input;
|
|
22
22
|
return [...(observe ? ["computer_observe"] : []), ...(act ? ["computer_act"] : []), ...(has("screen") ? ["computer_screenshot"] : []), ...(observe || act ? [SCRIPT_TOOL] : []), HANDOFF_TOOL];
|
|
23
23
|
}
|
|
24
|
-
|
|
24
|
+
/** computer_act's parameters on a computer with no ui group: no expect, which only the ui group checks, so neither the
|
|
25
|
+
* expect nor the wait on one (an empty act with an expect) is offered there. */
|
|
26
|
+
const ACT_WITHOUT_UI = (() => {
|
|
27
|
+
const schema = COMPUTER_TOOL_SCHEMAS.computer_act;
|
|
28
|
+
const { expect: _, ...properties } = schema.properties;
|
|
29
|
+
return { ...schema, properties: { ...properties, steps: { ...properties.steps, description: "Run in order." } } };
|
|
30
|
+
})();
|
|
31
|
+
const def = (kind, name, description, replaySafe, parameters = COMPUTER_TOOL_SCHEMAS[name]) => ({
|
|
25
32
|
name,
|
|
26
33
|
source: "host",
|
|
27
34
|
gateName: `host:${kind}/${name}`,
|
|
28
35
|
settingsKey: kind,
|
|
29
36
|
description,
|
|
30
|
-
parameters
|
|
37
|
+
parameters,
|
|
31
38
|
replaySafe,
|
|
32
39
|
});
|
|
33
40
|
/** The computer's tools in `kind`, under its settings key, for a computer with `groups` (the script's declarations
|
|
34
41
|
* hold only what they offer). A script and an act change the computer: never replayed. */
|
|
35
42
|
export function computerToolDefs(kind, groups) {
|
|
36
43
|
return Object.freeze([
|
|
37
|
-
|
|
38
|
-
def(kind, "
|
|
44
|
+
// With apps and no ui group, an observe that names an app opens it first: it changes the screen, so it never runs again.
|
|
45
|
+
def(kind, "computer_observe", OBSERVE, groups.includes("ui") || !groups.includes("apps")),
|
|
46
|
+
def(kind, "computer_act", ACT, false, groups.includes("ui") ? undefined : ACT_WITHOUT_UI),
|
|
39
47
|
def(kind, "computer_screenshot", SCREENSHOT, true),
|
|
40
48
|
def(kind, "computer_script", scriptWords(groups), false),
|
|
41
49
|
handoffDef(kind),
|
|
@@ -71,7 +71,7 @@ export type ComputerAnswer = {
|
|
|
71
71
|
readonly images: readonly ToolImage[];
|
|
72
72
|
};
|
|
73
73
|
/** The run's computer as its tools reach it: its groups (its hello's), and one call per op (observe, act, screenshot,
|
|
74
|
-
* input.act, apps.list, apps.open, shell.run, files.read, files.write, files.list, files.stat), which
|
|
74
|
+
* input.act, apps.list, apps.open, shell.run, processes.start, files.read, files.write, files.list, files.stat), which
|
|
75
75
|
* @parcha/agentrun-computer's surface answers the same for a per-step tool, a script and the claim's MCP endpoint. A
|
|
76
76
|
* refusal throws an error with a `kind` (stale, unsupported, ...) and the computer's words; an abort throws. */
|
|
77
77
|
export type ComputerPort = {
|
package/dist/kernel/types.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { JsonValue, SessionWriter, ToolImage } from "../types.js";
|
|
1
|
+
import type { JsonValue, NestedCalls, SessionWriter, ToolImage } from "../types.js";
|
|
2
2
|
export type ReplayPolicy = "safe" | "never";
|
|
3
3
|
export type SubmissionKind = "prompt" | "steer" | "followUp" | "withdraw";
|
|
4
4
|
/** One input a person sent the session, as the host recorded it. */
|
|
@@ -104,6 +104,11 @@ export interface HostTool<Input = any> {
|
|
|
104
104
|
description: string;
|
|
105
105
|
inputSchema: object;
|
|
106
106
|
replay: ReplayPolicy;
|
|
107
|
+
/** It only calls the session's other tools, each a call of its own (HostToolIO `nested`): the bridge writes no effect
|
|
108
|
+
* of its own for it, so a crash leaves it to run again, its nested calls answered from their records. */
|
|
109
|
+
nests?: true;
|
|
110
|
+
/** Callable by name (a nested call) but never listed to the model (the bridge leaves it out of `tools`). */
|
|
111
|
+
deferred?: true;
|
|
107
112
|
/** Its answer: the text, or the text with the images it shows. Recorded as the call's outcome, so a call answered
|
|
108
113
|
* from the record answers with the same images. */
|
|
109
114
|
execute(input: Input, io: HostToolIO): Promise<string | ToolOutput>;
|
|
@@ -119,5 +124,7 @@ export interface HostToolIO {
|
|
|
119
124
|
progress(chunk: unknown): void;
|
|
120
125
|
ctx: DriveContext;
|
|
121
126
|
stepId?: string;
|
|
127
|
+
/** For a tool that `nests`: the session's other tools by their names on the bridge, each call one of its own. */
|
|
128
|
+
nested?: NestedCalls;
|
|
122
129
|
}
|
|
123
130
|
export type { JsonValue };
|
package/dist/process/tools.d.ts
CHANGED
|
@@ -30,6 +30,8 @@ export interface ToolResult {
|
|
|
30
30
|
structured?: JsonValue;
|
|
31
31
|
/** The text was cut at HOST_RESULT_MAX_CHARS (`boundResult`); it says so in its last line. */
|
|
32
32
|
truncated?: true;
|
|
33
|
+
/** The gate refused the call: the text is its words, and nothing of the call was written or run. */
|
|
34
|
+
refused?: true;
|
|
33
35
|
}
|
|
34
36
|
/** One tool, harness-neutral. */
|
|
35
37
|
export interface BridgedTool {
|
package/dist/process/tools.js
CHANGED
|
@@ -51,24 +51,44 @@ export function toolBridge(ctx, tools, options = {}) {
|
|
|
51
51
|
const mutex = new Mutex();
|
|
52
52
|
const serial = options.serial ?? true;
|
|
53
53
|
const live = options.live ?? true;
|
|
54
|
+
// Each tool's run by name, outside the mutex: a nested call runs inside the call that made it, which holds the mutex.
|
|
55
|
+
const runs = new Map();
|
|
56
|
+
/** The session's tools as calls nested in `outer` (NestedCalls): each through its own run, gate first, keyed
|
|
57
|
+
* `tool:<outer>/<key>`, so a rerun of `outer` gets a recorded one's answer and never runs it twice. */
|
|
58
|
+
const nestedIn = (outer, signal) => ({
|
|
59
|
+
async call(name, args, key) {
|
|
60
|
+
const run = runs.get(name);
|
|
61
|
+
if (!run)
|
|
62
|
+
return { text: `unknown tool: ${name}`, isError: true, refused: true, fresh: true };
|
|
63
|
+
const callId = `${outer}/${key}`;
|
|
64
|
+
const fresh = !ctx.isMemoized(toolKey(callId));
|
|
65
|
+
const { interrupted, ...result } = await run(args, callId, signal, true);
|
|
66
|
+
return { ...result, ...(interrupted ? { interrupted: true } : {}), fresh };
|
|
67
|
+
},
|
|
68
|
+
// A value the call's first run fixed, as a replay-safe effect of its own: its rerun reads the first one.
|
|
69
|
+
memo: (key, value) => ctx.effect(`nested:${outer}/${key}`, { name: 'nested.memo', replay: 'safe', input: null }, async () => value),
|
|
70
|
+
});
|
|
54
71
|
const bridged = tools.map((tool) => {
|
|
55
|
-
const run = async (args, callId, signal) => {
|
|
72
|
+
const run = async (args, callId, signal, nested) => {
|
|
56
73
|
if (!callId)
|
|
57
74
|
throw new TypeError(`agentrun-kernel: a call to ${tool.name} has no call id; derive a stable one`);
|
|
58
75
|
const key = toolKey(callId);
|
|
76
|
+
// A tool that only nests calls writes nothing of its own: it runs, each nested call recorded as itself.
|
|
77
|
+
if (tool.nests)
|
|
78
|
+
return runNesting(args, callId, signal, nested);
|
|
59
79
|
const fresh = !ctx.isMemoized(key);
|
|
60
80
|
// The gate first: before the flush and the intent, so a refused or parked call leaves nothing in the log.
|
|
61
81
|
if (fresh && options.gate) {
|
|
62
82
|
// 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
83
|
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);
|
|
84
|
+
const refused = await askGate(options.gate, { callId, tool: tool.name, args: (args ?? {}), ...(replayed ? { replayed: true } : {}), ...(nested ? { nested } : {}) }, signal ? AbortSignal.any([signal, ctx.signal]) : ctx.signal);
|
|
65
85
|
if (refused)
|
|
66
|
-
return { text: refused.deny, isError: true };
|
|
86
|
+
return { text: refused.deny, isError: true, refused: true };
|
|
67
87
|
}
|
|
68
88
|
if (fresh && tool.replay === 'never')
|
|
69
89
|
await options.beforeNever?.({ name: tool.name, callId, args });
|
|
70
90
|
if (fresh && live)
|
|
71
|
-
ctx.live({ type: 'tool_start', name: tool.name, args, callId });
|
|
91
|
+
ctx.live({ type: 'tool_start', name: tool.name, args, callId, ...(nested ? { parent: callId.slice(0, callId.lastIndexOf('/')) } : {}) });
|
|
72
92
|
try {
|
|
73
93
|
const output = await ctx.effect(key, {
|
|
74
94
|
name: `tool.${tool.name}`,
|
|
@@ -93,6 +113,39 @@ export function toolBridge(ctx, tools, options = {}) {
|
|
|
93
113
|
throw err;
|
|
94
114
|
}
|
|
95
115
|
};
|
|
116
|
+
/** A tool that `nests`: asked at the gate as itself, then run with the session's tools as its nested calls, no effect
|
|
117
|
+
* of its own written. Its error result is its answer; a throw while the drive or the call is aborted (a nested call
|
|
118
|
+
* parked, the session let go) halts the drive, as an effect's does, so the harness is never handed a result. */
|
|
119
|
+
const runNesting = async (args, callId, signal, nested) => {
|
|
120
|
+
const aborted = signal ? AbortSignal.any([signal, ctx.signal]) : ctx.signal;
|
|
121
|
+
if (options.gate) {
|
|
122
|
+
const refused = await askGate(options.gate, { callId, tool: tool.name, args: (args ?? {}), ...(nested ? { nested } : {}) }, aborted);
|
|
123
|
+
if (refused)
|
|
124
|
+
return { text: refused.deny, isError: true, refused: true };
|
|
125
|
+
}
|
|
126
|
+
if (live)
|
|
127
|
+
ctx.live({ type: 'tool_start', name: tool.name, args, callId });
|
|
128
|
+
let output;
|
|
129
|
+
try {
|
|
130
|
+
output = await tool.execute(args, { signal: aborted, progress: () => { }, ctx, stepId: `${toolKey(callId)}#0`, nested: nestedIn(callId, aborted) });
|
|
131
|
+
}
|
|
132
|
+
catch (err) {
|
|
133
|
+
if (aborted.aborted) {
|
|
134
|
+
ctx.halt?.(err);
|
|
135
|
+
throw err;
|
|
136
|
+
}
|
|
137
|
+
const { text, truncated } = boundResult(err instanceof Error ? err.message : String(err));
|
|
138
|
+
if (live)
|
|
139
|
+
ctx.live({ type: 'tool_end', name: tool.name, callId, isError: true, result: text, ...(truncated ? { truncated } : {}) });
|
|
140
|
+
return { text, isError: true, ...(truncated ? { truncated } : {}) };
|
|
141
|
+
}
|
|
142
|
+
const { text: whole, images, structured } = typeof output === 'object' && output !== null ? output : { text: String(output), images: undefined, structured: undefined };
|
|
143
|
+
const { text, truncated } = boundResult(String(whole));
|
|
144
|
+
if (live)
|
|
145
|
+
ctx.live({ type: 'tool_end', name: tool.name, callId, result: text, ...(truncated ? { truncated } : {}) });
|
|
146
|
+
return { text, isError: false, ...(images?.length ? { images } : {}), ...(structured !== undefined ? { structured } : {}), ...(truncated ? { truncated } : {}) };
|
|
147
|
+
};
|
|
148
|
+
runs.set(tool.name, run);
|
|
96
149
|
return {
|
|
97
150
|
name: tool.name,
|
|
98
151
|
description: tool.description,
|
|
@@ -103,7 +156,8 @@ export function toolBridge(ctx, tools, options = {}) {
|
|
|
103
156
|
});
|
|
104
157
|
const byName = new Map(bridged.map((t) => [t.name, t]));
|
|
105
158
|
return {
|
|
106
|
-
|
|
159
|
+
// What is listed to the model: a deferred tool is run by name (a nested call, `get`, `call`) and never listed.
|
|
160
|
+
tools: bridged.filter((_, index) => !tools[index].deferred),
|
|
107
161
|
get: (name) => byName.get(name),
|
|
108
162
|
call: async (name, args, callId, signal) => {
|
|
109
163
|
const tool = byName.get(name);
|