@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,81 @@
1
+ import * as clients from '@restatedev/restate-sdk-clients';
2
+ import type { VirtualObjectDefinition } from '@restatedev/restate-sdk-core';
3
+ import type { ChatMessage, Messages, MessagesRequest, Part, Turn } from './common.ts';
4
+ import type { Status, Stopped, Synced, SyncRequest } from './object.ts';
5
+ import type { Notifications, Resolved, Signal, Waiting, Watch } from './signals.ts';
6
+ export type { ChatMessage, Messages, MessagesRequest, Notifications, Part, Resolved, Signal, Status, Stopped, Synced, SyncRequest, Turn, Waiting, Watch, };
7
+ /** The handlers of an agent (`agent()` of any framework), as Restate's client calls them. */
8
+ export interface Agent {
9
+ /** Answer `message`. */
10
+ chat(ctx: unknown, message: string): Promise<string>;
11
+ /** The conversation, a page at a time, or what is new or changed since a cursor, also while a message is answered. */
12
+ messages(ctx: unknown, request?: MessagesRequest): Promise<Messages>;
13
+ /** The conversation since a cursor, the status and the revision; with `revision`, once there is a newer one. */
14
+ sync(ctx: unknown, request?: SyncRequest): Promise<Synced>;
15
+ /** What the agent is doing: the message it answers, and what its tools wait for. */
16
+ status(ctx: unknown): Promise<Status>;
17
+ /** Stop the message it answers: cancel its invocation. */
18
+ stop(ctx: unknown): Promise<Stopped>;
19
+ /** Forget the conversation (stopping the message it answers): its database and state too. */
20
+ clear(ctx: unknown): Promise<Stopped>;
21
+ /** What its tools wait for. */
22
+ pending(ctx: unknown): Promise<Waiting[]>;
23
+ /** Resolve a wait: by its id, or the oldest for a name. */
24
+ signal(ctx: unknown, signal: Signal): Promise<Resolved>;
25
+ /** The revision of its conversation, which each change increases. */
26
+ notifications(ctx: unknown): Promise<Notifications>;
27
+ /** The revision, once there is one newer than `revision`, or at the timeout. */
28
+ watch(ctx: unknown, watch: Watch): Promise<Notifications>;
29
+ }
30
+ /**
31
+ * The agent `name`, as Restate's client takes it: its name, typed with the
32
+ * handlers of an agent (or `H`, an object of your own's).
33
+ */
34
+ export declare const agent: <H = Agent, P extends string = string>(name: P) => VirtualObjectDefinition<P, H>;
35
+ /** What {@link follow} gives each time the conversation changes. */
36
+ export interface Followed {
37
+ /** What the agent is doing now. */
38
+ status: Status;
39
+ /**
40
+ * The messages new or changed since the last time, by when they changed: a
41
+ * message may come again, changed (a tool call with its output, say), with
42
+ * its `id`, which a UI keeps them by, and orders them by.
43
+ */
44
+ messages: ChatMessage[];
45
+ /**
46
+ * The id of the conversation's first message: one kept from before is
47
+ * gone (`clear` forgot it), and a UI drops it.
48
+ */
49
+ first: number;
50
+ /** Where this leaves off: `follow(..., { cursor })` carries on from here, later or elsewhere. */
51
+ cursor: number;
52
+ /** What the agent's tools wait for now (`status.waiting`). */
53
+ waiting: Waiting[];
54
+ }
55
+ /**
56
+ * `message` to read, such as in a terminal: its text after its role, and
57
+ * each tool call on a line of its own, with its output (`…` until it has one).
58
+ */
59
+ export declare const asText: ({ role, parts }: ChatMessage) => string;
60
+ /** Where {@link follow} starts, and what stops it. */
61
+ export interface FollowOptions {
62
+ /** The messages new or changed since this cursor (a page's, or a `Followed`'s); by default, all of them. */
63
+ cursor?: number;
64
+ /** Following ends once it aborts. */
65
+ signal?: AbortSignal;
66
+ /** How long one wait for a change lasts at most, in seconds (default 50). */
67
+ timeoutSeconds?: number;
68
+ }
69
+ /**
70
+ * The conversation of the agent `definition` (such as `agent('assistant')`)
71
+ * with key `key`, as it changes, through `ingress` (Restate's client): what
72
+ * the agent is doing and the messages so far, then each change, until
73
+ * `signal` aborts.
74
+ *
75
+ * Each change is one `sync`, which waits in Restate for the next. A network
76
+ * failure (or Restate's, restarting) does not end it: it tries again, and a
77
+ * sync it retries keeps its idempotency key, so it joins the one already
78
+ * waiting.
79
+ */
80
+ export declare function follow(ingress: clients.Ingress, definition: VirtualObjectDefinition<string, Agent>, key: string, { cursor, signal, timeoutSeconds }?: FollowOptions): AsyncGenerator<Followed, void, void>;
81
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,OAAO,MAAM,iCAAiC,CAAC;AAC3D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAC5E,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,eAAe,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACtF,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACxE,OAAO,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AAEpF,YAAY,EACV,WAAW,EACX,QAAQ,EACR,eAAe,EACf,aAAa,EACb,IAAI,EACJ,QAAQ,EACR,MAAM,EACN,MAAM,EACN,OAAO,EACP,MAAM,EACN,WAAW,EACX,IAAI,EACJ,OAAO,EACP,KAAK,GACN,CAAC;AAEF,6FAA6F;AAC7F,MAAM,WAAW,KAAK;IACpB,wBAAwB;IACxB,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACrD,sHAAsH;IACtH,QAAQ,CAAC,GAAG,EAAE,OAAO,EA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AM,CAAC;IACf,8DAA8D;IAC9D,OAAO,EAAE,OAAO,EAAE,CAAC;CACpB;AAED;;;GAGG;AACH,eAAO,MAAM,MAAM,oBAAqB,WAAW,WAOpC,CAAC;AAEhB,sDAAsD;AACtD,MAAM,WAAW,aAAa;IAC5B,4GAA4G;IAC5G,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,qCAAqC;IACrC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,6EAA6E;IAC7E,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AA8BD;;;;;;;;;;GAUG;AACH,wBAAuB,MAAM,CAC3B,OAAO,EAAE,OAAO,CAAC,OAAO,EACxB,UAAU,EAAE,uBAAuB,CAAC,MAAM,EAAE,KAAK,CAAC,EAClD,GAAG,EAAE,MAAM,EACX,EAAE,MAAU,EAAE,MAAM,EAAE,cAAmB,EAAE,GAAE,aAAkB,GAC9D,cAAc,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAoBtC"}
package/dist/client.js ADDED
@@ -0,0 +1,88 @@
1
+ // An agent for Restate's client (@restatedev/restate-sdk-clients), from a
2
+ // chat UI or any other code: the agent's definition as the client takes it,
3
+ // its name and the types of its handlers, and the types of what they answer;
4
+ // and `follow`, which follows its conversation as it changes. It imports
5
+ // Restate's client, and nothing of the agent's code or the SDK, so a web app
6
+ // bundles it as it is.
7
+ //
8
+ // import * as clients from '@restatedev/restate-sdk-clients';
9
+ // import { agent, follow } from '@restatedev/agents/client';
10
+ //
11
+ // const restate = clients.connect({ url: 'http://localhost:8080' });
12
+ // const alice = restate.objectClient(agent('assistant'), 'alice');
13
+ // const { messages } = await alice.messages({ limit: 20 });
14
+ // for await (const { status, messages } of follow(restate, agent('assistant'), 'alice')) { ... }
15
+ import * as clients from '@restatedev/restate-sdk-clients';
16
+ /**
17
+ * The agent `name`, as Restate's client takes it: its name, typed with the
18
+ * handlers of an agent (or `H`, an object of your own's).
19
+ */
20
+ export const agent = (name) => ({ name });
21
+ /**
22
+ * `message` to read, such as in a terminal: its text after its role, and
23
+ * each tool call on a line of its own, with its output (`…` until it has one).
24
+ */
25
+ export const asText = ({ role, parts }) => parts
26
+ .map((part) => part.type === 'text'
27
+ ? `${role}: ${part.text}`
28
+ : ` ${part.name}(${JSON.stringify(part.input)}) -> ${part.output ?? '…'}`)
29
+ .join('\n');
30
+ /** Whether a retry may answer: a network failure, Restate's (5xx) or too many requests (429); not a 4xx. */
31
+ const transient = (error) => !(error instanceof clients.HttpCallError) || error.status >= 500 || error.status === 429;
32
+ /**
33
+ * One `sync` of `followed`, tried again a second later with the same
34
+ * idempotency key until it answers, unless its error would last; undefined
35
+ * once `signal` aborts.
36
+ */
37
+ async function syncRetried(followed, request, signal) {
38
+ const opts = clients.rpc.opts({ signal, idempotencyKey: crypto.randomUUID() });
39
+ for (;;) {
40
+ if (signal?.aborted)
41
+ return undefined;
42
+ try {
43
+ return await followed.sync(request, opts);
44
+ }
45
+ catch (error) {
46
+ if (signal?.aborted)
47
+ return undefined;
48
+ if (!transient(error))
49
+ throw error;
50
+ console.warn('follow: retrying', error);
51
+ await new Promise((resolve) => setTimeout(resolve, 1000));
52
+ }
53
+ }
54
+ }
55
+ /**
56
+ * The conversation of the agent `definition` (such as `agent('assistant')`)
57
+ * with key `key`, as it changes, through `ingress` (Restate's client): what
58
+ * the agent is doing and the messages so far, then each change, until
59
+ * `signal` aborts.
60
+ *
61
+ * Each change is one `sync`, which waits in Restate for the next. A network
62
+ * failure (or Restate's, restarting) does not end it: it tries again, and a
63
+ * sync it retries keeps its idempotency key, so it joins the one already
64
+ * waiting.
65
+ */
66
+ export async function* follow(ingress, definition, key, { cursor = 0, signal, timeoutSeconds = 50 } = {}) {
67
+ const followed = ingress.objectClient(definition, key);
68
+ let revision;
69
+ for (;;) {
70
+ const synced = await syncRetried(followed, { cursor, revision, timeoutSeconds }, signal);
71
+ if (!synced)
72
+ return;
73
+ // Nothing changed (the wait timed out): wait again.
74
+ if (synced.revision !== revision || synced.messages.length > 0) {
75
+ yield {
76
+ status: synced.status,
77
+ messages: synced.messages,
78
+ first: synced.first ?? 0,
79
+ cursor: synced.cursor,
80
+ waiting: synced.status.waiting,
81
+ };
82
+ }
83
+ cursor = synced.cursor;
84
+ // With more to read, at once; else once something changes.
85
+ revision = synced.more ? undefined : synced.revision;
86
+ }
87
+ }
88
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,4EAA4E;AAC5E,6EAA6E;AAC7E,yEAAyE;AACzE,6EAA6E;AAC7E,uBAAuB;AACvB,EAAE;AACF,gEAAgE;AAChE,+DAA+D;AAC/D,EAAE;AACF,uEAAuE;AACvE,qEAAqE;AACrE,8DAA8D;AAC9D,mGAAmG;AACnG,OAAO,KAAK,OAAO,MAAM,iCAAiC,CAAC;AA+C3D;;;GAGG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,CAAuC,IAAO,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAkC,CAAC;AAuBpH;;;GAGG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,EAAE,IAAI,EAAE,KAAK,EAAe,EAAE,EAAE,CACrD,KAAK;KACF,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACZ,IAAI,CAAC,IAAI,KAAK,MAAM;IAClB,CAAC,CAAC,GAAG,IAAI,KAAK,IAAI,CAAC,IAAI,EAAE;IACzB,CAAC,CAAC,KAAK,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,IAAI,CAAC,MAAM,IAAI,GAAG,EAAE,CAC7E;KACA,IAAI,CAAC,IAAI,CAAC,CAAC;AAYhB,4GAA4G;AAC5G,MAAM,SAAS,GAAG,CAAC,KAAc,EAAE,EAAE,CACnC,CAAC,CAAC,KAAK,YAAY,OAAO,CAAC,aAAa,CAA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c,EAAE,EAAE,MAAM,CAAC,CAAC;QACzF,IAAI,CAAC,MAAM;YAAE,OAAO;QACpB,oDAAoD;QACpD,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC/D,MAAM;gBACJ,MAAM,EAAE,MAAM,CAAC,MAAM;gBACrB,QAAQ,EAAE,MAAM,CAAC,QAAQ;gBACzB,KAAK,EAAE,MAAM,CAAC,KAAK,IAAI,CAAC;gBACxB,MAAM,EAAE,MAAM,CAAC,MAAM;gBACrB,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,OAAO;aAC/B,CAAC;QACJ,CAAC;QACD,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;QACvB,2DAA2D;QAC3D,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC;IACvD,CAAC;AACH,CAAC"}
@@ -0,0 +1,261 @@
1
+ import * as restate from '@restatedev/sessions';
2
+ import type { Said } from './log.ts';
3
+ /**
4
+ * A value, or a function of the invocation's context that gives it: the
5
+ * same for every message, or each user's (from the object's database, say).
6
+ *
7
+ * pi.chat({ model: 'openai/gpt-6-sol' })
8
+ * pi.chat(async (ctx) => ({ model: await userModel(ctx) }))
9
+ */
10
+ export type Configure<T> = T | ((ctx: restate.SessionContext) => T | Promise<T>);
11
+ /** `value` for the invocation of `ctx`. */
12
+ export declare const configured: <T>(value: Configure<T>, ctx: restate.SessionContext) => Promise<T>;
13
+ /**
14
+ * The id of the next prompt of the invocation of `ctx`: the invocation's id,
15
+ * then `<id>:2`, `<id>:3`... A retried attempt makes its prompts in the same
16
+ * order, so each gets the same id again, and its answer.
17
+ */
18
+ export declare const nextPromptId: (ctx: restate.SessionContext) => string;
19
+ /** The default model of pi, OpenCode and LangGraph, with OPENAI_API_KEY. */
20
+ export declare const DEFAULT_MODEL = "openai/gpt-6-sol";
21
+ /** The default model of Claude agents, with ANTHROPIC_API_KEY. */
22
+ export declare const CLAUDE_MODEL = "anthropic/claude-sonnet-5-5";
23
+ /**
24
+ * The model, as `provider/model-id` (such as `openai/gpt-6-sol`):
25
+ * `model`, or else MODEL, or else the framework's default.
26
+ */
27
+ export declare const modelOf: (model: string | undefined, fallback?: string) => string;
28
+ /** `provider/model-id` as its provider and model id, split at the first `/` (`openrouter/meta-llama/llama-4`). */
29
+ export declare const providerOf: (model: string) => [provider: string, id: string];
30
+ /**
31
+ * The error code of a message the model's provider refused (a missing or
32
+ * wrong API key, an unknown model): 424, Failed Dependency, as its HTTP
33
+ * status.
34
+ */
35
+ export declare const REFUSED = 424;
36
+ /** What to check when a model's provider refuses a request. */
37
+ export declare const CHECK_MODEL = "check the agent's model (its `model` option, or MODEL) and its provider's API key";
38
+ /**
39
+ * An agent's model that it cannot take: not `provider/model-id`, another
40
+ * provider's, or one its framework does not know. Terminal ({@link REFUSED}),
41
+ * wherever it is thrown: a retry takes the same model.
42
+ */
43
+ export declare class ModelError extends restate.TerminalError {
44
+ constructor(message: string);
45
+ }
46
+ /** `model`, the explicit `model` option of `framework`'s agent, if it is not `provider/model-id`. */
47
+ export declare const checkModelName: (framework: string, model: string | undefined) => void;
48
+ /**
49
+ * The model id of `model`, for a framework with only `provider`'s models:
50
+ * `provider/model-id`, or the id alone.
51
+ */
52
+ export declare const modelIdOf: (model: string, provider: string) => string;
53
+ /** A chat message: the request's body as text, or the string it is as JSON (`"Hi"`). */
54
+ export declare const messageSerde: restate.Serde<string>;
55
+ /**
56
+ * What a cancelled turn answers, and each tool call it cut off: the model
57
+ * sees it in the conversation that goes on.
58
+ */
59
+ export declare const CANCELLED = "Cancelled: the turn was stopped before it finished.";
60
+ /**
61
+ * What a prompt answers that the model's provider refused for good (see
62
+ * {@link refusal}): the prompt is over, and the model sees it in the
63
+ * conversation that goes on, rather than answer it with the next message.
64
+ */
65
+ export declare const UNANSWERED = "Unanswered: the model's provider refused the request.";
66
+ /** The message a `chat` handler is answering: its invocation, and when it started. */
67
+ export interface Turn {
68
+ /** The invocation's id: `/restate/invocation/<id>/attach` waits for its answer. */
69
+ invocationId: string;
70
+ /** When it started, as an ISO date. */
71
+ since: string;
72
+ }
73
+ /**
74
+ * Why a turn stopped when its attempt ended before it did: Restate suspended
75
+ * the attempt, gave up on it, or lost its connection. Nothing the attempt
76
+ * does after is stored, and the next attempt goes on with the turn, so it
77
+ * stops without answering: unlike a cancellation, nothing is cancelled.
78
+ */
79
+ export declare class AttemptEnded extends Error {
80
+ constructor();
81
+ }
82
+ /**
83
+ * The signal that stops the turn of `ctx` (of a `chat` handler,
84
+ * `chatHandler`), and an agent's `prompt` stops its framework's work with it.
85
+ * It aborts with a `restate.CancelledError` once Restate cancels the
86
+ * invocation (the turn ends, answered as cancelled), or with an
87
+ * {@link AttemptEnded} once the attempt ends first (the work stops, and
88
+ * answers nothing).
89
+ */
90
+ export declare const stopSignalOf: (ctx: object) => AbortSignal | undefined;
91
+ /** Agent `name` runs in the background: see `background` in object.ts. */
92
+ export declare const inBackground: (name: string) => undefined;
93
+ /**
94
+ * The `messages` view `view` of a framework that keeps a conversation apart
95
+ * (OpenCode, in a database of its own): `clear` empties it too, as an agent
96
+ * with this view is cleared.
97
+ */
98
+ export declare const alsoClearing: <V extends object>(view: V, clear: (ctx: restate.SessionContext) => Promise<void>) => V;
99
+ /** When the agent `name`, whose `messages` view is `view`, is cleared, clear what that view keeps apart too. */
100
+ export declare const onClear: (name: string, view: object | undefined) => void;
101
+ /** Clear what the agent of `ctx` keeps beside its database ({@link onClear}). */
102
+ export declare const cleared: (ctx: restate.SessionContext) => Promise<void | undefined>;
103
+ /**
104
+ * A tool call of the turn of `ctx` starts: {@link publish} it, which forgets
105
+ * the calls whose results are stored (calls.ts) before the tool makes its
106
+ * own. In the background, which publishes the turn's end only, it forgets
107
+ * them alone.
108
+ */
109
+ export declare function toolCallStarted(ctx: restate.SessionContext): Promise<void>;
110
+ /** A tool call of the turn of `ctx` (a `chat` handler's) ended: {@link publish} it, unless the agent runs in the background. */
111
+ export declare function toolCallEnded(ctx: restate.SessionContext): Promise<void>;
112
+ /** A promise that rejects with `signal`'s reason once it aborts. */
113
+ export declare const aborted: (signal: AbortSignal) => Promise<never>;
114
+ /**
115
+ * `answer` as a chat handler, which takes its message as plain text or as a
116
+ * JSON string, so that both of these work:
117
+ *
118
+ * curl localhost:8080/assistant/alice/chat -d 'Hi'
119
+ * curl localhost:8080/assistant/alice/chat --json '"Hi"'
120
+ *
121
+ * While it answers, the object's `status` says so (its {@link Turn}). Its
122
+ * invocation's cancellation (Restate's, explicit: `cancelled(ctx)` of
123
+ * @restatedev/sessions/internal) aborts {@link stopSignalOf} its
124
+ * context, whenever it comes, and cancels the calls its tools made
125
+ * (`cancelCalls(ctx)`): the agent's `prompt`
126
+ * ends the turn, and the handler fails with a `restate.CancelledError`. An
127
+ * attempt that ends first (`attemptCompletedSignal`) aborts it too, with an
128
+ * {@link AttemptEnded}: the work stops, and the next attempt goes on with it.
129
+ *
130
+ * It publishes when it starts and ends ({@link publish}), for the clients
131
+ * that follow the conversation.
132
+ */
133
+ export declare const chatHandler: <A = string>(answer: (ctx: restate.SessionContext, message: string) => Promise<A>) => {
134
+ input: restate.Serde<string>;
135
+ accept: string;
136
+ explicitCancellation: boolean;
137
+ handler: (ctx: restate.SessionContext, text: string) => Promise<A>;
138
+ };
139
+ /** A tool's error, which fails the attempt (Restate retries it): the error `cause` of tool `tool`. */
140
+ export declare class ToolError extends Error {
141
+ readonly tool: string;
142
+ constructor(tool: string, cause: unknown);
143
+ }
144
+ /**
145
+ * `error` is a tool's: a framework's own tool (Claude's, LangChain's...)
146
+ * that failed, whose error is never taken for the model's provider refusing
147
+ * (a tool that calls a model API may fail as one does). `tool()`'s are
148
+ * {@link ToolError}s.
149
+ */
150
+ export declare function fromTool(error: unknown): void;
151
+ /**
152
+ * `error` as a terminal error ({@link REFUSED}), if a retry does not change
153
+ * it: a model the agent cannot take, or its provider's refusal.
154
+ */
155
+ export declare function refusal(error: unknown): restate.TerminalError | undefined;
156
+ /**
157
+ * A prompt's stored answer, as the prompt returns it: {@link UNANSWERED},
158
+ * stored as its provider refused it, fails as the prompt did then
159
+ * ({@link REFUSED}), also in a retry after a crash right after it was stored.
160
+ */
161
+ export declare function storedAnswer(answer: string): string;
162
+ /** A message of a conversation, as an agent's `messages` handler returns it. */
163
+ export interface ChatMessage {
164
+ /** Its id, from 0, in the order of the conversation; the same however it changes. `before` takes it. */
165
+ id: number;
166
+ role: 'user' | 'assistant';
167
+ parts: Part[];
168
+ }
169
+ /**
170
+ * What a message says: text, or a tool call with its output once it ran,
171
+ * and `error: true` if the output is the tool's error (`Error: <message>` of
172
+ * a `restate.TerminalError`, say).
173
+ */
174
+ export type Part = {
175
+ type: 'text';
176
+ text: string;
177
+ } | {
178
+ type: 'tool';
179
+ id: string;
180
+ name: string;
181
+ input: unknown;
182
+ output?: string;
183
+ error?: true;
184
+ };
185
+ /**
186
+ * Which messages to read: the latest `limit`, or those before a message, for
187
+ * a page of the conversation; or those new or changed since a `cursor`, to
188
+ * follow it.
189
+ */
190
+ export interface MessagesRequest {
191
+ /** At most this many messages (default 50). */
192
+ limit?: number;
193
+ /** The messages before this one (its `id`): older ones, such as for scrolling back. */
194
+ before?: number;
195
+ /** The messages new or changed since this cursor (a page's `cursor`), by when they changed. */
196
+ cursor?: number;
197
+ }
198
+ /**
199
+ * A page of messages: oldest first; or, with a `cursor`, those new or
200
+ * changed since it, by when they changed. Keep them by `id`: a message comes
201
+ * again once it changed (its tool call's output came, say).
202
+ */
203
+ export interface Messages {
204
+ messages: ChatMessage[];
205
+ /** Whether there are more: older ones, or with a `cursor`, newer ones. */
206
+ more: boolean;
207
+ /** The cursor to read on from: what changes after this page. */
208
+ cursor: number;
209
+ /**
210
+ * The id of the conversation's first message, once it was cleared
211
+ * (`clear`): a client drops the messages it kept from before.
212
+ */
213
+ first?: number;
214
+ }
215
+ /**
216
+ * A conversation as `messages` gives it, built from a framework's transcript:
217
+ * each message is started by `say`, a tool call goes to the assistant's
218
+ * message, and its result to its call. Messages without parts are left out.
219
+ *
220
+ * A message, once given out by `messages()`, is never changed: a change
221
+ * makes a new one in its place. So a framework can keep its transcript and
222
+ * add to it as its conversation grows, and the log stores only the messages
223
+ * that are not the ones it stored last (see log.ts).
224
+ */
225
+ export declare class Transcript {
226
+ #private;
227
+ /** A new message of `role`, with `text` if there is any. */
228
+ say(role: ChatMessage['role'], text?: string): void;
229
+ /** Tool call `id` of the assistant's message. */
230
+ call(id: string, name: string, input: unknown): void;
231
+ /** The output of tool call `id`; an error's if the framework says so, or it is a tool's `Error: <message>`. */
232
+ result(id: string, output: string, error?: boolean): void;
233
+ /**
234
+ * Whether tool call `id` has its output: not an error's, unless it is
235
+ * `failed`, the error the call answered with.
236
+ */
237
+ answered(id: string, failed?: string): boolean;
238
+ /** Its messages, in order: those with parts. */
239
+ messages(): Said[];
240
+ }
241
+ /**
242
+ * A framework's transcript as it stands, while it answers (see
243
+ * {@link transcribing}): a new one, or the one it keeps and adds to.
244
+ */
245
+ export type Read = () => Promise<Transcript>;
246
+ /**
247
+ * Run `work`, a framework's turn (or a compaction, a reset), with `read`
248
+ * giving the framework's transcript as it stands, from the framework as
249
+ * `work` holds it open: each publish meanwhile (a tool call's start and end)
250
+ * takes it into the conversation's log, and so does `work`'s end, before the
251
+ * framework closes. `messages` and `sync` read the log.
252
+ */
253
+ export declare function transcribing<T>(ctx: restate.SessionContext, read: Read, work: () => Promise<T>): Promise<T>;
254
+ /**
255
+ * The handler of an agent's conversation as clients read it, from its log:
256
+ * a page of it (`{limit, before}`), or what is new or changed since a cursor
257
+ * (`{cursor}`). It is a view: it answers while a message is answered, with
258
+ * what was stored so far, and stores nothing.
259
+ */
260
+ export declare const messagesHandler: () => (ctx: restate.ViewContext, request?: MessagesRequest) => Promise<Messages>;
261
+ //# sourceMappingURL=common.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file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