@theoremjs/studio 0.3.4-next.649.gf83cea1 → 0.3.4-next.673.ga492632

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 (92) hide show
  1. package/README.md +8 -5
  2. package/cookbooks/catalog.js +18 -5
  3. package/cookbooks/tools.js +3 -3
  4. package/mod.d.ts +3 -3
  5. package/mod.js +3 -3
  6. package/package.json +4 -4
  7. package/page/assets/Banner-BxvBuYgz.js +4 -0
  8. package/page/assets/{ConsoleFrame-B7ruuMVo.js → ConsoleFrame-_YA1HkXX.js} +1 -1
  9. package/page/assets/{MenuBottomSheet-Bso4osRe.js → MenuBottomSheet-BbniF3mM.js} +1 -1
  10. package/page/assets/{SchemaFields-DEqlS2cS.js → SchemaFields-Bg4OxBw3.js} +1 -1
  11. package/page/assets/{ToolResultCharts-DV0Cds5H.js → ToolResultCharts-PhjAbSXq.js} +1 -1
  12. package/page/assets/{TraceInspector-CBybmNzh.js → TraceInspector-fiuM6pWK.js} +1 -1
  13. package/page/assets/{TraceOverview-CO9Oh2_v.js → TraceOverview-BzerB7QI.js} +1 -1
  14. package/page/assets/{_virtual_studio-type-sources-hU0nQlME.js → _virtual_studio-type-sources-BwSqfSwd.js} +17 -3
  15. package/page/assets/{browser-connection-Dim6ghw7.js → browser-connection-DSUHVCT5.js} +2 -2
  16. package/page/assets/browser-engine-SBozuru0.js +11 -0
  17. package/page/assets/browser-transport-BHWgtIIH.js +45 -0
  18. package/page/assets/{crypto-CgKfdKF3.js → crypto-CD14HeXH.js} +1 -1
  19. package/page/assets/{encode-files-mmy8V0Ya.js → encode-files-DhoC5hWG.js} +1 -1
  20. package/page/assets/{export-agent-CuUh1bR8.js → export-agent-GKC4g6Ei.js} +1 -1
  21. package/page/assets/{guardrail-tester-Bi8kF5JO.js → guardrail-tester-HDwGIn2U.js} +1 -1
  22. package/page/assets/index-Xice1eg1.js +145 -0
  23. package/page/assets/{live-messages-MuPbOsZr.js → live-messages-CiLmR89m.js} +1 -1
  24. package/page/assets/reader-DrOfMM8I.js +5 -0
  25. package/page/assets/{shaped-data-BIkh6Bis.js → shaped-data-H1miOZm2.js} +1 -1
  26. package/page/assets/{stub-fr8Q8_U3.js → stub-nxRsh1jo.js} +4 -4
  27. package/page/assets/{studio-code-pane-DnKDFRIG.js → studio-code-pane-DPxkcxON.js} +3 -3
  28. package/page/assets/{studio-console-C8I1MOzW.js → studio-console-CdUQW84-.js} +1 -1
  29. package/page/assets/{studio-decision-wzSt60HL.js → studio-decision-B9Zvbyst.js} +1 -1
  30. package/page/assets/{studio-embedding-DOOXOgyT.js → studio-embedding-Ds3gGEie.js} +1 -1
  31. package/page/assets/{studio-host-console-Dz8tEAST.js → studio-host-console-Bqya7q0s.js} +2 -2
  32. package/page/assets/{studio-labels-C5heV8lN.js → studio-labels-D1VY2Jy8.js} +1 -1
  33. package/page/assets/studio-live-Ccx0NJuI.js +5 -0
  34. package/page/assets/{studio-map-DzrF-FCH.js → studio-map-B4_FRhhr.js} +1 -1
  35. package/page/assets/studio-session-CjUQSXx0.js +1 -0
  36. package/page/assets/studio-trace-replay-DXW5DXpK.js +3 -0
  37. package/page/assets/{studio-type-checker-DCAG9kT0.js → studio-type-checker-BbUSqqOS.js} +1 -1
  38. package/page/assets/tool-schema-BmRYaywn.js +17 -0
  39. package/page/assets/{trace-record-CGww68wU.js → trace-record-DxgSKmYY.js} +1 -1
  40. package/page/assets/tree-3N-1RPZz.js +3 -0
  41. package/page/assets/{turn-client-Bn130DZC.js → turn-client-DN8PawJr.js} +2 -2
  42. package/page/assets/{use-one-call-B_dBxZ07.js → use-one-call-mxMqUe5Q.js} +1 -1
  43. package/page/assets/{use-second-ticker-DtnVtLQo.js → use-second-ticker-CEwOSS-d.js} +1 -1
  44. package/page/assets/{workspace-Cy2likdd.js → workspace-CTSW941G.js} +1 -1
  45. package/page/index.html +16 -16
  46. package/replay.d.ts +13 -8
  47. package/replay.js +33 -31
  48. package/run-payload.d.ts +20 -6
  49. package/run-payload.js +85 -13
  50. package/runtime-scope.js +1 -0
  51. package/runtime.js +1 -0
  52. package/server/project.js +5 -32
  53. package/transport.d.ts +1 -3
  54. package/transport.js +0 -9
  55. package/ui/lib/acting-as.js +1 -6
  56. package/ui/lib/run-keys.d.ts +15 -5
  57. package/ui/lib/run-keys.js +80 -16
  58. package/ui/lib/studio-conversation.d.ts +2 -3
  59. package/ui/lib/studio-conversation.js +28 -65
  60. package/ui/lib/studio-keep.d.ts +34 -0
  61. package/ui/lib/studio-keep.js +202 -0
  62. package/ui/lib/studio-map-kept.d.ts +2 -2
  63. package/ui/lib/studio-map-kept.js +5 -10
  64. package/ui/lib/studio-open.d.ts +1 -1
  65. package/ui/lib/studio-open.js +5 -5
  66. package/ui/lib/studio-page.js +1 -7
  67. package/ui/lib/studio-restore.d.ts +2 -3
  68. package/ui/lib/studio-restore.js +8 -48
  69. package/ui/lib/studio-run-open.d.ts +10 -5
  70. package/ui/lib/studio-run-open.js +18 -9
  71. package/ui/lib/studio-session.d.ts +38 -5
  72. package/ui/lib/studio-session.js +133 -3
  73. package/ui/lib/studio-store.js +8 -30
  74. package/ui/profile-editor.js +3 -6
  75. package/ui/studio-compare.js +266 -49
  76. package/ui/studio-run.js +29 -15
  77. package/ui/studio-screen.d.ts +1 -1
  78. package/ui/studio-screen.js +8 -9
  79. package/ui/studio-trace-replay.js +39 -14
  80. package/vite.mjs +1 -1
  81. package/page/assets/Banner-DnfOgQq4.js +0 -4
  82. package/page/assets/browser-engine-BQs_4RXH.js +0 -11
  83. package/page/assets/browser-transport-K6LWGuCA.js +0 -45
  84. package/page/assets/index-8zuMVtQh.js +0 -145
  85. package/page/assets/reader-YWCb-VWE.js +0 -5
  86. package/page/assets/studio-live-ed1SR-Py.js +0 -5
  87. package/page/assets/studio-session-yEqFQo5o.js +0 -1
  88. package/page/assets/studio-trace-replay-WLO52a22.js +0 -3
  89. package/page/assets/tool-schema-BJnLgvo3.js +0 -17
  90. package/page/assets/tree-CvHjrQ-G.js +0 -3
  91. package/run-payload-core.d.ts +0 -28
  92. package/run-payload-core.js +0 -117
@@ -1,13 +1,10 @@
1
1
  /**
2
- * Reading the studio's workspace back from this tab's sessionStorage. A kept workspace that no
3
- * longer fits the current shape is set aside, and a draft kept by the one-agent studio opens as
4
- * a workspace holding it.
2
+ * Reading the studio's workspace back from this tab's records. A kept workspace that no longer
3
+ * fits the current shape is set aside.
5
4
  */
6
- import { agentDraft, createBlankDraft, editedSince, STUDIO_WORKSPACE_VERSION, workspaceFromDraft, } from "../../mod.js";
5
+ import { agentDraft, createBlankDraft, editedSince, STUDIO_WORKSPACE_VERSION, } from "../../mod.js";
7
6
  import { CHAT_PREFIX, isRecord, session, WORKSPACE_KEY, } from "./studio-session.js";
8
7
  import { keptTool, keptWorkspace } from "./studio-store.js";
9
- const V1_DRAFT_KEY = 'theorem.studio.v1';
10
- const V1_CHAT_KEY = 'theorem.studio.v1.chat';
11
8
  /**
12
9
  * True when `value` has every section `shape` has, all the way down, and lists, text and
13
10
  * switches where it has them. A draft kept before the draft changed shape fails it, so it is
@@ -55,14 +52,6 @@ function isStoredWorkspace(value) {
55
52
  isWorkspace(value.workspace) &&
56
53
  typeof value.revision === 'number');
57
54
  }
58
- /** A one-agent draft kept before workspaces, as the studio kept it. */
59
- function isV1Draft(value) {
60
- return (isRecord(value) &&
61
- value.v === 1 &&
62
- hasShapeOf(value.draft, createBlankDraft()) &&
63
- typeof value.revision === 'number' &&
64
- typeof value.selectedId === 'string');
65
- }
66
55
  function parsed(store, key) {
67
56
  const raw = store.getItem(key);
68
57
  if (!raw)
@@ -74,24 +63,9 @@ function parsed(store, key) {
74
63
  return null;
75
64
  }
76
65
  }
77
- /**
78
- * A one-agent draft from before workspaces, as a workspace holding it. Its conversation was kept
79
- * whole, before conversations were sealed, so nothing can resume it. Either way the old keys go.
80
- */
81
- function migrateV1(store) {
82
- const kept = parsed(store, V1_DRAFT_KEY);
83
- if (kept === undefined)
84
- return undefined;
85
- store.removeItem(V1_DRAFT_KEY);
86
- store.removeItem(V1_CHAT_KEY);
87
- if (!isV1Draft(kept))
88
- return 'discarded';
89
- const workspace = workspaceFromDraft(kept.draft, kept.selectedId);
90
- return { workspace, revision: kept.revision };
91
- }
92
66
  function forgetAll(store) {
93
67
  store.removeItem(WORKSPACE_KEY);
94
- for (const key of Object.keys(store)) {
68
+ for (const key of store.keys()) {
95
69
  if (key.startsWith(CHAT_PREFIX))
96
70
  store.removeItem(key);
97
71
  }
@@ -105,12 +79,8 @@ export function restoreStudio() {
105
79
  if (!store)
106
80
  return { kind: 'none' };
107
81
  const kept = parsed(store, WORKSPACE_KEY);
108
- if (kept === undefined) {
109
- const migrated = migrateV1(store);
110
- if (migrated === 'discarded')
111
- return { kind: 'discarded' };
112
- return migrated ? { kind: 'restored', value: migrated } : { kind: 'none' };
113
- }
82
+ if (kept === undefined)
83
+ return { kind: 'none' };
114
84
  if (isStoredWorkspace(kept)) {
115
85
  const { workspace, revision } = kept;
116
86
  return { kind: 'restored', value: { workspace, revision } };
@@ -164,12 +134,7 @@ export function setAside(key, edits) {
164
134
  workspace: keptWorkspace(edits),
165
135
  revision: 0,
166
136
  };
167
- try {
168
- session()?.setItem(asideKey(key), JSON.stringify(record));
169
- }
170
- catch {
171
- // Quota or a blocked store: the offer on the page still holds the edits.
172
- }
137
+ session()?.setItem(asideKey(key), JSON.stringify(record));
173
138
  }
174
139
  /** Forgets a project's set-aside edits: the builder brought them back or let them go. */
175
140
  export function dropAside(key) {
@@ -199,12 +164,7 @@ export function keepReading(key, print, read) {
199
164
  revision: 0,
200
165
  files: print,
201
166
  };
202
- try {
203
- session()?.setItem(readingKey(key), JSON.stringify(record));
204
- }
205
- catch {
206
- // Quota or a blocked store: a profile removed here comes back after a reload.
207
- }
167
+ session()?.setItem(readingKey(key), JSON.stringify(record));
208
168
  }
209
169
  /** The files as the studio read them when they printed as `print`, if this tab kept that reading. */
210
170
  export function keptReading(key, print) {
@@ -1,15 +1,20 @@
1
1
  import { type StudioRunPayload } from '../../mod.ts';
2
2
  import { type ProjectSession } from './studio-project.ts';
3
- /** What a run tab opens on: the compiled agent, and the project it belongs to if it has one. */
3
+ /**
4
+ * What a run tab opens on: the compiled agent, and the project it belongs to if it has one.
5
+ * `masked` when its tools' credentials were masked to keep it, so it asks the studio tab for them.
6
+ */
4
7
  export type StudioRunOpened = {
5
8
  payload: StudioRunPayload;
9
+ masked: boolean;
6
10
  project: ProjectSession | null;
7
11
  };
8
12
  /**
9
- * What the run tab at `url` opens on, or `null` when its agent is gone. The compiled agent is kept
10
- * in this browser's storage under the id in the address, so this runs in the browser. `project`
11
- * says whether this host can have a project open; without it, the address's project is ignored.
13
+ * What the run tab at `url` opens on, or `null` when its agent is gone or this package no longer
14
+ * defines it. The studio tab hands the compiled agent to this tab through the browser's keep,
15
+ * under the id in the address, so this runs in the browser. `project` says whether this host can
16
+ * have a project open; without it, the address's project is ignored.
12
17
  */
13
18
  export declare function openStudioRun(url: string, options: {
14
19
  project: boolean;
15
- }): StudioRunOpened | null;
20
+ }): Promise<StudioRunOpened | null>;
@@ -1,16 +1,25 @@
1
- import { clearStaleStudioRuns, loadStudioRunPayload, readStudioRunIdFromUrl, } from "../../mod.js";
1
+ import { keptStudioRun, readStudioRunIdFromUrl, studioRunDefines, } from "../../mod.js";
2
2
  import { projectSession } from "./studio-project.js";
3
+ import { isRecord, takeRun } from "./studio-session.js";
3
4
  /**
4
- * What the run tab at `url` opens on, or `null` when its agent is gone. The compiled agent is kept
5
- * in this browser's storage under the id in the address, so this runs in the browser. `project`
6
- * says whether this host can have a project open; without it, the address's project is ignored.
5
+ * What the run tab at `url` opens on, or `null` when its agent is gone or this package no longer
6
+ * defines it. The studio tab hands the compiled agent to this tab through the browser's keep,
7
+ * under the id in the address, so this runs in the browser. `project` says whether this host can
8
+ * have a project open; without it, the address's project is ignored.
7
9
  */
8
- export function openStudioRun(url, options) {
9
- clearStaleStudioRuns();
10
+ export async function openStudioRun(url, options) {
10
11
  const runId = readStudioRunIdFromUrl(url);
11
- const payload = runId ? loadStudioRunPayload(runId) : null;
12
- if (!payload)
12
+ const kept = runId ? await takeRun(runId) : undefined;
13
+ let record;
14
+ try {
15
+ record = kept === undefined ? undefined : JSON.parse(kept);
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ const payload = isRecord(record) ? keptStudioRun(record.payload) : null;
21
+ if (!isRecord(record) || !payload || !studioRunDefines(payload))
13
22
  return null;
14
23
  const name = options.project ? new URL(url).searchParams.get('project') : null;
15
- return { payload, project: name ? projectSession(name) : null };
24
+ return { payload, masked: record.masked === true, project: name ? projectSession(name) : null };
16
25
  }
@@ -1,8 +1,11 @@
1
1
  /**
2
- * Where the studio keeps itself: this tab's sessionStorage, under the keys and in the record
3
- * shape the workspace store, its restore, and the kept conversations share.
2
+ * Where the studio keeps itself: this tab's records in the browser's keep (see `studio-keep.ts`),
3
+ * under the keys and in the record shape the workspace store, its restore, and the kept
4
+ * conversations share. The tab's id waits in its sessionStorage, so a reload finds its records,
5
+ * and a duplicated tab starts with a copy of them.
4
6
  */
5
7
  import type { STUDIO_WORKSPACE_VERSION, StudioWorkspace } from '../../mod.ts';
8
+ import { type Keep } from './studio-keep.ts';
6
9
  export declare const WORKSPACE_KEY = "theorem.studio.v2";
7
10
  /** A project's workspace is kept under its own name, apart from the website's and other projects'. */
8
11
  export declare const projectKey: (name: string) => string;
@@ -21,7 +24,7 @@ export interface RestoredStudio {
21
24
  files: string;
22
25
  };
23
26
  }
24
- /** What sessionStorage holds. */
27
+ /** What the tab keeps for a workspace. */
25
28
  export interface StoredWorkspace {
26
29
  v: typeof STUDIO_WORKSPACE_VERSION;
27
30
  workspace: StudioWorkspace;
@@ -29,6 +32,36 @@ export interface StoredWorkspace {
29
32
  /** For a project's workspace: the print of the files its starts stand on. */
30
33
  files?: string;
31
34
  }
32
- /** This tab's sessionStorage, or null where there is none or it is blocked. */
33
- export declare function session(): Storage | null;
35
+ /** This tab's records: read from memory, each change written through to the keep. Never throws. */
36
+ export interface TabStorage {
37
+ getItem(name: string): string | null;
38
+ setItem(name: string, value: string): void;
39
+ removeItem(name: string): void;
40
+ keys(): string[];
41
+ }
42
+ /** The part of the Web Locks API the tab uses. */
43
+ export type TabLocks = Pick<LockManager, 'request' | 'query'>;
44
+ /** This tab's records, once `openTabStorage` has opened them; null before. */
45
+ export declare function session(): TabStorage | null;
34
46
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
47
+ /** This tab's sessionStorage, or null where there is none or it is blocked. */
48
+ export declare function tabSession(): Storage | null;
49
+ /**
50
+ * Opens this tab's records, and clears those of tabs that have closed: now, and each `GONE_MS`
51
+ * while the page is open, so a tab seen closed is cleared at the next sweep. `copy` false opens a run tab, which
52
+ * starts with no copy of the tab that opened it. `keep` and `locks` replace the browser's, as a
53
+ * test does.
54
+ */
55
+ export declare function openTabStorage(options?: {
56
+ copy?: boolean;
57
+ keep?: Keep;
58
+ locks?: TabLocks;
59
+ }): Promise<TabStorage>;
60
+ /** This tab's records, opened once for the page. A run tab opens them with `copy` false. */
61
+ export declare function tabStorage(options?: {
62
+ copy?: boolean;
63
+ }): Promise<TabStorage>;
64
+ /** Keeps a run for the tab it opens in. The tab must have opened its records. */
65
+ export declare function handOffRun(run: string, value: string): void;
66
+ /** The run this tab opens, taken from the tab that handed it off, or kept since it was. */
67
+ export declare function takeRun(run: string): Promise<string | undefined>;
@@ -1,10 +1,25 @@
1
+ import { GONE_MS, indexedDbKeep, memoryKeep } from "./studio-keep.js";
1
2
  export const WORKSPACE_KEY = 'theorem.studio.v2';
2
3
  /** A project's workspace is kept under its own name, apart from the website's and other projects'. */
3
4
  export const projectKey = (name) => `${WORKSPACE_KEY}.project:${name}`;
4
5
  /** One conversation per agent, under this and the agent's key. */
5
6
  export const CHAT_PREFIX = 'theorem.studio.v2.chat:';
6
- /** This tab's sessionStorage, or null where there is none or it is blocked. */
7
+ /** In this tab's sessionStorage: the id its records are kept under. */
8
+ const TAB_ID = 'theorem.studio.tab';
9
+ const TAB_LOCK = 'theorem.studio.tab:';
10
+ /** Held while a tab claims its records and while a sweep runs, so a sweep never sees a tab half open. */
11
+ const SWEEP_LOCK = 'theorem.studio.sweep';
12
+ let open;
13
+ let opening;
14
+ /** This tab's records, once `openTabStorage` has opened them; null before. */
7
15
  export function session() {
16
+ return open?.storage ?? null;
17
+ }
18
+ export function isRecord(value) {
19
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
20
+ }
21
+ /** This tab's sessionStorage, or null where there is none or it is blocked. */
22
+ export function tabSession() {
8
23
  try {
9
24
  return typeof sessionStorage === 'undefined' ? null : sessionStorage;
10
25
  }
@@ -12,6 +27,121 @@ export function session() {
12
27
  return null;
13
28
  }
14
29
  }
15
- export function isRecord(value) {
16
- return typeof value === 'object' && value !== null && !Array.isArray(value);
30
+ /** Holds `name` for as long as the page lives, if no one holds it now. */
31
+ function hold(locks, name) {
32
+ return new Promise((resolve) => {
33
+ void locks.request(name, { ifAvailable: true }, (lock) => {
34
+ resolve(lock !== null);
35
+ return lock ? new Promise(() => { }) : undefined;
36
+ });
37
+ });
38
+ }
39
+ /**
40
+ * The tab's id, and the tab it is a copy of when another open tab holds the id it found. With
41
+ * `copy` false the tab starts with no records: a run tab finds its opener's id, and is not a copy.
42
+ */
43
+ async function tabIdentity(locks, copy) {
44
+ const store = tabSession();
45
+ let found = null;
46
+ try {
47
+ found = store?.getItem(TAB_ID) ?? null;
48
+ }
49
+ catch {
50
+ // A tab that keeps nothing in sessionStorage starts fresh on each load.
51
+ }
52
+ if (found && (!locks || (await hold(locks, `${TAB_LOCK}${found}`))))
53
+ return { id: found };
54
+ const id = crypto.randomUUID();
55
+ if (locks)
56
+ await hold(locks, `${TAB_LOCK}${id}`);
57
+ try {
58
+ store?.setItem(TAB_ID, id);
59
+ }
60
+ catch {
61
+ // As above.
62
+ }
63
+ return found && copy ? { id, from: found } : { id };
64
+ }
65
+ /** Clears the records of tabs that have closed. Runs after the tab opens; nothing waits for it. */
66
+ async function sweepClosed(keep, locks) {
67
+ await locks.request(SWEEP_LOCK, async () => {
68
+ const { held = [] } = await locks.query();
69
+ const alive = new Set(held.flatMap((lock) => lock.name?.startsWith(TAB_LOCK) ? [lock.name.slice(TAB_LOCK.length)] : []));
70
+ await keep.sweep(alive, Date.now());
71
+ });
72
+ }
73
+ /** The browser's keep and locks; a keep in memory where IndexedDB or Web Locks is missing or refused. */
74
+ async function browserKeep() {
75
+ const locks = typeof navigator === 'undefined' ? undefined : navigator.locks;
76
+ if (!locks || typeof indexedDB === 'undefined')
77
+ return { keep: memoryKeep() };
78
+ try {
79
+ return { keep: await indexedDbKeep(), locks };
80
+ }
81
+ catch {
82
+ return { keep: memoryKeep() };
83
+ }
84
+ }
85
+ /**
86
+ * Opens this tab's records, and clears those of tabs that have closed: now, and each `GONE_MS`
87
+ * while the page is open, so a tab seen closed is cleared at the next sweep. `copy` false opens a run tab, which
88
+ * starts with no copy of the tab that opened it. `keep` and `locks` replace the browser's, as a
89
+ * test does.
90
+ */
91
+ export async function openTabStorage(options = {}) {
92
+ const { keep, locks } = options.keep
93
+ ? { keep: options.keep, locks: options.locks }
94
+ : await browserKeep();
95
+ const claim = async () => {
96
+ const { id, from } = await tabIdentity(locks, options.copy ?? true);
97
+ return { id, kept: await keep.claim(id, from) };
98
+ };
99
+ const { id, kept } = locks ? await locks.request(SWEEP_LOCK, claim) : await claim();
100
+ const records = new Map(kept);
101
+ const storage = {
102
+ getItem: (name) => records.get(name) ?? null,
103
+ setItem: (name, value) => {
104
+ records.set(name, value);
105
+ keep.put(id, name, value);
106
+ },
107
+ removeItem: (name) => {
108
+ if (records.delete(name))
109
+ keep.remove(id, name);
110
+ },
111
+ keys: () => [...records.keys()],
112
+ };
113
+ open = { id, keep, records, storage };
114
+ opening = Promise.resolve(storage);
115
+ if (locks) {
116
+ const sweep = () => {
117
+ sweepClosed(keep, locks).catch(() => { });
118
+ };
119
+ sweep();
120
+ setInterval(sweep, GONE_MS);
121
+ }
122
+ return storage;
123
+ }
124
+ /** This tab's records, opened once for the page. A run tab opens them with `copy` false. */
125
+ export function tabStorage(options) {
126
+ opening ??= openTabStorage(options);
127
+ return opening;
128
+ }
129
+ /** Keeps a run for the tab it opens in. The tab must have opened its records. */
130
+ export function handOffRun(run, value) {
131
+ open?.keep.handOff(run, open.id, value);
132
+ }
133
+ const RUN_PREFIX = 'theorem.studio.run:';
134
+ /** The run this tab opens, taken from the tab that handed it off, or kept since it was. */
135
+ export async function takeRun(run) {
136
+ await tabStorage({ copy: false });
137
+ if (!open)
138
+ return undefined;
139
+ const name = `${RUN_PREFIX}${run}`;
140
+ const kept = open.records.get(name);
141
+ if (kept !== undefined)
142
+ return kept;
143
+ const taken = await open.keep.takeRun(run, open.id, name);
144
+ if (taken !== undefined)
145
+ open.records.set(name, taken);
146
+ return taken;
17
147
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The studio's workspace, kept in this tab's sessionStorage so it outlives a reload or a trip
2
+ * The studio's workspace, kept in this tab's records so it outlives a reload or a trip
3
3
  * to the docs and back. Every change bumps a revision, so th30 can tell its own edits from the
4
4
  * visitor's. Keys never come here: the vault stays in memory, and a tool's URLs and headers are kept
5
5
  * with their credentials masked.
@@ -108,7 +108,7 @@ function agentOf(workspace, id) {
108
108
  return id === root || id.startsWith(`${root}/`);
109
109
  })?.key;
110
110
  }
111
- /** Writes the workspace, masked, to sessionStorage. */
111
+ /** Keeps the workspace, masked, in the tab's records. */
112
112
  function writeWorkspace(state) {
113
113
  state.timer = undefined;
114
114
  const record = {
@@ -117,12 +117,7 @@ function writeWorkspace(state) {
117
117
  revision: state.revision,
118
118
  ...(state.files === undefined ? {} : { files: state.files }),
119
119
  };
120
- try {
121
- session()?.setItem(state.slot, JSON.stringify(record));
122
- }
123
- catch {
124
- // Quota or a blocked store: the page keeps working on what is in memory.
125
- }
120
+ session()?.setItem(state.slot, JSON.stringify(record));
126
121
  }
127
122
  /** Queues a write, unless one is already queued. */
128
123
  function scheduleWrite(state) {
@@ -189,24 +184,13 @@ function sharedCarry(state, made) {
189
184
  function isQuiet(state) {
190
185
  if (getPref('askShared') === 'never')
191
186
  return true;
192
- try {
193
- return session()?.getItem(`${state.slot}${QUIET_SUFFIX}`) === '1';
194
- }
195
- catch {
196
- return false;
197
- }
187
+ return session()?.getItem(`${state.slot}${QUIET_SUFFIX}`) === '1';
198
188
  }
199
189
  /** Sets whether shared values are asked about, as Settings does: asking again also ends this tab's "don't ask again". */
200
190
  function setQuiet(state, quiet) {
201
191
  setPref('askShared', quiet ? 'never' : 'always');
202
- if (!quiet) {
203
- try {
204
- session()?.removeItem(`${state.slot}${QUIET_SUFFIX}`);
205
- }
206
- catch {
207
- // Storage is off: nothing was kept to end.
208
- }
209
- }
192
+ if (!quiet)
193
+ session()?.removeItem(`${state.slot}${QUIET_SUFFIX}`);
210
194
  notifyListeners(state);
211
195
  }
212
196
  /** What agreeing to `reach` covers: the places the files write, or the tools. */
@@ -372,14 +356,8 @@ export function createStudioStore(initial, sites, toolSites) {
372
356
  return;
373
357
  for (const key of reachKeys(pending.reach))
374
358
  state.agreed.add(key);
375
- if (quiet) {
376
- try {
377
- session()?.setItem(`${state.slot}${QUIET_SUFFIX}`, '1');
378
- }
379
- catch {
380
- // Storage is full or off: the builder is asked again.
381
- }
382
- }
359
+ if (quiet)
360
+ session()?.setItem(`${state.slot}${QUIET_SUFFIX}`, '1');
383
361
  commitWorkspace(state, pending.carry, pending.by);
384
362
  },
385
363
  /** Whether a change to a shared value is made without asking. */
@@ -27,6 +27,7 @@ import { VStack } from '@astryxdesign/core/VStack';
27
27
  import { IconAbc, IconAdjustmentsHorizontal, IconAlertTriangle, IconAlignLeft, IconAntennaBars1, IconAntennaBars2, IconAntennaBars3, IconAntennaBars4, IconAntennaBars5, IconAntennaBarsOff, IconArrowDown, IconArrowLeft, IconArrowUp, IconBan, IconBandage, IconBiohazard, IconBolt, IconBraces, IconBulb, IconBulbOff, IconCertificate, IconCheck, IconChevronRight, IconCircleDashed, IconDatabase, IconDeviceDesktop, IconEraser, IconEye, IconEyeOff, IconFeather, IconFlag, IconFlame, IconFlask, IconFold, IconGauge, IconHandOff, IconHandStop, IconHeadset, IconHourglass, IconHttpDelete, IconHttpGet, IconHttpPatch, IconHttpPost, IconHttpPut, IconInfoCircle, IconInputAi, IconKey, IconLayersUnion, IconLockOpen, IconLogin, IconMessage, IconMicrophone, IconPackage, IconPaperclip, IconPencil, IconPlayerPause, IconPlayerPlay, IconPlayerStop, IconPlayerTrackNext, IconPlugConnected, IconPlus, IconRefresh, IconRegex, IconRuler, IconSearch, IconSend, IconServer, IconShieldLock, IconShieldOff, IconShieldSearch, IconSquareRoundedNumber0, IconSquareRoundedNumber2, IconTool, IconTrash, IconUser, IconUserCheck, IconWaveSine, IconWriting, IconX, } from '@tabler/icons-react';
28
28
  import { ATTACHMENT_ACCEPT_MIMES, CONTINUE_STOP_KINDS, fieldMeta, HTTP_METHODS, IMAGE_ATTACHMENT_ACCEPT_MIMES, labelDefault, PROFILE_HANDLE_MAX_CHARS, PROFILE_ID_MAX_CHARS, profileGraphFacet, SPEECH_AUDIO_FORMATS, THINKING_LEVELS, VOICE_ACCEPT_MIMES, } from '@theoremjs/agents';
29
29
  import { BOUNDARIES, BOUNDARY_META, DETECT_ACTION_META, DETECT_ACTIONS, DETECTOR_BOUNDARIES, DETECTOR_GROUP_META, DETECTOR_GROUPS, DETECTOR_META, DETECTORS, TOOL_BOUNDARIES, TOOL_KINDS, } from '@theoremjs/agents/guardrails';
30
+ import { MODEL_SELECT_MIN_MODELS } from '@theoremjs/agents/interface';
30
31
  import { createContext, lazy, Suspense, useContext, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, } from 'react';
31
32
  import { acceptSections, agentToolTarget, bindingSlots, COMPACTION_DRAFT_DEFAULTS, canSize, defaultEffortRequired, defaultModelRequired, definitionOf, draftAllows, draftKey, expandAccept, GOOGLE_BUILTIN_TOOLS, GOOGLE_IMAGE_ASPECT_RATIOS, GOOGLE_IMAGE_OUTPUT_MIMES, GOOGLE_IMAGE_RESOLUTIONS, GOOGLE_SPEECH_FORMATS, GOOGLE_SPEECH_VOICES, INLINE_LABELS, includableFacets, includeFacet, inputLimitsRequired, isGoogleRoute, isOpenRouterRoute, keptLimits, kernelDefinitions, LABEL_AREAS, LOCAL_PROVIDER_ID, labelAreaOf, lentCompression, MODEL_LIMITS, modelRoute, modelSlots, newCriteria, newCriterion, newDecisionImage, newDecisionQuestion, newModelBinding, newOwnDetector, newPattern, newSlot, newSlotChoice, newToolSpec, nextAccept, onStudioLocal, optionAt, PROFILE_LABEL_KEYS, plantsCanary, protocolOptionFields, removeModelBinding, STUDIO_TRACE_DESTINATION, sampleToolInput, sectionNote, servedProtocols, servesProfileType, setProfileType, studioNetworkNote, studioNodeRef, studioRunsProvider, studioTaintNote, TIMER_MAX_MS, takesContinueInstruction, toolSpecKeyOf, toolSpecNodeId, updateModelBinding, withOption, writeAsk, } from "../mod.js";
32
33
  import { AddProviderButton } from "./add-provider.js";
@@ -196,9 +197,7 @@ function ModelPolicySection({ draft, type, set, }) {
196
197
  const { models } = draft;
197
198
  return (_jsxs(InspectorSection, { title: "Policy", children: [_jsx(ChoiceRow, { label: "Default", path: "profile.defaultModel", field: "defaultModel", value: models.defaultModel, isRequired: defaultModelRequired(draft), options: draft.modelBindings.map((binding) => binding.modelId), onChange: (defaultModel) => {
198
199
  set({ defaultModel });
199
- } }), _jsx(SwitchRow, { label: "Switching", path: "profile.allowModelSelect", field: "allowModelSelect",
200
- // invariant: as modelSelectEnabled, the picker shows only with two models or more.
201
- value: models.allowModelSelect, isDisabled: draft.modelBindings.length < 2, disabledMessage: "Add a second model to let people switch.", onChange: (allowModelSelect) => {
200
+ } }), _jsx(SwitchRow, { label: "Switching", path: "profile.allowModelSelect", field: "allowModelSelect", value: models.allowModelSelect, isDisabled: draft.modelBindings.length < MODEL_SELECT_MIN_MODELS, disabledMessage: "Add a second model to let people switch.", onChange: (allowModelSelect) => {
202
201
  set({ allowModelSelect });
203
202
  } }), type !== 'embedding' && (_jsxs(_Fragment, { children: [_jsx(SegmentedRow, { label: "Conversation history kept by", path: "providerContinuation.history", field: "providerHistory", value: models.providerHistory ?? 'host', segments: HISTORY_HOLDER_SEGMENTS, onChange: (providerHistory) => {
204
203
  set({ providerHistory });
@@ -866,8 +865,6 @@ function PresetRow({ google, label, path, value, preset, hasSearch, onChange, })
866
865
  /** OpenRouter's image vocabularies; the kernel takes free strings, so these are the studio's. */
867
866
  const OPENROUTER_IMAGE_QUALITIES = ['auto', 'low', 'medium', 'high'];
868
867
  const OPENROUTER_IMAGE_BACKGROUNDS = ['auto', 'transparent', 'opaque'];
869
- /** A pinned file rides in every turn's request, so it stays small. */
870
- const REFERENCE_MAX_BYTES = 4 * 1024 * 1024;
871
868
  /** A picked file's type and its bytes in base64. */
872
869
  async function fileData(file) {
873
870
  const url = await new Promise((resolve, reject) => {
@@ -961,7 +958,7 @@ function ImageReferencesEditor({ references, onChange, }) {
961
958
  replace(reference.key, next);
962
959
  }, onRemove: () => {
963
960
  onChange(references.filter((candidate) => candidate.key !== reference.key));
964
- } }, reference.key))), _jsx(FileInput, { label: "Add images", isLabelHidden: true, mode: "dropzone", accept: "image/*", isMultiple: true, maxSize: REFERENCE_MAX_BYTES, isLoading: reading, placeholder: "Drop images or choose files, up to 4 MB each", value: null, changeAction: changeAction, onChange: () => undefined }), _jsx(Button, { label: "Add link", variant: "ghost", size: "sm", icon: _jsx(Icon, { icon: IconPlus, size: "sm" }), onClick: () => {
961
+ } }, reference.key))), _jsx(FileInput, { label: "Add images", isLabelHidden: true, mode: "dropzone", accept: "image/*", isMultiple: true, isLoading: reading, placeholder: "Drop images or choose files", value: null, changeAction: changeAction, onChange: () => undefined }), _jsx(Button, { label: "Add link", variant: "ghost", size: "sm", icon: _jsx(Icon, { icon: IconPlus, size: "sm" }), onClick: () => {
965
962
  onChange([...references, { key: draftKey('reference'), uri: '' }]);
966
963
  } })] }));
967
964
  }