@stigmer/client 0.1.3 → 0.3.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 (76) hide show
  1. package/README.md +10 -0
  2. package/app-handover.d.ts +186 -0
  3. package/app-handover.d.ts.map +1 -0
  4. package/app-handover.js +630 -0
  5. package/app-handover.js.map +1 -0
  6. package/gen/agent.d.ts +2 -1
  7. package/gen/agent.d.ts.map +1 -1
  8. package/gen/agent.js +2 -0
  9. package/gen/agent.js.map +1 -1
  10. package/gen/organization.d.ts +2 -0
  11. package/gen/organization.d.ts.map +1 -1
  12. package/gen/organization.js +8 -0
  13. package/gen/organization.js.map +1 -1
  14. package/gen/run.d.ts +7 -1
  15. package/gen/run.d.ts.map +1 -1
  16. package/gen/run.js +23 -1
  17. package/gen/run.js.map +1 -1
  18. package/iam-principal.d.ts +11 -0
  19. package/iam-principal.d.ts.map +1 -1
  20. package/iam-principal.js +16 -0
  21. package/iam-principal.js.map +1 -1
  22. package/index.d.ts +11 -5
  23. package/index.d.ts.map +1 -1
  24. package/index.js +10 -3
  25. package/index.js.map +1 -1
  26. package/node.d.ts.map +1 -1
  27. package/node.js +12 -0
  28. package/node.js.map +1 -1
  29. package/package.json +9 -4
  30. package/platform.d.ts +41 -3
  31. package/platform.d.ts.map +1 -1
  32. package/platform.js +56 -3
  33. package/platform.js.map +1 -1
  34. package/run/format-elapsed.d.ts +10 -0
  35. package/run/format-elapsed.d.ts.map +1 -0
  36. package/run/format-elapsed.js +25 -0
  37. package/run/format-elapsed.js.map +1 -0
  38. package/run/step-words.d.ts +78 -0
  39. package/run/step-words.d.ts.map +1 -0
  40. package/run/step-words.js +316 -0
  41. package/run/step-words.js.map +1 -0
  42. package/run/tool-view.d.ts +49 -2
  43. package/run/tool-view.d.ts.map +1 -1
  44. package/run/tool-view.js +113 -17
  45. package/run/tool-view.js.map +1 -1
  46. package/run/turn-activity.d.ts +9 -7
  47. package/run/turn-activity.d.ts.map +1 -1
  48. package/run/turn-activity.js +24 -144
  49. package/run/turn-activity.js.map +1 -1
  50. package/run/turn-ending.d.ts +59 -0
  51. package/run/turn-ending.d.ts.map +1 -0
  52. package/run/turn-ending.js +405 -0
  53. package/run/turn-ending.js.map +1 -0
  54. package/run/turn-steps.d.ts +16 -0
  55. package/run/turn-steps.d.ts.map +1 -0
  56. package/run/turn-steps.js +65 -0
  57. package/run/turn-steps.js.map +1 -0
  58. package/session-events.d.ts +3 -1
  59. package/session-events.d.ts.map +1 -1
  60. package/session-events.js +1 -0
  61. package/session-events.js.map +1 -1
  62. package/src/app-handover.ts +777 -0
  63. package/src/gen/agent.ts +4 -1
  64. package/src/gen/organization.ts +7 -0
  65. package/src/gen/run.ts +21 -1
  66. package/src/iam-principal.ts +21 -0
  67. package/src/index.ts +55 -1
  68. package/src/node.ts +12 -0
  69. package/src/platform.ts +80 -3
  70. package/src/run/format-elapsed.ts +22 -0
  71. package/src/run/step-words.ts +360 -0
  72. package/src/run/tool-view.ts +133 -19
  73. package/src/run/turn-activity.ts +27 -146
  74. package/src/run/turn-ending.ts +487 -0
  75. package/src/run/turn-steps.ts +81 -0
  76. package/src/session-events.ts +4 -1
@@ -0,0 +1,777 @@
1
+ /**
2
+ * The code that puts an agent's chat in a builder's own app: one source for
3
+ * the text every surface hands over (the console's agent page, and anything
4
+ * else that writes a builder's token route and chat), so each says exactly
5
+ * the same thing and a compiler can hold all of it (the docs snippet gate
6
+ * compiles every stack's output as whole files).
7
+ *
8
+ * Two files, for a server that signs people in:
9
+ *
10
+ * - a token route for the builder's backend, `GET /api/stigmer-token`,
11
+ * answering `{ accessToken, expiresAt }` (the shape `createTokenCache`
12
+ * takes), minted with an admin service account's key read from
13
+ * `STIGMER_API_KEY`; one per stack, on the stack's standard library
14
+ * (Node's `node:http`, Python's `http.server`, Go's `net/http`, the JDK's
15
+ * `com.sun.net.httpserver`), or a Next.js route handler. A standard
16
+ * library route is something every reader can compile and run as it
17
+ * stands, and its one minting call moves into any framework;
18
+ * - the chat for their React app, `<AgentChat>` behind `createTokenCache`,
19
+ * in the light or dark of the person's system, as most apps start out.
20
+ *
21
+ * Beside them, what the builder needs to see it run: a short page that shows
22
+ * the chat in a box with a height, and the settings file the backend reads
23
+ * its key and development user from (`appSettingsText`). Every file is named
24
+ * by its path in the builder's project: a Next.js app is one app, holding the
25
+ * route, the chat and the page, so one install covers it; the other stacks'
26
+ * backends serve a React app of its own, which holds the chat and the page.
27
+ * The client's Node transport (`@connectrpc/connect-node`, an optional peer
28
+ * of `@stigmer/client`) is installed only by a line whose files run
29
+ * `@stigmer/client/node`: the Node and Next.js routes. A React app of its own
30
+ * runs the chat in the browser and installs no transport.
31
+ *
32
+ * Who is signed in is the one thing Stigmer cannot know. Every route asks one
33
+ * function, `currentUser`, which the builder replaces with their own sign-in.
34
+ * Until then it answers the person named by `STIGMER_DEV_USER` while that is
35
+ * set, and nobody otherwise, so a route pasted into production unchanged
36
+ * refuses everyone rather than minting for whoever calls it.
37
+ *
38
+ * For a server that trusts every caller (`stigmer up`), only the chat, with
39
+ * no token at all: there is no one to sign in, and the server refuses to
40
+ * mint. That text says it is for development.
41
+ *
42
+ * The text carries no secret: the key is read from the environment, and the
43
+ * functions here never take one. Every value written into code (the
44
+ * organization, the agent, the address) is written as a string literal by
45
+ * `JSON.stringify`, whose escapes are valid in all five languages, so no
46
+ * value can break out of its literal. Framework-free and import-free, so the
47
+ * plain-Node docs gate loads the built module as it stands.
48
+ */
49
+
50
+ /** A backend the handover writes a token route for. */
51
+ export type AppHandoverStack = "nextjs" | "node" | "python" | "go" | "java";
52
+
53
+ /** The backends, in the order a picker offers them, with their names. */
54
+ export const APP_HANDOVER_STACKS: readonly { readonly id: AppHandoverStack; readonly name: string }[] = [
55
+ { id: "nextjs", name: "Next.js" },
56
+ { id: "node", name: "Node" },
57
+ { id: "python", name: "Python" },
58
+ { id: "go", name: "Go" },
59
+ { id: "java", name: "Java" },
60
+ ];
61
+
62
+ /**
63
+ * Which server the code talks to: `"sign-in"`, one that signs its callers in
64
+ * (Stigmer Cloud, or a self-hosted server with sign-in turned on), where a
65
+ * backend mints each user's token; `"local"`, one that trusts every caller,
66
+ * where the chat sends no token and there is no backend.
67
+ */
68
+ export type AppHandoverMode = "sign-in" | "local";
69
+
70
+ /** The language a handed-over block is written in, for highlighting. */
71
+ export type AppHandoverLanguage = "bash" | "xml" | "typescript" | "tsx" | "python" | "go" | "java";
72
+
73
+ /** A whole file to add, at its path in the builder's project. */
74
+ export interface AppHandoverSource {
75
+ /** The file's path in the builder's project ("server.ts", "app/api/stigmer-token/route.ts"). */
76
+ readonly file: string;
77
+ readonly language: AppHandoverLanguage;
78
+ /** The whole file. */
79
+ readonly code: string;
80
+ }
81
+
82
+ /** One file to add, and what to install for it. */
83
+ export interface AppHandoverFile extends AppHandoverSource {
84
+ /** The install command (or, for Java, the Maven dependency). */
85
+ readonly install: string;
86
+ readonly installLanguage: "bash" | "xml";
87
+ }
88
+
89
+ /** What the handover gives a builder. */
90
+ export interface AppHandover {
91
+ /** The token route, for a server that signs people in; absent for a local one. */
92
+ readonly backend?: AppHandoverFile;
93
+ /** The chat component for their React app. */
94
+ readonly chat: AppHandoverFile;
95
+ /**
96
+ * A page to try it: the chat mounted in a box with a height, beside the
97
+ * chat in the same app (`app/agent/page.tsx` for Next.js, the React app's
98
+ * `src/App.tsx` otherwise).
99
+ */
100
+ readonly page: AppHandoverSource;
101
+ /** Where the page opens once the app runs: `"/agent"` for Next.js, `"/"` for a React app of its own. */
102
+ readonly pagePath: string;
103
+ /**
104
+ * Whether the backend and the chat are one app (Next.js), so one install
105
+ * covers both (`backend.install`); otherwise each file names its own.
106
+ */
107
+ readonly oneApp: boolean;
108
+ /**
109
+ * The settings file the backend reads (`.env.local` for Next.js, `.env`
110
+ * otherwise), for a server that signs people in; its text is
111
+ * {@link appSettingsText}'s. Absent for a local server, which needs none.
112
+ */
113
+ readonly settingsFile?: string;
114
+ /**
115
+ * Whether the backend reads {@link settingsFile} as handed over: Next.js
116
+ * loads `.env.local` itself, and the Node route's run line passes
117
+ * `--env-file=.env`. Python's, Go's and Java's routes read their
118
+ * environment, so the values must reach it some other way. Absent for a
119
+ * local server.
120
+ */
121
+ readonly readsSettingsFile?: boolean;
122
+ }
123
+
124
+ /** What {@link buildAppHandover} writes the code for. */
125
+ export interface AppHandoverInput {
126
+ readonly mode: AppHandoverMode;
127
+ /** The backend, for the token route. The chat is the same for every stack. */
128
+ readonly stack: AppHandoverStack;
129
+ /** The Stigmer API's public address, `https://…` or `http://…`. */
130
+ readonly baseUrl: string;
131
+ /** The organization's slug. */
132
+ readonly org: string;
133
+ /** The agent's slug. */
134
+ readonly agent: string;
135
+ /**
136
+ * A published release of the SDKs (`"0.1.3"`), named in Java's Maven
137
+ * dependency. Without one, the dependency takes the newest 0.x release and
138
+ * says where to find it to pin it.
139
+ */
140
+ readonly sdkVersion?: string;
141
+ }
142
+
143
+ /** The path every token route serves and the chat fetches. */
144
+ export const APP_TOKEN_ROUTE = "/api/stigmer-token";
145
+
146
+ /** The environment variable the routes read the service account's key from. */
147
+ export const APP_API_KEY_VARIABLE = "STIGMER_API_KEY";
148
+
149
+ /** The environment variable naming the person a route signs in until the builder's own sign-in replaces it. */
150
+ export const APP_DEV_USER_VARIABLE = "STIGMER_DEV_USER";
151
+
152
+ /** The chat component's name, as the builder mounts it: `<StigmerAgentChat />`. */
153
+ export const APP_CHAT_COMPONENT = "StigmerAgentChat";
154
+
155
+ /** The port a standard-library route listens on when `PORT` is unset. */
156
+ export const APP_TOKEN_ROUTE_PORT = 3001;
157
+
158
+ /** What the settings file holds in place of the key while the key is not on screen: where the key goes. */
159
+ export const APP_API_KEY_PLACEHOLDER = "<paste your service account's key here>";
160
+
161
+ /** What the settings file holds in place of the developer's email while it is not known. */
162
+ export const APP_DEV_USER_PLACEHOLDER = "<your email>";
163
+
164
+ /** The values {@link appSettingsText} writes, each a placeholder when absent. */
165
+ export interface AppSettingsValues {
166
+ /** The service account's key, while it is on screen; never stored. */
167
+ readonly apiKey?: string;
168
+ /** The email of the person the route signs in until the app has a sign-in of its own. */
169
+ readonly devUser?: string;
170
+ }
171
+
172
+ /**
173
+ * The backend's settings file (`AppHandover.settingsFile`): the service
174
+ * account's key, and the person the route signs in while the app has no
175
+ * sign-in of its own. A value not given is a placeholder that says what
176
+ * goes there. A line break in a value is dropped, so a value is one line.
177
+ *
178
+ * @example
179
+ * ```typescript
180
+ * appSettingsText({ devUser: "ada@acme.example" });
181
+ * // STIGMER_API_KEY=<paste your service account's key here>
182
+ * // STIGMER_DEV_USER=ada@acme.example
183
+ * ```
184
+ */
185
+ export function appSettingsText(values: AppSettingsValues = {}): string {
186
+ const line = (value: string | undefined, placeholder: string) =>
187
+ value === undefined || value.trim() === "" ? placeholder : value.replace(/[\r\n]/g, "");
188
+ return [
189
+ `${APP_API_KEY_VARIABLE}=${line(values.apiKey, APP_API_KEY_PLACEHOLDER)}`,
190
+ `${APP_DEV_USER_VARIABLE}=${line(values.devUser, APP_DEV_USER_PLACEHOLDER)}`,
191
+ "",
192
+ ].join("\n");
193
+ }
194
+
195
+ /**
196
+ * The code that puts `org/agent`'s chat in a builder's app, for their stack.
197
+ *
198
+ * @throws {Error} when `baseUrl` is not an absolute `http://` or `https://` address
199
+ *
200
+ * @example
201
+ * ```typescript
202
+ * import { buildAppHandover } from "@stigmer/client";
203
+ *
204
+ * const { backend, chat, page } = buildAppHandover({
205
+ * mode: "sign-in",
206
+ * stack: "node",
207
+ * baseUrl: "https://api.stigmer.ai",
208
+ * org: "acme",
209
+ * agent: "variance-reporter",
210
+ * });
211
+ * // backend.file === "server.ts"; chat.file === "src/StigmerAgentChat.tsx"; page.file === "src/App.tsx"
212
+ * ```
213
+ */
214
+ export function buildAppHandover(input: AppHandoverInput): AppHandover {
215
+ const server = serverOf(input.baseUrl);
216
+ const code: Code = { org: lit(input.org), agentRef: lit(`${input.org}/${input.agent}`), server };
217
+ const app = APPS[input.stack];
218
+ const where = { page: app.page, pagePath: app.pagePath, oneApp: app.oneApp };
219
+ if (input.mode === "local") return { chat: localChat(code, app.chatFile), ...where };
220
+ return {
221
+ backend: backendFor(input.stack, code, input.sdkVersion),
222
+ chat: signInChat(code, app.chatFile),
223
+ ...where,
224
+ settingsFile: app.settingsFile,
225
+ readsSettingsFile: READS_SETTINGS_FILE[input.stack],
226
+ };
227
+ }
228
+
229
+ /** What every file is written from, each value already a string literal. */
230
+ interface Code {
231
+ readonly org: string;
232
+ readonly agentRef: string;
233
+ readonly server: Server;
234
+ }
235
+
236
+ /** The API's address as each SDK takes it. */
237
+ interface Server {
238
+ /** The URL literal, for the TypeScript clients. */
239
+ readonly url: string;
240
+ /** The gRPC target literal (`host:port`), for Go, Python and Java. */
241
+ readonly target: string;
242
+ /** Whether the address is `http://`, which Go, Python and Java must be told. */
243
+ readonly plaintext: boolean;
244
+ }
245
+
246
+ function serverOf(baseUrl: string): Server {
247
+ let url: URL;
248
+ try {
249
+ url = new URL(baseUrl);
250
+ } catch {
251
+ throw new Error(`buildAppHandover: baseUrl must be an absolute address, like https://api.stigmer.ai (got ${JSON.stringify(baseUrl)})`);
252
+ }
253
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
254
+ throw new Error(`buildAppHandover: baseUrl must be http:// or https:// (got ${JSON.stringify(baseUrl)})`);
255
+ }
256
+ const plaintext = url.protocol === "http:";
257
+ // The server answers gRPC and Connect on one port, so the target is the
258
+ // address's own host and port; a URL leaves out a port its scheme implies.
259
+ const port = url.port !== "" ? url.port : plaintext ? "80" : "443";
260
+ const origin = `${url.protocol}//${url.host}${url.pathname === "/" ? "" : url.pathname.replace(/\/$/, "")}`;
261
+ return { url: lit(origin), target: lit(`${url.hostname}:${port}`), plaintext };
262
+ }
263
+
264
+ /** A string literal for any of the five languages. */
265
+ function lit(value: string): string {
266
+ return JSON.stringify(value);
267
+ }
268
+
269
+ /** Each stack's route; a typed record, so a stack without one fails to compile. */
270
+ const BACKENDS: Record<AppHandoverStack, (code: Code, sdkVersion: string | undefined) => AppHandoverFile> = {
271
+ // One app: its one install covers the route, the chat and the page.
272
+ nextjs: (code) => ({ install: NEXT_APP_INSTALL, installLanguage: "bash", file: "app/api/stigmer-token/route.ts", language: "typescript", code: nextRoute(code) }),
273
+ node: (code) => ({ install: "npm install @stigmer/client @connectrpc/connect-node", installLanguage: "bash", file: "server.ts", language: "typescript", code: nodeRoute(code) }),
274
+ python: (code) => ({ install: "pip install stigmer-sdk", installLanguage: "bash", file: "stigmer_token.py", language: "python", code: pythonRoute(code) }),
275
+ go: (code) => ({ install: "go get go.stigmer.ai/sdk", installLanguage: "bash", file: "main.go", language: "go", code: goRoute(code) }),
276
+ java: (code, sdkVersion) => ({ install: mavenDependency(sdkVersion), installLanguage: "xml", file: "StigmerToken.java", language: "java", code: javaRoute(code) }),
277
+ };
278
+
279
+ function backendFor(stack: AppHandoverStack, code: Code, sdkVersion: string | undefined): AppHandoverFile {
280
+ return BACKENDS[stack](code, sdkVersion);
281
+ }
282
+
283
+ /** Whether each stack's route, run as it says, reads the settings file itself. */
284
+ const READS_SETTINGS_FILE: Record<AppHandoverStack, boolean> = {
285
+ nextjs: true,
286
+ node: true,
287
+ python: false,
288
+ go: false,
289
+ java: false,
290
+ };
291
+
292
+ /** Where a stack's app keeps the chat and the page that tries it, and the settings file its backend reads. */
293
+ interface AppSide {
294
+ readonly oneApp: boolean;
295
+ readonly chatFile: string;
296
+ readonly page: AppHandoverSource;
297
+ readonly pagePath: string;
298
+ readonly settingsFile: string;
299
+ }
300
+
301
+ /** A Next.js app: the route, the chat and a page of its own, one app; Next.js reads `.env.local` itself. */
302
+ const NEXT_APP: AppSide = {
303
+ oneApp: true,
304
+ chatFile: `components/${APP_CHAT_COMPONENT}.tsx`,
305
+ page: {
306
+ file: "app/agent/page.tsx",
307
+ language: "tsx",
308
+ code: `import { ${APP_CHAT_COMPONENT} } from "@/components/${APP_CHAT_COMPONENT}";
309
+
310
+ export default function AgentPage() {
311
+ return (
312
+ <main style={{ height: "100vh" }}>
313
+ <${APP_CHAT_COMPONENT} />
314
+ </main>
315
+ );
316
+ }
317
+ `,
318
+ },
319
+ pagePath: "/agent",
320
+ settingsFile: ".env.local",
321
+ };
322
+
323
+ /** A React app of its own (as `npm create vite` makes one) beside a backend: the chat and its root page in `src`. */
324
+ const REACT_APP: AppSide = {
325
+ oneApp: false,
326
+ chatFile: `src/${APP_CHAT_COMPONENT}.tsx`,
327
+ page: {
328
+ file: "src/App.tsx",
329
+ language: "tsx",
330
+ code: `import { ${APP_CHAT_COMPONENT} } from "./${APP_CHAT_COMPONENT}";
331
+
332
+ export default function App() {
333
+ return (
334
+ <main style={{ height: "100vh" }}>
335
+ <${APP_CHAT_COMPONENT} />
336
+ </main>
337
+ );
338
+ }
339
+ `,
340
+ },
341
+ pagePath: "/",
342
+ settingsFile: ".env",
343
+ };
344
+
345
+ /** Each stack's app side; a typed record, so a stack without one fails to compile. */
346
+ const APPS: Record<AppHandoverStack, AppSide> = {
347
+ nextjs: NEXT_APP,
348
+ node: REACT_APP,
349
+ python: REACT_APP,
350
+ go: REACT_APP,
351
+ java: REACT_APP,
352
+ };
353
+
354
+ /** A version is pinned only when it is a plain release; anything else (a dev build) is not on Maven Central. */
355
+ const RELEASE = /^\d+\.\d+\.\d+$/;
356
+
357
+ function mavenDependency(sdkVersion: string | undefined): string {
358
+ const pinned = sdkVersion !== undefined && RELEASE.test(sdkVersion);
359
+ return [
360
+ ...(pinned ? [] : ["<!-- The newest 0.x release. Pin the one you test with: https://central.sonatype.com/artifact/ai.stigmer/stigmer-sdk -->"]),
361
+ "<dependency>",
362
+ " <groupId>ai.stigmer</groupId>",
363
+ " <artifactId>stigmer-sdk</artifactId>",
364
+ ` <version>${pinned ? sdkVersion : "[0.1,1.0)"}</version>`,
365
+ "</dependency>",
366
+ ].join("\n");
367
+ }
368
+
369
+ const CURRENT_USER_NOTE = [
370
+ "Replace this with your own sign-in: return the person this request is",
371
+ "from, or nobody. Until then it signs in the email in STIGMER_DEV_USER",
372
+ "while that is set, and nobody otherwise.",
373
+ ];
374
+
375
+ const REFUSED = "Stigmer refused the token; the reason is in your server's log.";
376
+
377
+ function nodeRoute({ org, server }: Code): string {
378
+ return `// Your backend's Stigmer token route. GET /api/stigmer-token answers the
379
+ // signed-in person's token, { accessToken, expiresAt }, which the chat in
380
+ // your app asks for. Run it with: npx tsx --env-file=.env server.ts
381
+ import { createServer, type IncomingMessage } from "node:http";
382
+ import { createNodeClient } from "@stigmer/client/node";
383
+
384
+ const ORG = ${org};
385
+
386
+ // The service account's key, never sent to a browser.
387
+ const stigmer = createNodeClient({
388
+ baseUrl: ${server.url},
389
+ apiKey: process.env.STIGMER_API_KEY!,
390
+ });
391
+
392
+ interface User {
393
+ id: string;
394
+ email?: string;
395
+ name?: string;
396
+ }
397
+
398
+ ${CURRENT_USER_NOTE.map((l) => `// ${l}`).join("\n")}
399
+ function currentUser(req: IncomingMessage): User | null {
400
+ const devUser = process.env.STIGMER_DEV_USER;
401
+ return devUser ? { id: devUser, email: devUser } : null;
402
+ }
403
+
404
+ createServer(async (req, res) => {
405
+ if (req.method !== "GET" || req.url !== "/api/stigmer-token") {
406
+ res.writeHead(404).end();
407
+ return;
408
+ }
409
+ const user = currentUser(req);
410
+ if (!user) {
411
+ res.writeHead(401, { "content-type": "text/plain" }).end("Nobody is signed in.");
412
+ return;
413
+ }
414
+ try {
415
+ const { accessToken, expiresAt } = await stigmer.tokens.mintUserToken({
416
+ org: ORG,
417
+ userId: user.id,
418
+ userEmail: user.email,
419
+ userName: user.name,
420
+ });
421
+ res.writeHead(200, { "content-type": "application/json" });
422
+ res.end(JSON.stringify({ accessToken, expiresAt: expiresAt.toISOString() }));
423
+ } catch (err) {
424
+ console.error(err);
425
+ res.writeHead(502, { "content-type": "text/plain" }).end(${lit(REFUSED)});
426
+ }
427
+ }).listen(Number(process.env.PORT ?? ${APP_TOKEN_ROUTE_PORT}));
428
+ `;
429
+ }
430
+
431
+ function nextRoute({ org, server }: Code): string {
432
+ return `// Your app's Stigmer token route. GET /api/stigmer-token answers the
433
+ // signed-in person's token, { accessToken, expiresAt }, which the chat asks for.
434
+ import { createNodeClient } from "@stigmer/client/node";
435
+
436
+ // Every request answers for whoever is signed in: never prerender it.
437
+ export const dynamic = "force-dynamic";
438
+
439
+ const ORG = ${org};
440
+
441
+ // The service account's key, never sent to a browser.
442
+ const stigmer = createNodeClient({
443
+ baseUrl: ${server.url},
444
+ apiKey: process.env.STIGMER_API_KEY!,
445
+ });
446
+
447
+ interface User {
448
+ id: string;
449
+ email?: string;
450
+ name?: string;
451
+ }
452
+
453
+ ${CURRENT_USER_NOTE.map((l) => `// ${l}`).join("\n")}
454
+ async function currentUser(request: Request): Promise<User | null> {
455
+ const devUser = process.env.STIGMER_DEV_USER;
456
+ return devUser ? { id: devUser, email: devUser } : null;
457
+ }
458
+
459
+ export async function GET(request: Request): Promise<Response> {
460
+ const user = await currentUser(request);
461
+ if (!user) return new Response("Nobody is signed in.", { status: 401 });
462
+ try {
463
+ const { accessToken, expiresAt } = await stigmer.tokens.mintUserToken({
464
+ org: ORG,
465
+ userId: user.id,
466
+ userEmail: user.email,
467
+ userName: user.name,
468
+ });
469
+ return Response.json({ accessToken, expiresAt: expiresAt.toISOString() });
470
+ } catch (err) {
471
+ console.error(err);
472
+ return new Response(${lit(REFUSED)}, { status: 502 });
473
+ }
474
+ }
475
+ `;
476
+ }
477
+
478
+ function pythonRoute({ org, server }: Code): string {
479
+ const insecure = server.plaintext ? ", insecure=True" : "";
480
+ return `"""Your backend's Stigmer token route.
481
+
482
+ GET /api/stigmer-token answers the signed-in person's token,
483
+ { accessToken, expiresAt }, which the chat in your app asks for.
484
+ Run it with: python stigmer_token.py
485
+ """
486
+
487
+ import json
488
+ import logging
489
+ import os
490
+ from dataclasses import dataclass
491
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
492
+
493
+ from stigmer import StigmerClient
494
+
495
+ ORG = ${org}
496
+
497
+ # The service account's key, never sent to a browser.
498
+ client = StigmerClient(os.environ["STIGMER_API_KEY"], base_url=${server.target}${insecure})
499
+
500
+
501
+ @dataclass
502
+ class User:
503
+ id: str
504
+ email: str | None = None
505
+ name: str | None = None
506
+
507
+
508
+ def current_user(request: BaseHTTPRequestHandler) -> User | None:
509
+ """${CURRENT_USER_NOTE.join("\n ")}
510
+ """
511
+ dev_user = os.environ.get("STIGMER_DEV_USER")
512
+ return User(id=dev_user, email=dev_user) if dev_user else None
513
+
514
+
515
+ class TokenRoute(BaseHTTPRequestHandler):
516
+ def do_GET(self) -> None:
517
+ if self.path != "/api/stigmer-token":
518
+ self.send_error(404)
519
+ return
520
+ user = current_user(self)
521
+ if user is None:
522
+ self.answer(401, "text/plain", b"Nobody is signed in.")
523
+ return
524
+ try:
525
+ token = client.tokens.mint_user_token(
526
+ org=ORG, user_id=user.id, user_email=user.email, user_name=user.name
527
+ )
528
+ except Exception:
529
+ logging.exception("minting a Stigmer token")
530
+ self.answer(502, "text/plain", ${lit(REFUSED)}.encode())
531
+ return
532
+ body = {"accessToken": token.access_token, "expiresAt": token.expires_at.isoformat()}
533
+ self.answer(200, "application/json", json.dumps(body).encode())
534
+
535
+ def answer(self, status: int, content_type: str, body: bytes) -> None:
536
+ self.send_response(status)
537
+ self.send_header("Content-Type", content_type)
538
+ self.end_headers()
539
+ self.wfile.write(body)
540
+
541
+
542
+ if __name__ == "__main__":
543
+ port = int(os.environ.get("PORT", "${APP_TOKEN_ROUTE_PORT}"))
544
+ ThreadingHTTPServer(("", port), TokenRoute).serve_forever()
545
+ `;
546
+ }
547
+
548
+ function goRoute({ org, server }: Code): string {
549
+ const insecure = server.plaintext ? ",\n\t\tstigmer.WithInsecure()," : ",";
550
+ return `// Your backend's Stigmer token route. GET /api/stigmer-token answers the
551
+ // signed-in person's token, { accessToken, expiresAt }, which the chat in
552
+ // your app asks for. Run it with: go run .
553
+ package main
554
+
555
+ import (
556
+ "encoding/json"
557
+ "log"
558
+ "net/http"
559
+ "os"
560
+ "time"
561
+
562
+ stigmer "go.stigmer.ai/sdk"
563
+ )
564
+
565
+ const org = ${org}
566
+
567
+ type user struct{ ID, Email, Name string }
568
+
569
+ ${CURRENT_USER_NOTE.map((l) => `// ${l}`).join("\n")}
570
+ func currentUser(r *http.Request) *user {
571
+ if devUser := os.Getenv("STIGMER_DEV_USER"); devUser != "" {
572
+ return &user{ID: devUser, Email: devUser}
573
+ }
574
+ return nil
575
+ }
576
+
577
+ func main() {
578
+ // The service account's key, never sent to a browser.
579
+ client, err := stigmer.NewClient(
580
+ stigmer.WithAPIKey(os.Getenv("STIGMER_API_KEY")),
581
+ stigmer.WithBaseURL(${server.target})${insecure}
582
+ )
583
+ if err != nil {
584
+ log.Fatal(err)
585
+ }
586
+ defer client.Close()
587
+
588
+ http.HandleFunc("GET /api/stigmer-token", func(w http.ResponseWriter, r *http.Request) {
589
+ u := currentUser(r)
590
+ if u == nil {
591
+ http.Error(w, "Nobody is signed in.", http.StatusUnauthorized)
592
+ return
593
+ }
594
+ token, err := client.Tokens.MintUserToken(r.Context(), &stigmer.MintUserTokenInput{
595
+ Org: org,
596
+ UserID: u.ID,
597
+ UserEmail: u.Email,
598
+ UserName: u.Name,
599
+ })
600
+ if err != nil {
601
+ log.Print(err)
602
+ http.Error(w, ${lit(REFUSED)}, http.StatusBadGateway)
603
+ return
604
+ }
605
+ w.Header().Set("Content-Type", "application/json")
606
+ json.NewEncoder(w).Encode(map[string]string{
607
+ "accessToken": token.AccessToken,
608
+ "expiresAt": token.ExpiresAt.Format(time.RFC3339),
609
+ })
610
+ })
611
+
612
+ port := os.Getenv("PORT")
613
+ if port == "" {
614
+ port = "${APP_TOKEN_ROUTE_PORT}"
615
+ }
616
+ log.Fatal(http.ListenAndServe(":"+port, nil))
617
+ }
618
+ `;
619
+ }
620
+
621
+ function javaRoute({ org, server }: Code): string {
622
+ const insecure = server.plaintext ? "\n .insecure()" : "";
623
+ return `// Your backend's Stigmer token route. GET /api/stigmer-token answers the
624
+ // signed-in person's token, { accessToken, expiresAt }, which the chat in
625
+ // your app asks for.
626
+ import ai.stigmer.sdk.MintUserTokenInput;
627
+ import ai.stigmer.sdk.MintUserTokenResult;
628
+ import ai.stigmer.sdk.StigmerClient;
629
+ import com.sun.net.httpserver.HttpExchange;
630
+ import com.sun.net.httpserver.HttpServer;
631
+ import java.io.IOException;
632
+ import java.io.OutputStream;
633
+ import java.net.InetSocketAddress;
634
+ import java.nio.charset.StandardCharsets;
635
+
636
+ public class StigmerToken {
637
+ static final String ORG = ${org};
638
+
639
+ record User(String id, String email, String name) {}
640
+
641
+ ${CURRENT_USER_NOTE.map((l) => ` // ${l}`).join("\n")}
642
+ static User currentUser(HttpExchange exchange) {
643
+ String devUser = System.getenv("STIGMER_DEV_USER");
644
+ return devUser == null || devUser.isEmpty() ? null : new User(devUser, devUser, null);
645
+ }
646
+
647
+ public static void main(String[] args) throws IOException {
648
+ // The service account's key, never sent to a browser.
649
+ StigmerClient client = StigmerClient.builder(System.getenv("STIGMER_API_KEY"))
650
+ .baseUrl(${server.target})${insecure}
651
+ .build();
652
+
653
+ int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "${APP_TOKEN_ROUTE_PORT}"));
654
+ HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
655
+ server.createContext("/api/stigmer-token", exchange -> {
656
+ if (!exchange.getRequestMethod().equals("GET") || !exchange.getRequestURI().getPath().equals("/api/stigmer-token")) {
657
+ answer(exchange, 404, "text/plain", "Not found.");
658
+ return;
659
+ }
660
+ User user = currentUser(exchange);
661
+ if (user == null) {
662
+ answer(exchange, 401, "text/plain", "Nobody is signed in.");
663
+ return;
664
+ }
665
+ MintUserTokenResult token;
666
+ try {
667
+ token = client.tokens().mintUserToken(MintUserTokenInput.builder()
668
+ .org(ORG)
669
+ .userId(user.id())
670
+ .userEmail(user.email())
671
+ .userName(user.name())
672
+ .build());
673
+ } catch (RuntimeException err) {
674
+ err.printStackTrace();
675
+ answer(exchange, 502, "text/plain", ${lit(REFUSED)});
676
+ return;
677
+ }
678
+ // A token and an ISO 8601 instant hold no character JSON escapes.
679
+ answer(exchange, 200, "application/json",
680
+ "{\\"accessToken\\":\\"" + token.accessToken() + "\\",\\"expiresAt\\":\\"" + token.expiresAt() + "\\"}");
681
+ });
682
+ server.start();
683
+ }
684
+
685
+ static void answer(HttpExchange exchange, int status, String contentType, String body) throws IOException {
686
+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
687
+ exchange.getResponseHeaders().set("Content-Type", contentType);
688
+ exchange.sendResponseHeaders(status, bytes.length);
689
+ try (OutputStream out = exchange.getResponseBody()) {
690
+ out.write(bytes);
691
+ }
692
+ }
693
+ }
694
+ `;
695
+ }
696
+
697
+ /** The chat's install: browser code only, so no Node transport. */
698
+ const CHAT_INSTALL = "npm install @stigmer/client @stigmer/react-sdk @stigmer/apis @bufbuild/protobuf";
699
+
700
+ /** A Next.js app's one install: the chat's, and the transport its route runs on `@stigmer/client/node`. */
701
+ const NEXT_APP_INSTALL = `${CHAT_INSTALL} @connectrpc/connect-node`;
702
+
703
+ function signInChat({ agentRef, server }: Code, file: string): AppHandoverFile {
704
+ return {
705
+ install: CHAT_INSTALL,
706
+ installLanguage: "bash",
707
+ file,
708
+ language: "tsx",
709
+ code: `"use client";
710
+
711
+ // The agent's chat, for the person signed in to your app. Mount it as
712
+ // <StigmerAgentChat /> in a box with a height: it fills the box.
713
+ import { Stigmer, createTokenCache } from "@stigmer/client";
714
+ import { AgentChat, StigmerProvider } from "@stigmer/react-sdk/chat";
715
+ import "@stigmer/react-sdk/styles.css";
716
+
717
+ // Your backend's token route. A backend apart from this app is reached
718
+ // through this app's proxy, or by its full address.
719
+ const TOKEN_ROUTE = ${lit(APP_TOKEN_ROUTE)};
720
+
721
+ // Asks your backend for a token once, and again a minute before it expires.
722
+ // When your user signs out, call tokens.invalidate().
723
+ const tokens = createTokenCache(async () => {
724
+ const res = await fetch(TOKEN_ROUTE);
725
+ if (!res.ok) throw new Error(\`\${TOKEN_ROUTE} answered \${res.status}: \${await res.text()}\`);
726
+ return res.json();
727
+ });
728
+
729
+ const stigmer = new Stigmer({
730
+ baseUrl: ${server.url},
731
+ getAccessToken: tokens.getAccessToken,
732
+ });
733
+
734
+ export function ${APP_CHAT_COMPONENT}() {
735
+ return (
736
+ <StigmerProvider client={stigmer} colorMode="system">
737
+ <AgentChat agent={${agentRef}} />
738
+ </StigmerProvider>
739
+ );
740
+ }
741
+ `,
742
+ };
743
+ }
744
+
745
+ function localChat({ agentRef, server }: Code, file: string): AppHandoverFile {
746
+ return {
747
+ install: CHAT_INSTALL,
748
+ installLanguage: "bash",
749
+ file,
750
+ language: "tsx",
751
+ code: `"use client";
752
+
753
+ // Development only. This Stigmer runs on your computer and trusts every
754
+ // caller, so your app talks to it with no sign-in while you build. Going
755
+ // live needs a Stigmer that signs people in, and a token route.
756
+ //
757
+ // The agent's chat. Mount it as <StigmerAgentChat /> in a box with a
758
+ // height: it fills the box.
759
+ import { Stigmer } from "@stigmer/client";
760
+ import { AgentChat, StigmerProvider } from "@stigmer/react-sdk/chat";
761
+ import "@stigmer/react-sdk/styles.css";
762
+
763
+ const stigmer = new Stigmer({
764
+ baseUrl: ${server.url},
765
+ getAccessToken: () => null,
766
+ });
767
+
768
+ export function ${APP_CHAT_COMPONENT}() {
769
+ return (
770
+ <StigmerProvider client={stigmer} colorMode="system">
771
+ <AgentChat agent={${agentRef}} />
772
+ </StigmerProvider>
773
+ );
774
+ }
775
+ `,
776
+ };
777
+ }