@restatedev/agents 0.6.0 → 0.8.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/README.md +41 -14
- package/dist/agentlib/agent.d.ts +32 -0
- package/dist/agentlib/agent.d.ts.map +1 -0
- package/dist/agentlib/agent.js +172 -0
- package/dist/agentlib/agent.js.map +1 -0
- package/dist/agentlib/index.d.ts +5 -0
- package/dist/agentlib/index.d.ts.map +1 -0
- package/dist/agentlib/index.js +15 -0
- package/dist/agentlib/index.js.map +1 -0
- package/dist/agentlib/messages.d.ts +39 -0
- package/dist/agentlib/messages.d.ts.map +1 -0
- package/dist/agentlib/messages.js +177 -0
- package/dist/agentlib/messages.js.map +1 -0
- package/dist/agentlib/model.d.ts +29 -0
- package/dist/agentlib/model.d.ts.map +1 -0
- package/dist/agentlib/model.js +131 -0
- package/dist/agentlib/model.js.map +1 -0
- package/dist/agentlib/options.d.ts +58 -0
- package/dist/agentlib/options.d.ts.map +1 -0
- package/dist/agentlib/options.js +2 -0
- package/dist/agentlib/options.js.map +1 -0
- package/dist/agentlib/runtime.d.ts +37 -0
- package/dist/agentlib/runtime.d.ts.map +1 -0
- package/dist/agentlib/runtime.js +216 -0
- package/dist/agentlib/runtime.js.map +1 -0
- package/dist/agentlib/state.d.ts +114 -0
- package/dist/agentlib/state.d.ts.map +1 -0
- package/dist/agentlib/state.js +52 -0
- package/dist/agentlib/state.js.map +1 -0
- package/dist/agentlib/steering.d.ts +23 -0
- package/dist/agentlib/steering.d.ts.map +1 -0
- package/dist/agentlib/steering.js +48 -0
- package/dist/agentlib/steering.js.map +1 -0
- package/dist/agentlib/tools.d.ts +33 -0
- package/dist/agentlib/tools.d.ts.map +1 -0
- package/dist/agentlib/tools.js +243 -0
- package/dist/agentlib/tools.js.map +1 -0
- package/dist/agentlib/turn.d.ts +82 -0
- package/dist/agentlib/turn.d.ts.map +1 -0
- package/dist/agentlib/turn.js +253 -0
- package/dist/agentlib/turn.js.map +1 -0
- package/dist/claude/index.d.ts.map +1 -1
- package/dist/claude/index.js +3 -0
- package/dist/claude/index.js.map +1 -1
- package/dist/common.d.ts +8 -0
- package/dist/common.d.ts.map +1 -1
- package/dist/common.js +12 -0
- package/dist/common.js.map +1 -1
- package/dist/companion.d.ts +2 -1
- package/dist/companion.d.ts.map +1 -1
- package/dist/companion.js.map +1 -1
- package/dist/deepseek/index.d.ts +2 -6
- package/dist/deepseek/index.d.ts.map +1 -1
- package/dist/deepseek/index.js +6 -14
- package/dist/deepseek/index.js.map +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/langgraph/checkpointer.d.ts +1 -1
- package/dist/langgraph/checkpointer.d.ts.map +1 -1
- package/dist/langgraph/checkpointer.js +14 -5
- package/dist/langgraph/checkpointer.js.map +1 -1
- package/dist/opencode/index.d.ts.map +1 -1
- package/dist/opencode/index.js +11 -18
- package/dist/opencode/index.js.map +1 -1
- package/dist/pi/index.d.ts +2 -2
- package/dist/pi/index.d.ts.map +1 -1
- package/dist/pi/index.js +2 -3
- package/dist/pi/index.js.map +1 -1
- package/dist/pi/storage.d.ts +7 -0
- package/dist/pi/storage.d.ts.map +1 -1
- package/dist/pi/storage.js +12 -0
- package/dist/pi/storage.js.map +1 -1
- package/dist/tools.d.ts +53 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +32 -15
- package/dist/tools.js.map +1 -1
- package/package.json +115 -85
- package/src/agentlib/README.md +229 -0
- package/src/agentlib/agent.ts +214 -0
- package/src/agentlib/index.ts +16 -0
- package/src/agentlib/messages.ts +207 -0
- package/src/agentlib/model.ts +150 -0
- package/src/agentlib/options.ts +62 -0
- package/src/agentlib/runtime.ts +252 -0
- package/src/agentlib/state.ts +93 -0
- package/src/agentlib/steering.ts +53 -0
- package/src/agentlib/tools.ts +353 -0
- package/src/agentlib/turn.ts +302 -0
- package/src/claude/index.ts +3 -0
- package/src/common.ts +15 -0
- package/src/companion.ts +2 -1
- package/src/deepseek/index.ts +8 -18
- package/src/index.ts +6 -4
- package/src/langgraph/checkpointer.ts +25 -14
- package/src/opencode/index.ts +12 -17
- package/src/pi/index.ts +9 -4
- package/src/pi/storage.ts +13 -0
- package/src/tools.ts +118 -52
package/src/deepseek/index.ts
CHANGED
|
@@ -50,6 +50,7 @@ import { TokenMeter } from '@deepseek-ai/dsh-token-meter';
|
|
|
50
50
|
import { ToolResultPruner } from '@deepseek-ai/dsh-compaction-tool-result-pruner';
|
|
51
51
|
import { BasicCompactionEngine, type BasicCompactionConfig } from '@deepseek-ai/dsh-compaction-basic';
|
|
52
52
|
import { ApprovalService, type ApprovalOutcome } from '@deepseek-ai/dsh-user-approval';
|
|
53
|
+
import * as nativeExecutor from '@deepseek-ai/dsh-tool-executor-native';
|
|
53
54
|
import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
|
|
54
55
|
import {
|
|
55
56
|
defineTool,
|
|
@@ -74,13 +75,14 @@ import {
|
|
|
74
75
|
RETURNED_UNRECORDED,
|
|
75
76
|
stopSignalOf,
|
|
76
77
|
toolCallStarted,
|
|
78
|
+
approves,
|
|
77
79
|
} from '../common.ts';
|
|
78
80
|
import { answerOnce, type Items, type Parsed, type Run, type Turn } from '../conversation.ts';
|
|
79
81
|
import { tookSteers } from '../steering.ts';
|
|
80
82
|
import { conversationView } from '../messages.ts';
|
|
81
83
|
import { type Answer, withChecked } from '../output.ts';
|
|
82
84
|
import { type Definition, sessionObject } from '../object.ts';
|
|
83
|
-
import { isTool, jsonSchemaOf, type Tool as AnyTool, waitFor } from '../tools.ts';
|
|
85
|
+
import { type Approval, isTool, jsonSchemaOf, type Tool as AnyTool, waitFor } from '../tools.ts';
|
|
84
86
|
import type { z } from 'zod';
|
|
85
87
|
import { SqlSessionPersistence } from './persistence.ts';
|
|
86
88
|
|
|
@@ -147,6 +149,8 @@ async function boot(
|
|
|
147
149
|
await harness.plugin(SessionStore);
|
|
148
150
|
await harness.plugin(SystemPrompt, system ? { personaPrefix: system } : {});
|
|
149
151
|
await harness.plugin(ToolRuntime, {});
|
|
152
|
+
// The executor that runs the model's tool calls as the model asks for them.
|
|
153
|
+
await harness.plugin(nativeExecutor);
|
|
150
154
|
// Without it, the harness denies a call that asks for an approval. With it,
|
|
151
155
|
// the model is also told that some calls may ask for one.
|
|
152
156
|
if (approvals) await harness.plugin(ApprovalService, {});
|
|
@@ -280,24 +284,10 @@ const native = (t: AnyTool, ctx: restate.SessionContext): ToolDefinition =>
|
|
|
280
284
|
/** The signal that a tool call waits for, to the agent, when it needs a person's approval (`approval`). */
|
|
281
285
|
export const APPROVAL = 'approval';
|
|
282
286
|
|
|
283
|
-
|
|
284
|
-
export type Approval = readonly string[] | ((call: { name: string; args: unknown }) => boolean);
|
|
287
|
+
export type { Approval };
|
|
285
288
|
|
|
286
|
-
/**
|
|
287
|
-
const
|
|
288
|
-
|
|
289
|
-
/**
|
|
290
|
-
* What the value of an {@link APPROVAL} signal decides about its tool call:
|
|
291
|
-
* `true`, `{ "approved": true }`, or a text such as "approved" or "yes"
|
|
292
|
-
* approves it once; anything else rejects it, so a value that does not say
|
|
293
|
-
* "approved" never runs the tool.
|
|
294
|
-
*/
|
|
295
|
-
const decided = (value: unknown): ApprovalOutcome =>
|
|
296
|
-
value === true ||
|
|
297
|
-
(typeof value === 'string' && APPROVED.has(value.trim().toLowerCase())) ||
|
|
298
|
-
(typeof value === 'object' && value !== null && (value as { approved?: unknown }).approved === true)
|
|
299
|
-
? 'allowed-once'
|
|
300
|
-
: 'rejected';
|
|
289
|
+
/** What the value of an {@link APPROVAL} signal decides about its tool call (see `approves`): approved once, or rejected. */
|
|
290
|
+
const decided = (value: unknown): ApprovalOutcome => (approves(value) ? 'allowed-once' : 'rejected');
|
|
301
291
|
|
|
302
292
|
/**
|
|
303
293
|
* Have the harness of the agent of `agentCtx` ask for an approval before
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @restatedev/agents: agent frameworks in Restate session objects. Each framework
|
|
2
|
-
// is a subpath (@restatedev/agents/pi, /langgraph, /claude, /deepseek); this is what they share: session objects, tools for
|
|
2
|
+
// is a subpath (@restatedev/agents/pi, /langgraph, /claude, /deepseek, /opencode, /agentlib); this is what they share: session objects, tools for
|
|
3
3
|
// any of them, and the tools that are Restate itself.
|
|
4
4
|
|
|
5
5
|
export {
|
|
@@ -32,8 +32,10 @@ export { call, send, signal, subagent, tool, workflow, type Tool, type ToolCall,
|
|
|
32
32
|
export { webhook, webhookMessage, type WebhookAuth, type WebhookEvent, type WebhookOptions } from './webhook.ts';
|
|
33
33
|
|
|
34
34
|
/**
|
|
35
|
-
* @restatedev/sessions' `serve`: the services on PORT,
|
|
36
|
-
*
|
|
37
|
-
*
|
|
35
|
+
* @restatedev/sessions' `serve`: the services on PORT, or connected out to
|
|
36
|
+
* Restate Cloud where RESTATE_CONNECT_KEY is set, either way with what they
|
|
37
|
+
* need beside them (each agent's companion); and `served`, those services,
|
|
38
|
+
* for an endpoint of your own (`restate.endpoint()`), or for the SDK's own
|
|
39
|
+
* `restate.connect`, which without it leaves the companions unserved.
|
|
38
40
|
*/
|
|
39
41
|
export { serve, served } from '@restatedev/sessions';
|
|
@@ -11,7 +11,11 @@
|
|
|
11
11
|
// savers (a count and a random part): a thread forked from an earlier
|
|
12
12
|
// checkpoint takes the same counts again, and its values must not replace
|
|
13
13
|
// those of the branch it forked from.
|
|
14
|
-
// - `restate_langgraph_writes`: the pending writes of each checkpoint's tasks
|
|
14
|
+
// - `restate_langgraph_writes`: the pending writes of each checkpoint's tasks,
|
|
15
|
+
// with each task's path, and read back in LangGraph's order for them
|
|
16
|
+
// (`writesSortKey`: path, task id, index), the order live execution applies
|
|
17
|
+
// a step's writes in. A write without a path (graph input, a `Command`)
|
|
18
|
+
// comes first.
|
|
15
19
|
//
|
|
16
20
|
// Each `put` and `putWrites` is one SQL transaction, so a step is stored whole,
|
|
17
21
|
// in order with everything else the handler does. Operations run one at a
|
|
@@ -36,7 +40,9 @@ import {
|
|
|
36
40
|
copyCheckpoint,
|
|
37
41
|
maxChannelVersion,
|
|
38
42
|
TASKS,
|
|
43
|
+
compareWritesSortKeys,
|
|
39
44
|
WRITES_IDX_MAP,
|
|
45
|
+
writesSortKey,
|
|
40
46
|
type ChannelVersions,
|
|
41
47
|
type Checkpoint,
|
|
42
48
|
type CheckpointListOptions,
|
|
@@ -78,6 +84,7 @@ export const SCHEMA = new Schema('restate-agents.langgraph', [
|
|
|
78
84
|
channel TEXT NOT NULL,
|
|
79
85
|
type TEXT NOT NULL,
|
|
80
86
|
value BLOB NOT NULL,
|
|
87
|
+
task_path TEXT,
|
|
81
88
|
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
|
|
82
89
|
)`,
|
|
83
90
|
]);
|
|
@@ -260,10 +267,15 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
260
267
|
// A checkpoint of an earlier format (v < 4) keeps its pending sends as
|
|
261
268
|
// writes of its parent.
|
|
262
269
|
if (checkpoint.v < 4 && parentId !== null) await this.#migratePendingSends(checkpoint, threadId, ns, parentId);
|
|
263
|
-
const writes =
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
270
|
+
const writes = (
|
|
271
|
+
(await this.#db.values(
|
|
272
|
+
'SELECT task_id, channel, type, value, task_path, idx FROM restate_langgraph_writes WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?',
|
|
273
|
+
[threadId, ns, checkpointId],
|
|
274
|
+
)) as [string, string, string, Uint8Array, string | null, number][]
|
|
275
|
+
)
|
|
276
|
+
.map((row) => ({ row, key: writesSortKey(row[4] ?? '', row[0], row[5]) }))
|
|
277
|
+
.toSorted((a, b) => compareWritesSortKeys(a.key, b.key))
|
|
278
|
+
.map(({ row }) => row);
|
|
267
279
|
const config = (id: string) => ({ configurable: { thread_id: threadId, checkpoint_ns: ns, checkpoint_id: id } });
|
|
268
280
|
return {
|
|
269
281
|
config: config(checkpointId),
|
|
@@ -271,13 +283,11 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
271
283
|
metadata: await this.serde.loadsTyped(type, metadata),
|
|
272
284
|
parentConfig: parentId === null ? undefined : config(parentId),
|
|
273
285
|
pendingWrites: await Promise.all(
|
|
274
|
-
(
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
],
|
|
280
|
-
),
|
|
286
|
+
writes.map(async ([taskId, channel, writeType, value]): Promise<CheckpointPendingWrite> => [
|
|
287
|
+
taskId,
|
|
288
|
+
channel,
|
|
289
|
+
await this.serde.loadsTyped(writeType, value),
|
|
290
|
+
]),
|
|
281
291
|
),
|
|
282
292
|
};
|
|
283
293
|
}
|
|
@@ -428,7 +438,7 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
428
438
|
});
|
|
429
439
|
}
|
|
430
440
|
|
|
431
|
-
putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string): Promise<void> {
|
|
441
|
+
putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string, taskPath?: string): Promise<void> {
|
|
432
442
|
return this.#serial(async () => {
|
|
433
443
|
const { thread_id, checkpoint_ns = '', checkpoint_id } = config.configurable ?? {};
|
|
434
444
|
if (!thread_id) throw new Error('Missing thread_id field in config.configurable.');
|
|
@@ -447,13 +457,14 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
447
457
|
channel,
|
|
448
458
|
type,
|
|
449
459
|
stored,
|
|
460
|
+
taskPath ?? null,
|
|
450
461
|
];
|
|
451
462
|
}),
|
|
452
463
|
);
|
|
453
464
|
await this.#db.transaction(async (tx) => {
|
|
454
465
|
for (const row of rows) {
|
|
455
466
|
await tx.execute(
|
|
456
|
-
`${verb} INTO restate_langgraph_writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
467
|
+
`${verb} INTO restate_langgraph_writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value, task_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
457
468
|
row,
|
|
458
469
|
);
|
|
459
470
|
}
|
package/src/opencode/index.ts
CHANGED
|
@@ -96,6 +96,7 @@ import {
|
|
|
96
96
|
RETURNED_UNRECORDED,
|
|
97
97
|
stopSignalOf,
|
|
98
98
|
toolCallStarted,
|
|
99
|
+
approves,
|
|
99
100
|
} from '../common.ts';
|
|
100
101
|
import { answerOnce, invocationOf, type Call, type Items, type Parsed, STEPS, type Turn } from '../conversation.ts';
|
|
101
102
|
import { conversationView } from '../messages.ts';
|
|
@@ -797,27 +798,21 @@ function toolsPlugin(
|
|
|
797
798
|
/** The signal that an OpenCode tool call waits for, to the agent, when OpenCode asks for a permission (`approval`). */
|
|
798
799
|
export const APPROVAL = 'approval';
|
|
799
800
|
|
|
800
|
-
/** The texts that approve an ask, whatever their case. */
|
|
801
|
-
const APPROVED: ReadonlySet<string> = new Set(['approved', 'approve', 'yes', 'ok', 'allow', 'allowed']);
|
|
802
|
-
|
|
803
801
|
/**
|
|
804
|
-
* What the value of an {@link APPROVAL} signal decides
|
|
805
|
-
*
|
|
806
|
-
* anything else denies, with the reason it gives, if any (a text, or
|
|
802
|
+
* What the value of an {@link APPROVAL} signal decides (see `approves`):
|
|
803
|
+
* it allows, or denies with the reason it gives, if any (a text, or
|
|
807
804
|
* `{ "reason": "..." }`).
|
|
808
805
|
*/
|
|
809
806
|
function decided(value: unknown): { allowed: true } | { allowed: false; reason?: string } {
|
|
810
|
-
if (value
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
}
|
|
820
|
-
return { allowed: false };
|
|
807
|
+
if (approves(value)) return { allowed: true };
|
|
808
|
+
const given =
|
|
809
|
+
typeof value === 'string'
|
|
810
|
+
? value
|
|
811
|
+
: typeof value === 'object' && value !== null
|
|
812
|
+
? (value as { reason?: unknown }).reason
|
|
813
|
+
: undefined;
|
|
814
|
+
const reason = typeof given === 'string' ? given.trim() : '';
|
|
815
|
+
return { allowed: false, ...(reason ? { reason } : {}) };
|
|
821
816
|
}
|
|
822
817
|
|
|
823
818
|
/**
|
package/src/pi/index.ts
CHANGED
|
@@ -38,10 +38,15 @@
|
|
|
38
38
|
// and a coding tool cut off by a crash is not run again (the model is told
|
|
39
39
|
// it was interrupted).
|
|
40
40
|
import * as restate from '@restatedev/sessions';
|
|
41
|
-
import
|
|
42
|
-
|
|
41
|
+
import {
|
|
42
|
+
awaitWithContext,
|
|
43
|
+
BACKGROUND_CONTEXT,
|
|
44
|
+
type Context,
|
|
45
|
+
withCancel,
|
|
46
|
+
withoutAbortSignal,
|
|
47
|
+
} from '@earendil-works/chord/context';
|
|
43
48
|
import { mkdir } from 'node:fs/promises';
|
|
44
|
-
import {
|
|
49
|
+
import type { Message, MutableModels } from '@earendil-works/pi-ai';
|
|
45
50
|
import { createModels } from '@earendil-works/pi-ai/models';
|
|
46
51
|
import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
|
|
47
52
|
import {
|
|
@@ -300,7 +305,7 @@ const native = (t: AnyTool, ctx: restate.SessionContext): ToolRegistration =>
|
|
|
300
305
|
defineTool({
|
|
301
306
|
name: t.name,
|
|
302
307
|
description: t.description,
|
|
303
|
-
parameters:
|
|
308
|
+
parameters: jsonSchemaOf(t), // JSON Schema, as pi takes it
|
|
304
309
|
replay: 'safe', // a crash runs it again, with the same call id
|
|
305
310
|
// Aborted (the conversation's work, on a cancellation), it waits no more.
|
|
306
311
|
execute: async (args, { callId }, task) => ({
|
package/src/pi/storage.ts
CHANGED
|
@@ -33,6 +33,11 @@ class Executor implements SqliteExecutor {
|
|
|
33
33
|
async run(sql: string, ...params: SqliteValue[]) {
|
|
34
34
|
await this.db.execute(sql, params);
|
|
35
35
|
}
|
|
36
|
+
/** `run`, resolving with the rows it changed: SQLite's `changes()`, read next on the same connection. */
|
|
37
|
+
async runCounted(sql: string, ...params: SqliteValue[]): Promise<number> {
|
|
38
|
+
await this.db.execute(sql, params);
|
|
39
|
+
return (await this.db.get<{ n: number }>('SELECT changes() AS n'))!.n;
|
|
40
|
+
}
|
|
36
41
|
async get<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T | undefined> {
|
|
37
42
|
return this.db.get<T>(sql, params);
|
|
38
43
|
}
|
|
@@ -68,6 +73,14 @@ export class SqlKvDatabase extends Executor implements SqliteDatabase {
|
|
|
68
73
|
return result;
|
|
69
74
|
}
|
|
70
75
|
|
|
76
|
+
/**
|
|
77
|
+
* Outside a transaction, the statement and its count are one: another
|
|
78
|
+
* statement between them would be what `changes()` counted.
|
|
79
|
+
*/
|
|
80
|
+
override runCounted(sql: string, ...params: SqliteValue[]): Promise<number> {
|
|
81
|
+
return this.#session.transaction((tx) => new Executor(tx).runCounted(sql, ...params));
|
|
82
|
+
}
|
|
83
|
+
|
|
71
84
|
/** The session is the caller's to end, after the calls made before. */
|
|
72
85
|
async close() {}
|
|
73
86
|
}
|
package/src/tools.ts
CHANGED
|
@@ -17,6 +17,7 @@ import { callOf } from './calls.ts';
|
|
|
17
17
|
import { companionHere, NoCompanion } from './companion.ts';
|
|
18
18
|
|
|
19
19
|
const TOOL = Symbol.for('restate-agents.tool');
|
|
20
|
+
const SPEC = Symbol.for('restate-agents.tool-spec');
|
|
20
21
|
|
|
21
22
|
/** A tool call: the agent's context, and the id of the model's call. */
|
|
22
23
|
export interface ToolCall {
|
|
@@ -51,6 +52,38 @@ export interface Tool {
|
|
|
51
52
|
run(args: unknown, call: ToolCall): Promise<string>;
|
|
52
53
|
}
|
|
53
54
|
|
|
55
|
+
/**
|
|
56
|
+
* What a tool does, beside its `run` (which takes a session object's
|
|
57
|
+
* context): for a framework whose agent is no session object (agentlib's,
|
|
58
|
+
* on the classic SDK), which makes the same calls its own way. Restate's
|
|
59
|
+
* tools say which call; a `tool()`, its `run`.
|
|
60
|
+
*/
|
|
61
|
+
export type ToolSpec =
|
|
62
|
+
| { kind: 'run'; run: (input: never, context: ToolContext) => unknown }
|
|
63
|
+
| { kind: 'call'; target: Target; handler: string; options: TargetOptions<z.ZodObject | undefined> }
|
|
64
|
+
| {
|
|
65
|
+
kind: 'send';
|
|
66
|
+
target: Target;
|
|
67
|
+
handler: string;
|
|
68
|
+
options: TargetOptions<z.ZodObject | undefined> & { delay?: restate.Duration };
|
|
69
|
+
}
|
|
70
|
+
| { kind: 'workflow'; target: Target; options: TargetOptions<z.ZodObject | undefined> }
|
|
71
|
+
| { kind: 'signal'; name: string; shown: boolean }
|
|
72
|
+
| { kind: 'subagent'; agent: string; handler: string };
|
|
73
|
+
|
|
74
|
+
/** `t`, saying what it does: see {@link ToolSpec}. */
|
|
75
|
+
const withSpec = (t: Tool, spec: ToolSpec): Tool => Object.defineProperty(t, SPEC, { value: spec });
|
|
76
|
+
|
|
77
|
+
/** What tool `t` does: see {@link ToolSpec}. */
|
|
78
|
+
export const specOf = (t: Tool): ToolSpec => (t as Tool & { [SPEC]: ToolSpec })[SPEC];
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Which tool calls wait for a person's approval before they run: the names
|
|
82
|
+
* of their tools, or a function of a call that says whether it does. The
|
|
83
|
+
* DeepSeek and agentlib agents take it as their `approval`.
|
|
84
|
+
*/
|
|
85
|
+
export type Approval = readonly string[] | ((call: { name: string; args: unknown }) => boolean);
|
|
86
|
+
|
|
54
87
|
/** The JSON schema of `t`'s input, which a framework offers the model. */
|
|
55
88
|
export const jsonSchemaOf = (t: Tool) => z.toJSONSchema(t.input) as Record<string, unknown>;
|
|
56
89
|
|
|
@@ -58,7 +91,7 @@ export const jsonSchemaOf = (t: Tool) => z.toJSONSchema(t.input) as Record<strin
|
|
|
58
91
|
export const isTool = (value: unknown): value is Tool => typeof value === 'object' && value !== null && TOOL in value;
|
|
59
92
|
|
|
60
93
|
/** A result as text: a string as it is, nothing as "done", anything else as JSON. */
|
|
61
|
-
const text = (value: unknown) =>
|
|
94
|
+
export const text = (value: unknown) =>
|
|
62
95
|
typeof value === 'string' ? value : value === null || value === undefined ? 'done' : JSON.stringify(value);
|
|
63
96
|
|
|
64
97
|
/**
|
|
@@ -83,6 +116,14 @@ export const tool = <S extends z.ZodObject>(options: {
|
|
|
83
116
|
description: string;
|
|
84
117
|
input: S;
|
|
85
118
|
run: (input: z.infer<S>, context: ToolContext) => unknown;
|
|
119
|
+
}): Tool => withSpec(ownTool(options), { kind: 'run', run: options.run });
|
|
120
|
+
|
|
121
|
+
/** {@link tool}, without its spec: Restate's tools give their own. */
|
|
122
|
+
const ownTool = <S extends z.ZodObject>(options: {
|
|
123
|
+
name: string;
|
|
124
|
+
description: string;
|
|
125
|
+
input: S;
|
|
126
|
+
run: (input: z.infer<S>, context: ToolContext) => unknown;
|
|
86
127
|
}): Tool => ({
|
|
87
128
|
[TOOL]: true,
|
|
88
129
|
name: options.name,
|
|
@@ -142,12 +183,12 @@ async function once<T>(
|
|
|
142
183
|
}
|
|
143
184
|
|
|
144
185
|
/** A service, virtual object or workflow, as its definition (`restate.service(...)` and so on), of handlers `M`. */
|
|
145
|
-
type Target<M = unknown> =
|
|
186
|
+
export type Target<M = unknown> =
|
|
146
187
|
| restate.ServiceDefinition<string, M>
|
|
147
188
|
| restate.VirtualObjectDefinition<string, M>
|
|
148
189
|
| restate.WorkflowDefinition<string, M>;
|
|
149
190
|
/** Whether a target is keyed: a virtual object (key) or a workflow (id). */
|
|
150
|
-
const keyed = (target: Target) => 'object' in target || 'workflow' in target;
|
|
191
|
+
export const keyed = (target: Target) => 'object' in target || 'workflow' in target;
|
|
151
192
|
|
|
152
193
|
/**
|
|
153
194
|
* Call `method` of `service`, with JSON in and out, once per tool call (see
|
|
@@ -187,7 +228,7 @@ export const runWorkflow = async (
|
|
|
187
228
|
{ service, key, input }: { service: string; key: string; input: unknown },
|
|
188
229
|
): Promise<unknown> => attach(ctx, await start(ctx, { service, handler: 'run', key, input }));
|
|
189
230
|
|
|
190
|
-
interface TargetOptions<S extends z.ZodObject | undefined> {
|
|
231
|
+
export interface TargetOptions<S extends z.ZodObject | undefined> {
|
|
191
232
|
/** The tool's name, for the model; by default the handler's, such as `orders_status`. */
|
|
192
233
|
name?: string;
|
|
193
234
|
/** What it does, for the model. */
|
|
@@ -238,20 +279,23 @@ export const call = <M, S extends z.ZodObject | undefined = undefined>(
|
|
|
238
279
|
handler: keyof M & string,
|
|
239
280
|
options: TargetOptions<S>,
|
|
240
281
|
): Tool =>
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
282
|
+
withSpec(
|
|
283
|
+
ownTool({
|
|
284
|
+
name: options.name ?? `${target.name}_${handler}`,
|
|
285
|
+
description: options.description,
|
|
286
|
+
input: inputOf(target, options),
|
|
287
|
+
run: async (input, context) =>
|
|
288
|
+
once(`${target.name}/${handler}`, input, context, async (c) =>
|
|
289
|
+
invoke(c, {
|
|
290
|
+
service: target.name,
|
|
291
|
+
method: handler,
|
|
292
|
+
workflow: 'workflow' in target,
|
|
293
|
+
...(await split(target, options, input, c.ctx)),
|
|
294
|
+
}),
|
|
295
|
+
),
|
|
296
|
+
}),
|
|
297
|
+
{ kind: 'call', target: target as Target, handler, options },
|
|
298
|
+
);
|
|
255
299
|
|
|
256
300
|
/**
|
|
257
301
|
* A tool that sends to `handler` of `target`, without waiting for it: a
|
|
@@ -262,17 +306,24 @@ export const send = <M, S extends z.ZodObject | undefined = undefined>(
|
|
|
262
306
|
handler: keyof M & string,
|
|
263
307
|
options: TargetOptions<S> & { delay?: restate.Duration },
|
|
264
308
|
): Tool =>
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
309
|
+
withSpec(
|
|
310
|
+
ownTool({
|
|
311
|
+
name: options.name ?? `${target.name}_${handler}`,
|
|
312
|
+
description: options.description,
|
|
313
|
+
input: inputOf(target, options),
|
|
314
|
+
run: async (input, context) =>
|
|
315
|
+
once(`${target.name}/${handler}`, input, context, async ({ ctx, idempotencyKey }) => {
|
|
316
|
+
const { key, parameter } = await split(target, options, input, ctx);
|
|
317
|
+
ctx.send({ service: target.name, handler, key, input: parameter, delay: options.delay, idempotencyKey });
|
|
318
|
+
return sentTo(target.name, key, handler);
|
|
319
|
+
}),
|
|
320
|
+
}),
|
|
321
|
+
{ kind: 'send', target: target as Target, handler, options },
|
|
322
|
+
);
|
|
323
|
+
|
|
324
|
+
/** What a send tool answers: where it sent. */
|
|
325
|
+
export const sentTo = (service: string, key: string | undefined, handler: string) =>
|
|
326
|
+
`sent to ${service}${key === undefined ? '' : `/${key}`}/${handler}`;
|
|
276
327
|
|
|
277
328
|
/**
|
|
278
329
|
* A tool that runs the workflow `target` (its `run` handler) to the end, and
|
|
@@ -286,19 +337,22 @@ export const workflow = <S extends z.ZodObject | undefined = undefined>(
|
|
|
286
337
|
target: restate.WorkflowDefinition<string, { run: unknown }>,
|
|
287
338
|
options: TargetOptions<S>,
|
|
288
339
|
): Tool =>
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
340
|
+
withSpec(
|
|
341
|
+
ownTool({
|
|
342
|
+
name: options.name ?? target.name,
|
|
343
|
+
description: options.description,
|
|
344
|
+
input: z.object(options.input?.shape ?? {}),
|
|
345
|
+
run: async (input, context) =>
|
|
346
|
+
once(target.name, input, context, async (c) =>
|
|
347
|
+
runWorkflow(c.ctx, {
|
|
348
|
+
service: target.name,
|
|
349
|
+
key: options.key === undefined ? `${c.ctx.key}-${c.callId}` : await configured(options.key, c.ctx),
|
|
350
|
+
input: options.input ? input : undefined,
|
|
351
|
+
}),
|
|
352
|
+
),
|
|
353
|
+
}),
|
|
354
|
+
{ kind: 'workflow', target: target as Target, options },
|
|
355
|
+
);
|
|
302
356
|
|
|
303
357
|
/** An object with a `chat` handler; another object needs subagent's `handler`. */
|
|
304
358
|
type WithChat<M> = M extends { chat: unknown }
|
|
@@ -332,10 +386,19 @@ export function subagent<M>(
|
|
|
332
386
|
handler,
|
|
333
387
|
}: { description?: string; name?: string; handler?: keyof M & string } = {},
|
|
334
388
|
): Tool {
|
|
335
|
-
return
|
|
389
|
+
return withSpec(subagentTool(agent.name, toolName, description, handler ?? 'chat'), {
|
|
390
|
+
kind: 'subagent',
|
|
391
|
+
agent: agent.name,
|
|
392
|
+
handler: handler ?? 'chat',
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** {@link subagent}'s tool, without its spec. */
|
|
397
|
+
function subagentTool(agentName: string, toolName: string, description: string | undefined, handler: string): Tool {
|
|
398
|
+
return ownTool({
|
|
336
399
|
name: toolName,
|
|
337
400
|
description:
|
|
338
|
-
`Hand a task to the ${
|
|
401
|
+
`Hand a task to the ${agentName} agent${description ? ` (${description})` : ''}, and get its answer. ` +
|
|
339
402
|
'Tasks of different names run at once; the same name continues the same task.',
|
|
340
403
|
input: z.object({
|
|
341
404
|
name: z
|
|
@@ -345,8 +408,8 @@ export function subagent<M>(
|
|
|
345
408
|
task: z.string().describe('The task in full: the agent sees nothing else'),
|
|
346
409
|
}),
|
|
347
410
|
run: async ({ name, task }, context) =>
|
|
348
|
-
once(
|
|
349
|
-
invoke(c, { service:
|
|
411
|
+
once(agentName, { name, task }, context, (c) =>
|
|
412
|
+
invoke(c, { service: agentName, key: `${c.ctx.key}.${name}`, method: handler, parameter: task }),
|
|
350
413
|
),
|
|
351
414
|
});
|
|
352
415
|
}
|
|
@@ -375,12 +438,15 @@ export function subagent<M>(
|
|
|
375
438
|
* for the next wait for its name.
|
|
376
439
|
*/
|
|
377
440
|
export const signal = (name: string, options: { description: string; input?: z.ZodObject; name?: string }): Tool =>
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
441
|
+
withSpec(
|
|
442
|
+
ownTool({
|
|
443
|
+
name: options.name ?? `wait_for_${name}`,
|
|
444
|
+
description: options.description,
|
|
445
|
+
input: z.object(options.input?.shape ?? {}),
|
|
446
|
+
run: async (input, context) => wait(context, name, input, { shown: options.input !== undefined }),
|
|
447
|
+
}),
|
|
448
|
+
{ kind: 'signal', name, shown: options.input !== undefined },
|
|
449
|
+
);
|
|
384
450
|
|
|
385
451
|
/**
|
|
386
452
|
* Wait for signal `name` as tool call `toolCall`, once however often it runs;
|