@providerkit/agents 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE-APACHE-2.0 +202 -0
- package/README.md +2108 -52
- package/THIRD_PARTY_NOTICES.md +521 -0
- package/dist/a2a/auth.d.ts +10 -0
- package/dist/a2a/auth.d.ts.map +1 -0
- package/dist/a2a/auth.js +52 -0
- package/dist/a2a/auth.js.map +1 -0
- package/dist/a2a/client.d.ts +74 -0
- package/dist/a2a/client.d.ts.map +1 -0
- package/dist/a2a/client.js +601 -0
- package/dist/a2a/client.js.map +1 -0
- package/dist/a2a/index.d.ts +22 -0
- package/dist/a2a/index.d.ts.map +1 -0
- package/dist/a2a/index.js +11 -0
- package/dist/a2a/index.js.map +1 -0
- package/dist/a2a/memory-runs.d.ts +62 -0
- package/dist/a2a/memory-runs.d.ts.map +1 -0
- package/dist/a2a/memory-runs.js +349 -0
- package/dist/a2a/memory-runs.js.map +1 -0
- package/dist/a2a/policy.d.ts +15 -0
- package/dist/a2a/policy.d.ts.map +1 -0
- package/dist/a2a/policy.js +114 -0
- package/dist/a2a/policy.js.map +1 -0
- package/dist/a2a/push.d.ts +34 -0
- package/dist/a2a/push.d.ts.map +1 -0
- package/dist/a2a/push.js +180 -0
- package/dist/a2a/push.js.map +1 -0
- package/dist/a2a/remote.d.ts +155 -0
- package/dist/a2a/remote.d.ts.map +1 -0
- package/dist/a2a/remote.js +1196 -0
- package/dist/a2a/remote.js.map +1 -0
- package/dist/a2a/server.d.ts +110 -0
- package/dist/a2a/server.d.ts.map +1 -0
- package/dist/a2a/server.js +1139 -0
- package/dist/a2a/server.js.map +1 -0
- package/dist/a2a/signing.d.ts +21 -0
- package/dist/a2a/signing.d.ts.map +1 -0
- package/dist/a2a/signing.js +305 -0
- package/dist/a2a/signing.js.map +1 -0
- package/dist/a2a/tasks.d.ts +88 -0
- package/dist/a2a/tasks.d.ts.map +1 -0
- package/dist/a2a/tasks.js +170 -0
- package/dist/a2a/tasks.js.map +1 -0
- package/dist/a2a/wire.d.ts +267 -0
- package/dist/a2a/wire.d.ts.map +1 -0
- package/dist/a2a/wire.js +1202 -0
- package/dist/a2a/wire.js.map +1 -0
- package/dist/background-types.d.ts +76 -0
- package/dist/background-types.d.ts.map +1 -0
- package/dist/background-types.js +2 -0
- package/dist/background-types.js.map +1 -0
- package/dist/child.d.ts +25 -0
- package/dist/child.d.ts.map +1 -0
- package/dist/child.js +129 -0
- package/dist/child.js.map +1 -0
- package/dist/code-driver.d.ts +40 -0
- package/dist/code-driver.d.ts.map +1 -0
- package/dist/code-driver.js +2 -0
- package/dist/code-driver.js.map +1 -0
- package/dist/code-mode.d.ts +3 -0
- package/dist/code-mode.d.ts.map +1 -0
- package/dist/code-mode.js +2 -0
- package/dist/code-mode.js.map +1 -0
- package/dist/code-script.d.ts +3 -0
- package/dist/code-script.d.ts.map +1 -0
- package/dist/code-script.js +149 -0
- package/dist/code-script.js.map +1 -0
- package/dist/code.d.ts +75 -0
- package/dist/code.d.ts.map +1 -0
- package/dist/code.js +326 -0
- package/dist/code.js.map +1 -0
- package/dist/compaction.d.ts +15 -0
- package/dist/compaction.d.ts.map +1 -0
- package/dist/compaction.js +168 -0
- package/dist/compaction.js.map +1 -0
- package/dist/delegation.d.ts +85 -16
- package/dist/delegation.d.ts.map +1 -1
- package/dist/delegation.js +240 -106
- package/dist/delegation.js.map +1 -1
- package/dist/evals/driver.d.ts +10 -0
- package/dist/evals/driver.d.ts.map +1 -0
- package/dist/evals/driver.js +192 -0
- package/dist/evals/driver.js.map +1 -0
- package/dist/evals/journal.d.ts +26 -0
- package/dist/evals/journal.d.ts.map +1 -0
- package/dist/evals/journal.js +483 -0
- package/dist/evals/journal.js.map +1 -0
- package/dist/evals/judge.d.ts +31 -0
- package/dist/evals/judge.d.ts.map +1 -0
- package/dist/evals/judge.js +142 -0
- package/dist/evals/judge.js.map +1 -0
- package/dist/evals/report.d.ts +38 -0
- package/dist/evals/report.d.ts.map +1 -0
- package/dist/evals/report.js +241 -0
- package/dist/evals/report.js.map +1 -0
- package/dist/evals/runner.d.ts +24 -0
- package/dist/evals/runner.d.ts.map +1 -0
- package/dist/evals/runner.js +655 -0
- package/dist/evals/runner.js.map +1 -0
- package/dist/evals/scorers.d.ts +36 -0
- package/dist/evals/scorers.d.ts.map +1 -0
- package/dist/evals/scorers.js +259 -0
- package/dist/evals/scorers.js.map +1 -0
- package/dist/evals/simulation.d.ts +7 -0
- package/dist/evals/simulation.d.ts.map +1 -0
- package/dist/evals/simulation.js +38 -0
- package/dist/evals/simulation.js.map +1 -0
- package/dist/evals/testing.d.ts +36 -0
- package/dist/evals/testing.d.ts.map +1 -0
- package/dist/evals/testing.js +87 -0
- package/dist/evals/testing.js.map +1 -0
- package/dist/evals/trajectory.d.ts +11 -0
- package/dist/evals/trajectory.d.ts.map +1 -0
- package/dist/evals/trajectory.js +180 -0
- package/dist/evals/trajectory.js.map +1 -0
- package/dist/evals/types.d.ts +431 -0
- package/dist/evals/types.d.ts.map +1 -0
- package/dist/evals/types.js +4 -0
- package/dist/evals/types.js.map +1 -0
- package/dist/evals.d.ts +14 -0
- package/dist/evals.d.ts.map +1 -0
- package/dist/evals.js +9 -0
- package/dist/evals.js.map +1 -0
- package/dist/extensions.d.ts +33 -0
- package/dist/extensions.d.ts.map +1 -0
- package/dist/extensions.js +188 -0
- package/dist/extensions.js.map +1 -0
- package/dist/handoff.d.ts +58 -0
- package/dist/handoff.d.ts.map +1 -0
- package/dist/handoff.js +160 -0
- package/dist/handoff.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -1
- package/dist/input.d.ts +42 -0
- package/dist/input.d.ts.map +1 -0
- package/dist/input.js +266 -0
- package/dist/input.js.map +1 -0
- package/dist/mcp.d.ts +77 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +505 -0
- package/dist/mcp.js.map +1 -0
- package/dist/memory-store.d.ts +11 -0
- package/dist/memory-store.d.ts.map +1 -0
- package/dist/memory-store.js +272 -0
- package/dist/memory-store.js.map +1 -0
- package/dist/memory.d.ts +212 -0
- package/dist/memory.d.ts.map +1 -0
- package/dist/memory.js +613 -0
- package/dist/memory.js.map +1 -0
- package/dist/otel.d.ts +74 -0
- package/dist/otel.d.ts.map +1 -0
- package/dist/otel.js +427 -0
- package/dist/otel.js.map +1 -0
- package/dist/progress.d.ts +17 -0
- package/dist/progress.d.ts.map +1 -0
- package/dist/progress.js +193 -0
- package/dist/progress.js.map +1 -0
- package/dist/quickjs.d.ts +19 -0
- package/dist/quickjs.d.ts.map +1 -0
- package/dist/quickjs.js +519 -0
- package/dist/quickjs.js.map +1 -0
- package/dist/recovery.d.ts +10 -0
- package/dist/recovery.d.ts.map +1 -0
- package/dist/recovery.js +62 -0
- package/dist/recovery.js.map +1 -0
- package/dist/request.d.ts +88 -0
- package/dist/request.d.ts.map +1 -0
- package/dist/request.js +422 -0
- package/dist/request.js.map +1 -0
- package/dist/run.d.ts +16 -4
- package/dist/run.d.ts.map +1 -1
- package/dist/run.js +2016 -245
- package/dist/run.js.map +1 -1
- package/dist/runs.d.ts +77 -34
- package/dist/runs.d.ts.map +1 -1
- package/dist/runs.js +267 -85
- package/dist/runs.js.map +1 -1
- package/dist/schema-to-ts.d.ts +4 -0
- package/dist/schema-to-ts.d.ts.map +1 -0
- package/dist/schema-to-ts.js +191 -0
- package/dist/schema-to-ts.js.map +1 -0
- package/dist/session.d.ts +23 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +137 -0
- package/dist/session.js.map +1 -0
- package/dist/snapshot.d.ts +57 -8
- package/dist/snapshot.d.ts.map +1 -1
- package/dist/snapshot.js +1206 -109
- package/dist/snapshot.js.map +1 -1
- package/dist/steering.d.ts +75 -0
- package/dist/steering.d.ts.map +1 -0
- package/dist/steering.js +214 -0
- package/dist/steering.js.map +1 -0
- package/dist/subagents.d.ts +141 -0
- package/dist/subagents.d.ts.map +1 -0
- package/dist/subagents.js +746 -0
- package/dist/subagents.js.map +1 -0
- package/dist/tool-retry.d.ts +12 -0
- package/dist/tool-retry.d.ts.map +1 -0
- package/dist/tool-retry.js +53 -0
- package/dist/tool-retry.js.map +1 -0
- package/dist/tree.d.ts +62 -6
- package/dist/tree.d.ts.map +1 -1
- package/dist/tree.js +192 -23
- package/dist/tree.js.map +1 -1
- package/dist/types.d.ts +767 -52
- package/dist/types.d.ts.map +1 -1
- package/dist/workflow-snapshot.d.ts +8 -0
- package/dist/workflow-snapshot.d.ts.map +1 -0
- package/dist/workflow-snapshot.js +276 -0
- package/dist/workflow-snapshot.js.map +1 -0
- package/dist/workflow-types.d.ts +171 -0
- package/dist/workflow-types.d.ts.map +1 -0
- package/dist/workflow-types.js +2 -0
- package/dist/workflow-types.js.map +1 -0
- package/dist/workflow.d.ts +19 -0
- package/dist/workflow.d.ts.map +1 -0
- package/dist/workflow.js +1053 -0
- package/dist/workflow.js.map +1 -0
- package/examples/a2a-remote.ts +85 -0
- package/examples/a2a-server.ts +100 -0
- package/examples/background.ts +18 -4
- package/examples/code-mode.ts +76 -0
- package/examples/conversation.ts +57 -0
- package/examples/evals.ts +79 -0
- package/examples/guardrails.ts +56 -0
- package/examples/handoff.ts +79 -0
- package/examples/memory.ts +44 -0
- package/examples/otel.ts +99 -0
- package/examples/steering.ts +69 -0
- package/examples/structured-handoff.ts +92 -0
- package/examples/subagents.ts +127 -0
- package/examples/workflow.ts +74 -0
- package/package.json +58 -6
- package/src/a2a/auth.ts +62 -0
- package/src/a2a/client.ts +733 -0
- package/src/a2a/index.ts +74 -0
- package/src/a2a/memory-runs.ts +448 -0
- package/src/a2a/policy.ts +148 -0
- package/src/a2a/push.ts +251 -0
- package/src/a2a/remote.ts +1652 -0
- package/src/a2a/server.ts +1390 -0
- package/src/a2a/signing.ts +348 -0
- package/src/a2a/tasks.ts +260 -0
- package/src/a2a/wire.ts +1443 -0
- package/src/background-types.ts +86 -0
- package/src/child.ts +181 -0
- package/src/code-driver.ts +48 -0
- package/src/code-mode.ts +12 -0
- package/src/code-script.ts +149 -0
- package/src/code.ts +424 -0
- package/src/compaction.ts +212 -0
- package/src/delegation.ts +444 -155
- package/src/evals/driver.ts +222 -0
- package/src/evals/journal.ts +605 -0
- package/src/evals/judge.ts +188 -0
- package/src/evals/report.ts +295 -0
- package/src/evals/runner.ts +826 -0
- package/src/evals/scorers.ts +339 -0
- package/src/evals/simulation.ts +46 -0
- package/src/evals/testing.ts +126 -0
- package/src/evals/trajectory.ts +223 -0
- package/src/evals/types.ts +463 -0
- package/src/evals.ts +72 -0
- package/src/extensions.ts +247 -0
- package/src/handoff.ts +214 -0
- package/src/index.ts +51 -0
- package/src/input.ts +319 -0
- package/src/mcp.ts +690 -0
- package/src/memory-store.ts +366 -0
- package/src/memory.ts +893 -0
- package/src/otel.ts +568 -0
- package/src/progress.ts +214 -0
- package/src/quickjs.ts +524 -0
- package/src/recovery.ts +90 -0
- package/src/request.ts +513 -0
- package/src/run.ts +2678 -313
- package/src/runs.ts +464 -133
- package/src/schema-to-ts.ts +194 -0
- package/src/session.ts +178 -0
- package/src/snapshot.ts +1595 -124
- package/src/steering.ts +329 -0
- package/src/subagents.ts +1084 -0
- package/src/tool-retry.ts +86 -0
- package/src/tree.ts +223 -27
- package/src/types.ts +711 -52
- package/src/workflow-snapshot.ts +366 -0
- package/src/workflow-types.ts +213 -0
- package/src/workflow.ts +1316 -0
package/src/runs.ts
CHANGED
|
@@ -1,14 +1,44 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
createRuns,
|
|
3
|
+
ChildResult,
|
|
4
|
+
ChildSpec,
|
|
5
|
+
Run,
|
|
6
|
+
RunEvent,
|
|
7
|
+
StoredRun,
|
|
8
|
+
} from "@gusnips/server/runs";
|
|
9
|
+
import { createProgress, type EventDurability } from "./progress.ts";
|
|
10
|
+
export type { EventDurability, ProgressGap } from "./progress.ts";
|
|
11
|
+
import { checkMemoryBinding, readMemoryBinding, type MemoryBinding } from "./memory.ts";
|
|
12
|
+
import type { RemoteAgent, RemoteOutcome } from "./a2a/remote.ts";
|
|
13
|
+
import { requestHash } from "./request.ts";
|
|
14
|
+
import type { NodeOutcome } from "./delegation.ts";
|
|
15
|
+
import type { Workflow, WorkflowOutcome } from "./workflow-types.ts";
|
|
2
16
|
import { AGENT_RUNTIME } from "./delegation.ts";
|
|
3
|
-
import {
|
|
4
|
-
|
|
17
|
+
import {
|
|
18
|
+
checkOptions,
|
|
19
|
+
checkChildProgress,
|
|
20
|
+
copyData,
|
|
21
|
+
equalData,
|
|
22
|
+
immutableCopy,
|
|
23
|
+
isId,
|
|
24
|
+
isRecord,
|
|
25
|
+
isSession,
|
|
26
|
+
isSessionStatus,
|
|
27
|
+
readModelSettings,
|
|
28
|
+
} from "./snapshot.ts";
|
|
29
|
+
import { openRequests, readAnswers, untilAbort, wakeAt } from "./tree.ts";
|
|
5
30
|
import type {
|
|
6
31
|
Agent,
|
|
7
32
|
AgentHost,
|
|
33
|
+
AgentInput,
|
|
8
34
|
ChildEnvelope,
|
|
35
|
+
RecordedModelSettings,
|
|
9
36
|
RunOptions,
|
|
10
37
|
RunOutcome,
|
|
11
|
-
|
|
38
|
+
TreeNode,
|
|
39
|
+
ResumeOptions,
|
|
40
|
+
Session,
|
|
41
|
+
SessionStatus,
|
|
12
42
|
} from "./types.ts";
|
|
13
43
|
|
|
14
44
|
export type BackgroundRuns = Pick<
|
|
@@ -16,54 +46,98 @@ export type BackgroundRuns = Pick<
|
|
|
16
46
|
"create" | "read" | "tail" | "cancel"
|
|
17
47
|
>;
|
|
18
48
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
49
|
+
/** Minimum worker capabilities. Server 0.19/0.20 remain valid in best-effort mode,
|
|
50
|
+
* including their child callbacks; only awaited mode needs append. */
|
|
51
|
+
export interface BackgroundWorker extends Pick<
|
|
52
|
+
Run,
|
|
53
|
+
"id" | "owner" | "input" | "checkpoint" | "resumed" | "crashes" | "signal" | "save" | "emit"
|
|
54
|
+
> {
|
|
55
|
+
append?: (events: readonly { type: string; data?: unknown }[]) => Promise<void>;
|
|
56
|
+
child<T>(
|
|
57
|
+
key: string,
|
|
58
|
+
spec: ChildSpec,
|
|
59
|
+
fn: (run: BackgroundWorker) => Promise<T>,
|
|
60
|
+
): Promise<ChildResult<T>>;
|
|
31
61
|
}
|
|
32
62
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
63
|
+
import type {
|
|
64
|
+
BackgroundCancelResult,
|
|
65
|
+
BackgroundContinuationInput,
|
|
66
|
+
BackgroundContinuationResult,
|
|
67
|
+
BackgroundContext,
|
|
68
|
+
BackgroundPolicy,
|
|
69
|
+
Continuation,
|
|
70
|
+
SegmentHook,
|
|
71
|
+
} from "./background-types.ts";
|
|
72
|
+
export type {
|
|
73
|
+
BackgroundCancelResult,
|
|
74
|
+
BackgroundContinuationInput,
|
|
75
|
+
BackgroundContinuationResult,
|
|
76
|
+
BackgroundContext,
|
|
77
|
+
BackgroundPolicy,
|
|
78
|
+
Continuation,
|
|
79
|
+
SegmentHook,
|
|
80
|
+
} from "./background-types.ts";
|
|
49
81
|
|
|
50
|
-
export interface BackgroundOptions<T> {
|
|
82
|
+
export interface BackgroundOptions<T> extends BackgroundBase {
|
|
51
83
|
agent: Agent<T>;
|
|
84
|
+
}
|
|
85
|
+
export interface BackgroundRemoteOptions<T> extends Omit<
|
|
86
|
+
BackgroundBase,
|
|
87
|
+
"session" | "historyLimit" | "prepareHistory" | "memory"
|
|
88
|
+
> {
|
|
89
|
+
agent: RemoteAgent<T>;
|
|
90
|
+
}
|
|
91
|
+
export interface BackgroundWorkflowOptions<I, O> extends Omit<
|
|
92
|
+
BackgroundBase,
|
|
93
|
+
"session" | "historyLimit" | "prepareHistory"
|
|
94
|
+
> {
|
|
95
|
+
workflow: Workflow<I, O>;
|
|
96
|
+
}
|
|
97
|
+
interface BackgroundBase {
|
|
52
98
|
/** Dedicated handler key for this agent version. */
|
|
53
99
|
kind: string;
|
|
100
|
+
/** Injected create must resolve after its transaction commits. Only then is enqueue called. */
|
|
54
101
|
runs: BackgroundRuns;
|
|
102
|
+
/** Optional durable, owner-scoped create-or-reconcile capability. Required only to cancel
|
|
103
|
+
* a suspended logical run. Also used for answers when supplied. Never substitute a local
|
|
104
|
+
* cache or an idempotency flag for atomic host storage. See BackgroundContinuationInput. */
|
|
105
|
+
createContinuation?: (
|
|
106
|
+
input: BackgroundContinuationInput,
|
|
107
|
+
) => Promise<BackgroundContinuationResult>;
|
|
108
|
+
/** Coalesced progress uses emit by default. Awaited mode needs Run.append (server 0.21+). */
|
|
109
|
+
events?: EventDurability;
|
|
55
110
|
/** Await durable queue acceptance. A worker calls runs.drive(id, background.handlers).
|
|
56
111
|
* The host must also run runs.sweep on boot and periodically, and drain on shutdown. */
|
|
57
112
|
enqueue: (id: string) => Promise<void>;
|
|
58
113
|
policy: (context: BackgroundContext) => BackgroundPolicy | Promise<BackgroundPolicy>;
|
|
114
|
+
/** Awaited before execution and after the SDK journal settles. May repeat after worker loss;
|
|
115
|
+
* the host must deduplicate/reconcile external effects. This is not host-row commit proof. */
|
|
116
|
+
onSegment?: SegmentHook;
|
|
117
|
+
/** Trusted. Return the session `id` names, after checking that `owner` may use it: an id
|
|
118
|
+
* from a request is not authorization. `start` reads its history inside the authenticated
|
|
119
|
+
* request; the worker gets it again, with the stored owner, to append the turn. */
|
|
120
|
+
session?: (owner: string, id: string) => Session | Promise<Session>;
|
|
121
|
+
/** Authenticate scopes in start and again in the worker. A changed erasure revision refuses
|
|
122
|
+
* resume; this factory never recalls notes or ingests a completed run automatically. */
|
|
123
|
+
memory?: (owner: string) => MemoryBinding | Promise<MemoryBinding>;
|
|
124
|
+
/** How many of the session's newest messages `start` loads. */
|
|
125
|
+
historyLimit?: number;
|
|
126
|
+
/** Runs once in `start`, before the run is saved. See RunOptions.prepareHistory. */
|
|
127
|
+
prepareHistory?: RunOptions["prepareHistory"];
|
|
59
128
|
}
|
|
60
129
|
|
|
61
|
-
|
|
130
|
+
/** Server-side: the snapshot holds the whole conversation, prompts and tool data. Send a
|
|
131
|
+
* browser a projection, never this object. */
|
|
132
|
+
export interface BackgroundRun<T, R extends NodeOutcome<T> = RunOutcome<T>> {
|
|
62
133
|
id: string;
|
|
63
134
|
/** Host completion is not SDK completion: a successful segment can be suspended or failed. */
|
|
64
135
|
status: StoredRun["status"];
|
|
65
|
-
snapshot:
|
|
66
|
-
outcome
|
|
136
|
+
snapshot: R["snapshot"];
|
|
137
|
+
/** outcome.session says whether the worker's append saved the turn. */
|
|
138
|
+
outcome: R | null;
|
|
139
|
+
/** Earliest pending wake in the tree. The host schedules continuation. */
|
|
140
|
+
wakeAt?: number;
|
|
67
141
|
error: StoredRun["error"];
|
|
68
142
|
}
|
|
69
143
|
|
|
@@ -81,62 +155,114 @@ export class BackgroundEnqueueError extends Error {
|
|
|
81
155
|
}
|
|
82
156
|
}
|
|
83
157
|
|
|
84
|
-
interface Segment {
|
|
158
|
+
interface Segment<N extends TreeNode = TreeNode> {
|
|
85
159
|
format: 1;
|
|
86
|
-
snapshot:
|
|
160
|
+
snapshot: N;
|
|
87
161
|
continuation?: Continuation;
|
|
88
162
|
}
|
|
89
163
|
|
|
90
|
-
/**
|
|
91
|
-
*
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
}
|
|
105
|
-
if (node.state.status !== "suspended" || !equalData(node.state.approval, pending.approval))
|
|
106
|
-
return false;
|
|
107
|
-
for (const [index, ancestor] of route.entries()) {
|
|
108
|
-
const state = ancestor.state;
|
|
109
|
-
if (
|
|
110
|
-
state.status !== "running" &&
|
|
111
|
-
!(
|
|
112
|
-
state.status === "suspended" &&
|
|
113
|
-
equalData(state.approval, pending.approval) &&
|
|
114
|
-
equalData(state.path, pending.path.slice(index))
|
|
115
|
-
)
|
|
116
|
-
)
|
|
117
|
-
return false;
|
|
118
|
-
}
|
|
119
|
-
for (const [index, ancestor] of route.entries())
|
|
120
|
-
ancestor.state = { ...copyData(pending), path: pending.path.slice(index) };
|
|
121
|
-
return true;
|
|
164
|
+
/** A root segment's stored result. The session status is only known to the worker that
|
|
165
|
+
* appended, so it is kept beside the snapshot rather than derived from it. */
|
|
166
|
+
interface Settled {
|
|
167
|
+
format: 1;
|
|
168
|
+
snapshot: unknown;
|
|
169
|
+
session?: SessionStatus;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function settled(raw: unknown): Settled {
|
|
173
|
+
const invalid = () => new TypeError("This row's result is not an agent segment result.");
|
|
174
|
+
if (!isRecord(raw) || raw.format !== 1) throw invalid();
|
|
175
|
+
const session = raw.session;
|
|
176
|
+
if (session === undefined) return { format: 1, snapshot: raw.snapshot };
|
|
177
|
+
if (!isSessionStatus(session)) throw invalid();
|
|
178
|
+
return { format: 1, snapshot: raw.snapshot, session };
|
|
122
179
|
}
|
|
123
180
|
|
|
124
181
|
/** Background work uses the host's lease, queue and cancellation. Children stay in-process.
|
|
125
182
|
* Usage remains in stable SDK receipts; this binding never calls additive Run.spend. */
|
|
126
|
-
export function createBackgroundAgent<T>(
|
|
127
|
-
|
|
183
|
+
export function createBackgroundAgent<T>(
|
|
184
|
+
options: BackgroundOptions<T>,
|
|
185
|
+
): ReturnType<typeof bindBackground<AgentInput, RunOutcome<T>>>;
|
|
186
|
+
export function createBackgroundAgent<T>(
|
|
187
|
+
options: BackgroundRemoteOptions<T>,
|
|
188
|
+
): ReturnType<typeof bindBackground<AgentInput, RemoteOutcome<T>>>;
|
|
189
|
+
export function createBackgroundAgent<I, O>(
|
|
190
|
+
options: BackgroundWorkflowOptions<I, O>,
|
|
191
|
+
): ReturnType<typeof bindBackground<I, WorkflowOutcome<O>>>;
|
|
192
|
+
export function createBackgroundAgent<I, O>(
|
|
193
|
+
options: BackgroundOptions<O> | BackgroundRemoteOptions<O> | BackgroundWorkflowOptions<I, O>,
|
|
194
|
+
) {
|
|
195
|
+
if ("workflow" in options) {
|
|
196
|
+
const workflow = options.workflow;
|
|
197
|
+
return bindBackground<I, WorkflowOutcome<O>>(options, {
|
|
198
|
+
...workflow[AGENT_RUNTIME],
|
|
199
|
+
resume: (raw, opts) => workflow.resume(raw, opts),
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
const agent = options.agent;
|
|
203
|
+
if (agent.kind === "remote")
|
|
204
|
+
return bindBackground<AgentInput, RemoteOutcome<O>>(options, {
|
|
205
|
+
...agent[AGENT_RUNTIME],
|
|
206
|
+
resume: (raw, opts) => agent.resume(raw, opts),
|
|
207
|
+
});
|
|
208
|
+
const runtime = agent[AGENT_RUNTIME];
|
|
209
|
+
return bindBackground<AgentInput, RunOutcome<O>>(options, {
|
|
210
|
+
open: (input, opts, id) => runtime.open(input, opts, id),
|
|
211
|
+
restore: (raw) => runtime.restore(raw),
|
|
212
|
+
hydrate: (snapshot) => runtime.node.hydrate(snapshot),
|
|
213
|
+
resume: (raw, opts) => agent.resume(raw, opts),
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
function bindBackground<I, R extends NodeOutcome>(
|
|
217
|
+
options: BackgroundBase,
|
|
218
|
+
runtime: {
|
|
219
|
+
open(input: I, options: RunOptions, runId: string): Promise<R["snapshot"]>;
|
|
220
|
+
restore(raw: unknown): R["snapshot"];
|
|
221
|
+
hydrate(snapshot: TreeNode): R;
|
|
222
|
+
resume(raw: unknown, options: ResumeOptions): Promise<R>;
|
|
223
|
+
},
|
|
224
|
+
) {
|
|
225
|
+
const { kind, runs, enqueue, historyLimit, prepareHistory, events = "best-effort" } = options;
|
|
226
|
+
if (events !== "best-effort" && events !== "awaited")
|
|
227
|
+
throw new TypeError('events must be "best-effort" or "awaited".');
|
|
128
228
|
if (!isId(kind) || typeof enqueue !== "function" || typeof options.policy !== "function")
|
|
129
229
|
throw new TypeError(
|
|
130
230
|
"Provide a run kind, a durable enqueue callback and a trusted policy factory.",
|
|
131
231
|
);
|
|
132
|
-
|
|
232
|
+
if (options.createContinuation !== undefined && typeof options.createContinuation !== "function")
|
|
233
|
+
throw new TypeError(
|
|
234
|
+
"createContinuation must atomically create or reconcile a saved continuation.",
|
|
235
|
+
);
|
|
236
|
+
if (options.onSegment !== undefined && typeof options.onSegment !== "function")
|
|
237
|
+
throw new TypeError("onSegment must be a function.");
|
|
238
|
+
if (options.session !== undefined && typeof options.session !== "function")
|
|
239
|
+
throw new TypeError("The session option must be a factory: (owner, id) => Session.");
|
|
240
|
+
checkOptions({ historyLimit, prepareHistory });
|
|
241
|
+
if (options.memory !== undefined && typeof options.memory !== "function")
|
|
242
|
+
throw new TypeError("The memory option must be a trusted owner-to-binding factory.");
|
|
243
|
+
async function memoryFor(owner: string, signal: AbortSignal) {
|
|
244
|
+
return options.memory
|
|
245
|
+
? readMemoryBinding(await untilAbort(Promise.resolve(options.memory(owner)), signal))
|
|
246
|
+
: undefined;
|
|
247
|
+
}
|
|
248
|
+
async function sessionFor(owner: string, id: string, signal: AbortSignal): Promise<Session> {
|
|
249
|
+
const factory = options.session;
|
|
250
|
+
if (!factory)
|
|
251
|
+
throw new TypeError(
|
|
252
|
+
"This run uses a session. Pass a session factory to createBackgroundAgent.",
|
|
253
|
+
);
|
|
254
|
+
const session: unknown = await untilAbort(Promise.resolve(factory(owner, id)), signal);
|
|
255
|
+
if (!isSession(session) || session.id !== id)
|
|
256
|
+
throw new TypeError("The session factory must return the session with that id.");
|
|
257
|
+
return session;
|
|
258
|
+
}
|
|
133
259
|
|
|
134
260
|
async function policy(context: BackgroundContext): Promise<BackgroundPolicy> {
|
|
135
261
|
const value = await options.policy(immutableCopy(context));
|
|
136
262
|
for (const key of [
|
|
137
263
|
"authorizeResume",
|
|
138
|
-
"
|
|
139
|
-
"
|
|
264
|
+
"prepareRequest",
|
|
265
|
+
"resolveRequest",
|
|
140
266
|
"beforeTool",
|
|
141
267
|
"claimContinuation",
|
|
142
268
|
] as const)
|
|
@@ -145,7 +271,7 @@ export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
|
|
|
145
271
|
return value;
|
|
146
272
|
}
|
|
147
273
|
|
|
148
|
-
function segment(raw: unknown): Segment {
|
|
274
|
+
function segment(raw: unknown): Segment<R["snapshot"]> {
|
|
149
275
|
if (!isRecord(raw) || raw.format !== 1)
|
|
150
276
|
throw new TypeError("This row is not an agent background segment.");
|
|
151
277
|
const snapshot = runtime.restore(raw.snapshot);
|
|
@@ -153,30 +279,50 @@ export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
|
|
|
153
279
|
const continuation = raw.continuation;
|
|
154
280
|
if (
|
|
155
281
|
!isRecord(continuation) ||
|
|
282
|
+
snapshot.state.status !== "suspended" ||
|
|
156
283
|
!isId(continuation.id) ||
|
|
157
284
|
!isId(continuation.sourceId) ||
|
|
158
|
-
continuation.
|
|
285
|
+
!isRecord(continuation.answers) ||
|
|
286
|
+
!["answers", "cancel"].includes(String(continuation.kind)) ||
|
|
287
|
+
Object.keys(continuation).some(
|
|
288
|
+
(key) => !["id", "sourceId", "kind", "answers", "wakeAt"].includes(key),
|
|
289
|
+
) ||
|
|
290
|
+
(continuation.kind === "cancel" &&
|
|
291
|
+
(Object.keys(continuation.answers).length !== 0 ||
|
|
292
|
+
continuation.wakeAt !== undefined ||
|
|
293
|
+
continuation.id !== `cancel/${continuation.sourceId}`)) ||
|
|
294
|
+
(continuation.kind === "answers" &&
|
|
295
|
+
(Object.keys(continuation.answers).length === 0
|
|
296
|
+
? continuation.wakeAt === undefined
|
|
297
|
+
: continuation.wakeAt !== undefined)) ||
|
|
298
|
+
(continuation.wakeAt !== undefined &&
|
|
299
|
+
(typeof continuation.wakeAt !== "number" || continuation.wakeAt !== wakeAt(snapshot)))
|
|
159
300
|
)
|
|
160
301
|
throw new TypeError("The saved continuation is invalid.");
|
|
161
302
|
return {
|
|
162
303
|
format: 1,
|
|
163
304
|
snapshot,
|
|
164
|
-
continuation:
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
305
|
+
continuation:
|
|
306
|
+
continuation.kind === "cancel"
|
|
307
|
+
? {
|
|
308
|
+
kind: "cancel",
|
|
309
|
+
id: continuation.id,
|
|
310
|
+
sourceId: continuation.sourceId,
|
|
311
|
+
answers: {},
|
|
312
|
+
}
|
|
313
|
+
: {
|
|
314
|
+
kind: "answers",
|
|
315
|
+
id: continuation.id,
|
|
316
|
+
sourceId: continuation.sourceId,
|
|
317
|
+
...(typeof continuation.wakeAt === "number" ? { wakeAt: continuation.wakeAt } : {}),
|
|
318
|
+
answers: readAnswers(snapshot, continuation.answers),
|
|
319
|
+
},
|
|
169
320
|
};
|
|
170
321
|
}
|
|
171
322
|
|
|
172
|
-
function restore(raw: unknown, initial:
|
|
323
|
+
function restore(raw: unknown, initial: TreeNode): R["snapshot"] {
|
|
173
324
|
const saved = runtime.restore(raw);
|
|
174
|
-
|
|
175
|
-
saved.runId !== initial.runId ||
|
|
176
|
-
saved.input !== initial.input ||
|
|
177
|
-
!equalData(saved.tree, initial.tree)
|
|
178
|
-
)
|
|
179
|
-
throw new TypeError("The saved journal belongs to another logical run.");
|
|
325
|
+
checkChildProgress(initial, saved);
|
|
180
326
|
return saved;
|
|
181
327
|
}
|
|
182
328
|
|
|
@@ -187,29 +333,52 @@ export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
|
|
|
187
333
|
if (!row || row.owner !== owner || row.kind !== kind)
|
|
188
334
|
throw new Error("This background run was not found for this owner and agent.");
|
|
189
335
|
const initial = segment(row.input);
|
|
336
|
+
const result = row.status === "succeeded" ? settled(row.result) : undefined;
|
|
190
337
|
const snapshot = restore(
|
|
191
|
-
|
|
338
|
+
result ? result.snapshot : (row.checkpoint ?? initial.snapshot),
|
|
192
339
|
initial.snapshot,
|
|
193
340
|
);
|
|
194
341
|
if (row.status === "succeeded" && snapshot.state.status === "running")
|
|
195
342
|
throw new TypeError("The host segment ended without a settled agent journal.");
|
|
196
|
-
return { row, initial, snapshot };
|
|
343
|
+
return { row, initial, snapshot, session: result?.session };
|
|
197
344
|
}
|
|
198
345
|
|
|
199
|
-
async function read(owner: string, id: string): Promise<BackgroundRun<
|
|
200
|
-
const { row, snapshot } = await load(owner, id);
|
|
346
|
+
async function read(owner: string, id: string): Promise<BackgroundRun<unknown, R>> {
|
|
347
|
+
const { row, snapshot, session } = await load(owner, id);
|
|
201
348
|
return {
|
|
202
349
|
id: row.id,
|
|
203
350
|
status: row.status,
|
|
204
351
|
snapshot,
|
|
205
|
-
|
|
352
|
+
wakeAt: wakeAt(snapshot),
|
|
353
|
+
outcome:
|
|
354
|
+
snapshot.state.status === "running"
|
|
355
|
+
? null
|
|
356
|
+
: { ...runtime.hydrate(snapshot), ...(session ? { session } : {}) },
|
|
206
357
|
error: row.error,
|
|
207
358
|
};
|
|
208
359
|
}
|
|
209
360
|
|
|
210
361
|
async function create(owner: string, initial: Segment): Promise<{ id: string }> {
|
|
211
362
|
// Input is stored in the create transaction, before any id is acknowledged or queued.
|
|
212
|
-
const
|
|
363
|
+
const spec = { kind, owner, restart: "resume" as const, input: copyData(initial) };
|
|
364
|
+
const created =
|
|
365
|
+
options.createContinuation && initial.continuation
|
|
366
|
+
? await options.createContinuation(
|
|
367
|
+
immutableCopy({ ...spec, input: { ...initial, continuation: initial.continuation } }),
|
|
368
|
+
)
|
|
369
|
+
: await runs.create(spec);
|
|
370
|
+
if (options.createContinuation && initial.continuation) {
|
|
371
|
+
const saved = await runs.read(created.id, owner);
|
|
372
|
+
if (
|
|
373
|
+
!saved ||
|
|
374
|
+
saved.owner !== owner ||
|
|
375
|
+
saved.kind !== kind ||
|
|
376
|
+
!equalData(saved.input, initial)
|
|
377
|
+
)
|
|
378
|
+
throw new Error(
|
|
379
|
+
"The continuation host must commit the exact input before returning its id.",
|
|
380
|
+
);
|
|
381
|
+
}
|
|
213
382
|
try {
|
|
214
383
|
await enqueue(created.id);
|
|
215
384
|
} catch (cause) {
|
|
@@ -218,20 +387,50 @@ export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
|
|
|
218
387
|
return created;
|
|
219
388
|
}
|
|
220
389
|
|
|
221
|
-
async function drive(run:
|
|
390
|
+
async function drive(run: BackgroundWorker): Promise<Settled> {
|
|
222
391
|
run.signal.throwIfAborted();
|
|
392
|
+
// Capability refusal happens before policy, model or tool work. No timer survives drive.
|
|
393
|
+
const progress = createProgress(run, events);
|
|
394
|
+
try {
|
|
395
|
+
return await execute(run, progress);
|
|
396
|
+
} finally {
|
|
397
|
+
try {
|
|
398
|
+
await progress.flush();
|
|
399
|
+
} finally {
|
|
400
|
+
await progress.dispose();
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async function execute(
|
|
406
|
+
run: BackgroundWorker,
|
|
407
|
+
progress: ReturnType<typeof createProgress>,
|
|
408
|
+
): Promise<Settled> {
|
|
409
|
+
const signal = AbortSignal.any([run.signal, progress.signal]);
|
|
223
410
|
const initial = segment(run.input);
|
|
224
411
|
const snapshot = restore(run.checkpoint ?? initial.snapshot, initial.snapshot);
|
|
225
412
|
const trusted = await untilAbort(
|
|
226
413
|
policy({
|
|
227
414
|
owner: run.owner,
|
|
415
|
+
runId: snapshot.runId,
|
|
228
416
|
segmentId: run.id,
|
|
229
417
|
continuation: initial.continuation,
|
|
230
418
|
}),
|
|
231
419
|
run.signal,
|
|
232
420
|
);
|
|
233
421
|
run.signal.throwIfAborted();
|
|
234
|
-
|
|
422
|
+
// From the stored owner, never from the request that queued this segment.
|
|
423
|
+
const session =
|
|
424
|
+
snapshot.kind === "agent" && snapshot.session
|
|
425
|
+
? await sessionFor(run.owner, snapshot.session.id, run.signal)
|
|
426
|
+
: undefined;
|
|
427
|
+
const memory = await memoryFor(run.owner, signal);
|
|
428
|
+
checkMemoryBinding(snapshot, memory);
|
|
429
|
+
run.signal.throwIfAborted();
|
|
430
|
+
if (initial.continuation?.wakeAt !== undefined && Date.now() < initial.continuation.wakeAt)
|
|
431
|
+
throw new Error("The saved workflow wake is not due yet.");
|
|
432
|
+
if (initial.continuation) {
|
|
433
|
+
await untilAbort(Promise.resolve(trusted.authorizeResume(immutableCopy(snapshot))), signal);
|
|
235
434
|
await untilAbort(
|
|
236
435
|
Promise.resolve(
|
|
237
436
|
trusted.claimContinuation(
|
|
@@ -241,16 +440,26 @@ export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
|
|
|
241
440
|
),
|
|
242
441
|
run.signal,
|
|
243
442
|
);
|
|
244
|
-
|
|
443
|
+
}
|
|
444
|
+
if (run.resumed) await progress.resync(run.crashes);
|
|
445
|
+
const parents = new Map<string, BackgroundWorker>([[snapshot.runId, run]]);
|
|
245
446
|
const host: AgentHost & { authorizeResume: BackgroundPolicy["authorizeResume"] } = {
|
|
447
|
+
progress,
|
|
246
448
|
authorizeResume(saved) {
|
|
247
449
|
run.signal.throwIfAborted();
|
|
248
450
|
return untilAbort(Promise.resolve(trusted.authorizeResume(saved)), run.signal);
|
|
249
451
|
},
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
beforeTool: (request,
|
|
452
|
+
prepareRequest: (request) => trusted.prepareRequest(request),
|
|
453
|
+
resolveRequest: (request, evidence) => trusted.resolveRequest(request, evidence),
|
|
454
|
+
beforeTool: (request, decided) => trusted.beforeTool(request, decided),
|
|
455
|
+
...(trusted.beforeStep ? { beforeStep: trusted.beforeStep } : {}),
|
|
456
|
+
...(trusted.reconcileStep ? { reconcileStep: trusted.reconcileStep } : {}),
|
|
457
|
+
...(trusted.reconcileToolRetry ? { reconcileToolRetry: trusted.reconcileToolRetry } : {}),
|
|
458
|
+
...(trusted.needsApproval ? { needsApproval: trusted.needsApproval } : {}),
|
|
459
|
+
...(trusted.answerNow ? { answerNow: trusted.answerNow } : {}),
|
|
253
460
|
canRunConcurrently: (request) => trusted.canRunConcurrently?.(request) === true,
|
|
461
|
+
...(trusted.loadMedia ? { loadMedia: trusted.loadMedia } : {}),
|
|
462
|
+
...(trusted.inbox ? { inbox: trusted.inbox } : {}),
|
|
254
463
|
async checkpoint(saved) {
|
|
255
464
|
run.signal.throwIfAborted();
|
|
256
465
|
await run.save(saved);
|
|
@@ -292,38 +501,108 @@ export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
|
|
|
292
501
|
}
|
|
293
502
|
},
|
|
294
503
|
};
|
|
295
|
-
|
|
296
|
-
//
|
|
297
|
-
const pending =
|
|
298
|
-
const
|
|
299
|
-
continuation
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
signal
|
|
504
|
+
// A recovered segment may already have saved some decisions. Reuse only still-open
|
|
505
|
+
// ids from this exact claim; never apply the old evidence to a replacement request.
|
|
506
|
+
const pending = new Set(openRequests(snapshot).map((request) => request.id));
|
|
507
|
+
const answers = Object.fromEntries(
|
|
508
|
+
Object.entries(initial.continuation?.answers ?? {}).filter(([id]) => pending.has(id)),
|
|
509
|
+
);
|
|
510
|
+
async function notifySegment(phase: "start" | "end", saved: TreeNode): Promise<void> {
|
|
511
|
+
if (!options.onSegment) return;
|
|
512
|
+
signal.throwIfAborted();
|
|
513
|
+
const journal = immutableCopy(saved);
|
|
514
|
+
await untilAbort(Promise.resolve(host.authorizeResume(journal)), signal);
|
|
515
|
+
signal.throwIfAborted();
|
|
516
|
+
await untilAbort(
|
|
517
|
+
Promise.resolve(
|
|
518
|
+
options.onSegment(
|
|
519
|
+
Object.freeze({
|
|
520
|
+
phase,
|
|
521
|
+
owner: run.owner,
|
|
522
|
+
id: run.id,
|
|
523
|
+
runId: journal.runId,
|
|
524
|
+
signal,
|
|
525
|
+
state: journal.state,
|
|
526
|
+
snapshot: journal,
|
|
527
|
+
}),
|
|
528
|
+
),
|
|
529
|
+
),
|
|
530
|
+
signal,
|
|
531
|
+
);
|
|
532
|
+
signal.throwIfAborted();
|
|
533
|
+
}
|
|
534
|
+
await notifySegment("start", snapshot);
|
|
535
|
+
const result = await runtime.resume(snapshot, {
|
|
536
|
+
// The host lease remains live so authorization, checkpoints and segment end still run.
|
|
537
|
+
// This signal stops local execution only; it does not grant a remote CancelTask.
|
|
538
|
+
signal:
|
|
539
|
+
initial.continuation?.kind === "cancel"
|
|
540
|
+
? AbortSignal.any([signal, AbortSignal.abort()])
|
|
541
|
+
: signal,
|
|
304
542
|
context: trusted.context,
|
|
543
|
+
onEvent: trusted.onEvent,
|
|
544
|
+
onLifecycle: trusted.onLifecycle,
|
|
545
|
+
bindModelProvider: trusted.bindModelProvider,
|
|
546
|
+
memory,
|
|
305
547
|
host,
|
|
306
|
-
...(
|
|
307
|
-
|
|
308
|
-
: {}),
|
|
309
|
-
onEvent: (event) => run.emit("agent", event),
|
|
548
|
+
...(session ? { session } : {}),
|
|
549
|
+
answers,
|
|
310
550
|
});
|
|
311
551
|
// The portable loop reports cancellation as data. The run service needs its control
|
|
312
552
|
// exception back, or a cancelled/lost/draining worker could record a successful job.
|
|
313
553
|
run.signal.throwIfAborted();
|
|
314
|
-
|
|
554
|
+
await notifySegment("end", result.snapshot);
|
|
555
|
+
return {
|
|
556
|
+
format: 1,
|
|
557
|
+
snapshot: result.snapshot,
|
|
558
|
+
...("session" in result && result.session ? { session: result.session } : {}),
|
|
559
|
+
};
|
|
315
560
|
}
|
|
316
561
|
|
|
317
|
-
const handlers: Readonly<Record<string,
|
|
562
|
+
const handlers: Readonly<Record<string, (run: BackgroundWorker) => Promise<unknown>>> =
|
|
563
|
+
Object.freeze({ [kind]: drive });
|
|
318
564
|
return Object.freeze({
|
|
319
565
|
handlers,
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
566
|
+
/** Saves the run before returning its id. With `sessionId`, the session's history is read
|
|
567
|
+
* here, inside the authenticated request, and frozen into the run. `context` is only for
|
|
568
|
+
* resolving instructions and tools here; worker tools use policy.context. `signal` stops
|
|
569
|
+
* creation; it does not cancel the run once it is saved. */
|
|
570
|
+
async start(
|
|
571
|
+
owner: string,
|
|
572
|
+
input: I,
|
|
573
|
+
start: Pick<RunOptions, "runId" | "signal" | "context" | "enabledTools"> & {
|
|
574
|
+
sessionId?: string;
|
|
575
|
+
modelSettings?: RecordedModelSettings;
|
|
576
|
+
} = {},
|
|
577
|
+
): Promise<{ id: string }> {
|
|
578
|
+
if (!isId(owner)) throw new TypeError("Provide an authenticated owner.");
|
|
579
|
+
if (
|
|
580
|
+
!isRecord(start) ||
|
|
581
|
+
(start.runId !== undefined && !isId(start.runId)) ||
|
|
582
|
+
(start.sessionId !== undefined && !isId(start.sessionId)) ||
|
|
583
|
+
(start.signal !== undefined && !(start.signal instanceof AbortSignal))
|
|
584
|
+
)
|
|
585
|
+
throw new TypeError("Use non-empty run/session ids and an AbortSignal when supplied.");
|
|
586
|
+
checkOptions(start);
|
|
587
|
+
const modelSettings = readModelSettings(start.modelSettings);
|
|
588
|
+
if (modelSettings.onActivity || modelSettings.onRateLimit)
|
|
589
|
+
throw new TypeError(
|
|
590
|
+
"Background modelSettings cannot keep observers. Set onActivity and onRateLimit on the agent instead.",
|
|
591
|
+
);
|
|
592
|
+
const signal = start.signal ?? new AbortController().signal;
|
|
593
|
+
signal.throwIfAborted();
|
|
594
|
+
const session =
|
|
595
|
+
start.sessionId === undefined
|
|
596
|
+
? undefined
|
|
597
|
+
: await sessionFor(owner, start.sessionId, signal);
|
|
598
|
+
const memory = await memoryFor(owner, signal);
|
|
599
|
+
const snapshot = await runtime.open(
|
|
600
|
+
input,
|
|
601
|
+
{ ...start, memory, session, historyLimit, prepareHistory, signal },
|
|
602
|
+
start.runId ?? crypto.randomUUID(),
|
|
603
|
+
);
|
|
604
|
+
signal.throwIfAborted();
|
|
605
|
+
return create(owner, { format: 1, snapshot: runtime.restore(snapshot) });
|
|
327
606
|
},
|
|
328
607
|
read,
|
|
329
608
|
async *observe(
|
|
@@ -338,27 +617,79 @@ export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
|
|
|
338
617
|
yield event;
|
|
339
618
|
}
|
|
340
619
|
},
|
|
341
|
-
async wait(
|
|
620
|
+
async wait(
|
|
621
|
+
owner: string,
|
|
622
|
+
id: string,
|
|
623
|
+
signal?: AbortSignal,
|
|
624
|
+
): Promise<BackgroundRun<unknown, R>> {
|
|
342
625
|
await load(owner, id);
|
|
343
626
|
for await (const _event of runs.tail(id, 0, signal)) signal?.throwIfAborted();
|
|
344
627
|
signal?.throwIfAborted();
|
|
345
628
|
return read(owner, id);
|
|
346
629
|
},
|
|
347
|
-
async cancel(owner: string, id: string): Promise<
|
|
348
|
-
await load(owner, id);
|
|
349
|
-
|
|
630
|
+
async cancel(owner: string, id: string): Promise<BackgroundCancelResult> {
|
|
631
|
+
const { row, snapshot, initial } = await load(owner, id);
|
|
632
|
+
// A second Stop must not abort the worker that still needs to save logical cancellation.
|
|
633
|
+
if (initial.continuation?.kind === "cancel") return { id, requested: true };
|
|
634
|
+
if (row.status === "succeeded" && snapshot.state.status === "suspended") {
|
|
635
|
+
if (!options.createContinuation)
|
|
636
|
+
throw new TypeError(
|
|
637
|
+
"Cancelling a suspended run requires the host's durable createContinuation capability. No segment was created.",
|
|
638
|
+
);
|
|
639
|
+
const continuation: Continuation = {
|
|
640
|
+
id: `cancel/${id}`,
|
|
641
|
+
sourceId: id,
|
|
642
|
+
kind: "cancel",
|
|
643
|
+
answers: {},
|
|
644
|
+
};
|
|
645
|
+
// The new worker must claim the current logical segment under its owner's policy.
|
|
646
|
+
// A repeated command has the same claim; a different worker cannot consume it again.
|
|
647
|
+
const created = await create(owner, { format: 1, snapshot, continuation });
|
|
648
|
+
return { id: created.id, requested: true };
|
|
649
|
+
}
|
|
650
|
+
if (row.status !== "queued" && row.status !== "running") return { id, requested: false };
|
|
651
|
+
return { id, requested: await runs.cancel(id) };
|
|
350
652
|
},
|
|
351
653
|
/** Queues decision evidence, not permission. The leased worker claims it; read or wait
|
|
352
654
|
* for that segment's outcome to learn whether the host accepted it. */
|
|
353
|
-
async resume(
|
|
655
|
+
async resume(
|
|
656
|
+
owner: string,
|
|
657
|
+
id: string,
|
|
658
|
+
answers: Readonly<Record<string, unknown>>,
|
|
659
|
+
): Promise<{ id: string }> {
|
|
354
660
|
const { row, snapshot } = await load(owner, id);
|
|
355
661
|
if (row.status !== "succeeded" || snapshot.state.status !== "suspended")
|
|
356
662
|
throw new Error("Only a settled, suspended agent segment can accept a decision.");
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
663
|
+
const submitted = readAnswers(snapshot, answers);
|
|
664
|
+
if (!Object.keys(submitted).length) {
|
|
665
|
+
const at = wakeAt(snapshot);
|
|
666
|
+
if (at === undefined || at > Date.now())
|
|
667
|
+
throw new TypeError(
|
|
668
|
+
at === undefined
|
|
669
|
+
? "Provide at least one answer by request id."
|
|
670
|
+
: `This workflow wakes at ${at}. Continue at or after that time.`,
|
|
671
|
+
);
|
|
672
|
+
}
|
|
673
|
+
if (
|
|
674
|
+
openRequests(snapshot).some(
|
|
675
|
+
(request) =>
|
|
676
|
+
Object.hasOwn(submitted, request.id) && request.scope.expiresAt <= Date.now(),
|
|
677
|
+
)
|
|
678
|
+
)
|
|
679
|
+
throw new Error("A request expired. Ask the host to renew it before continuing.");
|
|
680
|
+
const evidence = {
|
|
681
|
+
sourceId: id,
|
|
682
|
+
answers: submitted,
|
|
683
|
+
...(!Object.keys(submitted).length ? { wakeAt: wakeAt(snapshot) } : {}),
|
|
684
|
+
};
|
|
685
|
+
const continuation: Continuation = {
|
|
686
|
+
kind: "answers",
|
|
687
|
+
// With durable admission an uncertain response must reconcile the same exact claim.
|
|
688
|
+
id: options.createContinuation
|
|
689
|
+
? await requestHash({ owner, ...evidence })
|
|
690
|
+
: crypto.randomUUID(),
|
|
691
|
+
...evidence,
|
|
692
|
+
};
|
|
362
693
|
return create(owner, { format: 1, snapshot, continuation });
|
|
363
694
|
},
|
|
364
695
|
});
|