@parcha/agentrun-kernel 0.1.0-beta.35 → 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.
- package/CHANGELOG.md +7 -0
- package/README.md +0 -7
- package/dist/host/box.d.ts +0 -14
- package/dist/host/index.d.ts +1 -1
- package/dist/host/proxy.js +14 -1
- package/dist/index.d.ts +0 -2
- package/dist/index.js +0 -1
- package/dist/kernel/cap/index.d.ts +1 -1
- package/dist/kernel/cap/index.js +1 -1
- package/dist/kernel/cap/words.d.ts +3 -0
- package/dist/kernel/cap/words.js +4 -1
- package/dist/kernel/index.d.ts +0 -2
- package/dist/kernel/index.js +0 -1
- package/dist/kernel/registry/index.d.ts +1 -1
- package/dist/kernel/registry/index.js +1 -1
- package/dist/kernel/registry/limits.d.ts +0 -1
- package/dist/kernel/registry/limits.js +0 -1
- package/dist/process/records.d.ts +0 -16
- package/dist/process/records.js +0 -41
- package/dist/process/settle.d.ts +1 -1
- package/dist/process/settle.js +2 -2
- package/dist/process/zod.d.ts +0 -2
- package/dist/process/zod.js +0 -4
- package/dist/testing.d.ts +9 -4
- package/dist/testing.js +22 -16
- package/dist/types.d.ts +2 -3
- package/package.json +2 -2
- package/dist/delegate.d.ts +0 -87
- package/dist/delegate.js +0 -143
- package/dist/kernel/follow-up.d.ts +0 -67
- package/dist/kernel/follow-up.js +0 -146
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.36 (2026-11-13)
|
|
6
|
+
|
|
7
|
+
- The kernel and the Claude Agent test kit drop exports nothing in AgentRun used. From `@parcha/agentrun-kernel`: the `delegate` tool (`delegateTool`, `DELEGATE_TOOL`, `DELEGATE_RESULT_SCHEMA`, `delegateProblems` and the `DelegateAgent`, `DelegateEvent` and `DelegateOptions` types). From `./kernel`: the follow-up turn (`followUpOnce`, `followUpState`, `followUpKey`, `FOLLOW_UP_EFFECT`, `FOLLOW_UP_BUDGET_REACHED`, `FOLLOW_UP_CANCELLED` and their types) and `BASH_MAX_TIMEOUT_S`. From `./process`: `lastTurnEnd`, `summarizeBatch`, `batchTranscript` and `zodFromJsonSchema`. From `@parcha/agentrun-harness-claude/testing`: `lastUserText`. An embedder that imported one of them keeps its own copy: each was a small helper, or a feature the server never wired (a follow-up turn, a delegate tool). `zodShapeFromJsonSchema` stays.
|
|
8
|
+
- `@parcha/agentrun-kernel/host` no longer exports the types `BoxRecorder` and `Reaped`; nothing in the repo used them. A host that imported either declares its own shape.
|
|
9
|
+
- A run's spend-cap pause no longer says it spent "$0" when it spent less than a cent. The words round what was spent to the cent, so a run that had spent $0.003 read "this run has spent $0 of its $0.105 cap", as if nothing had been spent. A spend above $0 that rounds to $0 now reads "less than a cent" ("this run has spent less than a cent of its $0.105 cap"). A spend of exactly $0, and any spend of a cent or more, reads as before. The exact amount stays in the pause's `spent_usd`.
|
|
10
|
+
- A model request a provider refuses for a while (a 429 at capacity, an overload, a 5xx) no longer ends the run after pi's default three retries of about 17 seconds. The adapter loop gives pi 8 retries, 2s doubling to at most 30s apart (about two and a half minutes), and pi-ai retries a request refused before any output twice more inside each attempt, after the wait the provider asked for: the session's model proxy now passes an error answer's `retry-after`, `retry-after-ms` and `x-should-retry` on to the client. Each retry is a new request the run's cap judges and books: a refused one books nothing, and one that finds no room under the cap parks the run in the cap's words, never retried past it.
|
|
11
|
+
|
|
5
12
|
## 0.1.0-beta.35 (2026-11-11)
|
|
6
13
|
|
|
7
14
|
- On the runner, a learned workflow node that names a tier (`fast`, `strong`) now runs on the host's model of that tier (`AGENT_MODEL_FAST`, `AGENT_MODEL_STRONG`) instead of the run's own model. Its requests take the run's one route and stay under the run's cap, and each is booked at its own model's price. A tier the host names no model of still runs on the run's own model. A tier whose model can't be reached fails the workflow call and names why; it never runs on another model. This holds on every harness: pi, Claude Agent, Codex and OpenCode. On a CLI harness the tier's requests go through a proxy of their own beside the CLI session's, never through the CLI. A tier's model key saved in Settings → Model keys is opened for that tier's requests alone. It never goes into a tool's environment. A tier whose model has the same id as the run's model is still held and booked at the tier's own price. `AdapterSession.port` and the run ledger's `models` take an optional `tier`. The kernel's `ModelRequest`, `ModelProxyOptions` and in-flight records carry an optional `route`, and the cap's `modelOf(id, route)` prices a request by model and route.
|
package/README.md
CHANGED
|
@@ -38,13 +38,6 @@ harness adapter the way they run on Pi, durable in AgentRun's own store.
|
|
|
38
38
|
- `./kernel` is the durable kernel an adapter runs on (`openDrive` over the session's writer): an effect's intent, then
|
|
39
39
|
at most one outcome; after a crash a `safe` effect runs again and a `never` one is reported interrupted, never run
|
|
40
40
|
again. So a tool that costs money per call (a paid search) is `never`: `safe` means free to run again. A drive whose writer was fenced gets a `Restart` at its next write, so it never runs a new effect.
|
|
41
|
-
`followUpOnce` sends one more turn into a session that has answered, with a prompt the host names, at most once: it
|
|
42
|
-
is a `never` effect on its own key (`followUpKey(session, name)`), so a crash inside it leaves it interrupted, and the
|
|
43
|
-
turn a crash cut off is settled (`settleOpenTurn`), never resumed. Its prompt's submission has an id of its own
|
|
44
|
-
(`follow-up:<key>`), and the settle is named only that one, so it never withdraws a person's message. Its
|
|
45
|
-
`beforeRequest` goes ahead of the host's and holds the follow-up's paid requests to `reserveUsd`, counted from its
|
|
46
|
-
first request; an unknown spend is refused.
|
|
47
|
-
`followUpState(records)` tells a host, before it resumes an open turn, whether that turn is a follow-up's.
|
|
48
41
|
`./process` is the shared layer for harnesses that run as a child process: the native journal, the transcript, the
|
|
49
42
|
recovery note, the tool bridge, the built-ins' hook-pair calls, the inbox (and `waitForSubmissions`, for a harness that
|
|
50
43
|
waits for input while a turn runs), `zodShapeFromJsonSchema`, for harness SDKs whose tool APIs take zod, and
|
package/dist/host/box.d.ts
CHANGED
|
@@ -13,20 +13,6 @@ export interface BoxRecord {
|
|
|
13
13
|
startTime: string;
|
|
14
14
|
};
|
|
15
15
|
}
|
|
16
|
-
/** Where a box's record goes. `ahead` is synchronous (the file and its directory are synced before it returns) and runs
|
|
17
|
-
* before the spawn; `started` runs while bwrap waits, and no process of the harness runs until it resolves. */
|
|
18
|
-
export interface BoxRecorder {
|
|
19
|
-
ahead(record: BoxRecord): void;
|
|
20
|
-
started(record: BoxRecord): Promise<void>;
|
|
21
|
-
}
|
|
22
|
-
/** What a reap found, by the kernel's own count: the processes left in the recorded pid namespace, or the cgroup's.
|
|
23
|
-
* `none`: the record names neither a pid nor a cgroup, so there was nothing to count (a crash before the pid was
|
|
24
|
-
* known; --die-with-parent ends such a box with its parent). */
|
|
25
|
-
export interface Reaped {
|
|
26
|
-
empty: boolean;
|
|
27
|
-
left: number;
|
|
28
|
-
by: "pidns" | "cgroup" | "none";
|
|
29
|
-
}
|
|
30
16
|
export type BoxErrorCode = "bwrap_missing" | "bwrap_setuid" | "bwrap_userns_denied" | "box_probe_failed" | "box_refused" | "box_record_failed" | "box_start_failed"
|
|
31
17
|
/** A start while the session's last box is live, being reaped, or was not confirmed empty. */
|
|
32
18
|
| "box_busy"
|
package/dist/host/index.d.ts
CHANGED
|
@@ -8,5 +8,5 @@ export { serialWriter } from "./serial.js";
|
|
|
8
8
|
export { PARENT_WATCH_SHIM, parentWatched, parentWatchHere, SETPRIV } from "./parent-death.js";
|
|
9
9
|
export type { LaunchCommand, ParentWatch } from "./parent-death.js";
|
|
10
10
|
export { BoxError } from "./box.js";
|
|
11
|
-
export type { BoxErrorCode, BoxRecord
|
|
11
|
+
export type { BoxErrorCode, BoxRecord } from "./box.js";
|
|
12
12
|
export { type BinaryCheck, type BinaryProbe, checkedOnce, checkedOnceAsync, sha256OfFile, sha256OfFileAsync } from "./pinned-binary.js";
|
package/dist/host/proxy.js
CHANGED
|
@@ -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$/;
|
|
@@ -1126,7 +1129,17 @@ export async function startModelProxy(options, key) {
|
|
|
1126
1129
|
}
|
|
1127
1130
|
began = { ok: upstream.ok, status: upstream.status };
|
|
1128
1131
|
const contentType = upstream.headers.get("content-type") ?? "application/json";
|
|
1129
|
-
|
|
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);
|
|
1130
1143
|
const decoder = new TextDecoder();
|
|
1131
1144
|
// The provider's own words in an error reach the harness with the credential this proxy sent, and the values of the
|
|
1132
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, paidRefusal, 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";
|
package/dist/kernel/cap/index.js
CHANGED
|
@@ -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, paidRefusal, 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";
|
|
@@ -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;
|
package/dist/kernel/cap/words.js
CHANGED
|
@@ -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 ${
|
|
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) {
|
package/dist/kernel/index.d.ts
CHANGED
|
@@ -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";
|
package/dist/kernel/index.js
CHANGED
|
@@ -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,
|
|
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,
|
|
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;
|
package/dist/process/records.js
CHANGED
|
@@ -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
|
package/dist/process/settle.d.ts
CHANGED
|
@@ -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 (
|
|
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
|
}
|
package/dist/process/settle.js
CHANGED
|
@@ -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
|
|
26
|
-
// as it is
|
|
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
|
package/dist/process/zod.d.ts
CHANGED
|
@@ -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 {};
|
package/dist/process/zod.js
CHANGED
|
@@ -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/testing.d.ts
CHANGED
|
@@ -20,8 +20,7 @@ export declare function memorySessionStore(): SessionStore & {
|
|
|
20
20
|
* this request still streams (after its first call's text, before that call), so two of its requests are in flight.
|
|
21
21
|
* `sideFirst`: one admitted before this request, then `say` streamed before this request is admitted: text of the
|
|
22
22
|
* session's (a resumed turn's, say) with no request of this process's own yet, and a side call's the only one open. The
|
|
23
|
-
* side call is paid at `usd` with this request (at once, or once its `bookWhen` file exists).
|
|
24
|
-
* result is told (its tool_end) only once this file exists, as a harness still recording it would. */
|
|
23
|
+
* side call is paid at `usd` with this request (at once, or once its `bookWhen` file exists). */
|
|
25
24
|
/** `onRefused: "next"`: a request its host refuses (its admission throws) is not the turn's end: the client goes on to its
|
|
26
25
|
* next action, as a CLI whose request the proxy refused sends another. */
|
|
27
26
|
export type FauxRequest = {
|
|
@@ -47,7 +46,6 @@ export type FauxRequest = {
|
|
|
47
46
|
usd: number;
|
|
48
47
|
say: string;
|
|
49
48
|
};
|
|
50
|
-
resultWhen?: string;
|
|
51
49
|
};
|
|
52
50
|
/** One model request of the faux harness, and what its reply does. */
|
|
53
51
|
export type FauxAction = ({
|
|
@@ -108,13 +106,20 @@ export type FauxAction = ({
|
|
|
108
106
|
| {
|
|
109
107
|
cutBooked: true;
|
|
110
108
|
usd?: number | null;
|
|
109
|
+
}
|
|
110
|
+
/** The model answers with this text through a route that never reaches the session's port (a CLI sending past its
|
|
111
|
+
* model proxy): its text shows, and nothing is admitted or booked. */
|
|
112
|
+
| {
|
|
113
|
+
unbooked: string;
|
|
111
114
|
};
|
|
112
115
|
/** `note`: a note its host had for the request (ModelPort.note, the spend cap's wrap-up), as a real adapter's model proxy
|
|
113
116
|
* would add it to the body: filed with its text, for a test to see. */
|
|
114
117
|
/** `answered`: a request whose reply asks for calls came back (its `until` let go), so its calls are the model's to run.
|
|
115
|
-
* `said`: a call's own text (its `say`) was streamed, so a recovered turn never says it again.
|
|
118
|
+
* `said`: a call's own text (its `say`) was streamed, so a recovered turn never says it again. `unbooked`: an answer
|
|
119
|
+
* that booked no request (FauxAction `unbooked`), its script place kept. */
|
|
116
120
|
export declare const FAUX_RECORDS: {
|
|
117
121
|
readonly request: "faux.request";
|
|
122
|
+
readonly unbooked: "faux.unbooked";
|
|
118
123
|
readonly answered: "faux.answered";
|
|
119
124
|
readonly said: "faux.said";
|
|
120
125
|
readonly user: "faux.user";
|
package/dist/testing.js
CHANGED
|
@@ -42,8 +42,9 @@ export function memorySessionStore() {
|
|
|
42
42
|
/** `note`: a note its host had for the request (ModelPort.note, the spend cap's wrap-up), as a real adapter's model proxy
|
|
43
43
|
* would add it to the body: filed with its text, for a test to see. */
|
|
44
44
|
/** `answered`: a request whose reply asks for calls came back (its `until` let go), so its calls are the model's to run.
|
|
45
|
-
* `said`: a call's own text (its `say`) was streamed, so a recovered turn never says it again.
|
|
46
|
-
|
|
45
|
+
* `said`: a call's own text (its `say`) was streamed, so a recovered turn never says it again. `unbooked`: an answer
|
|
46
|
+
* that booked no request (FauxAction `unbooked`), its script place kept. */
|
|
47
|
+
export const FAUX_RECORDS = { request: "faux.request", unbooked: "faux.unbooked", answered: "faux.answered", said: "faux.said", user: "faux.user", turn: "faux.turn", turnEnd: "faux.turn_end", call: "faux.call", result: "faux.result", note: "faux.note" };
|
|
47
48
|
export function fauxAdapter(options) {
|
|
48
49
|
const stats = { requests: 0, calls: [], opened: [], closed: [] };
|
|
49
50
|
const adapter = {
|
|
@@ -66,10 +67,11 @@ export function fauxAdapter(options) {
|
|
|
66
67
|
const proxy = options.proxy ? await startModelProxy({ ...options.proxy.options, hooks: io.models }, randomBytes(32).toString("base64url")) : undefined;
|
|
67
68
|
io.signal.addEventListener("abort", () => void proxy?.close(), { once: true });
|
|
68
69
|
const append = (kind, data) => io.writer.append([{ kind, data }]);
|
|
69
|
-
// The script's place: one past its last request's (each faux.request keeps its action's index
|
|
70
|
-
// them, since an action refused with `onRefused: "next"` is
|
|
70
|
+
// The script's place: one past its last request's (each faux.request keeps its action's index, as each faux.unbooked
|
|
71
|
+
// does for an answer that booked none), never the count of them, since an action refused with `onRefused: "next"` is
|
|
72
|
+
// skipped with no record.
|
|
71
73
|
let cursor = records.reduce((next, r) => {
|
|
72
|
-
const index = r.kind === FAUX_RECORDS.request ? r.data?.index : undefined;
|
|
74
|
+
const index = r.kind === FAUX_RECORDS.request || r.kind === FAUX_RECORDS.unbooked ? r.data?.index : undefined;
|
|
73
75
|
return typeof index === "number" && index + 1 > next ? index + 1 : next;
|
|
74
76
|
}, 0);
|
|
75
77
|
const turnsStarted = records.filter((r) => r.kind === FAUX_RECORDS.turn).length;
|
|
@@ -95,12 +97,11 @@ export function fauxAdapter(options) {
|
|
|
95
97
|
// its calls runs on the recovery: the turn goes on with the script's next request, as a cut request's always has.
|
|
96
98
|
const begun = new Set(records.filter((r) => r.kind === FAUX_RECORDS.call || r.kind === FAUX_RECORDS.result).map((r) => r.data.callId));
|
|
97
99
|
const answered = new Set(records.filter((r) => r.kind === FAUX_RECORDS.answered).map((r) => r.data.index));
|
|
98
|
-
// Each keeps its
|
|
99
|
-
//
|
|
100
|
-
const resultWhenOf = (action) => (action && "resultWhen" in action && typeof action.resultWhen === "string" ? action.resultWhen : undefined);
|
|
100
|
+
// Each keeps its own text (`say`) unless it was said already (FAUX_RECORDS.said: the call that parked said its text
|
|
101
|
+
// before its gate).
|
|
101
102
|
const saidAlready = new Set(records.filter((r) => r.kind === FAUX_RECORDS.said).map((r) => r.data.callId));
|
|
102
103
|
let dangling = state === "open_turn" && answered.has(cursor - 1)
|
|
103
|
-
? callsOf(script[cursor - 1], cursor - 1).filter((call) => !begun.has(call.callId)).map(({ say, ...call }) => ({ ...call, ...(say && !saidAlready.has(call.callId) ? { say } : {})
|
|
104
|
+
? callsOf(script[cursor - 1], cursor - 1).filter((call) => !begun.has(call.callId)).map(({ say, ...call }) => ({ ...call, ...(say && !saidAlready.has(call.callId) ? { say } : {}) }))
|
|
104
105
|
: [];
|
|
105
106
|
/** What the session has been sent, as a model would be prompted with it. */
|
|
106
107
|
const prompt = records.filter((r) => r.kind === FAUX_RECORDS.user).map((r) => r.data.text);
|
|
@@ -134,8 +135,8 @@ export function fauxAdapter(options) {
|
|
|
134
135
|
});
|
|
135
136
|
/** One call of the model's: the host's gate first, before anything of it is written (a deny is its answer, in the
|
|
136
137
|
* gate's words, recorded so it is never asked again; a park holds the turn until it is stopped), then its intent,
|
|
137
|
-
* the tool, and its outcome.
|
|
138
|
-
const runCall = async (name, args, callId, signal
|
|
138
|
+
* the tool, and its outcome. */
|
|
139
|
+
const runCall = async (name, args, callId, signal) => {
|
|
139
140
|
const tool = tools.get(name);
|
|
140
141
|
const refused = tool && io.gate ? await askGate((call) => io.gate(call), { callId, tool: name, args: (args ?? {}) }, signal) : undefined;
|
|
141
142
|
if (refused)
|
|
@@ -145,8 +146,6 @@ export function fauxAdapter(options) {
|
|
|
145
146
|
const result = tool ? await tool.call(args, { callId, signal }).catch((error) => ({ text: error.message, isError: true })) : { text: `unknown tool ${name}`, isError: true };
|
|
146
147
|
if (tool)
|
|
147
148
|
stats.calls.push(name);
|
|
148
|
-
if (resultWhen)
|
|
149
|
-
await untilExists(resultWhen, signal);
|
|
150
149
|
await append(FAUX_RECORDS.result, { callId, isError: result.isError === true });
|
|
151
150
|
io.onEvent({ type: "tool_end", callId, name, isError: result.isError === true });
|
|
152
151
|
};
|
|
@@ -160,10 +159,10 @@ export function fauxAdapter(options) {
|
|
|
160
159
|
const signal = AbortSignal.any([io.signal, (turnSignal = new AbortController()).signal]);
|
|
161
160
|
try {
|
|
162
161
|
// A recovered turn: the calls its last request left dangling run first, then the model goes on.
|
|
163
|
-
for (const { name, args, callId, say
|
|
162
|
+
for (const { name, args, callId, say } of dangling.splice(0)) {
|
|
164
163
|
if (say)
|
|
165
164
|
await saying(callId, say);
|
|
166
|
-
await runCall(name, args, callId, signal
|
|
165
|
+
await runCall(name, args, callId, signal);
|
|
167
166
|
}
|
|
168
167
|
for (;;) {
|
|
169
168
|
const action = script[cursor];
|
|
@@ -175,6 +174,13 @@ export function fauxAdapter(options) {
|
|
|
175
174
|
turnSignal.abort(new Error(action.halt));
|
|
176
175
|
return await hang(signal);
|
|
177
176
|
}
|
|
177
|
+
if ("unbooked" in action) {
|
|
178
|
+
// Its place kept in a record of its own (no faux.request: no model request was booked), so a session opened
|
|
179
|
+
// again goes on past it, never answers it twice.
|
|
180
|
+
await append(FAUX_RECORDS.unbooked, { index: cursor++ });
|
|
181
|
+
io.onEvent({ type: "text", delta: action.unbooked });
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
178
184
|
// Measured as a real adapter's proxy measures its body: the prompt's UTF-8 bytes, with nothing a provider adds.
|
|
179
185
|
const measured = "inputTokensMax" in action && typeof action.inputTokensMax === "number" ? action.inputTokensMax : Buffer.byteLength(JSON.stringify({ system: spec.system, user: prompt }), "utf8");
|
|
180
186
|
// On the session's model: the proxy's, when it has one (the host's own requests go there on that model too).
|
|
@@ -267,7 +273,7 @@ export function fauxAdapter(options) {
|
|
|
267
273
|
const side = await io.models.beforeRequest({ model: "faux-small", side: true, inputTokensMax: 100 });
|
|
268
274
|
await io.models.afterRequest({ input: 10, output: 5, usd: action.sideDuring.usd }, side || undefined);
|
|
269
275
|
}
|
|
270
|
-
await runCall(name, args, callId, signal
|
|
276
|
+
await runCall(name, args, callId, signal);
|
|
271
277
|
}
|
|
272
278
|
if (bookAfter)
|
|
273
279
|
await book();
|
package/dist/types.d.ts
CHANGED
|
@@ -366,9 +366,8 @@ export interface AdapterSession {
|
|
|
366
366
|
recover(): Promise<void>;
|
|
367
367
|
/** Record the open turn as ended, interrupted, and send nothing: the turn is not to be resumed (a person stopped it, and
|
|
368
368
|
* an interrupt writes no end in the session). Only when `state` is `open_turn`; the session is `idle` after, here and
|
|
369
|
-
* when a later process opens it, and the next `send` is a turn of its own. A
|
|
370
|
-
*
|
|
371
|
-
* never carried, and the rest is left as it is. */
|
|
369
|
+
* when a later process opens it, and the next `send` is a turn of its own. A host that closes a cut turn of its own
|
|
370
|
+
* prompt names it (`opening`): that one is withdrawn and never carried, and the rest is left as it is. */
|
|
372
371
|
settleOpenTurn(options?: {
|
|
373
372
|
opening?: string;
|
|
374
373
|
}): Promise<void>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/agentrun-kernel",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.36",
|
|
4
4
|
"description": "Agent harnesses other than Pi, starting with Codex, behind one seam: a DSL node's runNode and an AgentRun run on a harness adapter, durable in AgentRun's own store.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentrun",
|
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
"test": "node --test --test-concurrency=8 'test/*.test.mjs'"
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
|
-
"@parcha/agentrun-dsl": "0.1.0-beta.
|
|
63
|
+
"@parcha/agentrun-dsl": "0.1.0-beta.36",
|
|
64
64
|
"ajv": "8.18.0",
|
|
65
65
|
"typebox": "1.3.27"
|
|
66
66
|
},
|
package/dist/delegate.d.ts
DELETED
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
import { type BeforeRequest } from "./runner.js";
|
|
2
|
-
import type { AgentAdapter, HarnessEvent, HostTool, NodeRequest, SessionStore } from "./types.js";
|
|
3
|
-
/** The tool's name, as the lead calls it. */
|
|
4
|
-
export declare const DELEGATE_TOOL = "delegate";
|
|
5
|
-
/** What every delegate answers: its finding, the sources it rests on, and what it could not settle. */
|
|
6
|
-
export declare const DELEGATE_RESULT_SCHEMA: Readonly<{
|
|
7
|
-
type: "object";
|
|
8
|
-
properties: {
|
|
9
|
-
answer: {
|
|
10
|
-
type: string;
|
|
11
|
-
};
|
|
12
|
-
citations: {
|
|
13
|
-
type: string;
|
|
14
|
-
items: {
|
|
15
|
-
type: string;
|
|
16
|
-
properties: {
|
|
17
|
-
url: {
|
|
18
|
-
type: string;
|
|
19
|
-
};
|
|
20
|
-
title: {
|
|
21
|
-
type: string;
|
|
22
|
-
};
|
|
23
|
-
quote: {
|
|
24
|
-
type: string;
|
|
25
|
-
};
|
|
26
|
-
};
|
|
27
|
-
required: string[];
|
|
28
|
-
additionalProperties: boolean;
|
|
29
|
-
};
|
|
30
|
-
};
|
|
31
|
-
gaps: {
|
|
32
|
-
type: string;
|
|
33
|
-
items: {
|
|
34
|
-
type: string;
|
|
35
|
-
};
|
|
36
|
-
};
|
|
37
|
-
};
|
|
38
|
-
required: string[];
|
|
39
|
-
additionalProperties: false;
|
|
40
|
-
}>;
|
|
41
|
-
/** One named sub-agent, as the host defines it. */
|
|
42
|
-
export interface DelegateAgent {
|
|
43
|
-
/** What the lead is told this agent is for. */
|
|
44
|
-
description: string;
|
|
45
|
-
/** The child's system prompt, verbatim. */
|
|
46
|
-
system: string;
|
|
47
|
-
/** The lead's tools this agent gets, by name: a subset of `DelegateOptions.tools`. */
|
|
48
|
-
tools: readonly string[];
|
|
49
|
-
/** The models-table tier the child runs on (the node's `tier`). */
|
|
50
|
-
tier?: NodeRequest["tier"];
|
|
51
|
-
/** The share of the lead's remaining time the child may take, in (0, 1] (default 1). */
|
|
52
|
-
deadlineShare?: number;
|
|
53
|
-
}
|
|
54
|
-
/** A child's event: the runner's event, with the delegate call it belongs to. */
|
|
55
|
-
export type DelegateEvent = HarnessEvent & {
|
|
56
|
-
delegate: {
|
|
57
|
-
agent: string;
|
|
58
|
-
callId: string;
|
|
59
|
-
parentKey: string;
|
|
60
|
-
};
|
|
61
|
-
};
|
|
62
|
-
export interface DelegateOptions {
|
|
63
|
-
/** The sub-agents by name (lowercase letters, digits and dashes). */
|
|
64
|
-
agents: Readonly<Record<string, DelegateAgent>>;
|
|
65
|
-
/** The lead's tools: each agent gets the ones it names, and no others. */
|
|
66
|
-
tools: readonly HostTool[];
|
|
67
|
-
/** The harness children run on, or one per agent (an agent's own skills, say). */
|
|
68
|
-
adapter: AgentAdapter | ((agent: string) => AgentAdapter);
|
|
69
|
-
/** The run's store: each child keeps its session there, under its own key. */
|
|
70
|
-
store: SessionStore;
|
|
71
|
-
/** The lead's session key: a child's is `<parentKey>/delegate:<call id>`. */
|
|
72
|
-
parentKey: string;
|
|
73
|
-
/** The lead's check before each paid request, so one budget covers the lead and its children. */
|
|
74
|
-
beforeRequest?: BeforeRequest;
|
|
75
|
-
/** Every child event, with the delegate call it belongs to. */
|
|
76
|
-
onEvent?: (event: DelegateEvent) => void;
|
|
77
|
-
/** The lead's deadline (epoch ms), if it has one: a child's is this, or its agent's share of the time left. */
|
|
78
|
-
deadlineAt?: () => number | undefined;
|
|
79
|
-
/** A child's limit when the lead has no deadline (absent: the runner's own default, 120 s; null for none). */
|
|
80
|
-
timeoutMs?: number | null;
|
|
81
|
-
/** The most paid requests a child makes per attempt (the runner's default when absent). */
|
|
82
|
-
maxTurns?: number | null;
|
|
83
|
-
}
|
|
84
|
-
/** What is wrong with the delegate's definition, or nothing: checked when the tool is made. */
|
|
85
|
-
export declare function delegateProblems(options: Pick<DelegateOptions, "agents" | "tools">): string[];
|
|
86
|
-
/** The `delegate` host tool: refuses a bad definition when made. */
|
|
87
|
-
export declare function delegateTool(options: DelegateOptions): HostTool;
|
package/dist/delegate.js
DELETED
|
@@ -1,143 +0,0 @@
|
|
|
1
|
-
// A lead hands one task to a named sub-agent, which runs as a child node on the same kernel. Written for AgentRun.
|
|
2
|
-
//
|
|
3
|
-
// `delegateTool` is an ordinary host tool, `delegate({ agent, task, context? })`, for a lead on any harness. Each call runs
|
|
4
|
-
// one child: an `agent` node, through `createHarnessRunner`, with the agent's own system prompt (as the host gave it) and
|
|
5
|
-
// its own subset of the lead's tools, answering in a fixed shape (`DELEGATE_RESULT_SCHEMA`). The child is durable under its
|
|
6
|
-
// own key, `step:<the lead's key>/delegate:<call id>`, so the call is replay-safe: a delegate that finished answers again
|
|
7
|
-
// from its recorded result, and one a crash cut off resumes from its own store (its finished paid requests are never sent
|
|
8
|
-
// again). Its paid requests are booked under that key and go through the lead's `beforeRequest`, so one budget covers the
|
|
9
|
-
// lead and every child; its deadline is the lead's, or the agent's share of what is left. Children run one at a time, and
|
|
10
|
-
// a child has no delegate tool (depth 1).
|
|
11
|
-
import { Mutex } from "./process/tools.js";
|
|
12
|
-
import { createHarnessRunner, RUNNER_RECORDS, SUBMIT_TOOL } from "./runner.js";
|
|
13
|
-
/** The tool's name, as the lead calls it. */
|
|
14
|
-
export const DELEGATE_TOOL = "delegate";
|
|
15
|
-
/** What every delegate answers: its finding, the sources it rests on, and what it could not settle. */
|
|
16
|
-
export const DELEGATE_RESULT_SCHEMA = Object.freeze({
|
|
17
|
-
type: "object",
|
|
18
|
-
properties: {
|
|
19
|
-
answer: { type: "string" },
|
|
20
|
-
citations: {
|
|
21
|
-
type: "array",
|
|
22
|
-
items: { type: "object", properties: { url: { type: "string" }, title: { type: "string" }, quote: { type: "string" } }, required: ["url"], additionalProperties: false },
|
|
23
|
-
},
|
|
24
|
-
gaps: { type: "array", items: { type: "string" } },
|
|
25
|
-
},
|
|
26
|
-
required: ["answer", "citations"],
|
|
27
|
-
additionalProperties: false,
|
|
28
|
-
});
|
|
29
|
-
const AGENT_NAME = /^[a-z][a-z0-9-]{0,63}$/;
|
|
30
|
-
/** What is wrong with the delegate's definition, or nothing: checked when the tool is made. */
|
|
31
|
-
export function delegateProblems(options) {
|
|
32
|
-
const problems = [];
|
|
33
|
-
const lead = new Set(options.tools.map((t) => t.name));
|
|
34
|
-
const names = Object.keys(options.agents);
|
|
35
|
-
if (names.length === 0)
|
|
36
|
-
problems.push("no agents to delegate to");
|
|
37
|
-
if (lead.has(DELEGATE_TOOL))
|
|
38
|
-
problems.push(`the lead already has a tool named ${DELEGATE_TOOL}`);
|
|
39
|
-
for (const name of names) {
|
|
40
|
-
const agent = options.agents[name];
|
|
41
|
-
if (!AGENT_NAME.test(name))
|
|
42
|
-
problems.push(`the agent name ${JSON.stringify(name.slice(0, 80))} is not lowercase letters, digits and dashes`);
|
|
43
|
-
if (typeof agent.system !== "string" || agent.system.length === 0)
|
|
44
|
-
problems.push(`the agent ${name} has no system prompt`);
|
|
45
|
-
const seen = new Set();
|
|
46
|
-
for (const tool of agent.tools) {
|
|
47
|
-
if (seen.has(tool))
|
|
48
|
-
problems.push(`the agent ${name} names the tool ${tool} twice`);
|
|
49
|
-
seen.add(tool);
|
|
50
|
-
if (tool === DELEGATE_TOOL)
|
|
51
|
-
problems.push(`the agent ${name} may not delegate further (depth 1)`);
|
|
52
|
-
else if (tool === SUBMIT_TOOL)
|
|
53
|
-
problems.push(`the agent ${name} names ${SUBMIT_TOOL}, which the runner gives every child itself`);
|
|
54
|
-
else if (!lead.has(tool))
|
|
55
|
-
problems.push(`the agent ${name} names the tool ${tool}, which the lead does not have`);
|
|
56
|
-
}
|
|
57
|
-
const share = agent.deadlineShare;
|
|
58
|
-
if (share !== undefined && !(share > 0 && share <= 1))
|
|
59
|
-
problems.push(`the agent ${name}'s deadline share ${share} is not in (0, 1]`);
|
|
60
|
-
}
|
|
61
|
-
return problems;
|
|
62
|
-
}
|
|
63
|
-
/** The `delegate` host tool: refuses a bad definition when made. */
|
|
64
|
-
export function delegateTool(options) {
|
|
65
|
-
const problems = delegateProblems(options);
|
|
66
|
-
if (problems.length)
|
|
67
|
-
throw new Error(`agentrun-kernel: delegate: ${problems.join("; ")}`);
|
|
68
|
-
const byName = new Map(options.tools.map((t) => [t.name, t]));
|
|
69
|
-
const names = Object.keys(options.agents);
|
|
70
|
-
// One child at a time, whatever the harness's own tool calls do.
|
|
71
|
-
const serial = new Mutex();
|
|
72
|
-
return {
|
|
73
|
-
name: DELEGATE_TOOL,
|
|
74
|
-
description: `Hand one task to a sub-agent, which works on it with its own tools and answers with its finding, its sources and its gaps. One at a time. The agents:\n${names.map((n) => `- ${n}: ${options.agents[n].description}`).join("\n")}`,
|
|
75
|
-
inputSchema: {
|
|
76
|
-
type: "object",
|
|
77
|
-
properties: {
|
|
78
|
-
agent: { type: "string", enum: names },
|
|
79
|
-
task: { type: "string", description: "What the sub-agent is to find out or do, complete in itself." },
|
|
80
|
-
context: { type: "string", description: "What it should know from your work so far." },
|
|
81
|
-
},
|
|
82
|
-
required: ["agent", "task"],
|
|
83
|
-
additionalProperties: false,
|
|
84
|
-
},
|
|
85
|
-
// A child is durable under its own key: run again after a crash, it answers from its record or resumes its session.
|
|
86
|
-
replay: "safe",
|
|
87
|
-
call: (args, { callId, signal, sessionDir }) => serial.run(async () => {
|
|
88
|
-
const { agent: name, task, context } = (args ?? {});
|
|
89
|
-
// An own entry only: a name like `constructor` is not an agent.
|
|
90
|
-
const agent = typeof name === "string" && Object.hasOwn(options.agents, name) ? options.agents[name] : undefined;
|
|
91
|
-
if (!agent)
|
|
92
|
-
return { text: `Not delegated: ${JSON.stringify(String(name).slice(0, 80))} is not one of the agents (${names.join(", ")}).`, isError: true };
|
|
93
|
-
if (typeof task !== "string" || task.trim() === "")
|
|
94
|
-
return { text: "Not delegated: give the task as text.", isError: true };
|
|
95
|
-
const tag = { agent: name, callId, parentKey: options.parentKey };
|
|
96
|
-
// The child's session: its step's id, so its records are the runner's under `step:<id>`.
|
|
97
|
-
const sessionId = `${options.parentKey}/delegate:${callId}`;
|
|
98
|
-
const deadlineAt = options.deadlineAt?.();
|
|
99
|
-
const left = deadlineAt === undefined ? undefined : deadlineAt - Date.now();
|
|
100
|
-
if (left !== undefined && left <= 0) {
|
|
101
|
-
// A child that delivered before a crash answers from its record, deadline or not; only new work is refused. Read,
|
|
102
|
-
// not opened: opening would fence the session for nothing.
|
|
103
|
-
const saved = (await options.store.read(`step:${sessionId}`)).findLast((r) => r.kind === RUNNER_RECORDS.accepted);
|
|
104
|
-
if (saved)
|
|
105
|
-
return { text: JSON.stringify(saved.data.value) };
|
|
106
|
-
return { text: "Not delegated: the lead has no time left.", isError: true };
|
|
107
|
-
}
|
|
108
|
-
const timeoutMs = left === undefined ? options.timeoutMs : Math.max(1, Math.floor(left * (agent.deadlineShare ?? 1)));
|
|
109
|
-
const runNode = createHarnessRunner(typeof options.adapter === "function" ? options.adapter(name) : options.adapter, {
|
|
110
|
-
store: options.store,
|
|
111
|
-
tools: agent.tools.map((t) => byName.get(t)),
|
|
112
|
-
signal,
|
|
113
|
-
// The lead's runner's private directories, if it has them: the child's is its own, by its own key.
|
|
114
|
-
...(sessionDir ? { sessionDir } : {}),
|
|
115
|
-
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
|
116
|
-
...(options.maxTurns === undefined ? {} : { maxTurns: options.maxTurns }),
|
|
117
|
-
...(options.beforeRequest ? { beforeRequest: options.beforeRequest } : {}),
|
|
118
|
-
...(options.onEvent ? { onEvent: (event) => options.onEvent({ ...event, delegate: tag }) } : {}),
|
|
119
|
-
});
|
|
120
|
-
try {
|
|
121
|
-
const answer = await runNode({
|
|
122
|
-
kind: "agent",
|
|
123
|
-
label: `delegate:${name}`,
|
|
124
|
-
system: [agent.system],
|
|
125
|
-
user: typeof context === "string" && context.trim() ? `${task}\n\nContext from the lead:\n${context}` : task,
|
|
126
|
-
schema: DELEGATE_RESULT_SCHEMA,
|
|
127
|
-
tools: [...agent.tools],
|
|
128
|
-
...(agent.tier === undefined ? {} : { tier: agent.tier }),
|
|
129
|
-
step: { sessionId, attempt: 0, earlierSessionIds: [] },
|
|
130
|
-
});
|
|
131
|
-
return { text: JSON.stringify(answer) };
|
|
132
|
-
}
|
|
133
|
-
catch (error) {
|
|
134
|
-
// Stopped (the lead paused, the process is draining): not an answer. Rethrown, the lead's harness records the call
|
|
135
|
-
// as interrupted and runs the same call id again on resume, which resumes this child. A child that failed on its
|
|
136
|
-
// own is an answer the lead reads.
|
|
137
|
-
if (signal?.aborted)
|
|
138
|
-
throw signal.reason ?? error;
|
|
139
|
-
return { text: `The delegate ${name} stopped without an answer: ${String(error?.message ?? error).slice(0, 400)}`, isError: true };
|
|
140
|
-
}
|
|
141
|
-
}),
|
|
142
|
-
};
|
|
143
|
-
}
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
import type { SessionState as AdapterSessionState, SessionStore, TurnStatus } from "../types.js";
|
|
2
|
-
import { foldSession } from "./drive.js";
|
|
3
|
-
/** The effect's key in the follow-up's own session. */
|
|
4
|
-
export declare const FOLLOW_UP_EFFECT = "follow-up";
|
|
5
|
-
/** What a request the reserve refuses says, first. */
|
|
6
|
-
export declare const FOLLOW_UP_BUDGET_REACHED = "follow_up_budget_reached";
|
|
7
|
-
/** What a request asked for after the follow-up was cancelled says, first. */
|
|
8
|
-
export declare const FOLLOW_UP_CANCELLED = "follow_up_cancelled";
|
|
9
|
-
/** The follow-up's own session key, beside the session it follows up. */
|
|
10
|
-
export declare const followUpKey: (session: string, name: string) => string;
|
|
11
|
-
/** The session as a follow-up drives it: an adapter's session, and how a turn a crash cut off is closed unsent. */
|
|
12
|
-
export interface FollowUpTarget {
|
|
13
|
-
readonly state: AdapterSessionState;
|
|
14
|
-
/** Send `text` as a new turn, its submission under `id`. */
|
|
15
|
-
send(text: string, options?: {
|
|
16
|
-
id?: string;
|
|
17
|
-
}): Promise<void>;
|
|
18
|
-
turnEnd(): Promise<{
|
|
19
|
-
status: TurnStatus;
|
|
20
|
-
error?: string;
|
|
21
|
-
}>;
|
|
22
|
-
/** Record the open turn as ended, interrupted, and send nothing. It withdraws only the submission it is named
|
|
23
|
-
* (`opening`), while that is unplaced and the oldest pending. */
|
|
24
|
-
settleOpenTurn(options?: {
|
|
25
|
-
opening?: string;
|
|
26
|
-
}): Promise<void>;
|
|
27
|
-
/** Stop the turn in flight. */
|
|
28
|
-
interrupt(): Promise<void>;
|
|
29
|
-
}
|
|
30
|
-
export interface FollowUpOptions {
|
|
31
|
-
store: SessionStore;
|
|
32
|
-
/** The key of the session it follows up. */
|
|
33
|
-
session: string;
|
|
34
|
-
/** The follow-up's name: one follow-up per name per session. */
|
|
35
|
-
name: string;
|
|
36
|
-
prompt: string;
|
|
37
|
-
/** The most its paid requests may cost, in dollars, counted from its first request. */
|
|
38
|
-
reserveUsd: number;
|
|
39
|
-
/** A request's worst case, held for each request in flight and the one asked for. Required: a host with no worst case
|
|
40
|
-
* passes 0, and the reserve may then be passed by the one request admitted last. */
|
|
41
|
-
worstUsd: number;
|
|
42
|
-
}
|
|
43
|
-
export type FollowUpResult = {
|
|
44
|
-
status: "done";
|
|
45
|
-
} | {
|
|
46
|
-
status: "interrupted";
|
|
47
|
-
} | {
|
|
48
|
-
status: "failed";
|
|
49
|
-
error: string;
|
|
50
|
-
};
|
|
51
|
-
export interface FollowUp {
|
|
52
|
-
readonly key: string;
|
|
53
|
-
/** Ahead of the host's own check on each paid request: undefined outside the follow-up's turn. */
|
|
54
|
-
beforeRequest(request: {
|
|
55
|
-
spentUsd: number | null;
|
|
56
|
-
inFlight: readonly unknown[];
|
|
57
|
-
}): undefined | {
|
|
58
|
-
refuse: string;
|
|
59
|
-
};
|
|
60
|
-
/** Sends the follow-up once, or answers from its record. */
|
|
61
|
-
run(target: FollowUpTarget, signal: AbortSignal): Promise<FollowUpResult>;
|
|
62
|
-
}
|
|
63
|
-
export type FollowUpState = "none" | "running" | "done" | "interrupted" | "failed";
|
|
64
|
-
/** The follow-up's state in its records, as written: `running` is one a process that died left without an outcome. A
|
|
65
|
-
* host reads it before it resumes an open turn: a turn of a `running` or `interrupted` follow-up is settled instead. */
|
|
66
|
-
export declare function followUpState(records: Parameters<typeof foldSession>[1]): FollowUpState;
|
|
67
|
-
export declare function followUpOnce(options: FollowUpOptions): FollowUp;
|
package/dist/kernel/follow-up.js
DELETED
|
@@ -1,146 +0,0 @@
|
|
|
1
|
-
import { foldSession, openDrive } from "./drive.js";
|
|
2
|
-
import { EffectFailure, EffectInterrupted } from "./errors.js";
|
|
3
|
-
/** The effect's key in the follow-up's own session. */
|
|
4
|
-
export const FOLLOW_UP_EFFECT = "follow-up";
|
|
5
|
-
/** What a request the reserve refuses says, first. */
|
|
6
|
-
export const FOLLOW_UP_BUDGET_REACHED = "follow_up_budget_reached";
|
|
7
|
-
/** What a request asked for after the follow-up was cancelled says, first. */
|
|
8
|
-
export const FOLLOW_UP_CANCELLED = "follow_up_cancelled";
|
|
9
|
-
/** The effect that records the follow-up's own cut turn settled: no later run settles another turn. */
|
|
10
|
-
const SETTLED_EFFECT = "follow-up.settled";
|
|
11
|
-
/** The run of each follow-up key in this process: a second run waits for it, never fences it. */
|
|
12
|
-
const runs = new WeakMap();
|
|
13
|
-
/** The follow-up's own session key, beside the session it follows up. */
|
|
14
|
-
export const followUpKey = (session, name) => `${session}:follow-up:${name}`;
|
|
15
|
-
/** The follow-up's state in its records, as written: `running` is one a process that died left without an outcome. A
|
|
16
|
-
* host reads it before it resumes an open turn: a turn of a `running` or `interrupted` follow-up is settled instead. */
|
|
17
|
-
export function followUpState(records) {
|
|
18
|
-
const effect = foldSession("", records).effects.get(FOLLOW_UP_EFFECT);
|
|
19
|
-
if (!effect)
|
|
20
|
-
return "none";
|
|
21
|
-
if (effect.status === "completed")
|
|
22
|
-
return "done";
|
|
23
|
-
if (effect.status === "failed")
|
|
24
|
-
return effect.error?.interrupted ? "interrupted" : "failed";
|
|
25
|
-
return "running";
|
|
26
|
-
}
|
|
27
|
-
export function followUpOnce(options) {
|
|
28
|
-
const { store, prompt, reserveUsd } = options;
|
|
29
|
-
const { worstUsd } = options;
|
|
30
|
-
if (typeof reserveUsd !== "number" || !Number.isFinite(reserveUsd) || reserveUsd <= 0)
|
|
31
|
-
throw new Error("reserveUsd must be a number of dollars above 0");
|
|
32
|
-
if (typeof worstUsd !== "number" || !Number.isFinite(worstUsd) || worstUsd < 0)
|
|
33
|
-
throw new Error("worstUsd must be given, a number of dollars, 0 or more");
|
|
34
|
-
const key = followUpKey(options.session, options.name);
|
|
35
|
-
// The id of the prompt's submission in the session: the follow-up's own, so a later run names it to the settle and a
|
|
36
|
-
// settle never withdraws input that is not the follow-up's.
|
|
37
|
-
const submission = `follow-up:${key}`;
|
|
38
|
-
let active = false;
|
|
39
|
-
let signalNow;
|
|
40
|
-
// The session's spentUsd when the follow-up's first request asks: the reserve counts from there. Whatever the session
|
|
41
|
-
// books after that counts against the reserve too: a task request whose cost was booked late (REQUEST_COST_LATE), and
|
|
42
|
-
// a harness's own background requests during the follow-up's turn (a CLI's small-model calls). Both refuse the
|
|
43
|
-
// follow-up sooner, never let it spend more.
|
|
44
|
-
let start;
|
|
45
|
-
const refuse = (why) => ({ refuse: `${FOLLOW_UP_BUDGET_REACHED}: ${why}` });
|
|
46
|
-
return {
|
|
47
|
-
key,
|
|
48
|
-
beforeRequest({ spentUsd, inFlight }) {
|
|
49
|
-
if (!active)
|
|
50
|
-
return undefined;
|
|
51
|
-
if (signalNow?.aborted)
|
|
52
|
-
return { refuse: `${FOLLOW_UP_CANCELLED}: the follow-up was cancelled; the request was not sent` };
|
|
53
|
-
if (spentUsd === null)
|
|
54
|
-
return refuse("what the session has spent is unknown, so the follow-up's reserve cannot be kept; the request was not sent");
|
|
55
|
-
start ??= spentUsd;
|
|
56
|
-
const used = spentUsd - start;
|
|
57
|
-
if (used + worstUsd * (inFlight.length + 1) > reserveUsd)
|
|
58
|
-
return refuse(`$${used.toFixed(6)} spent of a $${reserveUsd} reserve, and the next request could cost up to $${worstUsd}; the request was not sent`);
|
|
59
|
-
return undefined;
|
|
60
|
-
},
|
|
61
|
-
run(target, signal) {
|
|
62
|
-
const byKey = runs.get(store) ?? new Map();
|
|
63
|
-
runs.set(store, byKey);
|
|
64
|
-
const prior = byKey.get(key) ?? Promise.resolve();
|
|
65
|
-
// Waiting its turn, a run still hears its own signal: cancelled, it stops waiting and leaves the run before it alone.
|
|
66
|
-
const turn = new Promise((resolve, reject) => {
|
|
67
|
-
if (signal.aborted)
|
|
68
|
-
return reject(signal.reason);
|
|
69
|
-
const onAbort = () => reject(signal.reason);
|
|
70
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
71
|
-
void prior.then(() => {
|
|
72
|
-
signal.removeEventListener("abort", onAbort);
|
|
73
|
-
resolve();
|
|
74
|
-
});
|
|
75
|
-
});
|
|
76
|
-
const run = turn.then(() => runOnce(target, signal));
|
|
77
|
-
// The next run of the key waits for the one before this, whether this one ran or gave up waiting.
|
|
78
|
-
const settled = prior.then(() => run.catch(() => undefined));
|
|
79
|
-
byKey.set(key, settled);
|
|
80
|
-
void settled.then(() => byKey.get(key) === settled && byKey.delete(key));
|
|
81
|
-
return run;
|
|
82
|
-
},
|
|
83
|
-
};
|
|
84
|
-
async function runOnce(target, signal) {
|
|
85
|
-
const drive = await openDrive({ writer: await store.open(key), signal });
|
|
86
|
-
const known = drive.state().effects.get(FOLLOW_UP_EFFECT);
|
|
87
|
-
if (known?.status === "completed")
|
|
88
|
-
return { status: "done" };
|
|
89
|
-
if (known?.status === "failed") {
|
|
90
|
-
if (!known.error?.interrupted)
|
|
91
|
-
return { status: "failed", error: known.error?.message ?? "failed" };
|
|
92
|
-
// Its own turn may still be open in the session: closed unsent, never resumed, and once. An open turn after that
|
|
93
|
-
// is another's, and is left alone.
|
|
94
|
-
if (drive.state().effects.get(SETTLED_EFFECT)?.status !== "completed") {
|
|
95
|
-
if (target.state === "open_turn")
|
|
96
|
-
await target.settleOpenTurn({ opening: submission });
|
|
97
|
-
await drive.effect(SETTLED_EFFECT, { name: SETTLED_EFFECT, replay: "safe", input: null }, async () => null);
|
|
98
|
-
}
|
|
99
|
-
return { status: "interrupted" };
|
|
100
|
-
}
|
|
101
|
-
if (target.state === "open_turn")
|
|
102
|
-
throw new Error("the session has an open turn that is not this follow-up's: recover it before the follow-up");
|
|
103
|
-
try {
|
|
104
|
-
await drive.effect(FOLLOW_UP_EFFECT, { name: options.name, replay: "never", input: { prompt } }, async () => {
|
|
105
|
-
if (signal.aborted)
|
|
106
|
-
throw signal.reason;
|
|
107
|
-
active = true;
|
|
108
|
-
signalNow = signal;
|
|
109
|
-
// A cancel stops the turn and ends the run at once: no outcome is written, so the next process reads the
|
|
110
|
-
// follow-up interrupted, and a turn that ends after it never answers done.
|
|
111
|
-
let onAbort = () => { };
|
|
112
|
-
const aborted = new Promise((_, reject) => {
|
|
113
|
-
onAbort = () => {
|
|
114
|
-
void target.interrupt().catch(() => undefined);
|
|
115
|
-
reject(signal.reason);
|
|
116
|
-
};
|
|
117
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
118
|
-
});
|
|
119
|
-
aborted.catch(() => undefined);
|
|
120
|
-
try {
|
|
121
|
-
// A send the session refuses because it holds the id already cannot strand the follow-up: the effect is
|
|
122
|
-
// `never`, so a crash after the submission landed is recovered interrupted, and the prompt is never sent again.
|
|
123
|
-
await Promise.race([target.send(prompt, { id: submission }), aborted]);
|
|
124
|
-
const end = await Promise.race([target.turnEnd(), aborted]);
|
|
125
|
-
if (signal.aborted)
|
|
126
|
-
throw signal.reason;
|
|
127
|
-
if (end.status === "interrupted")
|
|
128
|
-
throw new EffectInterrupted(end.error ?? "the follow-up's turn was interrupted");
|
|
129
|
-
if (end.status !== "completed")
|
|
130
|
-
throw new Error(end.error ?? "the follow-up's turn failed");
|
|
131
|
-
return null;
|
|
132
|
-
}
|
|
133
|
-
finally {
|
|
134
|
-
active = false;
|
|
135
|
-
signal.removeEventListener("abort", onAbort);
|
|
136
|
-
}
|
|
137
|
-
});
|
|
138
|
-
return { status: "done" };
|
|
139
|
-
}
|
|
140
|
-
catch (error) {
|
|
141
|
-
if (error instanceof EffectFailure)
|
|
142
|
-
return error.error.interrupted ? { status: "interrupted" } : { status: "failed", error: error.error.message };
|
|
143
|
-
throw error;
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
}
|