@midsummer-ai/sdk 0.1.0-next.901 → 0.1.0-staging.1794311347

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 (123) hide show
  1. package/README.md +1 -1
  2. package/ai/contract.mjs +39 -0
  3. package/ai/index.d.mts +70 -12
  4. package/ai/index.mjs +74 -5
  5. package/ai/stand-in.mjs +26 -4
  6. package/apps.d.mts +63 -0
  7. package/apps.mjs +101 -0
  8. package/auth/client.d.mts +23 -0
  9. package/auth/client.mjs +45 -0
  10. package/auth/contract.d.mts +24 -0
  11. package/auth/contract.mjs +498 -0
  12. package/auth/files.d.mts +28 -0
  13. package/auth/files.mjs +231 -0
  14. package/auth/index.d.mts +199 -0
  15. package/auth/index.mjs +3 -0
  16. package/auth/key.d.mts +19 -0
  17. package/auth/key.mjs +28 -0
  18. package/auth/mail.d.mts +31 -0
  19. package/auth/mail.mjs +138 -0
  20. package/auth/password.d.mts +2 -0
  21. package/auth/password.mjs +2 -0
  22. package/auth/stand-in.d.mts +15 -0
  23. package/auth/stand-in.mjs +41 -0
  24. package/auth-1W-SzpD3.mjs +441 -0
  25. package/auth-B7rCtXFQ.d.mts +36 -0
  26. package/auth-Bf7IuulG.mjs +754 -0
  27. package/billing/contract.d.mts +29 -0
  28. package/billing/contract.mjs +121 -0
  29. package/billing/index.d.mts +92 -0
  30. package/billing/index.mjs +138 -0
  31. package/billing/stand-in.d.mts +23 -0
  32. package/billing/stand-in.mjs +70 -0
  33. package/build-Y6rsumMB.d.mts +104 -0
  34. package/bytes-C2pcyl9u.mjs +280 -0
  35. package/{connection-CDk7H1FL.mjs → client-BX56cXDt.mjs} +837 -31
  36. package/client-BshDU1b2.d.mts +155 -0
  37. package/client.d.mts +1 -1
  38. package/client.mjs +1 -105
  39. package/contract.d.mts +1 -1
  40. package/contract.mjs +2 -2
  41. package/database/build.d.mts +2 -2
  42. package/database/build.mjs +1694 -117
  43. package/database/client.d.mts +3 -60
  44. package/database/client.mjs +2 -125
  45. package/database/contract.d.mts +92 -2
  46. package/database/contract.mjs +2179 -3
  47. package/database/errors.d.mts +1 -22
  48. package/database/react.d.mts +133 -0
  49. package/database/react.mjs +488 -0
  50. package/database/server.d.mts +2 -3
  51. package/database/server.mjs +3 -320
  52. package/database/stand-in.d.mts +96 -9
  53. package/database/stand-in.mjs +1436 -116
  54. package/email/client.d.mts +5 -4
  55. package/email/client.mjs +1 -130
  56. package/email/contract.d.mts +17 -2
  57. package/email/contract.mjs +170 -4
  58. package/email/inbox.d.mts +2 -0
  59. package/email/inbox.mjs +2 -0
  60. package/email/index.d.mts +2 -74
  61. package/email/index.mjs +2 -59
  62. package/email/smtp.d.mts +1 -1
  63. package/email/smtp.mjs +24 -9
  64. package/email/stand-in.d.mts +25 -2
  65. package/email/stand-in.mjs +106 -8
  66. package/email-ynNo0HqT.mjs +473 -0
  67. package/errors-B1tO_wdm.mjs +28 -0
  68. package/errors-x2vXKi0u.d.mts +25 -0
  69. package/flags.d.mts +38 -0
  70. package/flags.mjs +52 -0
  71. package/flows/contract.d.mts +13 -0
  72. package/flows/contract.mjs +483 -0
  73. package/flows/index.d.mts +148 -0
  74. package/flows/index.mjs +347 -0
  75. package/here-1plIxb0D.mjs +54 -0
  76. package/images.d.mts +30 -0
  77. package/images.mjs +52 -0
  78. package/index-B9zs0wIp.d.mts +415 -0
  79. package/{index-sgdyoA2P.d.mts → index-CXiY5knc.d.mts} +10 -1
  80. package/index-m0wtx22n.d.mts +228 -0
  81. package/index.d.mts +2 -2
  82. package/index.mjs +3 -137
  83. package/key-BrRdFY-n.mjs +11 -0
  84. package/{names-DfCBKupJ.mjs → names-Do0ot5Ha.mjs} +2 -28
  85. package/package.json +254 -3
  86. package/queues/contract.mjs +144 -1
  87. package/queues/index.d.mts +168 -9
  88. package/queues/index.mjs +126 -7
  89. package/queues/stand-in.mjs +333 -31
  90. package/queues/wire.mjs +302 -16
  91. package/s3.d.mts +1 -1
  92. package/s3.mjs +3 -2
  93. package/server-B5HK2Ou9.d.mts +574 -0
  94. package/server-Drjni3-F.mjs +1895 -0
  95. package/socket.d.mts +1 -1
  96. package/socket.mjs +1 -262
  97. package/src-BKKy9km-.mjs +525 -0
  98. package/stand-in.d.mts +1 -1
  99. package/stand-in.mjs +2 -1
  100. package/storage/contract.d.mts +25 -0
  101. package/storage/contract.mjs +153 -0
  102. package/storage/files.d.mts +144 -0
  103. package/storage/files.mjs +513 -0
  104. package/{store-BzI9at5x.mjs → store-B-1coCxW.mjs} +1 -1
  105. package/store-gCz6XVaG.d.mts +15 -0
  106. package/{tabs-D-P8_ci_.mjs → tabs-CDplCS02.mjs} +1 -1
  107. package/vector/contract.d.mts +1 -1
  108. package/vector/contract.mjs +773 -1
  109. package/vector/index.d.mts +2 -2
  110. package/vector/index.mjs +87 -8
  111. package/vector/stand-in.d.mts +1 -1
  112. package/vector/stand-in.mjs +326 -23
  113. package/vector/wire.d.mts +11 -2
  114. package/vector/wire.mjs +2 -175
  115. package/wire-BdNDzlIN.mjs +554 -0
  116. package/wire.d.mts +1 -1
  117. package/wire.mjs +2 -1
  118. package/build-SQ44jwSa.d.mts +0 -41
  119. package/index-DdoK0y7D.d.mts +0 -192
  120. package/schema-BF-Y1EVu.mjs +0 -142
  121. package/schema-DS8x1Dn8.mjs +0 -115
  122. package/schema-f7E9uzUn.d.mts +0 -74
  123. package/server-C7O7CICU.d.mts +0 -182
package/README.md CHANGED
@@ -2,4 +2,4 @@
2
2
 
3
3
  The handles a Midsummer app's code uses for its Database, Storage, Queues, Vector DB, AI, Email and Agents, each with a stand-in for tests.
4
4
 
5
- Docs: https://docs.midsummer.new
5
+ Docs: https://docs.staging.midsummer.new
package/ai/contract.mjs CHANGED
@@ -38,6 +38,45 @@ const aiContract = [
38
38
  check((await stream.done).outputTokens > 0, "done counts the answer's tokens");
39
39
  }
40
40
  },
41
+ {
42
+ name: "a call made to use a tool gets the tool's call back whole, its arguments as JSON text, and answers once given its result",
43
+ async run(ai) {
44
+ const tools = [{
45
+ name: "lookup",
46
+ description: "Looks a word up.",
47
+ parameters: {
48
+ type: "object",
49
+ properties: { word: { type: "string" } }
50
+ }
51
+ }];
52
+ const [made] = (await ai.complete({
53
+ prompt: "Look up 'river'.",
54
+ tools,
55
+ toolChoice: { name: "lookup" }
56
+ })).toolCalls ?? [];
57
+ check(made !== void 0 && made.name === "lookup" && made.id.length > 0, "the tool's call comes back with an id and the tool's name");
58
+ check(typeof JSON.parse(made.arguments) === "object", "its arguments are JSON text");
59
+ check((await ai.complete({
60
+ messages: [
61
+ {
62
+ role: "user",
63
+ content: "Look up 'river'."
64
+ },
65
+ {
66
+ role: "assistant",
67
+ content: "",
68
+ toolCalls: [made]
69
+ },
70
+ {
71
+ role: "tool",
72
+ toolCallId: made.id,
73
+ content: "A large natural stream of water."
74
+ }
75
+ ],
76
+ tools
77
+ })).text.length > 0, "the Model answers once it has the tool's result");
78
+ }
79
+ },
41
80
  {
42
81
  name: "a Model that is not offered is refused as invalid",
43
82
  async run(ai) {
package/ai/index.d.mts CHANGED
@@ -1,16 +1,22 @@
1
1
  //#region src/ai/index.d.ts
2
2
  /**
3
- * AI: Model calls from a Project's code, through one AI key, streamed or whole, each with the tokens
4
- * and credits it spent.
3
+ * AI: Model calls from a Project's code, streamed or whole, each with the tokens and credits it spent.
4
+ * In a deployment, in any framework, `ai()` calls the team's AI Gateway with no key:
5
5
  *
6
- * const models = ai(aiClient("https://api.midsummer.new", { key: process.env.MIDSUMMER_AI_KEY! }))
6
+ * import { ai } from "@midsummer-ai/sdk/ai"
7
+ *
8
+ * const models = ai()
7
9
  * const answer = await models.complete({ prompt: "Name three rivers" })
8
10
  * const stream = models.stream({ model: "claude-sonnet-5-5", messages: [{ role: "user", content: "Hi" }] })
9
11
  * for await (const text of stream) write(text)
10
12
  * const { credits } = await stream.done
11
13
  *
12
- * The engine is where calls go: the Stand-in (`@midsummer-ai/sdk/ai/stand-in`) for `midsummer dev`,
13
- * or the platform (`aiClient`). Every engine is held to the cases in `@midsummer-ai/sdk/ai/contract`.
14
+ * A call can pass tools (its calls come back as `toolCalls`), ask for JSON to a schema
15
+ * (`responseFormat`), send images in a user message, set a reasoning effort, and name `fallback`
16
+ * Models asked in turn when one can't answer; `model` in what it spent is the one that replied.
17
+ *
18
+ * Given an engine, calls go there instead: the Stand-in (`@midsummer-ai/sdk/ai/stand-in`) in tests, or,
19
+ * from code outside Midsummer, the platform with an AI key (`ai(aiClient(origin, { key }))`). Every engine is held to the cases in `@midsummer-ai/sdk/ai/contract`.
14
20
  * A Model is named as `midsummer ai model list` lists it; leaving it out picks the default.
15
21
  *
16
22
  * Every failure is an `AiError`; its `code` tells you which kind: `invalid` (no such Model, nothing
@@ -22,9 +28,32 @@ declare class AiError extends Error {
22
28
  readonly code: AiErrorCode;
23
29
  constructor(code: AiErrorCode, why: string);
24
30
  }
31
+ /** A piece of a user message: text, or an image by its `https:` or `data:` address. */
32
+ type Part = {
33
+ readonly type: "text";
34
+ readonly text: string;
35
+ } | {
36
+ readonly type: "image";
37
+ readonly url: string;
38
+ };
39
+ /** A tool the Model called: the id its result refers to, the tool's name and its arguments as JSON text. */
40
+ interface ToolCall {
41
+ readonly id: string;
42
+ readonly name: string;
43
+ readonly arguments: string;
44
+ }
45
+ /** One message: an assistant's may carry the tool calls it made, and a `tool` message is the result of the call `toolCallId` refers to. */
25
46
  interface Message {
26
- readonly role: "system" | "user" | "assistant";
27
- readonly content: string;
47
+ readonly role: "system" | "user" | "assistant" | "tool";
48
+ readonly content: string | ReadonlyArray<Part>;
49
+ readonly toolCalls?: ReadonlyArray<ToolCall>;
50
+ readonly toolCallId?: string;
51
+ }
52
+ /** A tool the Model may call: its name, what it does and its arguments as a JSON schema. */
53
+ interface Tool {
54
+ readonly name: string;
55
+ readonly description?: string;
56
+ readonly parameters?: Readonly<Record<string, unknown>>;
28
57
  }
29
58
  /** What to ask: a `prompt` (after an optional `system` prompt) or a conversation of `messages`. */
30
59
  interface Ask {
@@ -36,6 +65,20 @@ interface Ask {
36
65
  readonly maxTokens?: number;
37
66
  /** 0 to 2. */
38
67
  readonly temperature?: number;
68
+ readonly tools?: ReadonlyArray<Tool>;
69
+ /** Whether the Model may call tools (`auto`), must not (`none`), must call one (`required`) or the one named. */
70
+ readonly toolChoice?: "auto" | "none" | "required" | {
71
+ readonly name: string;
72
+ };
73
+ /** An answer as JSON: to `schema` when given, else any JSON object. */
74
+ readonly responseFormat?: {
75
+ readonly type: "json";
76
+ readonly schema?: Readonly<Record<string, unknown>>;
77
+ readonly name?: string;
78
+ };
79
+ readonly reasoningEffort?: "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
80
+ /** Up to three Models asked in turn when the one before can't answer. */
81
+ readonly fallback?: ReadonlyArray<string>;
39
82
  /**
40
83
  * Names this call for a day. A retry with it after a lost answer gets the first call's answer and
41
84
  * is not charged again; while the first still runs, it fails as `conflict`.
@@ -44,15 +87,27 @@ interface Ask {
44
87
  }
45
88
  /** What a call spent: its tokens, and their price in credits under the catalogue version `catalogue`. */
46
89
  interface Spent {
90
+ /** The Model that replied: the one asked, or a fallback. */
47
91
  readonly model: string;
48
92
  readonly inputTokens: number;
93
+ /** Of `inputTokens`, those read from the provider's cache, priced as it prices them. */
94
+ readonly cachedTokens?: number;
49
95
  readonly outputTokens: number;
50
96
  readonly credits: number;
51
97
  readonly catalogue: string;
52
98
  }
53
- /** A piece of the answer, or, last, what the call spent. */
99
+ /** A piece of a tool call: `index` tells calls apart, `id` and `name` come with its first piece, `arguments` add up. */
100
+ interface ToolCallPiece {
101
+ readonly index: number;
102
+ readonly id?: string;
103
+ readonly name?: string;
104
+ readonly arguments: string;
105
+ }
106
+ /** A piece of the answer or of a tool call, or, last, what the call spent. */
54
107
  type AiEvent = {
55
108
  readonly text: string;
109
+ } | {
110
+ readonly toolCall: ToolCallPiece;
56
111
  } | {
57
112
  readonly done: Spent;
58
113
  };
@@ -62,16 +117,19 @@ interface AiEngine {
62
117
  }
63
118
  interface Answer extends Spent {
64
119
  readonly text: string;
120
+ readonly toolCalls?: ReadonlyArray<ToolCall>;
65
121
  }
66
- /** An answer's text as it arrives; `done` settles with what it spent once it has all arrived. */
122
+ /** An answer's text as it arrives; `done` settles with what it spent, and the tools it called, once it has all arrived. */
67
123
  interface AnswerStream extends AsyncIterable<string> {
68
- readonly done: Promise<Spent>;
124
+ readonly done: Promise<Spent & {
125
+ readonly toolCalls?: ReadonlyArray<ToolCall>;
126
+ }>;
69
127
  }
70
128
  interface Ai {
71
129
  complete(input: Ask): Promise<Answer>;
72
130
  stream(input: Ask): AnswerStream;
73
131
  }
74
- declare function ai(engine: AiEngine): Ai;
132
+ declare function ai(given?: AiEngine): Ai;
75
133
  type Fetch = (url: string, init: RequestInit) => Promise<Response>;
76
134
  /**
77
135
  * The platform's AI Gateway at `origin` (the API's), for the AI key `key`: each call is one POST to
@@ -91,4 +149,4 @@ declare function boundAi(handle: {
91
149
  ask(input: Ask): Promise<ReadableStream<Uint8Array>>;
92
150
  }): AiEngine;
93
151
  //#endregion
94
- export { Ai, AiEngine, AiError, AiErrorCode, AiEvent, Answer, AnswerStream, Ask, Message, Spent, ai, aiClient, boundAi };
152
+ export { Ai, AiEngine, AiError, AiErrorCode, AiEvent, Answer, AnswerStream, Ask, Message, Part, Spent, Tool, ToolCall, ToolCallPiece, ai, aiClient, boundAi };
package/ai/index.mjs CHANGED
@@ -1,4 +1,29 @@
1
+ import { n as late, t as here } from "../here-1plIxb0D.mjs";
1
2
  //#region src/ai/index.ts
3
+ /**
4
+ * AI: Model calls from a Project's code, streamed or whole, each with the tokens and credits it spent.
5
+ * In a deployment, in any framework, `ai()` calls the team's AI Gateway with no key:
6
+ *
7
+ * import { ai } from "@midsummer-ai/sdk/ai"
8
+ *
9
+ * const models = ai()
10
+ * const answer = await models.complete({ prompt: "Name three rivers" })
11
+ * const stream = models.stream({ model: "claude-sonnet-5-5", messages: [{ role: "user", content: "Hi" }] })
12
+ * for await (const text of stream) write(text)
13
+ * const { credits } = await stream.done
14
+ *
15
+ * A call can pass tools (its calls come back as `toolCalls`), ask for JSON to a schema
16
+ * (`responseFormat`), send images in a user message, set a reasoning effort, and name `fallback`
17
+ * Models asked in turn when one can't answer; `model` in what it spent is the one that replied.
18
+ *
19
+ * Given an engine, calls go there instead: the Stand-in (`@midsummer-ai/sdk/ai/stand-in`) in tests, or,
20
+ * from code outside Midsummer, the platform with an AI key (`ai(aiClient(origin, { key }))`). Every engine is held to the cases in `@midsummer-ai/sdk/ai/contract`.
21
+ * A Model is named as `midsummer ai model list` lists it; leaving it out picks the default.
22
+ *
23
+ * Every failure is an `AiError`; its `code` tells you which kind: `invalid` (no such Model, nothing
24
+ * asked), `forbidden` (the key is not valid), `quota` (the Team's usage is holding back its calls),
25
+ * `conflict` (a retry by `idempotencyKey` of a call still under way) or `unavailable` (try again).
26
+ */
2
27
  var AiError = class extends Error {
3
28
  code;
4
29
  constructor(code, why) {
@@ -7,22 +32,50 @@ var AiError = class extends Error {
7
32
  this.name = "AiError";
8
33
  }
9
34
  };
35
+ /** Tool call pieces, added up into whole calls in order. */
36
+ function toolCalls() {
37
+ const calls = /* @__PURE__ */ new Map();
38
+ return {
39
+ add({ index, id, name, arguments: more }) {
40
+ const made = calls.get(index) ?? {
41
+ id: "",
42
+ name: "",
43
+ arguments: ""
44
+ };
45
+ calls.set(index, {
46
+ id: id ?? made.id,
47
+ name: name ?? made.name,
48
+ arguments: made.arguments + more
49
+ });
50
+ },
51
+ whole: () => calls.size ? { toolCalls: [...calls.entries()].sort(([a], [b]) => a - b).map(([, made]) => made) } : {}
52
+ };
53
+ }
10
54
  /** Checks a question before it leaves the caller. */
11
55
  function checked(input) {
12
56
  if (Boolean(input.prompt) === Boolean(input.messages)) throw new AiError("invalid", "Give a prompt or messages.");
13
57
  if (input.messages && !input.messages.length) throw new AiError("invalid", "Give at least one message.");
14
58
  if (input.maxTokens !== void 0 && !(Number.isInteger(input.maxTokens) && input.maxTokens >= 1 && input.maxTokens <= 32e3)) throw new AiError("invalid", "maxTokens is a whole number from 1 to 32,000.");
15
59
  if (input.temperature !== void 0 && !(input.temperature >= 0 && input.temperature <= 2)) throw new AiError("invalid", "temperature is from 0 to 2.");
60
+ if ((input.fallback?.length ?? 0) > 3) throw new AiError("invalid", "Name at most 3 fallback models.");
16
61
  return input;
17
62
  }
18
- function ai(engine) {
63
+ function ai(given) {
64
+ const engine = given ?? late(() => {
65
+ const handle = here()?.ai;
66
+ if (handle) return boundAi(handle);
67
+ throw new AiError("forbidden", "This code runs outside a deployment, so it calls models with an AI key: ai(aiClient(origin, { key })).");
68
+ });
19
69
  return {
20
70
  async complete(input) {
21
71
  let text = "";
72
+ const calls = toolCalls();
22
73
  for await (const event of engine.ask(checked(input))) if ("text" in event) text += event.text;
74
+ else if ("toolCall" in event) calls.add(event.toolCall);
23
75
  else return {
24
76
  ...event.done,
25
- text
77
+ text,
78
+ ...calls.whole()
26
79
  };
27
80
  throw new AiError("unavailable", "The answer ended early. Try again.");
28
81
  },
@@ -45,8 +98,13 @@ function ai(engine) {
45
98
  }
46
99
  async function* texts() {
47
100
  try {
101
+ const calls = toolCalls();
48
102
  for await (const event of engine.ask(asked)) if ("text" in event) yield event.text;
49
- else return settle(event.done);
103
+ else if ("toolCall" in event) calls.add(event.toolCall);
104
+ else return settle({
105
+ ...event.done,
106
+ ...calls.whole()
107
+ });
50
108
  throw new AiError("unavailable", "The answer ended early. Try again.");
51
109
  } catch (error) {
52
110
  fail(error);
@@ -75,12 +133,23 @@ function parsed(line) {
75
133
  const count = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
76
134
  if (!object(event)) throw broken();
77
135
  if (typeof event.text === "string") return { text: event.text };
136
+ const call = event.toolCall;
137
+ if (object(call)) {
138
+ if (!count(call.index) || typeof call.arguments !== "string" || call.id !== void 0 && typeof call.id !== "string" || call.name !== void 0 && typeof call.name !== "string") throw broken();
139
+ return { toolCall: {
140
+ index: call.index,
141
+ ...typeof call.id === "string" ? { id: call.id } : {},
142
+ ...typeof call.name === "string" ? { name: call.name } : {},
143
+ arguments: call.arguments
144
+ } };
145
+ }
78
146
  const done = event.done;
79
147
  if (object(done)) {
80
- if (typeof done.model !== "string" || !count(done.inputTokens) || !count(done.outputTokens) || typeof done.credits !== "number" || !(done.credits >= 0) || typeof done.catalogue !== "string") throw broken();
148
+ if (typeof done.model !== "string" || !count(done.inputTokens) || !count(done.outputTokens) || typeof done.credits !== "number" || !(done.credits >= 0) || typeof done.catalogue !== "string" || done.cachedTokens !== void 0 && !count(done.cachedTokens)) throw broken();
81
149
  return { done: {
82
150
  model: done.model,
83
151
  inputTokens: done.inputTokens,
152
+ ...done.cachedTokens ? { cachedTokens: done.cachedTokens } : {},
84
153
  outputTokens: done.outputTokens,
85
154
  credits: done.credits,
86
155
  catalogue: done.catalogue
@@ -133,7 +202,7 @@ function aiClient(origin, options) {
133
202
  }
134
203
  if (!response.ok || !response.body) {
135
204
  const why = await response.json().then((body) => typeof body.error === "string" ? body.error : void 0, () => void 0);
136
- throw new AiError(CODES[response.status] ?? "unavailable", why ?? `The AI Gateway answered ${response.status}.`);
205
+ throw new AiError(CODES[response.status] ?? "unavailable", why ?? `The AI Gateway returned ${response.status}.`);
137
206
  }
138
207
  try {
139
208
  yield* eventsOf(response.body);
package/ai/stand-in.mjs CHANGED
@@ -9,8 +9,11 @@ import { AiError } from "./index.mjs";
9
9
  * await models.complete({ prompt: "Hi" }) // { text: "You asked: Hi", model: "stand-in", credits: 0, … }
10
10
  *
11
11
  * It offers the Models it is given (`stand-in` unless told), the first the default. Tokens are
12
- * counted at about four characters a token, and cost nothing.
12
+ * counted at about four characters a token, and cost nothing. Made to call a tool (`toolChoice`
13
+ * `required` or a name), it calls it with no arguments; a fallback is never needed.
13
14
  */
15
+ /** A message's text, without its images. */
16
+ const textOf = (content) => typeof content === "string" ? content : content.map((part) => part.type === "text" ? part.text : "").join("");
14
17
  function aiStandIn(options = {}) {
15
18
  const models = options.models?.length ? options.models : ["stand-in"];
16
19
  const tokens = (text) => Math.ceil(text.length / 4);
@@ -25,12 +28,31 @@ function aiStandIn(options = {}) {
25
28
  content: input.prompt ?? ""
26
29
  }]];
27
30
  const last = messages.filter((message) => message.role !== "system").at(-1);
28
- if (last?.role !== "user" || !last.content.trim()) throw new AiError("invalid", "End with a user message that asks something.");
29
- const answer = `You asked: ${last.content}`.slice(0, (input.maxTokens ?? 1024) * 4);
31
+ if (!(last?.role === "tool" || last?.role === "user" && textOf(last.content).trim())) throw new AiError("invalid", "End with a user message that asks something, or with the results of the tools the model called.");
32
+ const inputTokens = tokens(messages.map((message) => textOf(message.content)).join(""));
33
+ const tool = typeof input.toolChoice === "object" ? input.toolChoice.name : input.toolChoice === "required" ? input.tools?.[0]?.name : void 0;
34
+ if (tool && last.role === "user") {
35
+ if (!input.tools?.some((given) => given.name === tool)) throw new AiError("invalid", `toolChoice names ${tool}, which isn't one of the tools given.`);
36
+ yield { toolCall: {
37
+ index: 0,
38
+ id: "call_stand_in_1",
39
+ name: tool,
40
+ arguments: "{}"
41
+ } };
42
+ yield { done: {
43
+ model,
44
+ inputTokens,
45
+ outputTokens: 1,
46
+ credits: 0,
47
+ catalogue: "stand-in"
48
+ } };
49
+ return;
50
+ }
51
+ const answer = `You asked: ${textOf(last.content)}`.slice(0, (input.maxTokens ?? 1024) * 4);
30
52
  for (const piece of answer.match(/\S+\s*/g) ?? []) yield { text: piece };
31
53
  yield { done: {
32
54
  model,
33
- inputTokens: tokens(messages.map((message) => message.content).join("")),
55
+ inputTokens,
34
56
  outputTokens: tokens(answer),
35
57
  credits: 0,
36
58
  catalogue: "stand-in"
package/apps.d.mts ADDED
@@ -0,0 +1,63 @@
1
+ //#region src/apps.d.ts
2
+ /**
3
+ * For an app teams install on Midsummer: check that an event or a runner job Midsummer posted is
4
+ * genuine, and act in an installation with a token that is renewed before it ends.
5
+ *
6
+ * import { InstalledApp, verifyEvent } from "@midsummer-ai/sdk/apps"
7
+ *
8
+ * // In your events handler, with the body exactly as it arrived:
9
+ * if (!(await verifyEvent(request.headers, body, process.env.MIDSUMMER_SIGNING_SECRET!))) return new Response(null, { status: 401 })
10
+ * const event = JSON.parse(body) as AppEvent
11
+ *
12
+ * const app = new InstalledApp({ id: "oapp_…", secret: process.env.MIDSUMMER_APP_SECRET! })
13
+ * await app.request(event.data.installation.id, "/v1/mr/acme/web/mr-12/checks/style", { method: "PUT", body: JSON.stringify({ candidateId, state: "running" }) })
14
+ *
15
+ * Events are signed as Standard Webhooks says, so any of its libraries checks them too.
16
+ */
17
+ /** What Midsummer posts to an app: its `type`, when, and `data` with the installation it is for. */
18
+ interface AppEvent<Data extends Record<string, unknown> = Record<string, unknown>> {
19
+ readonly type: string;
20
+ readonly timestamp: string;
21
+ readonly data: Data & {
22
+ readonly installation: {
23
+ readonly id: string;
24
+ readonly team: string;
25
+ };
26
+ };
27
+ }
28
+ /**
29
+ * Whether a request Midsummer posted is genuine: signed with `secret` (`whsec_…`, shown when the
30
+ * app was registered) over its `webhook-id`, its `webhook-timestamp` and the body exactly as it
31
+ * arrived, and no older than five minutes. A rotated secret signs beside the one before for a day,
32
+ * so a request carries a signature from each, and either one passing is enough.
33
+ */
34
+ declare function verifyEvent(headers: Headers | Readonly<Record<string, string | undefined>>, body: string, secret: string, now?: number): Promise<boolean>;
35
+ /**
36
+ * An app acting in the teams that installed it. Each installation's token is asked for with the
37
+ * app's id and secret, kept until a minute before it ends, and asked for again after; a team that
38
+ * removes the app ends its tokens at once, and its calls answer 401.
39
+ */
40
+ declare class InstalledApp {
41
+ #private;
42
+ constructor(options: {
43
+ readonly id: string;
44
+ readonly secret: string;
45
+ readonly origin?: string;
46
+ readonly fetch?: typeof fetch;
47
+ });
48
+ /** An installation's token (`msinst_…`), from the one kept while it has over a minute left. Throws when Midsummer refuses the app's secret or the installation. */
49
+ token(installationId: string, now?: number): Promise<string>;
50
+ /** A call to Midsummer's API as the app in one installation, such as `/v1/mr/acme/web/mr-12/comments`; JSON unless the body says otherwise. */
51
+ request(installationId: string, path: string, init?: RequestInit): Promise<Response>;
52
+ /** Trades the one-time code a manifest's app was made with for its id, secret and signing secret, shown this once. */
53
+ static fromManifestCode(code: string, options?: {
54
+ readonly origin?: string;
55
+ readonly fetch?: typeof fetch;
56
+ }): Promise<{
57
+ readonly id: string;
58
+ readonly secret: string;
59
+ readonly signingSecret?: string;
60
+ }>;
61
+ }
62
+ //#endregion
63
+ export { AppEvent, InstalledApp, verifyEvent };
package/apps.mjs ADDED
@@ -0,0 +1,101 @@
1
+ //#region src/apps.ts
2
+ /** How old a signed event may be, and how far ahead of the clock: five minutes, as Standard Webhooks says. */
3
+ const TOLERANCE_SECONDS = 300;
4
+ /**
5
+ * Whether a request Midsummer posted is genuine: signed with `secret` (`whsec_…`, shown when the
6
+ * app was registered) over its `webhook-id`, its `webhook-timestamp` and the body exactly as it
7
+ * arrived, and no older than five minutes. A rotated secret signs beside the one before for a day,
8
+ * so a request carries a signature from each, and either one passing is enough.
9
+ */
10
+ async function verifyEvent(headers, body, secret, now = Date.now()) {
11
+ const read = (name) => (headers instanceof Headers ? headers.get(name) : headers[name]) ?? void 0;
12
+ const id = read("webhook-id"), timestamp = read("webhook-timestamp"), signatures = read("webhook-signature");
13
+ if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) return false;
14
+ if (Math.abs(now / 1e3 - Number(timestamp)) > TOLERANCE_SECONDS) return false;
15
+ const key = await crypto.subtle.importKey("raw", fromBase64(secret.replace(/^whsec_/, "")), {
16
+ name: "HMAC",
17
+ hash: "SHA-256"
18
+ }, false, ["sign"]);
19
+ const expected = toBase64(new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${id}.${timestamp}.${body}`))));
20
+ return signatures.split(" ").some((entry) => {
21
+ const [version, signature] = entry.split(",");
22
+ return version === "v1" && signature !== void 0 && same(signature, expected);
23
+ });
24
+ }
25
+ /**
26
+ * An app acting in the teams that installed it. Each installation's token is asked for with the
27
+ * app's id and secret, kept until a minute before it ends, and asked for again after; a team that
28
+ * removes the app ends its tokens at once, and its calls answer 401.
29
+ */
30
+ var InstalledApp = class {
31
+ #id;
32
+ #secret;
33
+ #origin;
34
+ #fetch;
35
+ #tokens = /* @__PURE__ */ new Map();
36
+ constructor(options) {
37
+ this.#id = options.id;
38
+ this.#secret = options.secret;
39
+ this.#origin = (options.origin ?? "https://api.midsummer.new").replace(/\/+$/, "");
40
+ this.#fetch = options.fetch ?? fetch;
41
+ }
42
+ /** An installation's token (`msinst_…`), from the one kept while it has over a minute left. Throws when Midsummer refuses the app's secret or the installation. */
43
+ async token(installationId, now = Date.now()) {
44
+ const kept = this.#tokens.get(installationId);
45
+ if (kept && kept.until - 6e4 > now) return kept.token;
46
+ const response = await this.#fetch(`${this.#origin}/v1/oauth/token`, {
47
+ method: "POST",
48
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
49
+ body: new URLSearchParams({
50
+ grant_type: "client_credentials",
51
+ client_id: this.#id,
52
+ client_secret: this.#secret,
53
+ installation_id: installationId
54
+ }).toString()
55
+ });
56
+ if (!response.ok) throw new Error(`Midsummer gave no token for ${installationId}: HTTP ${response.status} ${await response.text()}`);
57
+ const { access_token: token, expires_in: seconds } = await response.json();
58
+ this.#tokens.set(installationId, {
59
+ token,
60
+ until: now + seconds * 1e3
61
+ });
62
+ return token;
63
+ }
64
+ /** A call to Midsummer's API as the app in one installation, such as `/v1/mr/acme/web/mr-12/comments`; JSON unless the body says otherwise. */
65
+ async request(installationId, path, init = {}) {
66
+ const headers = new Headers(init.headers);
67
+ headers.set("Authorization", `Bearer ${await this.token(installationId)}`);
68
+ if (init.body !== void 0 && !headers.has("Content-Type")) headers.set("Content-Type", "application/json");
69
+ return this.#fetch(`${this.#origin}${path.startsWith("/") ? path : `/${path}`}`, {
70
+ ...init,
71
+ headers
72
+ });
73
+ }
74
+ /** Trades the one-time code a manifest's app was made with for its id, secret and signing secret, shown this once. */
75
+ static async fromManifestCode(code, options = {}) {
76
+ const origin = (options.origin ?? "https://api.midsummer.new").replace(/\/+$/, "");
77
+ const response = await (options.fetch ?? fetch)(`${origin}/v1/apps/conversions/${encodeURIComponent(code)}`, { method: "POST" });
78
+ if (!response.ok) throw new Error(`Midsummer refused the code: HTTP ${response.status} ${await response.text()}`);
79
+ return await response.json();
80
+ }
81
+ };
82
+ function fromBase64(text) {
83
+ const bytes = atob(text);
84
+ const out = new Uint8Array(bytes.length);
85
+ for (let index = 0; index < bytes.length; index += 1) out[index] = bytes.charCodeAt(index);
86
+ return out;
87
+ }
88
+ function toBase64(bytes) {
89
+ let text = "";
90
+ for (const byte of bytes) text += String.fromCharCode(byte);
91
+ return btoa(text);
92
+ }
93
+ /** Whether two signatures are the same, compared in time that does not depend on where they differ. */
94
+ function same(a, b) {
95
+ if (a.length !== b.length) return false;
96
+ let differ = 0;
97
+ for (let index = 0; index < a.length; index += 1) differ |= a.charCodeAt(index) ^ b.charCodeAt(index);
98
+ return differ === 0;
99
+ }
100
+ //#endregion
101
+ export { InstalledApp, verifyEvent };
@@ -0,0 +1,23 @@
1
+ import { AuthClient } from "better-auth/client";
2
+ import { AdminClientOptions, OrganizationClientOptions, adminClient, emailOTPClient, magicLinkClient, organizationClient, twoFactorClient } from "better-auth/client/plugins";
3
+ import { passkeyClient } from "@better-auth/passkey/client";
4
+ import { oauthProviderClient } from "@better-auth/oauth-provider/client";
5
+ //#region src/auth/client.d.ts
6
+ type AuthPlugin = ReturnType<typeof emailOTPClient> | ReturnType<typeof magicLinkClient> | ReturnType<typeof organizationClient<OrganizationClientOptions>> | ReturnType<typeof twoFactorClient> | ReturnType<typeof passkeyClient> | ReturnType<typeof adminClient<AdminClientOptions>> | ReturnType<typeof oauthProviderClient>;
7
+ /** What `authClient()` returns: better-auth's client with every plugin's methods, such as `emailOtp` and `organization`. */
8
+ type MidsummerAuthClient = AuthClient<{
9
+ basePath: string;
10
+ baseURL?: string;
11
+ plugins: AuthPlugin[];
12
+ }>;
13
+ /**
14
+ * The client plugins that match the server's. With `oauthProviderClient`, a sign-in on the app's sign-in page
15
+ * that an MCP client sent the person to carries on to the page that asks them, with nothing more to write.
16
+ */
17
+ declare const authPlugins: () => AuthPlugin[];
18
+ /** A client for the page's own sign-in, or the address `baseURL` gives when the app's server is elsewhere. */
19
+ declare function authClient(options?: {
20
+ readonly baseURL?: string;
21
+ }): MidsummerAuthClient;
22
+ //#endregion
23
+ export { MidsummerAuthClient, authClient, authPlugins };
@@ -0,0 +1,45 @@
1
+ import { createAuthClient } from "better-auth/client";
2
+ import { adminClient, emailOTPClient, magicLinkClient, organizationClient, twoFactorClient } from "better-auth/client/plugins";
3
+ import { passkeyClient } from "@better-auth/passkey/client";
4
+ import { oauthProviderClient } from "@better-auth/oauth-provider/client";
5
+ //#region src/auth/client.ts
6
+ /**
7
+ * Sign-in from the browser: better-auth's client with the plugins `@midsummer-ai/sdk/auth` turns on, talking to
8
+ * `/api/auth` on the page's own address.
9
+ *
10
+ * import { authClient } from "@midsummer-ai/sdk/auth/client"
11
+ *
12
+ * const auth = authClient()
13
+ * await auth.signUp.email({ email, password, name })
14
+ * await auth.emailOtp.sendVerificationOtp({ email, type: "sign-in" })
15
+ * await auth.signIn.emailOtp({ email, otp })
16
+ * await auth.signIn.social({ provider: "google", callbackURL: "/" })
17
+ * await auth.organization.create({ name: "Acme", slug: "acme" })
18
+ * const { data } = await auth.getSession()
19
+ *
20
+ * `auth.useSession` is a store any framework can subscribe to; in React, `better-auth/react`'s `createAuthClient`
21
+ * takes the same `plugins`.
22
+ */
23
+ /**
24
+ * The client plugins that match the server's. With `oauthProviderClient`, a sign-in on the app's sign-in page
25
+ * that an MCP client sent the person to carries on to the page that asks them, with nothing more to write.
26
+ */
27
+ const authPlugins = () => [
28
+ emailOTPClient(),
29
+ magicLinkClient(),
30
+ organizationClient(),
31
+ twoFactorClient(),
32
+ passkeyClient(),
33
+ adminClient(),
34
+ oauthProviderClient()
35
+ ];
36
+ /** A client for the page's own sign-in, or the address `baseURL` gives when the app's server is elsewhere. */
37
+ function authClient(options = {}) {
38
+ return createAuthClient({
39
+ basePath: "/api/auth",
40
+ ...options.baseURL ? { baseURL: options.baseURL } : {},
41
+ plugins: authPlugins()
42
+ });
43
+ }
44
+ //#endregion
45
+ export { authClient, authPlugins };
@@ -0,0 +1,24 @@
1
+ import { SignInMail } from "./mail.mjs";
2
+ import { Auth } from "./index.mjs";
3
+ //#region src/auth/contract.d.ts
4
+ interface AuthHarness {
5
+ /** Sign-in over a store with no users, made with `scopes: CONTRACT_SCOPES`. */
6
+ readonly auth: Auth;
7
+ /** The mail it sent, oldest first. */
8
+ outbox(): ReadonlyArray<SignInMail>;
9
+ /** How many calls reached the rows so far. */
10
+ calls(): number;
11
+ }
12
+ interface AuthContractCase {
13
+ readonly name: string;
14
+ run(harness: AuthHarness): Promise<void>;
15
+ }
16
+ declare const CONTRACT_ORIGIN = "https://shop.contract.test";
17
+ /** The scopes every harness's sign-in declares. */
18
+ declare const CONTRACT_SCOPES: {
19
+ readonly "notes:read": "Read your notes";
20
+ readonly "notes:write": "Add and change your notes";
21
+ };
22
+ declare const authContract: ReadonlyArray<AuthContractCase>;
23
+ //#endregion
24
+ export { AuthContractCase, AuthHarness, CONTRACT_ORIGIN, CONTRACT_SCOPES, authContract };