@midsummer-ai/sdk 0.1.0-staging.5448 → 0.1.0-staging.5454

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.
@@ -0,0 +1,6 @@
1
+ import { RunEvent, RunState, StartedRun, WatchOptions, WatchedRun } from "./site.mjs";
2
+ //#region src/agents/react.d.ts
3
+ /** The run `watch` names, as it is now and then as each of its steps is kept, until it ends; undefined until first read, or with no address. */
4
+ declare function useRun(watch: string | Pick<StartedRun, "watch"> | undefined, options?: WatchOptions): WatchedRun | undefined;
5
+ //#endregion
6
+ export { type RunEvent, type RunState, type StartedRun, type WatchedRun, useRun };
@@ -0,0 +1,36 @@
1
+ "use client";
2
+ import { watchRun } from "./site.mjs";
3
+ import { useEffect, useState } from "react";
4
+ //#region src/agents/react.ts
5
+ /**
6
+ * `@midsummer-ai/sdk/agents/react`: a run of one of your project's agents, followed live on a page.
7
+ *
8
+ * import { useRun } from "@midsummer-ai/sdk/agents/react"
9
+ *
10
+ * function Research({ started }: { started: StartedRun }) { // what the server's startRun returned
11
+ * const run = useRun(started) // undefined until the first read
12
+ * if (!run) return <p>Starting…</p>
13
+ * return <>
14
+ * <ol>{run.events.filter((event) => event.type === "log").map((event) => <li key={event.sequence}>{String((event.data as { message?: string })?.message)}</li>)}</ol>
15
+ * {run.state === "done" && <Answer value={run.output} />}
16
+ * {run.state === "failed" && <p>{run.error}</p>}
17
+ * </>
18
+ * }
19
+ *
20
+ * It follows the run its `watch` address names (`watchRun` in `@midsummer-ai/sdk/agents/site`) while the component is
21
+ * shown, and starts again when the address changes. React is a peer dependency: a project that does not import this
22
+ * entry does not need it.
23
+ */
24
+ /** The run `watch` names, as it is now and then as each of its steps is kept, until it ends; undefined until first read, or with no address. */
25
+ function useRun(watch, options) {
26
+ const address = typeof watch === "string" ? watch : watch?.watch;
27
+ const [run, setRun] = useState(void 0);
28
+ useEffect(() => {
29
+ setRun(void 0);
30
+ if (!address) return void 0;
31
+ return watchRun(address, setRun, options);
32
+ }, [address]);
33
+ return run;
34
+ }
35
+ //#endregion
36
+ export { useRun };
@@ -0,0 +1,54 @@
1
+ //#region src/agents/site.d.ts
2
+ /** A run as a site started it: what its server hands its page. */
3
+ interface StartedRun {
4
+ readonly id: string;
5
+ readonly agent: string;
6
+ readonly state: RunState;
7
+ readonly createdAt: number;
8
+ /** Where its page follows it, with a token for this run alone (`watchRun`). */
9
+ readonly watch: string;
10
+ }
11
+ /** Where a run is: waiting to start, running, done, failed or cancelled. */
12
+ type RunState = "queued" | "running" | "done" | "failed" | "cancelled";
13
+ /** One of a run's steps as it was kept: a log line, a model's answer, a tool's call, its start and its end. */
14
+ interface RunEvent {
15
+ readonly sequence: number;
16
+ readonly type: string;
17
+ readonly at: number;
18
+ readonly data?: unknown;
19
+ }
20
+ /** A run as its page sees it: where it is, every step kept so far, and once it ends its output or why it failed. */
21
+ interface WatchedRun {
22
+ readonly id: string;
23
+ readonly state: RunState;
24
+ readonly events: ReadonlyArray<RunEvent>;
25
+ readonly output?: unknown;
26
+ readonly error?: string;
27
+ /** Why the page can't follow it (an address that isn't a run's, or past its day), once following stopped. */
28
+ readonly problem?: string;
29
+ }
30
+ /**
31
+ * Starts a run of `agent`, one of the project's agents, from the site's own server, with `input` as its input. The same
32
+ * `key` returns the same run, so a form sent twice starts one. Throws `AgentError`: `not-found` for an agent the project
33
+ * has none of, `invalid` for one that runs nowhere in this environment, `unavailable` outside a deployment.
34
+ *
35
+ * const run = await startRun("researcher", { input: { question: "What changed in Acme's pricing?" }, key: formId })
36
+ */
37
+ declare function startRun(agent: string, options?: {
38
+ readonly input?: unknown;
39
+ readonly key?: string;
40
+ }): Promise<StartedRun>;
41
+ /** What `watchRun` uses to reach the platform: a page's own `fetch` and `WebSocket` unless given others. */
42
+ interface WatchOptions {
43
+ readonly fetch?: typeof fetch;
44
+ readonly WebSocket?: new (url: string) => WebSocket;
45
+ }
46
+ /**
47
+ * Follows a run from a page, by the `watch` address its server was given (or the started run itself): `onChange` gets
48
+ * the run as it is now, and again as each step is kept, until it ends, when following stops by itself. A dropped
49
+ * connection is opened again, reading what came in between, a few times before it gives up and says so in `problem`.
50
+ * Returns a function that stops following.
51
+ */
52
+ declare function watchRun(watch: string | Pick<StartedRun, "watch">, onChange: (run: WatchedRun) => void, options?: WatchOptions): () => void;
53
+ //#endregion
54
+ export { RunEvent, RunState, StartedRun, WatchOptions, WatchedRun, startRun, watchRun };
@@ -0,0 +1,164 @@
1
+ import { n as here } from "../here-BO-wQDjz.mjs";
2
+ import { AgentError } from "./index.mjs";
3
+ //#region src/agents/site.ts
4
+ /**
5
+ * `@midsummer-ai/sdk/agents/site`: runs of a project's agents from its own site. The site's server starts one
6
+ * (`startRun`), and its page follows it as it goes (`watchRun`, or `useRun` from `@midsummer-ai/sdk/agents/react`).
7
+ *
8
+ * // On the server, in a deployment on Midsummer: no key, the project's own agents, paid by the project.
9
+ * const run = await startRun("researcher", { input: { question } })
10
+ * return Response.json(run) // { id, agent, state, createdAt, watch }
11
+ *
12
+ * // On the page: the run as it is now, then again as each of its steps is kept, until it ends.
13
+ * const stop = watchRun(run, (now) => render(now.state, now.events, now.output))
14
+ *
15
+ * `watch` is the address the page follows that run at, with a token for that run alone, good for a day: hand it to the
16
+ * page, and anyone who has it can read that run, nothing else. The run starts on the agent's deployment in the
17
+ * environment the site's address serves, so a preview's page runs the agent its preview environment does.
18
+ */
19
+ /**
20
+ * Starts a run of `agent`, one of the project's agents, from the site's own server, with `input` as its input. The same
21
+ * `key` returns the same run, so a form sent twice starts one. Throws `AgentError`: `not-found` for an agent the project
22
+ * has none of, `invalid` for one that runs nowhere in this environment, `unavailable` outside a deployment.
23
+ *
24
+ * const run = await startRun("researcher", { input: { question: "What changed in Acme's pricing?" }, key: formId })
25
+ */
26
+ async function startRun(agent, options = {}) {
27
+ const handle = here()?.agents;
28
+ if (!handle) throw new AgentError("unavailable", "startRun starts runs from a site's server in a deployment on Midsummer. Start one by hand with midsummer agent run start.");
29
+ const answer = await handle.call("start", {
30
+ agent,
31
+ ...options.input === void 0 ? {} : { input: options.input },
32
+ ...options.key === void 0 ? {} : { key: options.key }
33
+ }).catch((error) => {
34
+ throw new AgentError("unavailable", error instanceof Error ? error.message : String(error));
35
+ });
36
+ if (!answer.ok) throw new AgentError([
37
+ "invalid",
38
+ "not-found",
39
+ "unavailable"
40
+ ].includes(answer.code) ? answer.code : answer.code === "conflict" ? "invalid" : "refused", answer.message);
41
+ return answer.value;
42
+ }
43
+ /** How often following a run tries again after its connection drops or a read fails, and how long it waits at most between tries. */
44
+ const RETRIES = 6;
45
+ const RETRY_MOST_MS = 15e3;
46
+ /** The most pages of steps one read takes, a hundred each. */
47
+ const PAGES_MOST = 50;
48
+ /**
49
+ * Follows a run from a page, by the `watch` address its server was given (or the started run itself): `onChange` gets
50
+ * the run as it is now, and again as each step is kept, until it ends, when following stops by itself. A dropped
51
+ * connection is opened again, reading what came in between, a few times before it gives up and says so in `problem`.
52
+ * Returns a function that stops following.
53
+ */
54
+ function watchRun(watch, onChange, options = {}) {
55
+ const address = typeof watch === "string" ? watch : watch.watch;
56
+ const send = options.fetch ?? globalThis.fetch.bind(globalThis);
57
+ const Socket = options.WebSocket ?? globalThis.WebSocket;
58
+ let run;
59
+ /** The last of the run's steps the reads have passed, shown or not: the next read starts after it. */
60
+ let after;
61
+ let socket;
62
+ let stopped = false;
63
+ let tries = 0;
64
+ let reading;
65
+ let again = false;
66
+ let timer;
67
+ const ended = () => run !== void 0 && run.state !== "queued" && run.state !== "running";
68
+ const tell = (next) => {
69
+ run = next;
70
+ if (!stopped) onChange(next);
71
+ };
72
+ const stop = () => {
73
+ stopped = true;
74
+ if (timer) clearTimeout(timer);
75
+ try {
76
+ socket?.close();
77
+ } catch {}
78
+ };
79
+ /** Tries again later, waiting longer each time, and says so once it gives up. */
80
+ const later = (work) => {
81
+ if (stopped) return;
82
+ if (++tries > RETRIES) {
83
+ if (run) tell({
84
+ ...run,
85
+ problem: `Lost the run ${RETRIES} times; read it again to see how it ended.`
86
+ });
87
+ return;
88
+ }
89
+ timer = setTimeout(work, Math.min(500 * 2 ** tries, RETRY_MOST_MS));
90
+ };
91
+ /** One page: the run as it is now, and the steps after the last one read. */
92
+ async function page() {
93
+ const url = new URL(address);
94
+ if (after !== void 0) url.searchParams.set("after", String(after));
95
+ const response = await send(url.toString());
96
+ const body = await response.json().catch(() => ({}));
97
+ if (!response.ok || !body.run) {
98
+ const problem = body.error ?? `Following the run failed (${response.status}).`;
99
+ tell({
100
+ ...run ?? {
101
+ id: url.pathname.split("/").at(-2) ?? "",
102
+ state: "queued",
103
+ events: []
104
+ },
105
+ problem
106
+ });
107
+ if (response.status === 403 || response.status === 404) stop();
108
+ throw new Error(problem);
109
+ }
110
+ const known = new Set(run?.events.map((event) => event.sequence));
111
+ const events = [...run?.events ?? [], ...(body.events ?? []).filter((event) => !known.has(event.sequence))].sort((a, b) => a.sequence - b.sequence);
112
+ if (typeof body.last === "number") after = body.last;
113
+ tell({
114
+ ...body.run,
115
+ events
116
+ });
117
+ return { more: body.more === true };
118
+ }
119
+ /** Reads every page there is now; asked while reading, it reads again once that read is done. */
120
+ function read() {
121
+ if (reading) {
122
+ again = true;
123
+ return reading;
124
+ }
125
+ reading = (async () => {
126
+ try {
127
+ for (let pages = 0; pages < PAGES_MOST && !stopped; pages++) if (!(await page()).more) break;
128
+ tries = 0;
129
+ } finally {
130
+ reading = void 0;
131
+ }
132
+ if (again && !stopped) {
133
+ again = false;
134
+ await read();
135
+ }
136
+ if (ended()) stop();
137
+ })();
138
+ return reading;
139
+ }
140
+ function open() {
141
+ if (stopped || ended() || !Socket) return;
142
+ const url = new URL(address);
143
+ url.protocol = url.protocol === "http:" ? "ws:" : "wss:";
144
+ const opened = new Socket(url.toString());
145
+ socket = opened;
146
+ opened.addEventListener("open", () => {
147
+ read().catch(() => void 0);
148
+ });
149
+ opened.addEventListener("message", () => {
150
+ read().catch(() => later(() => void read().catch(() => void 0)));
151
+ });
152
+ opened.addEventListener("close", () => {
153
+ if (stopped || ended() || socket !== opened) return;
154
+ later(() => {
155
+ read().then(open, open);
156
+ });
157
+ });
158
+ }
159
+ open();
160
+ read().catch(() => later(() => void read().catch(() => void 0)));
161
+ return stop;
162
+ }
163
+ //#endregion
164
+ export { startRun, watchRun };
package/here-BO-wQDjz.mjs CHANGED
@@ -21,7 +21,7 @@ function processEnv() {
21
21
  * This package's version: `0.0.0-dev` here, and in a published package the version it was published at, which the
22
22
  * release writes in its place as it stages the package (`stampSdk` in `scripts/release/packages.ts`).
23
23
  */
24
- const SDK_VERSION = "0.1.0-staging.5448";
24
+ const SDK_VERSION = "0.1.0-staging.5454";
25
25
  /**
26
26
  * The header that tells Midsummer which client made each of this package's calls: `Midsummer-Client: sdk/<version>
27
27
  * <part>`, `part` the product whose client it is (`database`, `storage`, `queues`, ...), so the platform counts which
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midsummer-ai/sdk",
3
- "version": "0.1.0-staging.5448",
3
+ "version": "0.1.0-staging.5454",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "description": "Midsummer's handles for an app's code: its Database, Storage, Queues, Vector DB, AI, Email and Agents, with stand-ins for tests.",
@@ -95,6 +95,14 @@
95
95
  "types": "./agents/contract.d.mts",
96
96
  "import": "./agents/contract.mjs"
97
97
  },
98
+ "./agents/site": {
99
+ "types": "./agents/site.d.mts",
100
+ "import": "./agents/site.mjs"
101
+ },
102
+ "./agents/react": {
103
+ "types": "./agents/react.d.mts",
104
+ "import": "./agents/react.mjs"
105
+ },
98
106
  "./queues": {
99
107
  "types": "./queues/index.d.mts",
100
108
  "import": "./queues/index.mjs"
@@ -357,6 +365,12 @@
357
365
  "agents/contract": [
358
366
  "./agents/contract.d.mts"
359
367
  ],
368
+ "agents/site": [
369
+ "./agents/site.d.mts"
370
+ ],
371
+ "agents/react": [
372
+ "./agents/react.d.mts"
373
+ ],
360
374
  "queues": [
361
375
  "./queues/index.d.mts"
362
376
  ],