@restatedev/agents 0.0.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.
Files changed (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +672 -2
  3. package/dist/calls.d.ts +29 -0
  4. package/dist/calls.d.ts.map +1 -0
  5. package/dist/calls.js +91 -0
  6. package/dist/calls.js.map +1 -0
  7. package/dist/claude/conversation.d.ts +33 -0
  8. package/dist/claude/conversation.d.ts.map +1 -0
  9. package/dist/claude/conversation.js +95 -0
  10. package/dist/claude/conversation.js.map +1 -0
  11. package/dist/claude/index.d.ts +77 -0
  12. package/dist/claude/index.d.ts.map +1 -0
  13. package/dist/claude/index.js +269 -0
  14. package/dist/claude/index.js.map +1 -0
  15. package/dist/client.d.ts +81 -0
  16. package/dist/client.d.ts.map +1 -0
  17. package/dist/client.js +88 -0
  18. package/dist/client.js.map +1 -0
  19. package/dist/common.d.ts +261 -0
  20. package/dist/common.d.ts.map +1 -0
  21. package/dist/common.js +438 -0
  22. package/dist/common.js.map +1 -0
  23. package/dist/deepseek/index.d.ts +68 -0
  24. package/dist/deepseek/index.d.ts.map +1 -0
  25. package/dist/deepseek/index.js +363 -0
  26. package/dist/deepseek/index.js.map +1 -0
  27. package/dist/deepseek/persistence.d.ts +61 -0
  28. package/dist/deepseek/persistence.d.ts.map +1 -0
  29. package/dist/deepseek/persistence.js +224 -0
  30. package/dist/deepseek/persistence.js.map +1 -0
  31. package/dist/index.d.ts +8 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +12 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/langgraph/checkpointer.d.ts +29 -0
  36. package/dist/langgraph/checkpointer.d.ts.map +1 -0
  37. package/dist/langgraph/checkpointer.js +275 -0
  38. package/dist/langgraph/checkpointer.js.map +1 -0
  39. package/dist/langgraph/index.d.ts +66 -0
  40. package/dist/langgraph/index.d.ts.map +1 -0
  41. package/dist/langgraph/index.js +265 -0
  42. package/dist/langgraph/index.js.map +1 -0
  43. package/dist/log.d.ts +29 -0
  44. package/dist/log.d.ts.map +1 -0
  45. package/dist/log.js +145 -0
  46. package/dist/log.js.map +1 -0
  47. package/dist/object.d.ts +169 -0
  48. package/dist/object.d.ts.map +1 -0
  49. package/dist/object.js +221 -0
  50. package/dist/object.js.map +1 -0
  51. package/dist/opencode/db.d.ts +40 -0
  52. package/dist/opencode/db.d.ts.map +1 -0
  53. package/dist/opencode/db.js +161 -0
  54. package/dist/opencode/db.js.map +1 -0
  55. package/dist/opencode/index.d.ts +100 -0
  56. package/dist/opencode/index.d.ts.map +1 -0
  57. package/dist/opencode/index.js +436 -0
  58. package/dist/opencode/index.js.map +1 -0
  59. package/dist/output.d.ts +17 -0
  60. package/dist/output.d.ts.map +1 -0
  61. package/dist/output.js +81 -0
  62. package/dist/output.js.map +1 -0
  63. package/dist/pi/index.d.ts +89 -0
  64. package/dist/pi/index.d.ts.map +1 -0
  65. package/dist/pi/index.js +293 -0
  66. package/dist/pi/index.js.map +1 -0
  67. package/dist/pi/storage.d.ts +5 -0
  68. package/dist/pi/storage.d.ts.map +1 -0
  69. package/dist/pi/storage.js +41 -0
  70. package/dist/pi/storage.js.map +1 -0
  71. package/dist/signals.d.ts +154 -0
  72. package/dist/signals.d.ts.map +1 -0
  73. package/dist/signals.js +256 -0
  74. package/dist/signals.js.map +1 -0
  75. package/dist/tools.d.ts +158 -0
  76. package/dist/tools.d.ts.map +1 -0
  77. package/dist/tools.js +211 -0
  78. package/dist/tools.js.map +1 -0
  79. package/dist/webhook.d.ts +71 -0
  80. package/dist/webhook.d.ts.map +1 -0
  81. package/dist/webhook.js +102 -0
  82. package/dist/webhook.js.map +1 -0
  83. package/package.json +218 -5
  84. package/src/calls.ts +138 -0
  85. package/src/claude/README.md +84 -0
  86. package/src/claude/conversation.ts +114 -0
  87. package/src/claude/index.ts +364 -0
  88. package/src/client.ts +176 -0
  89. package/src/common.ts +550 -0
  90. package/src/deepseek/README.md +110 -0
  91. package/src/deepseek/index.ts +464 -0
  92. package/src/deepseek/persistence.ts +293 -0
  93. package/src/index.ts +24 -0
  94. package/src/langgraph/README.md +87 -0
  95. package/src/langgraph/checkpointer.ts +364 -0
  96. package/src/langgraph/index.ts +349 -0
  97. package/src/log.ts +193 -0
  98. package/src/object.ts +319 -0
  99. package/src/opencode/README.md +125 -0
  100. package/src/opencode/db.ts +223 -0
  101. package/src/opencode/index.ts +559 -0
  102. package/src/output.ts +95 -0
  103. package/src/pi/README.md +105 -0
  104. package/src/pi/index.ts +382 -0
  105. package/src/pi/storage.ts +65 -0
  106. package/src/signals.ts +386 -0
  107. package/src/tools.ts +343 -0
  108. package/src/webhook.ts +161 -0
@@ -0,0 +1,154 @@
1
+ import type { SessionContext } from '@restatedev/sessions';
2
+ import { sdk as restate } from '@restatedev/sessions/internal';
3
+ import type { Turn } from './common.ts';
4
+ import type { Status } from './object.ts';
5
+ /** An agent's context, as far as its signals need it: any handler's or view's of its object. */
6
+ type AgentContext = {
7
+ readonly key: string;
8
+ readonly request: {
9
+ readonly target: {
10
+ readonly service: string;
11
+ };
12
+ };
13
+ };
14
+ /** The key of the signals of the agent of `ctx`. */
15
+ export declare const signalsOf: (ctx: AgentContext) => string;
16
+ /** Where an object of @restatedev/agents (`sessionObject()`, every `agent()`) points to its companion. */
17
+ declare const COMPANION: unique symbol;
18
+ /**
19
+ * An agent's companion, for one of its keys: its `signals` object, which
20
+ * knows what the agent is doing (the message it answers, what its tools wait
21
+ * for), and how to reach it.
22
+ */
23
+ export interface Companion {
24
+ /** The `signals` object, as a client takes it. */
25
+ object: typeof signals;
26
+ /** The key of the agent's key there: `<agent>:<key>`. */
27
+ key: string;
28
+ /** The agent, and its key. */
29
+ agent: Agent;
30
+ }
31
+ /**
32
+ * `definition`, pointing to its companion: what `sessionObject()` returns.
33
+ * `serve` serves its `signals` object beside it.
34
+ */
35
+ export declare const withCompanion: <D extends {
36
+ name: string;
37
+ }>(definition: D) => D;
38
+ /**
39
+ * The companion of `agent`'s key `key`: for anyone holding an agent (an
40
+ * `sessionObject()` or `agent()` of @restatedev/agents) to reach what it is doing.
41
+ */
42
+ export declare function companionOf(agent: {
43
+ name: string;
44
+ }, key: string): Companion;
45
+ /** Whether `agent` is an object of @restatedev/agents, with a companion. */
46
+ export declare const hasCompanion: (agent: object) => agent is object & Record<typeof COMPANION, unknown>;
47
+ /**
48
+ * Deliver `text` to `agent`'s key `key`, from any handler: a message of its
49
+ * own (as `chat`), which it answers after the messages before it. It is
50
+ * sent, not awaited: `opts` may give it an idempotency key, so that it is
51
+ * delivered once.
52
+ *
53
+ * deliver(ctx, triage, 'ENG-1', 'The issue was closed', { idempotencyKey: delivery });
54
+ */
55
+ export declare function deliver(ctx: Pick<restate.Context, 'genericSend'> | Pick<SessionContext, 'send'>, agent: {
56
+ name: string;
57
+ }, key: string, text: string, { idempotencyKey }?: {
58
+ idempotencyKey?: string;
59
+ }): void;
60
+ /** A wait for a signal, as `pending` lists it. */
61
+ export interface Waiting {
62
+ /** The wait's id, which `signal` takes to resolve this wait and no other. */
63
+ id: string;
64
+ /** The signal it waits for, such as `approval`. */
65
+ name: string;
66
+ /** What it waits for, as the model said it (such as the refund to approve), if the tool takes an input. */
67
+ input?: unknown;
68
+ /** When it started, as an ISO date. */
69
+ since: string;
70
+ }
71
+ /** Which wait a signal resolves, and with what. */
72
+ export interface Signal {
73
+ /** The wait of this id (from `pending`). */
74
+ id?: string;
75
+ /** Else the oldest wait for the signal of this name. */
76
+ name?: string;
77
+ /** Its value: what the wait answers the model with. */
78
+ value?: unknown;
79
+ /** With a `name` and no one waiting for it, keep the signal for the next wait for it (by default it is dropped). */
80
+ keep?: boolean;
81
+ }
82
+ /** What `signal` did: the id of the wait it resolved, or null if none waited (and it was dropped, or kept). */
83
+ export interface Resolved {
84
+ resolved: string | null;
85
+ }
86
+ /** The revision of an agent's conversation: each change of what a client reads increases it. */
87
+ export interface Notifications {
88
+ revision: number;
89
+ }
90
+ /** What `watch` waits for: a revision newer than `revision`, for at most `timeoutSeconds` (default 50, at most 60). */
91
+ export interface Watch {
92
+ revision: number;
93
+ timeoutSeconds?: number;
94
+ }
95
+ /** An agent: its object's name, and key. */
96
+ interface Agent {
97
+ service: string;
98
+ key: string;
99
+ }
100
+ /**
101
+ * The message the agent answers; the waits, in the order they started, each
102
+ * with its awakeable; the signals kept for the next wait; and the
103
+ * conversation's revision, with the `watch`es waiting for a newer one.
104
+ */
105
+ interface State {
106
+ /** The message the agent answers, from its turn's start to its close. */
107
+ turn: Turn;
108
+ waiting: (Waiting & {
109
+ awakeable: string;
110
+ })[];
111
+ kept: Record<string, unknown[]>;
112
+ revision: number;
113
+ watching: {
114
+ revision: number;
115
+ awakeable: string;
116
+ }[];
117
+ }
118
+ /**
119
+ * The signals of every agent, keyed `<agent>:<key>` ({@link signalsOf}).
120
+ * `serve` serves it beside the agents; the handlers marked `@internal` are
121
+ * called by the agents' own handlers, and Restate's ingress refuses them.
122
+ */
123
+ export declare const signals: restate.VirtualObjectDefinition<"signals", {
124
+ wait: (ctx: restate.ObjectSharedContext<State>, input: {
125
+ id: string;
126
+ name: string;
127
+ input?: unknown;
128
+ }) => Promise<unknown>;
129
+ resolve: (ctx: restate.ObjectContext<State>, { id, name, value, keep }: Signal) => Promise<{
130
+ resolved: null;
131
+ } | {
132
+ resolved: string;
133
+ }>;
134
+ pending: (ctx: restate.ObjectSharedContext<State>) => Promise<Waiting[]>;
135
+ listen: (ctx: restate.ObjectContext<State>, input: Waiting & {
136
+ awakeable: string;
137
+ }) => Promise<void>;
138
+ start: (ctx: restate.ObjectContext<State>, input: Turn) => Promise<void>;
139
+ awaitTurn: (ctx: restate.ObjectSharedContext<State>, input: string) => Promise<void>;
140
+ status: (ctx: restate.ObjectSharedContext<State>) => Promise<Status>;
141
+ watch: (ctx: restate.ObjectSharedContext<State>, input: Watch) => Promise<Notifications>;
142
+ close: (ctx: restate.ObjectContext<State>, input: string) => Promise<void>;
143
+ reset: (ctx: restate.ObjectContext<State>) => Promise<void>;
144
+ forget: (ctx: restate.ObjectContext<State>, input: string) => Promise<void>;
145
+ publish: (ctx: restate.ObjectContext<State>) => Promise<Notifications>;
146
+ notifications: (ctx: restate.ObjectSharedContext<State>) => Promise<Notifications>;
147
+ subscribe: (ctx: restate.ObjectContext<State>, input: {
148
+ revision: number;
149
+ awakeable: string;
150
+ }) => Promise<void>;
151
+ unsubscribe: (ctx: restate.ObjectContext<State>, input: string) => Promise<void>;
152
+ }>;
153
+ export {};
154
+ //# sourceMappingURL=signals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signals.d.ts","sourceRoot":"","sources":["../src/signals.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAW,GAAG,IAAI,OAAO,EAAE,MAAM,+BAA+B,CAAC;AACxE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAE1C,gGAAgG;AAChG,KAAK,YAAY,GAAG;IAAE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE;QAAE,QAAQ,CAAC,MAAM,EAAE;YAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,CAAA;CAAE,CAAC;AAKlH,oDAAoD;AACpD,eAAO,MAAM,SAAS,QAAS,YAAY,WAA+C,CAAC;AAE3F,0GAA0G;AAC1G,QAAA,MAAM,SAAS,eAAqC,CAAC;AAErD;;;;GAIG;AACH,MAAM,WAAW,SAAS;IACxB,kDAAkD;IAClD,MAAM,EAAE,OAAO,OAAO,CAAC;IACvB,yDAAyD;IACzD,GAAG,EAAE,MAAM,CAAC;IACZ,8BAA8B;IAC9B,KAAK,EAAE,KAAK,CAAC;CACd;AAED;;;GAGG;AACH,eAAO,MAAM,aAAa,GAAI,CAAC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AClB;AAED,uHAAuH;AACvH,MAAM,WAAW,KAAK;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,4CAA4C;AAC5C,UAAU,KAAK;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;GAIG;AACH,UAAU,KAAK;IACb,yEAAyE;IACzE,IAAI,EAAE,IAAI,CAAC;IACX,OAAO,EAAE,CAAC,OAAO,GAAG;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC,EAAE,CAAC;IAC7C,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CACrD;AAuCD;;;;GAIG;AACH,eAAO,MAAM,OAAO;;YAK8C,MAAM;cAAQ,MAAM;gBAAU,OAAO;;mBAe9E,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,6BAA4C,MAAM;;;;;;;mBAwBX,MAAM;;;;;;;;;;;;kBAyHb,MAAM;mBAAa,MAAM;;;EAkB5G,CAAC"}
@@ -0,0 +1,256 @@
1
+ import { needing, sdk as restate } from '@restatedev/sessions/internal';
2
+ /** The key of the signals of agent `service`'s key `key`: `<agent>:<key>`. */
3
+ const keyOf = (service, key) => `${service}:${key}`;
4
+ /** The key of the signals of the agent of `ctx`. */
5
+ export const signalsOf = (ctx) => keyOf(ctx.request.target.service, ctx.key);
6
+ /** Where an object of @restatedev/agents (`sessionObject()`, every `agent()`) points to its companion. */
7
+ const COMPANION = Symbol('restate-agents.companion');
8
+ /**
9
+ * `definition`, pointing to its companion: what `sessionObject()` returns.
10
+ * `serve` serves its `signals` object beside it.
11
+ */
12
+ export const withCompanion = (definition) => needing(Object.defineProperty(definition, COMPANION, {
13
+ value: (key) => ({
14
+ object: signals,
15
+ key: keyOf(definition.name, key),
16
+ agent: { service: definition.name, key },
17
+ }),
18
+ }), () => [signals]);
19
+ /**
20
+ * The companion of `agent`'s key `key`: for anyone holding an agent (an
21
+ * `sessionObject()` or `agent()` of @restatedev/agents) to reach what it is doing.
22
+ */
23
+ export function companionOf(agent, key) {
24
+ const companion = agent[COMPANION];
25
+ if (!companion)
26
+ throw new Error(`${agent.name} is not an agent of @restatedev/agents (a sessionObject() or an agent())`);
27
+ return companion(key);
28
+ }
29
+ /** Whether `agent` is an object of @restatedev/agents, with a companion. */
30
+ export const hasCompanion = (agent) => COMPANION in agent;
31
+ /**
32
+ * Deliver `text` to `agent`'s key `key`, from any handler: a message of its
33
+ * own (as `chat`), which it answers after the messages before it. It is
34
+ * sent, not awaited: `opts` may give it an idempotency key, so that it is
35
+ * delivered once.
36
+ *
37
+ * deliver(ctx, triage, 'ENG-1', 'The issue was closed', { idempotencyKey: delivery });
38
+ */
39
+ export function deliver(ctx, agent, key, text, { idempotencyKey } = {}) {
40
+ companionOf(agent, key); // an agent of @restatedev/agents, with a `chat` handler
41
+ const message = { service: agent.name, handler: 'chat', key, input: text, idempotencyKey };
42
+ // A session object's handler, or one of the SDK's.
43
+ if ('send' in ctx)
44
+ ctx.send(message);
45
+ else {
46
+ ctx.genericSend({
47
+ service: agent.name,
48
+ method: 'chat',
49
+ key,
50
+ parameter: text,
51
+ inputSerde: restate.serde.json,
52
+ idempotencyKey,
53
+ });
54
+ }
55
+ }
56
+ /** Increase the revision, and answer each `watch` waiting for it: the new revision. */
57
+ async function publish(ctx) {
58
+ const revision = ((await ctx.get('revision')) ?? 0) + 1;
59
+ ctx.set('revision', revision);
60
+ for (const { awakeable } of (await ctx.get('watching')) ?? [])
61
+ ctx.resolveAwakeable(awakeable, { revision });
62
+ ctx.clear('watching');
63
+ return { revision };
64
+ }
65
+ /** How long one `awaitTurn` waits for its turn to end, before a new one takes over. */
66
+ const WATCH = { hours: 1 };
67
+ /**
68
+ * `turn` (an invocation id) is over: forget it, if the agent answers it, and
69
+ * its tools' waits, which no one waits for any more, ending their `wait`s (a
70
+ * turn that ends as it should has none left, but a killed one leaves them).
71
+ * It publishes the change, for the clients that follow the conversation: a
72
+ * turn's own close (its last change), or the close of one that never closed
73
+ * itself. A close again changes nothing, and publishes nothing.
74
+ */
75
+ async function closed(ctx, turn) {
76
+ const answering = (await ctx.get('turn'))?.invocationId === turn;
77
+ if (answering)
78
+ ctx.clear('turn');
79
+ const waiting = (await ctx.get('waiting')) ?? [];
80
+ // A wait's id starts with the invocation id of the turn whose tool waits.
81
+ const ofTurn = (id) => id.startsWith(`${turn}:`);
82
+ const over = waiting.filter((w) => ofTurn(w.id));
83
+ const left = waiting.filter((w) => !ofTurn(w.id));
84
+ for (const w of over)
85
+ ctx.rejectAwakeable(w.awakeable, 'its turn is over');
86
+ if (over.length > 0)
87
+ ctx.set('waiting', left);
88
+ if (answering || over.length > 0)
89
+ await publish(ctx);
90
+ }
91
+ /** A handler that the agents' own handlers call, which clients cannot (through Restate's ingress). */
92
+ const internal = (fn) => restate.handlers.object.exclusive({ ingressPrivate: true }, fn);
93
+ /**
94
+ * The signals of every agent, keyed `<agent>:<key>` ({@link signalsOf}).
95
+ * `serve` serves it beside the agents; the handlers marked `@internal` are
96
+ * called by the agents' own handlers, and Restate's ingress refuses them.
97
+ */
98
+ export const signals = restate.object({
99
+ name: 'signals',
100
+ handlers: {
101
+ /** Wait for the signal `name`, as wait `id` (for `input`), and return its value. */
102
+ wait: restate.handlers.object.shared(async (ctx, wait) => {
103
+ const { id, promise } = ctx.awakeable();
104
+ const since = new Date(await ctx.date.now()).toISOString();
105
+ ctx.objectSendClient(signals, ctx.key).listen({ ...wait, since, awakeable: id });
106
+ try {
107
+ return await promise;
108
+ }
109
+ catch (error) {
110
+ // The agent's invocation was cancelled: no one waits any more.
111
+ if (error instanceof restate.CancelledError)
112
+ ctx.objectSendClient(signals, ctx.key).forget(wait.id);
113
+ throw error;
114
+ }
115
+ }),
116
+ /** Resolve the wait `id`, or else the oldest wait for `name`, with `value`. */
117
+ resolve: async (ctx, { id, name, value = null, keep = false }) => {
118
+ if (id === undefined && name === undefined)
119
+ throw new restate.TerminalError('a signal needs an id or a name');
120
+ const waiting = (await ctx.get('waiting')) ?? [];
121
+ const at = waiting.findIndex((w) => (id === undefined ? w.name === name : w.id === id));
122
+ if (at < 0) {
123
+ if (keep && name !== undefined && id === undefined) {
124
+ const kept = (await ctx.get('kept')) ?? {};
125
+ ctx.set('kept', { ...kept, [name]: [...(kept[name] ?? []), value] });
126
+ }
127
+ return { resolved: null };
128
+ }
129
+ const [wait] = waiting.splice(at, 1);
130
+ ctx.resolveAwakeable(wait.awakeable, value);
131
+ ctx.set('waiting', waiting);
132
+ await publish(ctx);
133
+ return { resolved: wait.id };
134
+ },
135
+ /** The waits, oldest first. */
136
+ pending: restate.handlers.object.shared(async (ctx) => ((await ctx.get('waiting')) ?? []).map(({ id, name, input, since }) => ({ id, name, input, since }))),
137
+ /** @internal A wait: resolved now with a signal kept for it, or else when one comes. */
138
+ listen: internal(async (ctx, wait) => {
139
+ const kept = (await ctx.get('kept')) ?? {};
140
+ const [value, ...rest] = kept[wait.name] ?? [];
141
+ if (kept[wait.name]?.length) {
142
+ ctx.resolveAwakeable(wait.awakeable, value);
143
+ ctx.set('kept', { ...kept, [wait.name]: rest });
144
+ return;
145
+ }
146
+ ctx.set('waiting', [...((await ctx.get('waiting')) ?? []), wait]);
147
+ await publish(ctx);
148
+ }),
149
+ /**
150
+ * @internal The agent's `chat` started answering `turn`: the same
151
+ * invocation again (a retry) keeps when it started. A turn before it that
152
+ * never closed itself (its invocation was killed) closes now, if its
153
+ * `awaitTurn` did not close it yet. `awaitTurn` watches the new turn, so
154
+ * that it closes even if no turn comes after it.
155
+ */
156
+ start: internal(async (ctx, turn) => {
157
+ const before = (await ctx.get('turn'))?.invocationId;
158
+ if (before === turn.invocationId)
159
+ return;
160
+ if (before !== undefined)
161
+ await closed(ctx, before);
162
+ ctx.set('turn', turn);
163
+ ctx.objectSendClient(signals, ctx.key).awaitTurn(turn.invocationId);
164
+ }),
165
+ /**
166
+ * @internal Wait for `turn` to end, without holding a process, and close
167
+ * it if it failed: its waits end, and `status` no longer says the agent
168
+ * answers it. A turn that never closed itself failed: it was killed, ran
169
+ * out of retries, or was lost. A turn that ends as it should, or is
170
+ * cancelled, closed itself already: its `close` is a call it waits for
171
+ * before it ends, so this `close` comes second, and changes nothing.
172
+ *
173
+ * It waits {@link WATCH} at most: a turn still answered then gets a new
174
+ * watch, which runs on the deployment of the day, rather than this one
175
+ * waiting for weeks on the one it started on (a turn that waits for an
176
+ * approval, say). A cancelled watch (an operator's) rejects the race
177
+ * itself, before either side's `map`: it closes nothing.
178
+ */
179
+ awaitTurn: restate.handlers.object.shared(
180
+ // It leaves nothing behind once done: a turn has one at a time.
181
+ { ingressPrivate: true, journalRetention: 0, idempotencyRetention: 0 }, async (ctx, turn) => {
182
+ const ended = await restate.RestatePromise.race([
183
+ // `map` gets the turn's failure too: a killed turn's (a TerminalError).
184
+ ctx
185
+ .invocation(restate.InvocationIdParser.fromString(turn))
186
+ .attach()
187
+ .map((_answer, failure) => ({ failed: failure !== undefined })),
188
+ ctx.sleep(WATCH).map(() => null),
189
+ ]);
190
+ if (ended?.failed)
191
+ ctx.objectSendClient(signals, ctx.key).close(turn);
192
+ else if (ended === null && (await ctx.get('turn'))?.invocationId === turn) {
193
+ ctx.objectSendClient(signals, ctx.key).awaitTurn(turn);
194
+ }
195
+ }),
196
+ /** What the agent does: the message it answers, if any, and the waits of its tools. */
197
+ status: restate.handlers.object.shared(async (ctx) => ({
198
+ answering: (await ctx.get('turn')) ?? null,
199
+ waiting: ((await ctx.get('waiting')) ?? []).map(({ id, name, input, since }) => ({ id, name, input, since })),
200
+ })),
201
+ /**
202
+ * The revision, once there is one newer than `revision`, or at the
203
+ * timeout (50 s by default, at most 60 s), whichever comes first. It
204
+ * waits in Restate, holding no process; a caller that retries it with the
205
+ * same idempotency key joins the same wait.
206
+ */
207
+ watch: restate.handlers.object.shared(async (ctx, { revision, timeoutSeconds = 50 }) => {
208
+ const { id, promise } = ctx.awakeable();
209
+ ctx.objectSendClient(signals, ctx.key).subscribe({ revision, awakeable: id });
210
+ const timeout = ctx.sleep({ seconds: Math.min(Math.max(timeoutSeconds, 0), 60) }).map(() => null);
211
+ const changed = await restate.RestatePromise.race([promise, timeout]);
212
+ if (changed)
213
+ return changed;
214
+ ctx.objectSendClient(signals, ctx.key).unsubscribe(id);
215
+ return { revision: (await ctx.get('revision')) ?? 0 };
216
+ }),
217
+ /** @internal The message `turn` (an invocation id) is answered, or its turn ended otherwise: see {@link closed}. */
218
+ close: internal(closed),
219
+ /**
220
+ * @internal The agent forgot its conversation (`clear`): forget its
221
+ * waits and kept signals, and publish the change.
222
+ */
223
+ reset: restate.handlers.object.exclusive({ ingressPrivate: true }, async (ctx) => {
224
+ ctx.clear('waiting');
225
+ ctx.clear('kept');
226
+ await publish(ctx);
227
+ }),
228
+ /** @internal Forget wait `id`, whose agent no longer waits. */
229
+ forget: internal(async (ctx, id) => {
230
+ const waiting = (await ctx.get('waiting')) ?? [];
231
+ ctx.set('waiting', waiting.filter((w) => w.id !== id));
232
+ await publish(ctx);
233
+ }),
234
+ /** @internal The conversation changed: increase its revision, and answer the `watch`es. */
235
+ publish: restate.handlers.object.exclusive({ ingressPrivate: true }, publish),
236
+ /** The conversation's revision. */
237
+ notifications: restate.handlers.object.shared(async (ctx) => ({
238
+ revision: (await ctx.get('revision')) ?? 0,
239
+ })),
240
+ /** @internal Answer `awakeable` once there is a revision newer than `revision`: at once, if there is. */
241
+ subscribe: internal(async (ctx, watch) => {
242
+ const revision = (await ctx.get('revision')) ?? 0;
243
+ if (revision > watch.revision) {
244
+ ctx.resolveAwakeable(watch.awakeable, { revision });
245
+ return;
246
+ }
247
+ ctx.set('watching', [...((await ctx.get('watching')) ?? []), watch]);
248
+ }),
249
+ /** @internal Forget the `watch` of `awakeable`, which no longer waits. */
250
+ unsubscribe: internal(async (ctx, awakeable) => {
251
+ const watching = (await ctx.get('watching')) ?? [];
252
+ ctx.set('watching', watching.filter((w) => w.awakeable !== awakeable));
253
+ }),
254
+ },
255
+ });
256
+ //# sourceMappingURL=signals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signals.js","sourceRoot":"","sources":["../src/signals.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,OAAO,EAAE,GAAG,IAAI,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAOxE,8EAA8E;AAC9E,MAAM,KAAK,GAAG,CAAC,OAAe,EAAE,GAAW,EAAE,EAAE,CAAC,GAAG,OAAO,IAAI,GAAG,EAAE,CAAC;AAEpE,oDAAoD;AACpD,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,GAAiB,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;AAE3F,0GAA0G;AAC1G,MAAM,SAAS,GAAG,MAAM,CAAC,0BAA0B,CAAC,CAAC;AAgBrD;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,CAA6B,UAAa,EAAK,EAAE,CAC5E,OAAO,CACL,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,SAAS,EAAE;IAC3C,KAAK,EAAE,CAAC,GAAW,EAAa,EAAE,CAAC,CAAC;QAClC,MAAM,EAAE,OAAO;QACf,GAAG,EAAE,KAAK,CAAC,UAAU,CAAC,IAAI,EAAE,GAAG,CAAC;QAChC,KAAK,EAAE,EAAE,OAAO,EAAE,UAAU,CAAC,IAAI,EAAE,GAAG,EAAE;KACzC,CAAC;CACH,CAAC,EACF,GAAG,EAAE,CAAC,CAAC,OAAO,CAAC,CAChB,CAAC;AAEJ;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,KAAuB,EAAE,GAAW;IAC9D,MAAM,SAAS,GAAI,KAAsD,CAAC,SA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,QAAQ,GAAG,CAAC,MAAM,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,EAAE,CAAC;YACnD,GAAG,CAAC,GAAG,CACL,UAAU,EACV,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,KAAK,SAAS,CAAC,CAClD,CAAC;QACJ,CAAC,CAAC;KACH;CACF,CAAC,CAAC"}
@@ -0,0 +1,158 @@
1
+ import * as restate from '@restatedev/sessions';
2
+ import { z } from 'zod';
3
+ import { type Configure } from './common.ts';
4
+ declare const TOOL: unique symbol;
5
+ /** A tool call: the agent's context, and the id of the model's call. */
6
+ export interface ToolCall {
7
+ /** The agent's context: Restate calls, `ctx.key`, `ctx.db`... */
8
+ ctx: restate.SessionContext;
9
+ /** The id of the model's tool call: the same when a crash runs the call again. */
10
+ callId: string;
11
+ }
12
+ /** What a tool's `run` gets besides its input. */
13
+ export interface ToolContext extends ToolCall {
14
+ /**
15
+ * The tool call's idempotency key, `<invocation id>:<call id>`: for a call
16
+ * the tool makes once, however often it runs (a Restate call's
17
+ * `idempotencyKey`, or a payment API's).
18
+ */
19
+ idempotencyKey: string;
20
+ }
21
+ /** A tool of any framework: see {@link tool}. */
22
+ export interface Tool {
23
+ readonly [TOOL]: true;
24
+ readonly name: string;
25
+ readonly description: string;
26
+ /** The input: a zod object. A framework offers it to the model as its JSON schema ({@link jsonSchemaOf}). */
27
+ readonly input: z.ZodObject;
28
+ /**
29
+ * Its result, as text for the model, of the model's arguments as they came:
30
+ * `run` checks them against `input`, and answers arguments that do not fit
31
+ * with what is wrong, for the model to call it again.
32
+ */
33
+ run(args: unknown, call: ToolCall): Promise<string>;
34
+ }
35
+ /** The JSON schema of `t`'s input, which a framework offers the model. */
36
+ export declare const jsonSchemaOf: (t: Tool) => Record<string, unknown>;
37
+ /** Whether `value` is a {@link Tool}, rather than a framework's own. */
38
+ export declare const isTool: (value: unknown) => value is Tool;
39
+ /**
40
+ * A tool, for any framework's agent:
41
+ *
42
+ * const weather = tool({
43
+ * name: 'get_weather',
44
+ * description: 'The current weather in a city.',
45
+ * input: z.object({ city: z.string() }),
46
+ * run: async ({ city }) => `Sunny in ${city}`,
47
+ * });
48
+ *
49
+ * `run` returns the result (or a promise of it), text or anything JSON; it
50
+ * gets the agent's `ctx`, the tool call's `callId`, and an `idempotencyKey`
51
+ * made of both, for what the tool must do once. A `restate.TerminalError` it throws (or
52
+ * a Restate call it makes fails with) is its answer, `Error: <message>`, for
53
+ * the model to act on; and so are arguments that do not fit `input`, which
54
+ * `run` never sees.
55
+ */
56
+ export declare const tool: <S extends z.ZodObject>(options: {
57
+ name: string;
58
+ description: string;
59
+ input: S;
60
+ run: (input: z.infer<S>, context: ToolContext) => unknown;
61
+ }) => Tool;
62
+ /** A service, virtual object or workflow, as its definition (`restate.service(...)` and so on), of handlers `M`. */
63
+ type Target<M = unknown> = restate.ServiceDefinition<string, M> | restate.VirtualObjectDefinition<string, M> | restate.WorkflowDefinition<string, M>;
64
+ interface TargetOptions<S extends z.ZodObject | undefined> {
65
+ /** The tool's name, for the model; by default the handler's, such as `orders_status`. */
66
+ name?: string;
67
+ /** What it does, for the model. */
68
+ description: string;
69
+ /** The handler's input: a zod object, which the model fills in. Without one, the handler takes none. */
70
+ input?: S;
71
+ /**
72
+ * For a virtual object, its key (or the workflow's id): fixed, or for an
73
+ * invocation. Without one, the model chooses it.
74
+ */
75
+ key?: Configure<string>;
76
+ }
77
+ /**
78
+ * A tool that calls `handler` of `target` and answers with its result:
79
+ *
80
+ * call(orders, 'status', {
81
+ * description: 'The status of an order.',
82
+ * input: z.object({ order: z.string() }),
83
+ * })
84
+ *
85
+ * Of a virtual object, the model chooses the key, unless `key` gives it.
86
+ */
87
+ export declare const call: <M, S extends z.ZodObject | undefined = undefined>(target: Target<M>, handler: keyof M & string, options: TargetOptions<S>) => Tool;
88
+ /**
89
+ * A tool that sends to `handler` of `target`, without waiting for it: a
90
+ * one-way call, made once, after `delay` if given (such as `{ minutes: 5 }`).
91
+ */
92
+ export declare const send: <M, S extends z.ZodObject | undefined = undefined>(target: Target<M>, handler: keyof M & string, options: TargetOptions<S> & {
93
+ delay?: restate.Duration;
94
+ }) => Tool;
95
+ /**
96
+ * A tool that runs the workflow `target` (its `run` handler) to the end, and
97
+ * answers with its result. Each tool call is a workflow of its own, with an
98
+ * id made of the agent's key and the tool call's id, unless `key` gives one.
99
+ */
100
+ export declare const workflow: <S extends z.ZodObject | undefined = undefined>(target: restate.WorkflowDefinition<string, {
101
+ run: unknown;
102
+ }>, options: TargetOptions<S>) => Tool;
103
+ /** An object with a `chat` handler; another object needs subagent's `handler`. */
104
+ type WithChat<M> = M extends {
105
+ chat: unknown;
106
+ } ? unknown : {
107
+ 'an agent with a chat handler, or a handler option': never;
108
+ };
109
+ /**
110
+ * A tool, named after `agent` (an agent, or any virtual object) unless `name` names it, that hands
111
+ * a task to it: to the object keyed `<this key>.<task name>`, through its
112
+ * `handler` (`chat`), and answers with its answer. Tasks of different names
113
+ * run at once; the same name continues the same task. The model reads what
114
+ * the agent is from its `description` (or `description` here).
115
+ *
116
+ * const coder = pi.agent({ name: 'coder', description: 'Builds and tests code in Python' });
117
+ * const lead = pi.agent({ name: 'lead', tools: [subagent(coder)] });
118
+ */
119
+ export declare function subagent<M>(agent: restate.VirtualObjectDefinition<string, M> & WithChat<M>, options?: {
120
+ description?: string;
121
+ name?: string;
122
+ }): Tool;
123
+ /** A sub-agent through another of its handlers. */
124
+ export declare function subagent<M>(agent: restate.VirtualObjectDefinition<string, M>, options: {
125
+ description?: string;
126
+ name?: string;
127
+ handler: keyof M & string;
128
+ }): Tool;
129
+ /**
130
+ * A tool that waits for the signal `name` to the agent, and answers with its
131
+ * value: a person's approval, say, or another system's result. The agent
132
+ * waits without holding a process. With an `input`, the model says what it
133
+ * waits for (such as the refund to approve), which `pending` shows.
134
+ *
135
+ * signal('approval', {
136
+ * description: 'Wait for a manager to approve a refund.',
137
+ * input: z.object({ order: z.string(), amount: z.number() }),
138
+ * })
139
+ *
140
+ * Each wait has an id: `pending` (each `sessionObject()` has it) lists them, and
141
+ * the agent's `signal` handler resolves one, by its id, or the oldest wait
142
+ * for a name:
143
+ *
144
+ * curl localhost:8080/support/alice/pending
145
+ * curl localhost:8080/support/alice/signal --json '{"id": "inv_1f…:toolu_01", "value": "approved"}'
146
+ * curl localhost:8080/support/alice/signal --json '{"name": "approval", "value": "approved"}'
147
+ *
148
+ * It answers with the id of the wait it resolved, or `null` if none waited:
149
+ * the signal is dropped then, unless it has `"keep": true`, which keeps it
150
+ * for the next wait for its name.
151
+ */
152
+ export declare const signal: (name: string, options: {
153
+ description: string;
154
+ input?: z.ZodObject;
155
+ name?: string;
156
+ }) => Tool;
157
+ export {};
158
+ //# sourceMappingURL=tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,OAAO,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAgB,KAAK,SAAS,EAAyB,MAAM,aAAa,CAAC;AAIlF,QAAA,MAAM,IAAI,eAAoC,CAAC;AAE/C,wEAAwE;AACxE,MAAM,WAAW,QAAQ;IACvB,iEAAiE;IACjE,GAAG,EAAE,OAAO,CAAC,cAAc,CAAC;IAC5B,kFAAkF;IAClF,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,kDAAkD;AAClD,MAAM,WAAW,WAAY,SAAQ,QAAQ;IAC3C;;;;OAIG;IACH,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,iDAAiD;AACjD,MAAM,WAAW,IAAI;IACnB,QAAQ,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,6GAA6G;IAC7G,QA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