@midsummer-ai/sdk 0.1.0-staging.5330 → 0.1.0-staging.5333

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.
@@ -32,6 +32,83 @@ interface AgentContext {
32
32
  artifact(name: string, content: string | Uint8Array, type?: string): Promise<void>;
33
33
  /** Asks the model, with the version's instructions; what it costs counts toward the version's spend ceiling. */
34
34
  ask(prompt: string): Promise<string>;
35
+ /**
36
+ * Asks the model a conversation, with tools it may call, a JSON Schema its answer fits, pictures and a model of its own.
37
+ * The tool calls come back to the code, which runs them and asks again with their results; the version's instructions
38
+ * are its system prompt.
39
+ *
40
+ * const { toolCalls } = await agent.ask({ prompt: "Weather in Oslo?", tools: [{ name: "weather", input: { type: "object", properties: { city: { type: "string" } } } }] })
41
+ */
42
+ ask(question: Question): Promise<Answer>;
43
+ /**
44
+ * Hands a goal to Midsummer's engine and waits for its answer: the model plans, calls tools and works until it is done,
45
+ * each step kept, for up to `maxSteps` turns and `budget` credits of the run's own. With `output`, the answer comes back
46
+ * as JSON fitting that schema; without, as the engine's words. A loop that couldn't finish throws its reason.
47
+ */
48
+ loop(loop: Loop): Promise<unknown>;
49
+ }
50
+ /** A JSON Schema, such as `{ type: "object", properties: { price: { type: "number" } }, required: ["price"] }`. */
51
+ type JsonSchema = Readonly<Record<string, unknown>>;
52
+ /** A goal for `agent.loop`. */
53
+ interface Loop {
54
+ /** What to get done, in words, as you would ask a person. */
55
+ readonly goal: string;
56
+ /** The schema its answer fits; plain words when left out. */
57
+ readonly output?: JsonSchema;
58
+ /** The model it works with, as `midsummer ai model list` shows them; Claude Opus when left out. */
59
+ readonly model?: string;
60
+ /** The most turns it takes, 1 to 200; 80 when left out. */
61
+ readonly maxSteps?: number;
62
+ /** The most credits it may spend; the run's own ceiling still holds. */
63
+ readonly budget?: number;
64
+ }
65
+ /** One message of a conversation `ask` is given. A tool's result is for the call named by `toolCallId`. */
66
+ type Message = {
67
+ readonly role: "user";
68
+ readonly content: string;
69
+ } | {
70
+ readonly role: "assistant";
71
+ readonly content: string;
72
+ readonly toolCalls?: ReadonlyArray<ToolCall>;
73
+ } | {
74
+ readonly role: "tool";
75
+ readonly content: string;
76
+ readonly toolCallId: string;
77
+ };
78
+ /** A tool the model may call: its name, what it does, and the schema of its input. */
79
+ interface Tool {
80
+ readonly name: string;
81
+ readonly description?: string;
82
+ readonly input: JsonSchema;
83
+ }
84
+ /** A call the model made of a tool `ask` was given. */
85
+ interface ToolCall {
86
+ readonly id: string;
87
+ readonly name: string;
88
+ readonly input: unknown;
89
+ }
90
+ /** A picture the model is shown, as base64, with the last of the question's own words. */
91
+ interface Picture {
92
+ readonly type: "image/png" | "image/jpeg" | "image/webp" | "image/gif";
93
+ readonly data: string;
94
+ }
95
+ /** A question `ask` takes beyond a prompt: give `prompt`, `messages`, or both (the prompt goes last). */
96
+ interface Question {
97
+ readonly prompt?: string;
98
+ readonly messages?: ReadonlyArray<Message>;
99
+ readonly tools?: ReadonlyArray<Tool>;
100
+ /** The schema the answer fits: it comes back as `output`, checked against it. */
101
+ readonly output?: JsonSchema;
102
+ readonly images?: ReadonlyArray<Picture>;
103
+ /** The model to ask, as `midsummer ai model list` shows them; the version's when left out. */
104
+ readonly model?: string;
105
+ readonly effort?: "low" | "medium" | "high" | "xhigh" | "max";
106
+ }
107
+ /** What the model returned: its words, the tool calls it made, and with `output`, the JSON it gave. */
108
+ interface Answer {
109
+ readonly text: string;
110
+ readonly toolCalls: ReadonlyArray<ToolCall>;
111
+ readonly output?: unknown;
35
112
  }
36
113
  /** An Agent: its `run`, and the tools it may be allowed. */
37
114
  interface Agent<Input = any, Output = unknown> {
@@ -69,10 +146,12 @@ type AgentCall = {
69
146
  readonly name: string;
70
147
  readonly type: string;
71
148
  readonly data: string;
72
- } | {
149
+ } | ({
73
150
  readonly kind: "ask";
74
- readonly prompt: string;
75
- };
151
+ readonly prompt?: string;
152
+ } & Omit<Question, "prompt">) | ({
153
+ readonly kind: "loop";
154
+ } & Loop);
76
155
  type RunStatus = "queued" | "running" | "completed" | "failed" | "cancelled";
77
156
  /** What a run is when it begins. */
78
157
  interface RunStart {
@@ -103,16 +182,18 @@ interface RunWire {
103
182
  readonly error: string;
104
183
  }): Promise<unknown>;
105
184
  }
106
- type AgentErrorCode = "refused" | "ended" | "invalid" | "not-found" | "unavailable";
185
+ /** `failed`: a loop the code waited on couldn't finish; the message gives the reason. */
186
+ type AgentErrorCode = "refused" | "ended" | "invalid" | "not-found" | "unavailable" | "failed";
107
187
  declare class AgentError extends Error {
108
188
  readonly code: AgentErrorCode;
109
189
  constructor(code: AgentErrorCode, message: string);
110
190
  }
111
- /** How a run ended. */
191
+ /** How a run ended, or, `paused`, that its code waits on loops still working and is run again once they end. */
112
192
  interface RunEnd {
113
193
  readonly status: RunStatus;
114
194
  readonly output?: unknown;
115
195
  readonly error?: string;
196
+ readonly paused?: true;
116
197
  }
117
198
  /**
118
199
  * Runs one Agent run to its end and returns how it ended. A run that already ended is not run
@@ -125,4 +206,4 @@ declare function httpWire(url: string, token: string, fetcher?: typeof fetch): R
125
206
  /** Runs the run the environment names, as the platform's host does: `MIDSUMMER_AGENT_WIRE` and `MIDSUMMER_AGENT_TOKEN`; the rest is the run's `env`. */
126
207
  declare function executeFromEnvironment(agent: Agent, env: Readonly<Record<string, string | undefined>>): Promise<RunEnd>;
127
208
  //#endregion
128
- export { Agent, AgentCall, AgentContext, AgentError, AgentErrorCode, RunEnd, RunStart, RunStatus, RunWire, execute, executeFromEnvironment, httpWire };
209
+ export { Agent, AgentCall, AgentContext, AgentError, AgentErrorCode, Answer, JsonSchema, Loop, Message, Picture, Question, RunEnd, RunStart, RunStatus, RunWire, Tool, ToolCall, execute, executeFromEnvironment, httpWire };
package/agents/index.mjs CHANGED
@@ -14,6 +14,11 @@ import { AsyncLocalStorage } from "node:async_hooks";
14
14
  * },
15
15
  * } satisfies Agent
16
16
  *
17
+ * `agent.loop({ goal })` lets the model drive: Midsummer's engine works on the goal, step by step, as the agent's team
18
+ * agent, and the call returns its answer (or, with `output`, that answer as JSON fitting the schema). While a loop
19
+ * works, the run waits without holding anything open, and it goes on from there once the loop ends; loops started
20
+ * together (`Promise.all`) all start at once.
21
+ *
17
22
  * `execute(agent, wire)` runs one Agent run: it begins the run, calls `run` with its input, and
18
23
  * finishes it with what `run` returns, or fails it with what `run` throws. Every await on `agent`
19
24
  * is a call the wire keeps, numbered in the order the code makes them, before it gets a reply. A
@@ -38,6 +43,8 @@ var AgentError = class extends Error {
38
43
  this.name = "AgentError";
39
44
  }
40
45
  };
46
+ /** What a loop's answer is fitted to its schema with: its own words, nothing added. */
47
+ const SHAPED = "Put this answer to the goal into the JSON the schema asks for. Use only what the answer says: leave out what it doesn't give rather than guessing, and keep its links.";
41
48
  function base64(content) {
42
49
  const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
43
50
  let text = "";
@@ -65,6 +72,22 @@ async function execute(agent, wire, env = {}) {
65
72
  const scope = scopes.getStore() ?? root;
66
73
  return `${scope.prefix}${scope.next++}`;
67
74
  };
75
+ let going = 0, waiting = 0;
76
+ let pause = () => {};
77
+ const paused = new Promise((resolve) => {
78
+ pause = () => resolve("paused");
79
+ });
80
+ const idle = () => queueMicrotask(() => {
81
+ if (going === 0 && waiting > 0) pause();
82
+ });
83
+ const tracked = (work) => {
84
+ going++;
85
+ return work.finally(() => {
86
+ going--;
87
+ idle();
88
+ });
89
+ };
90
+ const call = (id, asked) => tracked(wire.call(id, asked));
68
91
  const once = async (kind, name, input, work) => {
69
92
  const id = nextId();
70
93
  const asked = {
@@ -72,18 +95,54 @@ async function execute(agent, wire, env = {}) {
72
95
  name,
73
96
  ...input === void 0 ? {} : { input }
74
97
  };
75
- const kept = await wire.call(id, asked);
98
+ const kept = await call(id, asked);
76
99
  if (kept.done) return kept.value;
77
- const value = await scopes.run({
100
+ const value = await tracked(Promise.resolve(scopes.run({
78
101
  prefix: `${id}.`,
79
102
  next: 0
80
- }, work);
81
- return (await wire.call(id, {
103
+ }, work)));
104
+ return (await call(id, {
82
105
  ...asked,
83
106
  done: true,
84
107
  value: value === void 0 ? null : value
85
108
  })).value;
86
109
  };
110
+ const ask = async (question) => {
111
+ if (typeof question === "string") return call(nextId(), {
112
+ kind: "ask",
113
+ prompt: question
114
+ });
115
+ const answered = await call(nextId(), {
116
+ kind: "ask",
117
+ ...question
118
+ });
119
+ return typeof answered === "string" ? {
120
+ text: answered,
121
+ toolCalls: []
122
+ } : answered;
123
+ };
124
+ /** A loop's answer once it has one; until then, a promise that never settles, which pauses the run. */
125
+ const loop = async ({ output, ...given }) => {
126
+ const kept = await call(nextId(), {
127
+ kind: "loop",
128
+ ...given,
129
+ ...output === void 0 ? {} : { output }
130
+ });
131
+ if (!kept.done) {
132
+ waiting++;
133
+ idle();
134
+ return new Promise(() => {});
135
+ }
136
+ if (kept.error !== void 0) throw new AgentError("failed", kept.error);
137
+ if (output === void 0) return kept.value;
138
+ const shaped = await ask({
139
+ prompt: `${SHAPED}\n\nThe goal:\n${given.goal}\n\nThe answer:\n${kept.value ?? ""}`,
140
+ output,
141
+ ...given.model === void 0 ? {} : { model: given.model }
142
+ });
143
+ if (shaped.output === void 0) throw new AgentError("failed", `The loop's answer couldn't be put into its schema: ${shaped.unfit ?? "the model gave none."}`);
144
+ return shaped.output;
145
+ };
87
146
  const context = {
88
147
  runId: start.runId,
89
148
  agent: start.agent,
@@ -93,7 +152,7 @@ async function execute(agent, wire, env = {}) {
93
152
  tools: start.tools,
94
153
  env,
95
154
  log: async (message, data) => {
96
- await wire.call(nextId(), {
155
+ await call(nextId(), {
97
156
  kind: "log",
98
157
  message: String(message),
99
158
  ...data === void 0 ? {} : { data }
@@ -106,40 +165,43 @@ async function execute(agent, wire, env = {}) {
106
165
  return tool(input, context);
107
166
  }),
108
167
  memory: {
109
- get: (key) => wire.call(nextId(), {
168
+ get: (key) => call(nextId(), {
110
169
  kind: "memory.get",
111
170
  key
112
171
  }),
113
172
  set: async (key, value) => {
114
- await wire.call(nextId(), {
173
+ await call(nextId(), {
115
174
  kind: "memory.set",
116
175
  key,
117
176
  value
118
177
  });
119
178
  },
120
179
  delete: async (key) => {
121
- await wire.call(nextId(), {
180
+ await call(nextId(), {
122
181
  kind: "memory.delete",
123
182
  key
124
183
  });
125
184
  }
126
185
  },
127
186
  artifact: async (name, content, type = "text/plain") => {
128
- await wire.call(nextId(), {
187
+ await call(nextId(), {
129
188
  kind: "artifact",
130
189
  name,
131
190
  type,
132
191
  data: base64(content)
133
192
  });
134
193
  },
135
- ask: async (prompt) => await wire.call(nextId(), {
136
- kind: "ask",
137
- prompt
138
- })
194
+ ask,
195
+ loop
139
196
  };
140
197
  let output;
141
198
  try {
142
- output = await agent.run(start.input, context);
199
+ const ran = await Promise.race([Promise.resolve().then(() => agent.run(start.input, context)).then((value) => ({ value })), paused]);
200
+ if (ran === "paused") return {
201
+ status: "running",
202
+ paused: true
203
+ };
204
+ output = ran.value;
143
205
  } catch (error) {
144
206
  if (error instanceof AgentError && error.code === "ended") return {
145
207
  status: "cancelled",
@@ -1,4 +1,4 @@
1
- import { Agent, RunEnd, RunStatus, RunWire } from "./index.mjs";
1
+ import { Agent, Answer, Loop, Question, RunEnd, RunStatus, RunWire } from "./index.mjs";
2
2
  //#region src/agents/stand-in.d.ts
3
3
  interface StandInEvent {
4
4
  readonly sequence: number;
@@ -29,7 +29,8 @@ interface AgentStandIn {
29
29
  declare function agentStandIn(options?: {
30
30
  readonly tools?: ReadonlyArray<string>;
31
31
  readonly instructions?: string;
32
- readonly ask?: (prompt: string) => Promise<string> | string;
32
+ readonly ask?: (prompt: string, question: Question) => Promise<string | Answer> | string | Answer;
33
+ readonly loop?: (loop: Loop) => Promise<string> | string;
33
34
  }): AgentStandIn;
34
35
  //#endregion
35
36
  export { AgentStandIn, StandInEvent, agentStandIn };
@@ -10,7 +10,8 @@ import { AgentError, execute } from "./index.mjs";
10
10
  * const local = agentStandIn({ tools: ["greet"] })
11
11
  * const { end, events } = await local.run(agent, { name: "Ada" })
12
12
  *
13
- * Model questions are replied to by `ask` when given, else refused as not set up; spend is not kept.
13
+ * Model questions are replied to by `ask` when given, else refused as not set up; spend is not kept. A loop returns at
14
+ * once with the words `loop` gives, else is refused the same way.
14
15
  */
15
16
  const clone = (value) => value === void 0 ? value : JSON.parse(JSON.stringify(value));
16
17
  function agentStandIn(options = {}) {
@@ -110,9 +111,23 @@ function agentStandIn(options = {}) {
110
111
  size: data.length
111
112
  });
112
113
  }
113
- case "ask":
114
+ case "ask": {
114
115
  if (!options.ask) throw new AgentError("invalid", "Model questions are not set up in this Stand-in: give it `ask`.");
115
- return keep("model", await options.ask(call.prompt), { prompt: call.prompt });
116
+ const { kind: _kind, ...question } = call;
117
+ const said = await options.ask(call.prompt ?? "", question);
118
+ return keep("model", call.messages === void 0 && call.tools === void 0 && call.output === void 0 && call.images === void 0 && call.model === void 0 && call.effort === void 0 ? typeof said === "string" ? said : said.text : typeof said === "string" ? {
119
+ text: said,
120
+ toolCalls: []
121
+ } : said, { prompt: call.prompt ?? "" });
122
+ }
123
+ case "loop": {
124
+ if (!options.loop) throw new AgentError("invalid", "Loops are not set up in this Stand-in: give it `loop`.");
125
+ const { kind: _kind, ...loop } = call;
126
+ return keep("step", {
127
+ done: true,
128
+ value: await options.loop(loop)
129
+ }, { goal: call.goal });
130
+ }
116
131
  }
117
132
  },
118
133
  async finish(end) {
package/here-C2jhTheQ.mjs CHANGED
@@ -12,7 +12,7 @@ function processEnv() {
12
12
  * This package's version: `0.0.0-dev` here, and in a published package the version it was published at, which the
13
13
  * release writes in its place as it stages the package (`stampSdk` in `scripts/release/packages.ts`).
14
14
  */
15
- const SDK_VERSION = "0.1.0-staging.5330";
15
+ const SDK_VERSION = "0.1.0-staging.5333";
16
16
  /**
17
17
  * The header that tells Midsummer which client made each of this package's calls: `Midsummer-Client: sdk/<version>
18
18
  * <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.5330",
3
+ "version": "0.1.0-staging.5333",
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.",