@theoremjs/studio 0.3.4-next.544.gb5ef325 → 0.3.4-next.550.gf20b9cd

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 (173) hide show
  1. package/README.md +57 -17
  2. package/agreement.js +22 -7
  3. package/compile.js +61 -13
  4. package/cookbooks/catalog.d.ts +26 -3
  5. package/cookbooks/catalog.js +114 -60
  6. package/cookbooks/exchanges.d.ts +3 -0
  7. package/cookbooks/exchanges.js +7 -2
  8. package/cookbooks/mod.d.ts +3 -3
  9. package/cookbooks/mod.js +2 -2
  10. package/cookbooks/project.js +1 -3
  11. package/draft.d.ts +23 -5
  12. package/draft.js +10 -2
  13. package/media-accept.d.ts +7 -0
  14. package/media-accept.js +17 -0
  15. package/mod.d.ts +4 -4
  16. package/mod.js +3 -3
  17. package/package.json +4 -4
  18. package/page/assets/Banner-Bvkdyf59.js +2 -0
  19. package/page/assets/BottomSheet-Dbh6A5Vl.js +1 -0
  20. package/page/assets/{Card-Ghe4ozhC.js → Card-DruykyeB.js} +1 -1
  21. package/page/assets/CheckboxInput-CFZ_Wq8-.js +2 -0
  22. package/page/assets/CodeBlock-CfVOtDeO.js +52 -0
  23. package/page/assets/CollapsibleGroup-FIawJRo4.js +1 -0
  24. package/page/assets/ConsoleFrame-BTL67qHr.js +3 -0
  25. package/page/assets/ContextMenu-BngxR9na.js +2 -0
  26. package/page/assets/DateInput-B1ICJtHn.js +1 -0
  27. package/page/assets/{Dialog-BDUExlk_.js → Dialog-Sd04KQS2.js} +1 -1
  28. package/page/assets/EmptyState-C_uF9Wyj.js +1 -0
  29. package/page/assets/HoverCard-DMyWUvwP.js +1 -0
  30. package/page/assets/Icon-BqkS-pIq.js +3 -0
  31. package/page/assets/IconButton-DVUFx-8p.js +1 -0
  32. package/page/assets/ListItem-QF7KFt0h.js +1 -0
  33. package/page/assets/MenuBottomSheet-C4fG_GyZ.js +1 -0
  34. package/page/assets/MenuBottomSheetActionList-3L0HS4Kf.js +1 -0
  35. package/page/assets/SchemaFields-BT2XCbid.js +1 -0
  36. package/page/assets/ScrollableArea-BHfY7sWH.js +1 -0
  37. package/page/assets/SegmentedControlItem-BBGRPrxp.js +1 -0
  38. package/page/assets/{Text-BsiAsowd.js → Text-BOqCfzZC.js} +2 -2
  39. package/page/assets/{TimestampHoverCard-CCnmnVlQ.js → TimestampHoverCard-CDCVpEWM.js} +1 -1
  40. package/page/assets/{ToolResultCharts-BAIAtrxa.js → ToolResultCharts-rJr0Ksno.js} +1 -1
  41. package/page/assets/Tooltip-BWs5DLrM.js +1 -0
  42. package/page/assets/TraceInspector-DQI_wNzL.js +1 -0
  43. package/page/assets/{TraceOverview-C6T0S77W.js → TraceOverview-DmfmwSR6.js} +2 -2
  44. package/page/assets/{_virtual_studio-type-sources-C1mRXxbj.js → _virtual_studio-type-sources-CxP3L28S.js} +158 -78
  45. package/page/assets/browser-engine-B1PxEekk.js +11 -0
  46. package/page/assets/browser-transport-BOHBmYvp.js +47 -0
  47. package/page/assets/{embedding-space-view-BU2AjjAx.js → embedding-space-view-CN0VHXXH.js} +1 -1
  48. package/page/assets/{export-agent-m6Z0No6j.js → export-agent-BvEVKW_C.js} +8 -8
  49. package/page/assets/fieldParts-B7DYLgh4.js +1 -0
  50. package/page/assets/focusableSelector-DXZeMU85.js +1 -0
  51. package/page/assets/{guardrail-tester-oVuyo5d2.js → guardrail-tester-08T-hMFL.js} +2 -2
  52. package/page/assets/index-eSb7kilv.js +146 -0
  53. package/page/assets/isRenderable-DHkzpAoQ.js +1 -0
  54. package/page/assets/{labels-provider-Gus3heEH.js → labels-provider-DkA22zkP.js} +2 -2
  55. package/page/assets/{live-messages-BNhCuiuF.js → live-messages-DmTC8qc8.js} +1 -1
  56. package/page/assets/plainDate-BHiJcj7o.js +1 -0
  57. package/page/assets/reader-DoTXxl0W.js +7 -0
  58. package/page/assets/{stub-DPcZtI0s.js → stub-CKo_lxer.js} +1 -1
  59. package/page/assets/studio-code-pane-CEG07Zk7.js +8 -0
  60. package/page/assets/{studio-console-DoZMv_gr.js → studio-console-udt4MmTi.js} +1 -1
  61. package/page/assets/studio-decision-tocwLzxr.js +1 -0
  62. package/page/assets/studio-embedding-DQ84xzlj.js +2 -0
  63. package/page/assets/studio-host-console-BJOUpXHR.js +2 -0
  64. package/page/assets/studio-labels-Zqd84hcs.js +3 -0
  65. package/page/assets/studio-live-BmuHpeF4.js +5 -0
  66. package/page/assets/{studio-map-Dv8iCayn.js → studio-map-qP_i4hWG.js} +1 -1
  67. package/page/assets/studio-trace-replay-JUMs6EMA.js +2 -0
  68. package/page/assets/{studio-type-checker-B5DVxAZ0.js → studio-type-checker-B_CHmWnf.js} +1 -1
  69. package/page/assets/{tool-schema-CxLtS_Zt.js → tool-schema-CWGccblZ.js} +6 -6
  70. package/page/assets/{trace-patterns-CS99kExN.js → trace-patterns-D6TbkLLr.js} +1 -1
  71. package/page/assets/tree-B7VVMg1s.js +3 -0
  72. package/page/assets/{turn-client-BCi5WnI6.js → turn-client-CoLR6hrl.js} +1 -1
  73. package/page/assets/types-CL44MvsT.js +1 -0
  74. package/page/assets/{use-one-call-TEvndb3j.js → use-one-call-BKeMtY5F.js} +1 -1
  75. package/page/assets/use-second-ticker-GWBt83pd.css +1 -0
  76. package/page/assets/use-trace-records-B1vrKQmA.js +1 -0
  77. package/page/assets/useAdaptivePresentation-Bma4-u1a.js +1 -0
  78. package/page/assets/useAnnounce-DTSHZvjg.js +1 -0
  79. package/page/assets/useClipboard-CbN9bb4J.js +1 -0
  80. package/page/assets/useDevWarning-Z9SoixOP.js +1 -0
  81. package/page/assets/useFocusReturnVisibility-BHKv5Jwr.js +1 -0
  82. package/page/assets/useMenuPress-DLG1QOiE.js +1 -0
  83. package/page/assets/useResolvedRequired-DbsOcDqy.js +1 -0
  84. package/page/assets/useScrollableArea-DuF_pz9m.js +1 -0
  85. package/page/assets/useTooltip-c097gL_-.js +1 -0
  86. package/page/assets/workspace-NGa3jjDc.js +1 -0
  87. package/page/index.html +45 -38
  88. package/read-source.js +35 -8
  89. package/read-studio.mjs +99 -0
  90. package/replay.d.ts +3 -1
  91. package/replay.js +53 -5
  92. package/requirements.d.ts +3 -0
  93. package/requirements.js +10 -0
  94. package/server/alerts.d.ts +23 -0
  95. package/server/alerts.js +82 -0
  96. package/server/draft-handler.d.ts +3 -0
  97. package/server/draft-handler.js +5 -1
  98. package/server/events.d.ts +38 -0
  99. package/server/events.js +95 -0
  100. package/server/handler.d.ts +11 -3
  101. package/server/handler.js +64 -8
  102. package/server/project-source.d.ts +6 -3
  103. package/server/project-source.js +45 -4
  104. package/server/project.js +25 -3
  105. package/server/save-session.d.ts +2 -0
  106. package/server/save-session.js +7 -1
  107. package/server/serve.d.ts +1 -1
  108. package/server/serve.js +174 -18
  109. package/server/test-key.d.ts +19 -2
  110. package/server/test-key.js +51 -74
  111. package/server/watch.d.ts +8 -0
  112. package/server/watch.js +16 -5
  113. package/start.mjs +95 -5
  114. package/surface.js +1 -2
  115. package/ui/built/theme.css +2 -2
  116. package/ui/built/theme.css.d.ts +2 -2
  117. package/ui/built/theorem-studio.d.ts +2 -2
  118. package/ui/built/theorem-studio.js +3 -3
  119. package/ui/built/theorem-studio.variants.d.ts +2 -2
  120. package/ui/lib/export-agent.js +20 -2
  121. package/ui/lib/page-errors.d.ts +13 -0
  122. package/ui/lib/page-errors.js +31 -0
  123. package/ui/lib/studio-examples.js +0 -4
  124. package/ui/lib/studio-page.d.ts +8 -3
  125. package/ui/lib/studio-page.js +34 -13
  126. package/ui/profile-editor.js +186 -34
  127. package/ui/studio-decision.js +4 -1
  128. package/ui/studio-runner.d.ts +1 -1
  129. package/ui/studio-runner.js +7 -3
  130. package/ui/studio-screen.js +24 -18
  131. package/ui/studio-trace-replay.js +1 -8
  132. package/workspace.d.ts +1 -0
  133. package/workspace.js +3 -2
  134. package/page/assets/Banner-BUrqNrQ9.js +0 -2
  135. package/page/assets/BottomSheet-BQPskY35.js +0 -1
  136. package/page/assets/CheckboxInput-C9kbVyhK.js +0 -2
  137. package/page/assets/CodeBlock-Kjgv83A6.js +0 -52
  138. package/page/assets/CollapsibleGroup-PavPZ114.js +0 -1
  139. package/page/assets/ConsoleFrame-BpbXMWsq.js +0 -3
  140. package/page/assets/ContextMenu-D_6fLWw7.js +0 -2
  141. package/page/assets/DateInput-BJt-UTCy.js +0 -1
  142. package/page/assets/EmptyState-C8W4JKBZ.js +0 -1
  143. package/page/assets/HoverCard-C6thuzrf.js +0 -1
  144. package/page/assets/Icon-ZfFwTt8n.js +0 -3
  145. package/page/assets/IconButton-CG5klqF1.js +0 -1
  146. package/page/assets/ScrollableArea-C8AVuqnt.js +0 -1
  147. package/page/assets/Section-DJ97F7QE.js +0 -1
  148. package/page/assets/SegmentedControlItem-BLuJOusN.js +0 -1
  149. package/page/assets/Tooltip-CTEuMRLe.js +0 -1
  150. package/page/assets/TraceInspector-CvaN-GcS.js +0 -1
  151. package/page/assets/browser-engine-BS9Kn2Gx.js +0 -11
  152. package/page/assets/browser-transport-eqZ9n2AK.js +0 -47
  153. package/page/assets/fieldParts-Cs6Amprh.js +0 -1
  154. package/page/assets/index-Q8T7gvHP.js +0 -149
  155. package/page/assets/reader-BT_YeHdq.js +0 -7
  156. package/page/assets/studio-code-pane-BB8Q348A.js +0 -8
  157. package/page/assets/studio-decision-BPT3x1kT.js +0 -1
  158. package/page/assets/studio-embedding-cH6PQupx.js +0 -2
  159. package/page/assets/studio-host-console-ZvV5TFC4.js +0 -2
  160. package/page/assets/studio-labels-Dwd-ojX5.js +0 -3
  161. package/page/assets/studio-live-DDInnfd7.js +0 -5
  162. package/page/assets/studio-trace-replay-Dl792A2v.js +0 -2
  163. package/page/assets/tree-Bi2FOU_h.js +0 -3
  164. package/page/assets/types-s-3wFTyD.js +0 -1
  165. package/page/assets/use-second-ticker-CnxaP3LD.css +0 -1
  166. package/page/assets/use-trace-records-BkAYJz0M.js +0 -1
  167. package/page/assets/useAdaptivePresentation-BY_zvjIp.js +0 -1
  168. package/page/assets/useClipboard-B1amtN2V.js +0 -1
  169. package/page/assets/useDevWarning-Cna3kqg1.js +0 -1
  170. package/page/assets/useScrollableArea-vxuztwym.js +0 -1
  171. package/page/assets/useTooltip-rxACYEAC.js +0 -1
  172. package/page/assets/workspace-BiCkglEt.js +0 -1
  173. /package/page/assets/{use-second-ticker-VX91zrxj.js → use-second-ticker-DhbZ0Soz.js} +0 -0
@@ -946,11 +946,51 @@ function madeBy(project, target, key) {
946
946
  return named;
947
947
  }
948
948
  /**
949
- * Walks the project's files from `entry`, the setup module, following each import. Yields each
950
- * file as it is read, so a caller can say where the walk is. Returns every file read.
949
+ * The entry modules of Theorem's own package, when the project is that package: a file there
950
+ * imports `./mod.ts` where an application imports `@theoremjs/agents`. The walk stops at them, as
951
+ * it stops at `node_modules`.
952
+ */
953
+ function theoremEntries(root, read) {
954
+ const text = read(resolve(root, 'deno.json'));
955
+ if (text === undefined)
956
+ return new Set();
957
+ let config;
958
+ try {
959
+ config = JSON.parse(text);
960
+ }
961
+ catch {
962
+ return new Set();
963
+ }
964
+ if (typeof config.name !== 'string' || !config.name.startsWith('@theoremjs/'))
965
+ return new Set();
966
+ const { exports } = config;
967
+ const entries = typeof exports === 'string'
968
+ ? [exports]
969
+ : exports !== null && typeof exports === 'object'
970
+ ? Object.values(exports).filter((entry) => typeof entry === 'string')
971
+ : [];
972
+ return new Set(entries.map((entry) => resolve(root, entry)));
973
+ }
974
+ /** The path the setup's `entry` export names, as it writes it: a string the walk follows as an import. */
975
+ function namedEntry(setup) {
976
+ const initializer = setupExport(setup, 'entry')?.initializer;
977
+ const value = initializer && unwrapped(initializer);
978
+ return value && ts.isStringLiteralLike(value) ? value.text : undefined;
979
+ }
980
+ /** The application entry the setup at `setupFile` names, as a path, read from the file as it is now. */
981
+ export function entryOf(setupFile) {
982
+ const setup = ts.createSourceFile(setupFile, Deno.readTextFileSync(setupFile), ts.ScriptTarget.Latest, true);
983
+ const named = namedEntry(setup);
984
+ return named === undefined ? undefined : resolve(dirname(setupFile), named);
985
+ }
986
+ /**
987
+ * Walks the project's files from `entry`, the setup module, following each import and the
988
+ * application entry the setup names. Yields each file as it is read, so a caller can say where
989
+ * the walk is. Returns every file read.
951
990
  */
952
991
  export function* walkProject(entry, root, read) {
953
992
  const files = new Map();
993
+ const theorem = theoremEntries(root, read);
954
994
  const queue = [{ file: resolve(entry) }];
955
995
  for (let step = queue.shift(); step !== undefined; step = queue.shift()) {
956
996
  const path = step.file;
@@ -962,9 +1002,10 @@ export function* walkProject(entry, root, read) {
962
1002
  const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true);
963
1003
  files.set(path, source);
964
1004
  yield step;
965
- for (const specifier of specifiers(source)) {
1005
+ const app = files.size === 1 ? namedEntry(source) : undefined;
1006
+ for (const specifier of app ? [app, ...specifiers(source)] : specifiers(source)) {
966
1007
  const next = importedFile(path, specifier, (file) => read(file) !== undefined, root);
967
- if (next && !files.has(next))
1008
+ if (next && !files.has(next) && !theorem.has(next))
968
1009
  queue.push({ file: next, from: path });
969
1010
  }
970
1011
  }
package/server/project.js CHANGED
@@ -20,11 +20,31 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
20
20
  }
21
21
  return path;
22
22
  };
23
- import { basename, resolve } from 'node:path';
23
+ import { basename, dirname, resolve } from 'node:path';
24
24
  import { pathToFileURL } from 'node:url';
25
25
  import { defaultKernelScope } from '@theoremjs/agents';
26
26
  import { editedImages, editedQuestions, registerEdits } from "./edits.js";
27
27
  import { createStudioHandler } from "./handler.js";
28
+ /**
29
+ * The application's turn wiring: the `theorem` its entry exports. A setup written before the entry
30
+ * existed fails here, and says what moved where.
31
+ */
32
+ async function wiringOf(setupPath, setup) {
33
+ const moved = ['default', 'provider'].filter((name) => setup[name] !== undefined);
34
+ if (moved.length > 0) {
35
+ throw new Error(`${setupPath} exports ${moved.map((name) => `\`${name}\``).join(' and ')}. The app's wiring moved to its entry: export \`theorem\` (a TurnWiring) from the entry, with registration in \`theorem.register\` and keys in \`theorem.provider\`, and export \`entry\` from the setup.`);
36
+ }
37
+ if (typeof setup.entry !== 'string' || !setup.entry) {
38
+ throw new Error(`${setupPath} names no entry. Export \`entry\`: the path of your app's entry point, relative to the setup file, which exports \`theorem\` (a TurnWiring).`);
39
+ }
40
+ const entryPath = resolve(dirname(resolve(setupPath)), setup.entry);
41
+ const entry = await import(__rewriteRelativeImportExtension(pathToFileURL(entryPath).href));
42
+ const theorem = entry.theorem;
43
+ if (!theorem || typeof theorem !== 'object') {
44
+ throw new Error(`${setup.entry} exports no \`theorem\`. Export the TurnWiring your app runs its turns with: \`export const theorem: TurnWiring = { register, provider, prepare }\`.`);
45
+ }
46
+ return theorem;
47
+ }
28
48
  /** The line this prints once it listens. `serve.ts` waits for it. */
29
49
  export const PROJECT_READY = 'theorem-studio-project-ready';
30
50
  if (import.meta.main) {
@@ -32,7 +52,8 @@ if (import.meta.main) {
32
52
  const flag = (name) => flags[flags.indexOf(`--${name}`) + 1] ?? '';
33
53
  const port = Number(flag('port'));
34
54
  const setup = await import(__rewriteRelativeImportExtension(pathToFileURL(resolve(setupPath)).href));
35
- await setup.default?.();
55
+ const theorem = await wiringOf(setupPath, setup);
56
+ await theorem.register?.();
36
57
  const load = await new Response(Deno.stdin.readable).json();
37
58
  let { questions, images } = setup;
38
59
  if (load.edits) {
@@ -46,7 +67,8 @@ if (import.meta.main) {
46
67
  listenHost: `127.0.0.1:${port}`,
47
68
  ...(setup.host ? { host: setup.host } : {}),
48
69
  ...(setup.people !== undefined ? { people: setup.people } : {}),
49
- ...(setup.provider ? { provider: setup.provider } : {}),
70
+ ...(theorem.provider ? { provider: theorem.provider } : {}),
71
+ ...(theorem.prepare ? { prepare: theorem.prepare } : {}),
50
72
  ...(questions ? { questions } : {}),
51
73
  ...(images ? { images } : {}),
52
74
  upgrade: (request) => Deno.upgradeWebSocket(request),
@@ -34,6 +34,8 @@ export interface SaveHost<Loaded> {
34
34
  stop(loaded: Loaded): Promise<void>;
35
35
  /** The workspace a load opened as. */
36
36
  opened(loaded: Loaded): StudioWorkspace;
37
+ /** The profiles a load registered that the studio could not open, by id. They are not unregistered. */
38
+ unopened?(loaded: Loaded): string[];
37
39
  }
38
40
  /** What one read of the project's files says. Each file is named from the project's folder. */
39
41
  export interface FilesRead {
@@ -329,13 +329,19 @@ export function createSaveSession(host, first) {
329
329
  const loaded = await refresh(first, said);
330
330
  const files = loaded ? source() : first;
331
331
  const opened = host.opened(project);
332
+ const names = projectNames(opened);
333
+ // A profile the studio could not open is still registered: the page says why it did not open.
334
+ const registered = {
335
+ ...names,
336
+ profiles: [...names.profiles, ...(host.unopened?.(project) ?? [])],
337
+ };
332
338
  const decisions = opened.agents
333
339
  .filter((agent) => agent.identity.profileType === 'decision')
334
340
  .map((agent) => agent.identity.agentId);
335
341
  return {
336
342
  shared: sharedSettings(files).map((setting) => ({ ...setting, file: inRoot(setting.file) })),
337
343
  origins: pageOrigins(sourceOrigins(files, decisions), projectNames(opened), files, inRoot),
338
- unregistered: unregisteredIn(files, projectNames(opened), inRoot),
344
+ unregistered: unregisteredIn(files, registered, inRoot),
339
345
  providerPlaces: providerPlaces(files, projectNames(opened), inRoot),
340
346
  ...(unloaded === undefined ? {} : { unloaded: unloaded.printed }),
341
347
  };
package/server/serve.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * Starts the studio's local server for one project.
3
3
  *
4
4
  * deno run -A studio/server/serve.ts <setup-module> [--port 4983] [--page http://localhost:5174]
5
- * [--deno-config <deno.json>] [--editor <command>]
5
+ * [--deno-config <deno.json>] [--editor <command>] [--no-watch] [--quiet] [--offline] [--verbose]
6
6
  *
7
7
  * The setup module is the project's: its default export registers the project's
8
8
  * tools, profiles, and providers; an optional `host` export gives tool handlers
package/server/serve.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * Starts the studio's local server for one project.
3
3
  *
4
4
  * deno run -A studio/server/serve.ts <setup-module> [--port 4983] [--page http://localhost:5174]
5
- * [--deno-config <deno.json>] [--editor <command>]
5
+ * [--deno-config <deno.json>] [--editor <command>] [--no-watch] [--quiet] [--offline] [--verbose]
6
6
  *
7
7
  * The setup module is the project's: its default export registers the project's
8
8
  * tools, profiles, and providers; an optional `host` export gives tool handlers
@@ -25,11 +25,13 @@ import { stripVTControlCharacters } from 'node:util';
25
25
  import { newConversationKey } from "../conversation-key.js";
26
26
  import { RUNNING_PATH } from '../ports.mjs';
27
27
  import { READ_STEPS } from "../read-steps.js";
28
+ import { alertText, keyLine, loadedText } from "./alerts.js";
28
29
  import { createEditedSession } from "./edited-session.js";
29
- import { corsHeaders, isForeign, json, STUDIO_BASE } from "./handler.js";
30
+ import { createEventLog, watchRun } from "./events.js";
31
+ import { corsHeaders, isForeign, json, KEYS_PATH, STUDIO_BASE, } from "./handler.js";
30
32
  import { answerOpen, chosenEditor, defaultEditor } from "./open-editor.js";
31
33
  import { PROJECT_READY } from "./project.js";
32
- import { isInside } from "./project-source.js";
34
+ import { entryOf, isInside } from "./project-source.js";
33
35
  import { answerSave, createSaveSession, isSaveRequest } from "./save-session.js";
34
36
  import { createWatchFeed, watchFiles } from "./watch.js";
35
37
  function flag(name, fallback) {
@@ -38,7 +40,7 @@ function flag(name, fallback) {
38
40
  }
39
41
  const setupPath = Deno.args.find((arg, i) => !arg.startsWith('--') && !Deno.args[i - 1]?.startsWith('--'));
40
42
  if (!setupPath) {
41
- console.error('usage: studio/server/serve.ts <setup-module> [--port 4983] [--page http://localhost:5174] [--deno-config deno.json] [--editor code] [--no-watch]');
43
+ console.error('usage: studio/server/serve.ts <setup-module> [--port 4983] [--page http://localhost:5174] [--deno-config deno.json] [--editor code] [--no-watch] [--quiet] [--offline] [--verbose]');
42
44
  Deno.exit(2);
43
45
  }
44
46
  const port = Number(flag('port', '4983'));
@@ -127,10 +129,11 @@ async function stop(loaded) {
127
129
  }
128
130
  await loaded.process.status;
129
131
  }
130
- /** Whether the project type-checks as it is on disk, and what the checker printed. */
132
+ /** Whether the project type-checks as it is on disk, from the setup and the entry it names, and what the checker printed. */
131
133
  async function typeChecks() {
134
+ const entry = entryOf(setupFile);
132
135
  const { success, stderr, stdout } = await new Deno.Command(Deno.execPath(), {
133
- args: ['check', ...configArgs, setupFile],
136
+ args: ['check', ...configArgs, setupFile, ...(entry ? [entry] : [])],
134
137
  cwd: root,
135
138
  env: { NO_COLOR: '1' },
136
139
  stdin: 'null',
@@ -205,26 +208,46 @@ const session = createSaveSession({
205
208
  },
206
209
  stop,
207
210
  opened: (loaded) => loaded.description.workspace,
211
+ unopened: (loaded) => loaded.description.problems.map((problem) => problem.profile),
208
212
  }, first);
209
213
  /** Passes a request on to a load of the project, and its answer back as it streams. */
210
214
  async function forward(request, loaded = session.project(), path) {
211
215
  const url = new URL(request.url);
216
+ const to = path ?? url.pathname;
212
217
  if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
213
- return forwardSocket(request, `${loaded.origin}${path ?? url.pathname}${url.search}`);
218
+ return forwardSocket(request, `${loaded.origin}${to}${url.search}`);
214
219
  }
215
220
  const headers = new Headers(request.headers);
216
221
  headers.delete('host');
217
- const body = request.method === 'GET' || request.method === 'HEAD' ? undefined : await request.arrayBuffer();
222
+ let response;
218
223
  try {
219
- return await fetch(`${loaded.origin}${path ?? url.pathname}${url.search}`, {
224
+ response = await fetch(`${loaded.origin}${to}${url.search}`, {
220
225
  method: request.method,
221
226
  headers,
222
- body,
227
+ body: await bodyOf(request),
223
228
  });
224
229
  }
225
230
  catch {
226
231
  return json(502, {}, corsHeaders(request, pageOrigins));
227
232
  }
233
+ return request.method === 'OPTIONS' ? response : watchedRun(request.method, to, response);
234
+ }
235
+ /** What a request carries on: nothing for a read. */
236
+ async function bodyOf(request) {
237
+ return request.method === 'GET' || request.method === 'HEAD'
238
+ ? undefined
239
+ : await request.arrayBuffer();
240
+ }
241
+ /** A run's answer, watched for a failure to tell the terminal of; any other answer as it is. */
242
+ function watchedRun(method, to, response) {
243
+ const profile = to.startsWith(PROFILES)
244
+ ? decodeURIComponent(to.slice(PROFILES.length).split('/')[0] ?? '')
245
+ : undefined;
246
+ if (profile === undefined)
247
+ return response;
248
+ if (verbose)
249
+ console.error(`theorem studio: run ${profile} ${method} ${to.slice(PROFILES.length + profile.length) || '/'} → ${response.status}`);
250
+ return watchRun(response, (said) => tell('run', `run ${profile} failed: ${said}`));
228
251
  }
229
252
  /**
230
253
  * Joins the page's socket to the same path of the project: a voice call. What the page sends
@@ -259,6 +282,10 @@ function forwardSocket(request, to) {
259
282
  project.addEventListener('error', shut(page));
260
283
  return response;
261
284
  }
285
+ /** Where the project serves each profile's runs. */
286
+ const PROFILES = `${STUDIO_BASE}/profiles/`;
287
+ const EVENTS = `${STUDIO_BASE}/events`;
288
+ const STATUS = `${STUDIO_BASE}/status`;
262
289
  const SAVE = `${STUDIO_BASE}/save`;
263
290
  const WATCH = `${STUDIO_BASE}/watch`;
264
291
  const OPEN = `${STUDIO_BASE}/open`;
@@ -312,12 +339,50 @@ const editor = {
312
339
  */
313
340
  async function described(said) {
314
341
  const files = await session.read(said);
315
- return {
342
+ const description = {
316
343
  ...session.project().description,
317
344
  ...files,
318
345
  editor: defaultEditor(editor),
319
346
  setup: relative(root, setupFile),
320
347
  };
348
+ tellTerminal(description);
349
+ return description;
350
+ }
351
+ /** Whether the command was started without printing anything about the project. */
352
+ const quiet = Deno.args.includes('--quiet');
353
+ /** Whether the command also prints each run as it ends, not only the ones that fail. */
354
+ const verbose = Deno.args.includes('--verbose');
355
+ /** Whether the command was started without asking each provider whether its key works. */
356
+ const offline = Deno.args.includes('--offline');
357
+ /** What the key checks said: none until they answer. */
358
+ let keysSaid;
359
+ /** The entry the setup names, from the folder the command ran in. */
360
+ function entryAt() {
361
+ const entry = entryOf(setupFile);
362
+ return entry ? { entry: relative(root, entry) } : {};
363
+ }
364
+ /** What happened that the builder should know of, for `theorem-studio errors` to read. */
365
+ const events = createEventLog();
366
+ /** What was printed last: `null` before the first print, so a clean project still says so. */
367
+ let told = null;
368
+ /** Keeps an event and prints it, unless it repeats the last one or the command is quiet. */
369
+ function tell(kind, text) {
370
+ if (events.add(kind, text) && !quiet)
371
+ console.error(`theorem studio: ${text}`);
372
+ }
373
+ /** Prints what the builder should look at when it is not what was printed last. */
374
+ function tellTerminal(description) {
375
+ const text = alertText(description);
376
+ if (text === told)
377
+ return;
378
+ const first = told === null;
379
+ told = text;
380
+ const said = text ?? `theorem studio: nothing ${first ? '' : 'left '}to look at`;
381
+ // why: a project that opens clean has nothing to keep; one that comes clean later does.
382
+ if (!(first && text === undefined))
383
+ events.add('look', said);
384
+ if (!quiet)
385
+ console.error(said);
321
386
  }
322
387
  /** Whether the request asks for the project as the page opens it, and whether for the steps of reading it first. */
323
388
  function opens(request) {
@@ -371,6 +436,60 @@ function watching(request) {
371
436
  const cors = corsHeaders(request, pageOrigins);
372
437
  return feed ? feed.subscribe(cors) : new Response(null, { status: 204, headers: cors });
373
438
  }
439
+ /**
440
+ * `GET <base>/status`: what the command printed when the project opened, as it is now: what
441
+ * loaded, what the keys said, and what to look at. Plain text, for `theorem-studio status`.
442
+ */
443
+ async function answerStatus(request) {
444
+ if (request.method !== 'GET' || new URL(request.url).pathname !== STATUS)
445
+ return undefined;
446
+ // why: the files are read again, so status agrees with them even when no page has asked since.
447
+ const description = await described();
448
+ const keys = offline ? 'offline' : (keysSaid ?? 'checking');
449
+ const look = alertText(description) ?? 'theorem studio: nothing to look at';
450
+ return new Response(`${loadedText(description, { ...entryAt(), keys })}\n${look}\n`, {
451
+ headers: { 'content-type': 'text/plain; charset=utf-8', ...corsHeaders(request, pageOrigins) },
452
+ });
453
+ }
454
+ /** The longest error the page may send. */
455
+ const PAGE_ERROR_BYTES = 8000;
456
+ /**
457
+ * The event log: `GET` lists it, `GET ?follow` streams it, and the page `POST`s `{ text }` for an
458
+ * error it met, which the log keeps as the page's.
459
+ */
460
+ async function answerEvents(request) {
461
+ const url = new URL(request.url);
462
+ if (url.pathname !== EVENTS)
463
+ return undefined;
464
+ const cors = corsHeaders(request, pageOrigins);
465
+ if (request.method === 'OPTIONS')
466
+ return new Response(null, { status: 204, headers: cors });
467
+ if (request.method === 'GET') {
468
+ return url.searchParams.has('follow') ? events.follow(cors) : json(200, events.list(), cors);
469
+ }
470
+ return request.method === 'POST' ? await keepPageError(request, cors) : json(405, {}, cors);
471
+ }
472
+ /** Keeps the error a page `POST`s as `{ text }`. */
473
+ async function keepPageError(request, cors) {
474
+ const sent = await request.text();
475
+ if (sent.length > PAGE_ERROR_BYTES)
476
+ return json(413, {}, cors);
477
+ const text = pageError(sent);
478
+ if (!text)
479
+ return json(400, {}, cors);
480
+ tell('page', `the page: ${text}`);
481
+ return json(200, {}, cors);
482
+ }
483
+ /** The error a page sent as `{ text }`, trimmed; nothing when it sent no text. */
484
+ function pageError(sent) {
485
+ try {
486
+ const { text } = JSON.parse(sent);
487
+ return typeof text === 'string' ? text.trim() || undefined : undefined;
488
+ }
489
+ catch {
490
+ return undefined;
491
+ }
492
+ }
374
493
  /** The setup this studio is open on, for a second studio command to find it already running. */
375
494
  function running(request) {
376
495
  if (request.method !== 'GET' || new URL(request.url).pathname !== RUNNING_PATH)
@@ -387,15 +506,25 @@ async function answered(request) {
387
506
  const cors = corsHeaders(request, pageOrigins);
388
507
  return 'workspace' in answer ? json(200, answer, cors) : json(answer.status, answer.body, cors);
389
508
  }
390
- Deno.serve({ hostname: '127.0.0.1', port }, async (request) => {
509
+ /** The studio's own routes, in the order they are asked; a request none answers goes to the project. */
510
+ const ROUTES = [
511
+ running,
512
+ watching,
513
+ openedSaying,
514
+ answerStatus,
515
+ answerEvents,
516
+ answered,
517
+ answerEdited,
518
+ ];
519
+ Deno.serve({ hostname: '127.0.0.1', port, onListen: () => { } }, async (request) => {
391
520
  if (isForeign(request, gate))
392
521
  return json(403, {}, {});
393
- return (running(request) ??
394
- watching(request) ??
395
- openedSaying(request) ??
396
- (await answered(request)) ??
397
- (await answerEdited(request)) ??
398
- forward(request));
522
+ for (const route of ROUTES) {
523
+ const response = await route(request);
524
+ if (response)
525
+ return response;
526
+ }
527
+ return forward(request);
399
528
  });
400
529
  for (const signal of ['SIGINT', 'SIGTERM']) {
401
530
  Deno.addSignalListener(signal, () => {
@@ -411,3 +540,30 @@ for (const signal of ['SIGINT', 'SIGTERM']) {
411
540
  });
412
541
  }
413
542
  console.log(`Theorem Studio: open ${pageOrigins[0]}/studio (server on http://127.0.0.1:${port})`);
543
+ if (!quiet) {
544
+ console.error(loadedText({ ...first.description, setup: relative(root, setupFile) }, { ...entryAt(), keys: offline ? 'offline' : 'checking' }));
545
+ }
546
+ // The project is read once now, so what it has to look at reaches the terminal before the page opens.
547
+ await described().catch((error) => console.error(error instanceof Error ? error.message : error));
548
+ // One request for each provider's key, once: the keys are read as the project loads.
549
+ if (!offline) {
550
+ fetch(session.project().origin + KEYS_PATH)
551
+ .then((response) => response.json())
552
+ .then((checks) => {
553
+ keysSaid = checks.map(keyLine);
554
+ for (const [at, check] of checks.entries()) {
555
+ const line = keysSaid[at] ?? '';
556
+ // A key that works is said once, here, and is not kept as something that went wrong.
557
+ if (check.state === 'accepted') {
558
+ if (!quiet)
559
+ console.error(`theorem studio: ${line}`);
560
+ }
561
+ else
562
+ tell('key', line);
563
+ }
564
+ })
565
+ .catch((error) => {
566
+ keysSaid = [`not checked: ${error}`];
567
+ tell('key', `the keys were not checked: ${error}`);
568
+ });
569
+ }
@@ -1,2 +1,19 @@
1
- /** `POST <base>/test-key` `{ key }`. */
2
- export declare function testKey(request: Request): Promise<Response>;
1
+ /**
2
+ * Asks a key's provider whether it accepts the key, with the check the provider's definition
3
+ * declares, so the builder can tell a bad key from a bad setting. The key is used for this one
4
+ * request: never logged, kept, or echoed back.
5
+ *
6
+ * @module
7
+ */
8
+ import { type ResolveHost } from '@theoremjs/agents';
9
+ import { type RegisteredProvider } from '@theoremjs/agents/kernel';
10
+ export interface TestKeyOptions {
11
+ /** A provider the project registers from a definition of its own, by id. */
12
+ projectProvider?: (id: string) => RegisteredProvider | undefined;
13
+ /** Resolves the provider's host, so a check from a shared server reaches public addresses only. */
14
+ resolveHost?: ResolveHost;
15
+ /** The server is the builder's alone: the check reaches whatever the provider names. */
16
+ draftNetwork?: boolean;
17
+ }
18
+ /** `POST <base>/test-key` `{ key, provider }`: a `KeyCheck`. */
19
+ export declare function testKey(request: Request, options?: TestKeyOptions): Promise<Response>;
@@ -1,83 +1,60 @@
1
1
  /**
2
- * Asks a key's provider whether it accepts the key, so the builder can tell a bad key
3
- * from a bad setting. The key is used for this one request: never logged, kept, or echoed back.
2
+ * Asks a key's provider whether it accepts the key, with the check the provider's definition
3
+ * declares, so the builder can tell a bad key from a bad setting. The key is used for this one
4
+ * request: never logged, kept, or echoed back.
5
+ *
6
+ * @module
4
7
  */
5
- import { z } from '@theoremjs/agents';
8
+ import { checkKey, fetchGuarded, z } from '@theoremjs/agents';
9
+ import { clientError } from '@theoremjs/agents/host';
10
+ import { createProviderRegistry } from '@theoremjs/agents/kernel';
6
11
  import { readBody } from '@theoremjs/web/server';
7
- const TIMEOUT_MS = 8000;
12
+ import { kernelDefinition, registerStudioProvider } from "../providers.js";
8
13
  const MAX_KEY_LENGTH = 512;
9
- const SAID_CAP = 300;
10
- const PROVIDERS = [
11
- {
12
- provider: 'google',
13
- matches: (key) => key.startsWith('AIza'),
14
- request: (key) => new Request('https://generativelanguage.googleapis.com/v1beta/models?pageSize=1', {
15
- headers: { 'x-goog-api-key': key },
16
- }),
17
- },
18
- {
19
- provider: 'openrouter',
20
- matches: (key) => key.startsWith('sk-or-'),
21
- request: (key) => new Request('https://openrouter.ai/api/v1/key', {
22
- headers: { Authorization: `Bearer ${key}` },
23
- }),
24
- },
25
- ];
26
- /** The provider's own error message, if it sent one, without the key. */
27
- async function providerSaid(response, key) {
14
+ const slotName = z.string().min(1).max(128);
15
+ /** What the page sends: the key, and the provider a model reading its slot is served by. */
16
+ const testKeySchema = z
17
+ .object({
18
+ key: z.string().max(MAX_KEY_LENGTH),
19
+ provider: z
20
+ .object({
21
+ id: z.string().min(1).max(128),
22
+ definition: z.string().min(1).max(128),
23
+ connection: z.record(z.string(), z.string().max(2048)).optional(),
24
+ keySlot: slotName.optional(),
25
+ fallbackKeySlot: slotName.optional(),
26
+ })
27
+ .strict(),
28
+ })
29
+ .strict();
30
+ /** `POST <base>/test-key` `{ key, provider }`: a `KeyCheck`. */
31
+ export async function testKey(request, options = {}) {
32
+ let asked;
28
33
  try {
29
- const body = await response.json();
30
- const error = body?.error;
31
- const first = Array.isArray(error) ? error[0] : error;
32
- const message = first?.message;
33
- if (typeof message !== 'string')
34
- return undefined;
35
- return message.replaceAll(key, '[the key]').slice(0, SAID_CAP);
34
+ asked = await readBody(request, testKeySchema);
36
35
  }
37
- catch {
38
- return undefined;
39
- }
40
- }
41
- /** `POST <base>/test-key` `{ key }`. */
42
- export async function testKey(request) {
43
- if (request.method !== 'POST')
44
- return new Response(null, { status: 405 });
45
- let key = '';
46
- try {
47
- const body = await readBody(request, z.unknown());
48
- const value = body?.key;
49
- key = typeof value === 'string' ? value.trim() : '';
50
- }
51
- catch {
52
- return Response.json({ ok: false, error: 'Send { key }.' }, { status: 400 });
53
- }
54
- if (!key || key.length > MAX_KEY_LENGTH) {
55
- return Response.json({ ok: false, error: 'No key to test.' }, {
56
- status: 400,
57
- });
58
- }
59
- const match = PROVIDERS.find((candidate) => candidate.matches(key));
60
- if (!match) {
61
- return Response.json({
62
- ok: false,
63
- error: 'Only Google (AIza…) and OpenRouter (sk-or-…) keys can be tested here.',
64
- });
36
+ catch (error) {
37
+ return Response.json(clientError(error), { status: 400 });
65
38
  }
39
+ let provider;
66
40
  try {
67
- const response = await fetch(match.request(key), { signal: AbortSignal.timeout(TIMEOUT_MS) });
68
- const result = {
69
- ok: response.ok,
70
- provider: match.provider,
71
- status: response.status,
72
- ...(response.ok ? {} : { said: await providerSaid(response, key) }),
73
- };
74
- return Response.json(result);
75
- }
76
- catch {
77
- return Response.json({
78
- ok: false,
79
- provider: match.provider,
80
- error: `Couldn't reach ${match.provider}.`,
81
- });
82
- }
41
+ const definition = kernelDefinition(asked.provider.definition);
42
+ provider = definition
43
+ ? registerStudioProvider(createProviderRegistry(), asked.provider, definition)
44
+ : options.projectProvider?.(asked.provider.id);
45
+ }
46
+ catch (error) {
47
+ return Response.json(clientError(error), { status: 400 });
48
+ }
49
+ if (!provider)
50
+ return Response.json({ provider: asked.provider.id, state: 'unchecked' });
51
+ const { resolveHost } = options;
52
+ const guarded = (url, init) => fetchGuarded(String(url), { headers: init?.headers, signal: init?.signal }, {
53
+ followRedirects: false,
54
+ ...(resolveHost ? { resolveHost } : {}),
55
+ });
56
+ return Response.json(await checkKey(provider, {
57
+ key: asked.key,
58
+ ...(options.draftNetwork ? {} : { fetch: guarded }),
59
+ }));
83
60
  }
package/server/watch.d.ts CHANGED
@@ -21,6 +21,14 @@ export interface FileWatchOptions {
21
21
  export declare function watchFiles(options: FileWatchOptions): {
22
22
  stop(): void;
23
23
  };
24
+ /**
25
+ * Subscriptions to a stream of values, as server-sent events: each value a line of JSON. A new
26
+ * subscription is sent `first()` before anything new.
27
+ */
28
+ export declare function createEventFeed<T>(): {
29
+ tell(value: T): void;
30
+ subscribe(headers: Record<string, string>, first?: readonly T[]): Response;
31
+ };
24
32
  /** The page's subscriptions to file changes, as server-sent events. */
25
33
  export declare function createWatchFeed(): {
26
34
  tell(files: string[]): void;