@providerkit/agents 0.0.0-stage → 0.1.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/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@providerkit/agents",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "An experimental, provider-independent agent loop with tools and resumable checkpoints.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Gustavo Salomé",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./runs": {
14
+ "types": "./dist/runs.d.ts",
15
+ "default": "./dist/runs.js"
16
+ }
17
+ },
18
+ "types": "./dist/index.d.ts",
19
+ "files": [
20
+ "dist",
21
+ "src",
22
+ "examples",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "sideEffects": false,
27
+ "engines": {
28
+ "node": ">=22"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "scripts": {
34
+ "build": "tsc",
35
+ "typecheck": "tsc --noEmit && tsc -p test",
36
+ "lint": "oxlint -c ../.oxlintrc.json src test examples",
37
+ "test": "vitest run",
38
+ "sync:docs": "cp ../LICENSE .",
39
+ "prepublishOnly": "bun run lint && bun run build && bun run typecheck && bun run sync:docs",
40
+ "release": "bun publish --access public"
41
+ },
42
+ "peerDependencies": {
43
+ "@providerkit/core": "^0.30.0",
44
+ "@gusnips/server": "^0.19.0"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "@gusnips/server": {
48
+ "optional": true
49
+ }
50
+ },
51
+ "devDependencies": {
52
+ "@providerkit/core": "0.30.0",
53
+ "@gusnips/server": "^0.19.0",
54
+ "@types/pg": "^8.15.0",
55
+ "pg": "^8.16.0",
56
+ "typescript": "^7.0.2",
57
+ "vitest": "^4.1.2"
58
+ },
59
+ "repository": {
60
+ "type": "git",
61
+ "url": "git+https://github.com/providerkit/providerkit.git",
62
+ "directory": "agents"
63
+ }
64
+ }
@@ -0,0 +1,405 @@
1
+ import { messageOf, type JsonObjectSchema, type ToolDefinition } from "@providerkit/core";
2
+ import {
3
+ checkChildProgress,
4
+ checkTree,
5
+ childRunId,
6
+ copyData,
7
+ equalData,
8
+ immutableCopy,
9
+ isId,
10
+ isRecord,
11
+ } from "./snapshot.ts";
12
+ import { fail, Halt, untilAbort, type ExecutionScope } from "./tree.ts";
13
+ import type {
14
+ Agent,
15
+ ChildEnvelope,
16
+ ChildPathStep,
17
+ DelegationExecution,
18
+ RunOptions,
19
+ RunOutcome,
20
+ RunSnapshot,
21
+ ToolResult,
22
+ } from "./types.ts";
23
+
24
+ /** Internal symbol holds no execution state. Every invocation receives its own scope. */
25
+ export const AGENT_RUNTIME = Symbol("agent-runtime");
26
+
27
+ export interface ApprovalEvidence {
28
+ path: readonly ChildPathStep[];
29
+ decision: unknown;
30
+ }
31
+
32
+ /** @internal */
33
+ export interface AgentRuntime<T> {
34
+ create(input: string, runId: string, tree?: RunSnapshot["tree"]): RunSnapshot;
35
+ restore(raw: unknown, tree?: RunSnapshot["tree"]): RunSnapshot;
36
+ hydrate(snapshot: RunSnapshot): RunOutcome<T>;
37
+ execute(
38
+ snapshot: RunSnapshot,
39
+ options: RunOptions,
40
+ scope: ExecutionScope,
41
+ evidence?: ApprovalEvidence,
42
+ ): Promise<RunOutcome<T>>;
43
+ }
44
+
45
+ export interface ChildHandle<T = unknown> {
46
+ readonly key: string;
47
+ readonly runId: string;
48
+ /** A started child, not another provider call. Repeated joins reuse the same outcome. */
49
+ join(): Promise<RunOutcome<T>>;
50
+ }
51
+
52
+ export type Joined<H extends readonly ChildHandle<unknown>[]> = {
53
+ [K in keyof H]: H[K] extends ChildHandle<infer T> ? RunOutcome<T> : never;
54
+ };
55
+
56
+ export interface DelegationContext {
57
+ child<T>(key: string, agent: Agent<T>, input: string): ChildHandle<T>;
58
+ /** Settles in caller order, not completion order. No child may outlive this barrier. */
59
+ join<const H extends readonly ChildHandle<unknown>[]>(handles: H): Promise<Joined<H>>;
60
+ }
61
+
62
+ export interface DelegationSpec<I, O> {
63
+ name: string;
64
+ description: string;
65
+ inputSchema: JsonObjectSchema;
66
+ validate: (raw: unknown) => I;
67
+ /** Fixed allow-list. Agents cannot add tools or specialists at runtime. */
68
+ specialists: readonly Agent<unknown>[];
69
+ /** Pure, deterministic coordination only: use child and join for work. This callback
70
+ * can replay after interruption; do not put external effects or mutable host state here. */
71
+ run: (input: I, context: DelegationContext) => Promise<O>;
72
+ summarize?: (output: O) => string;
73
+ }
74
+
75
+ /** Advertises a core tool definition, but deliberately is not an invokable core Tool. */
76
+ export interface Delegation {
77
+ readonly kind: "delegation";
78
+ readonly name: string;
79
+ readonly specialists: readonly Agent<unknown>[];
80
+ definition(): ToolDefinition;
81
+ /** @internal Errors and suspensions must not go through Tool.invoke's error conversion. */
82
+ execute(raw: unknown, context: DelegationContext): Promise<ToolResult>;
83
+ }
84
+
85
+ export interface SpecialistToolOptions<T> {
86
+ name: string;
87
+ description: string;
88
+ /** Pure; may run again when replaying coordination. */
89
+ summarize?: (output: T) => string;
90
+ }
91
+
92
+ export function isDelegation(value: { readonly name: string }): value is Delegation {
93
+ return "kind" in value && value.kind === "delegation";
94
+ }
95
+
96
+ export function defineDelegation<I, O>(spec: DelegationSpec<I, O>): Delegation {
97
+ if (
98
+ !isId(spec.name) ||
99
+ !isId(spec.description) ||
100
+ !isRecord(spec.inputSchema) ||
101
+ spec.inputSchema.type !== "object" ||
102
+ typeof spec.validate !== "function" ||
103
+ typeof spec.run !== "function" ||
104
+ (spec.summarize !== undefined && typeof spec.summarize !== "function")
105
+ )
106
+ throw new TypeError(
107
+ "A delegation needs a name, description, object schema, validator and coordinator.",
108
+ );
109
+ const specialists = Object.freeze([...spec.specialists]);
110
+ if (
111
+ specialists.some((agent) => !agent?.[AGENT_RUNTIME]) ||
112
+ new Set(specialists.map((agent) => agent.id)).size !== specialists.length
113
+ )
114
+ throw new TypeError("Register each specialist agent once, with a unique id.");
115
+ const definition = immutableCopy({
116
+ name: spec.name,
117
+ description: spec.description,
118
+ inputSchema: spec.inputSchema,
119
+ });
120
+ const { validate, run, summarize } = spec;
121
+ return Object.freeze({
122
+ kind: "delegation",
123
+ name: spec.name,
124
+ specialists,
125
+ definition: () => copyData(definition),
126
+ async execute(raw: unknown, context: DelegationContext): Promise<ToolResult> {
127
+ let input: I;
128
+ try {
129
+ input = validate(copyData(raw));
130
+ } catch (error) {
131
+ return { ok: false, kind: "invalid_input", content: messageOf(error) };
132
+ }
133
+ const output = await run(input, context);
134
+ const content = summarize ? summarize(output) : JSON.stringify(output);
135
+ if (typeof content !== "string") throw new TypeError("A delegation summary must be text.");
136
+ return { ok: true, content };
137
+ },
138
+ });
139
+ }
140
+
141
+ export function specialistTool<T>(agent: Agent<T>, options: SpecialistToolOptions<T>): Delegation {
142
+ return defineDelegation({
143
+ ...options,
144
+ inputSchema: {
145
+ type: "object",
146
+ properties: { input: { type: "string" } },
147
+ required: ["input"],
148
+ additionalProperties: false,
149
+ },
150
+ specialists: [agent],
151
+ validate(raw) {
152
+ if (!isRecord(raw) || !isId(raw.input) || Object.keys(raw).some((key) => key !== "input"))
153
+ throw new TypeError("Pass one non-empty input string to the specialist.");
154
+ return raw.input;
155
+ },
156
+ async run(input, context) {
157
+ const result = await context.child("result", agent, input).join();
158
+ if (result.status !== "completed") {
159
+ // A suspension is lifted with its child path by executeDelegation below.
160
+ const state = result.snapshot.state;
161
+ if (state.status === "running" || state.status === "completed")
162
+ throw new Error("The specialist outcome does not match its snapshot.");
163
+ throw new Halt(state);
164
+ }
165
+ return result.output;
166
+ },
167
+ });
168
+ }
169
+
170
+ /** The whole pure coordination barrier lends its parent's slot, not each join.
171
+ * Overlapping joins therefore cannot reacquire a slot while another join still waits. */
172
+ export async function executeDelegation(
173
+ descriptor: Delegation,
174
+ journal: DelegationExecution,
175
+ parent: RunSnapshot,
176
+ raw: unknown,
177
+ options: RunOptions,
178
+ scope: ExecutionScope,
179
+ signal: AbortSignal,
180
+ active: () => void,
181
+ evidence?: ApprovalEvidence,
182
+ ): Promise<ToolResult> {
183
+ let open = true;
184
+ const started = new Map<string, Promise<void>>();
185
+ const handles = new WeakSet<ChildHandle<unknown>>();
186
+
187
+ function child<T>(key: string, agent: Agent<T>, input: string): ChildHandle<T> {
188
+ if (!open)
189
+ throw new Error("This delegation has ended; start children only inside its coordinator.");
190
+ active();
191
+ if (!isId(key) || !isId(input))
192
+ throw new TypeError("A child needs a non-empty key and text input.");
193
+ if (!descriptor.specialists.includes(agent))
194
+ fail(
195
+ "unregistered_specialist",
196
+ "Register this specialist in the delegation before starting it.",
197
+ journal.operationId,
198
+ );
199
+ const runtime = agent[AGENT_RUNTIME];
200
+ let entry = journal.children.find((saved) => saved.key === key);
201
+ const resume = entry !== undefined;
202
+ if (entry) {
203
+ if (
204
+ entry.snapshot.agentId !== agent.id ||
205
+ entry.snapshot.version !== agent.version ||
206
+ entry.snapshot.input !== input
207
+ )
208
+ fail(
209
+ "child_key_conflict",
210
+ "This child key already belongs to another agent, version or input.",
211
+ journal.operationId,
212
+ );
213
+ } else {
214
+ scope.tree.reserveChild(scope.depth + 1);
215
+ entry = {
216
+ key,
217
+ snapshot: runtime.create(input, childRunId(journal.operationId, key), parent.tree),
218
+ };
219
+ journal.children.push(entry);
220
+ }
221
+ const saved = entry;
222
+ if (!started.has(key)) {
223
+ const work = async () => {
224
+ if (
225
+ saved.snapshot.state.status !== "running" &&
226
+ saved.snapshot.state.status !== "suspended"
227
+ )
228
+ return;
229
+ await scope.tree.save();
230
+ active();
231
+ const step = { operationId: journal.operationId, key, runId: saved.snapshot.runId };
232
+ const childEvidence =
233
+ evidence && equalData(evidence.path[0], step)
234
+ ? { path: evidence.path.slice(1), decision: evidence.decision }
235
+ : undefined;
236
+ let execution: Promise<ChildEnvelope> | undefined;
237
+ let hookOpen = true;
238
+ let executionSettled = false;
239
+ const execute = () => {
240
+ if (!hookOpen || execution)
241
+ throw new Error("A host child may execute once, before its hook returns.");
242
+ execution = (async () => {
243
+ if (resume) saved.snapshot.attemptId = crypto.randomUUID();
244
+ const result = await runtime.execute(
245
+ saved.snapshot,
246
+ { ...options, signal },
247
+ { tree: scope.tree, depth: scope.depth + 1 },
248
+ childEvidence,
249
+ );
250
+ executionSettled = true;
251
+ return { snapshot: result.snapshot };
252
+ })();
253
+ // A hook that throws or forgets to await cannot leave an unhandled child promise.
254
+ void execution.catch(() => {});
255
+ return execution;
256
+ };
257
+ let envelope: ChildEnvelope;
258
+ try {
259
+ envelope = options.host?.child
260
+ ? await untilAbort(
261
+ Promise.resolve(
262
+ options.host.child(
263
+ immutableCopy({
264
+ ...saved,
265
+ parentRunId: parent.runId,
266
+ operationId: journal.operationId,
267
+ resume,
268
+ }),
269
+ execute,
270
+ ),
271
+ ),
272
+ signal,
273
+ )
274
+ : await execute();
275
+ if (execution && !executionSettled)
276
+ fail(
277
+ "invalid_child_host",
278
+ "The child hook returned before its execution settled.",
279
+ journal.operationId,
280
+ );
281
+ } finally {
282
+ hookOpen = false;
283
+ if (execution) await execution;
284
+ }
285
+ if (!isRecord(envelope) || (envelope.reference !== undefined && !isId(envelope.reference)))
286
+ fail(
287
+ "invalid_child_host",
288
+ "The child hook must return a snapshot envelope.",
289
+ journal.operationId,
290
+ );
291
+ const restored = runtime.restore(envelope.snapshot, parent.tree);
292
+ checkChildProgress(saved.snapshot, restored);
293
+ if (restored.state.status === "running")
294
+ fail(
295
+ "invalid_child_host",
296
+ "The child hook returned an unfinished child.",
297
+ journal.operationId,
298
+ );
299
+ // Returning a cached suspended host segment cannot consume an SDK approval.
300
+ if (!execution && childEvidence && restored.state.status === "suspended")
301
+ fail(
302
+ "host_resume_unsupported",
303
+ "The host returned a cached suspension. Resume this child in a new or resumable host segment.",
304
+ journal.operationId,
305
+ );
306
+ const previous = saved.snapshot;
307
+ saved.snapshot = restored;
308
+ try {
309
+ checkTree(scope.tree.root);
310
+ } catch (error) {
311
+ saved.snapshot = previous;
312
+ throw error;
313
+ }
314
+ saved.reference = envelope.reference ?? saved.reference;
315
+ await scope.tree.save();
316
+ };
317
+ const promise = work().catch(async (error: unknown) => {
318
+ let failure = error;
319
+ try {
320
+ active();
321
+ } catch (stopped) {
322
+ failure = stopped;
323
+ }
324
+ if (saved.snapshot.state.status === "running") {
325
+ saved.snapshot.state =
326
+ failure instanceof Halt
327
+ ? failure.state
328
+ : {
329
+ status: "failed",
330
+ error: { code: "child_host_failed", message: messageOf(failure) },
331
+ };
332
+ await scope.tree.save();
333
+ }
334
+ throw failure;
335
+ });
336
+ started.set(key, promise);
337
+ void promise.catch(() => {});
338
+ }
339
+ const pending = started.get(key);
340
+ const handle = Object.freeze({
341
+ key,
342
+ runId: saved.snapshot.runId,
343
+ async join(): Promise<RunOutcome<T>> {
344
+ await pending;
345
+ return runtime.hydrate(saved.snapshot);
346
+ },
347
+ });
348
+ handles.add(handle);
349
+ return handle;
350
+ }
351
+
352
+ function join<const H extends readonly ChildHandle<unknown>[]>(items: H): Promise<Joined<H>>;
353
+ async function join(items: readonly ChildHandle<unknown>[]): Promise<RunOutcome<unknown>[]> {
354
+ if (items.some((handle) => !handles.has(handle)))
355
+ throw new TypeError("Join only handles created by this delegation context.");
356
+ return Promise.all(items.map((handle) => handle.join()));
357
+ }
358
+
359
+ let result: ToolResult | undefined;
360
+ let failure: { error: unknown } | undefined;
361
+ try {
362
+ result = await untilAbort(descriptor.execute(raw, Object.freeze({ child, join })), signal);
363
+ } catch (error) {
364
+ failure = { error };
365
+ } finally {
366
+ // Even ignored children belong to this parent, including children admitted on an
367
+ // earlier attempt that pure coordination did not revisit this time.
368
+ try {
369
+ for (const entry of journal.children) {
370
+ if (started.has(entry.key)) continue;
371
+ const agent = descriptor.specialists.find(
372
+ (agent) =>
373
+ agent.id === entry.snapshot.agentId && agent.version === entry.snapshot.version,
374
+ );
375
+ if (!agent)
376
+ fail("unregistered_specialist", "The saved child is not a registered specialist.");
377
+ child(entry.key, agent, entry.snapshot.input);
378
+ }
379
+ } catch (error) {
380
+ failure ??= { error };
381
+ }
382
+ open = false;
383
+ const settled = await Promise.allSettled(started.values());
384
+ const rejected = settled.find((item) => item.status === "rejected");
385
+ if (rejected?.status === "rejected") failure = { error: rejected.reason };
386
+ }
387
+ active();
388
+ if (failure && !(failure.error instanceof Halt && failure.error.state.status === "suspended"))
389
+ throw failure.error;
390
+ for (const entry of journal.children) {
391
+ const state = entry.snapshot.state;
392
+ if (state.status === "suspended") {
393
+ throw new Halt({
394
+ ...state,
395
+ path: [
396
+ { operationId: journal.operationId, key: entry.key, runId: entry.snapshot.runId },
397
+ ...state.path,
398
+ ],
399
+ });
400
+ }
401
+ }
402
+ if (failure) throw failure.error;
403
+ if (!result) throw new Error("The delegation ended without a result.");
404
+ return result;
405
+ }
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ export { defineAgent, RESULT_TOOL_NAME } from "./run.ts";
2
+ export { defineDelegation } from "./delegation.ts";
3
+ export type {
4
+ ChildHandle,
5
+ Delegation,
6
+ DelegationContext,
7
+ DelegationSpec,
8
+ Joined,
9
+ SpecialistToolOptions,
10
+ } from "./delegation.ts";
11
+ export type * from "./types.ts";