@theoremjs/studio 0.3.4-next.647.g436b659 → 0.3.4-next.671.gfa09ab2

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 (97) hide show
  1. package/README.md +8 -5
  2. package/cookbooks/catalog.js +18 -5
  3. package/cookbooks/tools.js +3 -3
  4. package/label-areas.d.ts +133 -0
  5. package/label-areas.js +154 -0
  6. package/mod.d.ts +4 -3
  7. package/mod.js +4 -3
  8. package/package.json +4 -4
  9. package/page/assets/Banner-DEVAsFER.js +4 -0
  10. package/page/assets/{ConsoleFrame-B7rArrs0.js → ConsoleFrame-CqUUcrR4.js} +1 -1
  11. package/page/assets/{MenuBottomSheet-CRiCEOWg.js → MenuBottomSheet-DOa09vl1.js} +1 -1
  12. package/page/assets/{SchemaFields-BoySuRuC.js → SchemaFields-CMwMU1Px.js} +1 -1
  13. package/page/assets/{ToolResultCharts-C_qojgbn.js → ToolResultCharts-CW23-D1x.js} +1 -1
  14. package/page/assets/{TraceInspector-DSLg92wY.js → TraceInspector-h030OQ82.js} +1 -1
  15. package/page/assets/{TraceOverview-TDZ4GUIz.js → TraceOverview-BsON_uZj.js} +1 -1
  16. package/page/assets/{_virtual_studio-type-sources-B0cSCDug.js → _virtual_studio-type-sources-BwSqfSwd.js} +23 -4
  17. package/page/assets/browser-connection-DSUHVCT5.js +3 -0
  18. package/page/assets/browser-engine-Cf6d-zNH.js +11 -0
  19. package/page/assets/browser-transport-BK4cbTE_.js +45 -0
  20. package/page/assets/{crypto-B6qD6nxk.js → crypto-CD14HeXH.js} +1 -1
  21. package/page/assets/{encode-files-CM9H0Lq5.js → encode-files-DhoC5hWG.js} +1 -1
  22. package/page/assets/{export-agent-BuZ4GIKx.js → export-agent-CaHsJPsM.js} +1 -1
  23. package/page/assets/{guardrail-tester-bc9lxU9X.js → guardrail-tester-BDhFLvT5.js} +1 -1
  24. package/page/assets/index-CqwmMJ4C.js +145 -0
  25. package/page/assets/{live-messages-CHHEtxno.js → live-messages-CiLmR89m.js} +1 -1
  26. package/page/assets/reader-DrOfMM8I.js +5 -0
  27. package/page/assets/shaped-data-H1miOZm2.js +20 -0
  28. package/page/assets/{stub-CWjTbSMX.js → stub-nxRsh1jo.js} +4 -4
  29. package/page/assets/{studio-code-pane-DevKnszl.js → studio-code-pane-C1wH63Y2.js} +3 -3
  30. package/page/assets/{studio-console-kpYOJazO.js → studio-console-DRzo4yTy.js} +1 -1
  31. package/page/assets/{studio-decision-Dq5LDTrl.js → studio-decision-C7QWMm7Q.js} +1 -1
  32. package/page/assets/{studio-embedding-Cebwv5_l.js → studio-embedding-D8KroBXY.js} +1 -1
  33. package/page/assets/{studio-host-console-CaaVHxrN.js → studio-host-console-HkX8BerX.js} +2 -2
  34. package/page/assets/{studio-labels-BQOD-taS.js → studio-labels-6w1SKC2D.js} +1 -1
  35. package/page/assets/studio-live-BmVeXAu4.js +5 -0
  36. package/page/assets/{studio-map-BOaPPVXK.js → studio-map-5ZU1nicW.js} +1 -1
  37. package/page/assets/studio-session-CjUQSXx0.js +1 -0
  38. package/page/assets/studio-trace-replay-CSbJSN5e.js +3 -0
  39. package/page/assets/{studio-type-checker-BQmVytwu.js → studio-type-checker-BbUSqqOS.js} +1 -1
  40. package/page/assets/tool-schema-BmRYaywn.js +17 -0
  41. package/page/assets/{trace-record-CtL5_CIg.js → trace-record-DxgSKmYY.js} +1 -1
  42. package/page/assets/tree-3N-1RPZz.js +3 -0
  43. package/page/assets/{turn-client-yriGS51g.js → turn-client-DN8PawJr.js} +2 -2
  44. package/page/assets/{use-one-call-8QTXCYlp.js → use-one-call-Br2IVJLU.js} +1 -1
  45. package/page/assets/{use-second-ticker-rObooyH6.js → use-second-ticker-CEwOSS-d.js} +1 -1
  46. package/page/assets/{workspace-WKa0_gWg.js → workspace-CTSW941G.js} +1 -1
  47. package/page/index.html +16 -16
  48. package/replay.d.ts +13 -8
  49. package/replay.js +33 -31
  50. package/run-payload.d.ts +20 -6
  51. package/run-payload.js +85 -13
  52. package/runtime-scope.js +1 -0
  53. package/runtime.js +1 -0
  54. package/server/project.js +5 -32
  55. package/transport.d.ts +1 -3
  56. package/transport.js +0 -9
  57. package/ui/inspector.js +11 -5
  58. package/ui/lib/acting-as.js +1 -6
  59. package/ui/lib/run-keys.d.ts +15 -5
  60. package/ui/lib/run-keys.js +80 -16
  61. package/ui/lib/studio-conversation.d.ts +2 -3
  62. package/ui/lib/studio-conversation.js +28 -65
  63. package/ui/lib/studio-keep.d.ts +34 -0
  64. package/ui/lib/studio-keep.js +202 -0
  65. package/ui/lib/studio-map-kept.d.ts +2 -2
  66. package/ui/lib/studio-map-kept.js +5 -10
  67. package/ui/lib/studio-open.d.ts +1 -1
  68. package/ui/lib/studio-open.js +5 -5
  69. package/ui/lib/studio-page.js +1 -7
  70. package/ui/lib/studio-restore.d.ts +2 -3
  71. package/ui/lib/studio-restore.js +8 -48
  72. package/ui/lib/studio-run-open.d.ts +10 -5
  73. package/ui/lib/studio-run-open.js +18 -9
  74. package/ui/lib/studio-session.d.ts +38 -5
  75. package/ui/lib/studio-session.js +133 -3
  76. package/ui/lib/studio-store.js +8 -30
  77. package/ui/profile-editor.js +37 -185
  78. package/ui/studio-compare.js +239 -46
  79. package/ui/studio-run.js +29 -15
  80. package/ui/studio-screen.d.ts +1 -1
  81. package/ui/studio-screen.js +8 -9
  82. package/ui/studio-trace-replay.js +39 -14
  83. package/vite.mjs +1 -1
  84. package/page/assets/Banner-CzP7eU2F.js +0 -4
  85. package/page/assets/browser-connection-QNf4S7Ff.js +0 -3
  86. package/page/assets/browser-engine-DpEz1HOI.js +0 -11
  87. package/page/assets/browser-transport-sRqTLzGF.js +0 -45
  88. package/page/assets/index-CVYQrx1w.js +0 -145
  89. package/page/assets/reader-DlrsIIkn.js +0 -5
  90. package/page/assets/shaped-data-DAdn_XvU.js +0 -20
  91. package/page/assets/studio-live-Bz8YuQcb.js +0 -5
  92. package/page/assets/studio-session-yEqFQo5o.js +0 -1
  93. package/page/assets/studio-trace-replay-Ck0X9hTR.js +0 -3
  94. package/page/assets/tool-schema-B_EOjDjg.js +0 -17
  95. package/page/assets/tree-DM7jRXMx.js +0 -3
  96. package/run-payload-core.d.ts +0 -28
  97. package/run-payload-core.js +0 -117
@@ -25,10 +25,11 @@ import { Token } from '@astryxdesign/core/Token';
25
25
  import { Tooltip } from '@astryxdesign/core/Tooltip';
26
26
  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
- import { ATTACHMENT_ACCEPT_MIMES, CONTINUE_STOP_KINDS, fieldMeta, HTTP_METHODS, IMAGE_ATTACHMENT_ACCEPT_MIMES, LABEL_KEYS, labelDefault, PROFILE_HANDLE_MAX_CHARS, PROFILE_ID_MAX_CHARS, profileGraphFacet, SPEECH_AUDIO_FORMATS, THINKING_LEVELS, VOICE_ACCEPT_MIMES, } from '@theoremjs/agents';
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
- 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, LOCAL_PROVIDER_ID, lentCompression, MODEL_LIMITS, modelRoute, modelSlots, newCriteria, newCriterion, newDecisionImage, newDecisionQuestion, newModelBinding, newOwnDetector, newPattern, newSlot, newSlotChoice, newToolSpec, nextAccept, onStudioLocal, optionAt, 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
+ 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";
33
34
  import { IconGoogle, IconOpenAi, IconOpenRouter, IconTypeSafe } from "./brand-icons.js";
34
35
  import { ChoiceRow, InspectorGroupTitle, InspectorRow, InspectorSection, ListRow, NamesRow, NumberRow, OriginLine, SegmentedRow, SetInCode, SliderRow, SwitchRow, TextAreaRow, TextRow, } from "./inspector.js";
@@ -196,7 +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", value: models.allowModelSelect, 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) => {
200
201
  set({ allowModelSelect });
201
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) => {
202
203
  set({ providerHistory });
@@ -469,9 +470,9 @@ function ProtocolOptionsSection({ providers, binding, type, set, }) {
469
470
  return null;
470
471
  return (_jsx(InspectorSection, { title: protocol.name, path: "models.*.options", children: _jsx(ProtocolOptionRows, { providers: providers, binding: binding, type: type, set: set }) }));
471
472
  }
472
- /** A setting a boolean option takes: left to the protocol, on, or off. */
473
+ /** A setting a boolean option takes: left to the provider, on, or off. */
473
474
  const OPTION_SWITCH_SEGMENTS = [
474
- { value: 'default', label: 'Protocol default', icon: IconCircleDashed },
475
+ PROVIDER_DEFAULT,
475
476
  { value: 'on', label: 'On', icon: IconCheck },
476
477
  { value: 'off', label: 'Off', icon: IconX },
477
478
  ];
@@ -864,8 +865,6 @@ function PresetRow({ google, label, path, value, preset, hasSearch, onChange, })
864
865
  /** OpenRouter's image vocabularies; the kernel takes free strings, so these are the studio's. */
865
866
  const OPENROUTER_IMAGE_QUALITIES = ['auto', 'low', 'medium', 'high'];
866
867
  const OPENROUTER_IMAGE_BACKGROUNDS = ['auto', 'transparent', 'opaque'];
867
- /** A pinned file rides in every turn's request, so it stays small. */
868
- const REFERENCE_MAX_BYTES = 4 * 1024 * 1024;
869
868
  /** A picked file's type and its bytes in base64. */
870
869
  async function fileData(file) {
871
870
  const url = await new Promise((resolve, reject) => {
@@ -959,7 +958,7 @@ function ImageReferencesEditor({ references, onChange, }) {
959
958
  replace(reference.key, next);
960
959
  }, onRemove: () => {
961
960
  onChange(references.filter((candidate) => candidate.key !== reference.key));
962
- } }, 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: () => {
963
962
  onChange([...references, { key: draftKey('reference'), uri: '' }]);
964
963
  } })] }));
965
964
  }
@@ -2282,179 +2281,32 @@ function ToolSpecEditor({ draft, setDraft, toolKey, onSelect, }) {
2282
2281
  onSelect('tools');
2283
2282
  } }) })] }));
2284
2283
  }
2285
- const LABEL_AREAS = [
2286
- {
2287
- prefix: 'error',
2288
- title: 'Errors',
2289
- note: 'When a turn fails.',
2290
- icon: IconAlertTriangle,
2291
- audience: 'visitor',
2292
- },
2293
- {
2294
- prefix: 'attachments',
2295
- title: 'Attachments',
2296
- note: "When a file can't be sent.",
2297
- icon: IconPaperclip,
2298
- audience: 'visitor',
2299
- },
2300
- {
2301
- prefix: 'voice',
2302
- title: 'Voice',
2303
- note: "When a voice note can't be recorded or used.",
2304
- icon: IconMicrophone,
2305
- audience: 'visitor',
2306
- },
2307
- {
2308
- prefix: 'session',
2309
- title: 'Session',
2310
- note: 'Waits, approvals, and signing in.',
2311
- icon: IconHourglass,
2312
- audience: 'visitor',
2313
- },
2314
- {
2315
- prefix: 'stop',
2316
- title: 'Stops',
2317
- note: 'Why a reply ended short.',
2318
- icon: IconPlayerStop,
2319
- audience: 'visitor',
2320
- },
2321
- {
2322
- prefix: 'composer',
2323
- title: 'Composer',
2324
- note: 'The model and effort pickers.',
2325
- icon: IconAdjustmentsHorizontal,
2326
- audience: 'visitor',
2327
- },
2328
- {
2329
- prefix: 'detect.blocked',
2330
- title: 'Blocked messages',
2331
- note: "When a detector stops the visitor's message.",
2332
- icon: IconShieldOff,
2333
- audience: 'visitor',
2334
- },
2335
- {
2336
- prefix: 'thought',
2337
- title: 'Thoughts',
2338
- note: 'What stands in for what a thought leaves out.',
2339
- icon: IconBulb,
2340
- audience: 'visitor',
2341
- },
2342
- {
2343
- prefix: 'live',
2344
- title: 'Live',
2345
- note: 'When a live session ends.',
2346
- icon: IconHeadset,
2347
- audience: 'visitor',
2348
- },
2349
- {
2350
- prefix: 'quota',
2351
- title: 'Quota',
2352
- note: 'When the daily limit is reached.',
2353
- icon: IconGauge,
2354
- audience: 'visitor',
2355
- },
2356
- {
2357
- prefix: 'tool',
2358
- title: 'Tools',
2359
- note: "When a tool call can't run.",
2360
- icon: IconTool,
2361
- audience: 'model',
2362
- },
2363
- {
2364
- prefix: 'repair',
2365
- title: 'Repair',
2366
- note: 'Fixing a reply that failed its schema.',
2367
- icon: IconBandage,
2368
- audience: 'model',
2369
- },
2370
- {
2371
- prefix: 'egress',
2372
- title: 'Egress',
2373
- note: 'A reply that fails its check, sent back or refused.',
2374
- icon: IconSend,
2375
- audience: 'model',
2376
- },
2377
- {
2378
- prefix: 'continue',
2379
- title: 'Resumption',
2380
- note: 'Picking up a reply that stopped short.',
2381
- icon: IconPlayerTrackNext,
2382
- audience: 'model',
2383
- },
2384
- {
2385
- prefix: 'canary',
2386
- title: 'Canary',
2387
- note: "The note that binds each turn's canary.",
2388
- icon: IconFeather,
2389
- audience: 'model',
2390
- },
2391
- {
2392
- prefix: 'taint',
2393
- title: 'Untrusted content',
2394
- note: 'Why a tool call was refused after reading it.',
2395
- icon: IconBiohazard,
2396
- audience: 'model',
2397
- },
2398
- {
2399
- prefix: 'advisory',
2400
- title: 'Advisories',
2401
- note: 'Notes beside content that tries to direct it.',
2402
- icon: IconInfoCircle,
2403
- audience: 'model',
2404
- },
2405
- {
2406
- prefix: 'detect',
2407
- title: 'Detectors',
2408
- note: 'When a detector stops a call or a result, and what it asks the model to leave out.',
2409
- icon: IconShieldSearch,
2410
- audience: 'model',
2411
- },
2412
- {
2413
- prefix: 'sign_in',
2414
- title: 'Sign-in',
2415
- note: 'Where a tool waits for the person to sign in to a service.',
2416
- icon: IconLogin,
2417
- audience: 'model',
2418
- },
2419
- {
2420
- prefix: 'user_data',
2421
- title: 'User data',
2422
- note: "The note on the fence around the user's message.",
2423
- icon: IconUser,
2424
- audience: 'model',
2425
- },
2426
- {
2427
- prefix: 'context',
2428
- title: 'Turn context',
2429
- note: 'The note on the fence around what the app or the host adds.',
2430
- icon: IconLayersUnion,
2431
- audience: 'model',
2432
- },
2433
- {
2434
- prefix: 'structured',
2435
- title: 'Structured replies',
2436
- note: 'Asking for the final answer as JSON or as an answer tool call.',
2437
- icon: IconBraces,
2438
- audience: 'model',
2439
- },
2440
- {
2441
- prefix: 'compaction',
2442
- title: 'Compaction',
2443
- note: 'Asking for the summary that replaces earlier turns.',
2444
- icon: IconFold,
2445
- audience: 'model',
2446
- },
2447
- ];
2448
- /** The area a label key is under: the one with the longest prefix that holds it. */
2449
- function areaOf(key) {
2450
- let found;
2451
- for (const area of LABEL_AREAS) {
2452
- const holds = key === area.prefix || key.startsWith(`${area.prefix}.`);
2453
- if (holds && (!found || area.prefix.length > found.prefix.length))
2454
- found = area;
2455
- }
2456
- return found;
2457
- }
2284
+ /** Each labels area's icon. */
2285
+ const LABEL_AREA_ICONS = {
2286
+ error: IconAlertTriangle,
2287
+ attachments: IconPaperclip,
2288
+ voice: IconMicrophone,
2289
+ session: IconHourglass,
2290
+ stop: IconPlayerStop,
2291
+ composer: IconAdjustmentsHorizontal,
2292
+ 'detect.blocked': IconShieldOff,
2293
+ thought: IconBulb,
2294
+ live: IconHeadset,
2295
+ quota: IconGauge,
2296
+ tool: IconTool,
2297
+ repair: IconBandage,
2298
+ egress: IconSend,
2299
+ continue: IconPlayerTrackNext,
2300
+ canary: IconFeather,
2301
+ taint: IconBiohazard,
2302
+ advisory: IconInfoCircle,
2303
+ detect: IconShieldSearch,
2304
+ sign_in: IconLogin,
2305
+ user_data: IconUser,
2306
+ context: IconLayersUnion,
2307
+ structured: IconBraces,
2308
+ compaction: IconFold,
2309
+ };
2458
2310
  const LABEL_AUDIENCES = [
2459
2311
  {
2460
2312
  value: 'visitor',
@@ -2560,8 +2412,8 @@ function SharedLabelRow({ labelKey, facet, draft, setDraft, onSelect, }) {
2560
2412
  return null;
2561
2413
  return (_jsxs(VStack, { gap: 1, children: [_jsx(TextAreaRow, { label: labelTitle(labelKey), path: `labels.${labelKey}`, rows: 2, value: shared.read(draft), placeholder: labelPlaceholder(draft, labelKey), onChange: (text) => {
2562
2414
  shared.write(setDraft, text);
2563
- } }), !shared.isOn(draft) && (_jsxs(HStack, { gap: 1, align: "center", children: [_jsxs(Text, { type: "supporting", children: [shared.setting, " is off."] }), _jsx(Button, { label: `Open ${profileGraphFacet(facet)?.label ?? facet}`, variant: "ghost", size: "sm", onClick: () => {
2564
- // A section left out of the profile has no node to open until it's back in.
2415
+ } }), !shared.isOn(draft) && (_jsxs(HStack, { gap: 1, align: "center", children: [_jsxs(Text, { type: "supporting", children: [shared.setting, " is off."] }), _jsx(Button, { label: `${draft.included.includes(facet) ? 'Open' : 'Add'} ${profileGraphFacet(facet)?.label ?? facet}`, variant: "ghost", size: "sm", onClick: () => {
2416
+ // why: a section left out of the profile has no node to open until it's added.
2565
2417
  setDraft((current) => includeFacet(current, facet));
2566
2418
  onSelect(facet);
2567
2419
  } })] }))] }));
@@ -2584,7 +2436,7 @@ function LabelsEditor({ draft, setDraft, onSelect, }) {
2584
2436
  function labelAreas(draft, needle, audience) {
2585
2437
  return LABEL_AREAS.filter((area) => needle || area.audience === audience)
2586
2438
  .map((area) => {
2587
- const all = LABEL_KEYS.filter((key) => areaOf(key) === area);
2439
+ const all = PROFILE_LABEL_KEYS.filter((key) => labelAreaOf(key) === area);
2588
2440
  const keys = needle
2589
2441
  ? all.filter((key) => [
2590
2442
  area.title,
@@ -2608,7 +2460,7 @@ function LabelAudiencePicker({ value, onChange, }) {
2608
2460
  }
2609
2461
  /** An area's heading: its icon, title and note, and how many of its lines are edited. */
2610
2462
  function LabelAreaTrigger({ area }) {
2611
- return (_jsxs(HStack, { gap: 2, align: "center", children: [_jsx(Icon, { icon: area.icon, size: "sm", color: "secondary" }), _jsx(StackItem, { size: "fill", children: _jsxs(VStack, { gap: 0, children: [_jsx(Text, { type: "supporting", weight: "semibold", color: "primary", children: area.title }), _jsx(Text, { type: "supporting", color: "secondary", children: area.note })] }) }), area.edited > 0 && _jsx(Badge, { variant: "info", label: `${String(area.edited)} edited` })] }));
2463
+ return (_jsxs(HStack, { gap: 2, align: "center", children: [_jsx(Icon, { icon: LABEL_AREA_ICONS[area.prefix], size: "sm", color: "secondary" }), _jsx(StackItem, { size: "fill", children: _jsxs(VStack, { gap: 0, children: [_jsx(Text, { type: "supporting", weight: "semibold", color: "primary", children: area.title }), _jsx(Text, { type: "supporting", color: "secondary", children: area.note })] }) }), area.edited > 0 && _jsx(Badge, { variant: "info", label: `${String(area.edited)} edited` })] }));
2612
2464
  }
2613
2465
  /** An area's lines; one that also sits beside its setting edits that setting's field. */
2614
2466
  function LabelAreaLines({ keys, draft, setDraft, onSelect, }) {
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Button } from '@astryxdesign/core/Button';
2
+ import { Center } from '@astryxdesign/core/Center';
3
3
  import { Divider } from '@astryxdesign/core/Divider';
4
4
  import { HStack } from '@astryxdesign/core/HStack';
5
5
  import { Icon } from '@astryxdesign/core/Icon';
@@ -8,8 +8,9 @@ import { StackItem } from '@astryxdesign/core/Stack';
8
8
  import { Text } from '@astryxdesign/core/Text';
9
9
  import { VStack } from '@astryxdesign/core/VStack';
10
10
  import { IconLayoutSidebarLeftCollapse, IconLayoutSidebarLeftExpand } from '@tabler/icons-react';
11
- import { ChatComposerBar, InPlace, PaneFailure, PaneLoading, TheoremChat, } from '@theoremjs/react/ui';
12
- import { createHttpTransport, createTraceFeed } from '@theoremjs/web/client';
11
+ import { createComposerPendingMessage, orderComposerPendingMessages, removeComposerPendingMessage, } from '@theoremjs/agents/interface';
12
+ import { ChatComposerBar, DEFAULT_CHAT_MAX_WIDTH, InPlace, PaneFailure, PaneLoading, TheoremChat, } from '@theoremjs/react/ui';
13
+ import { clientFailure, composerFieldsFromDraft, composerHasPayload, createHttpTransport, createTraceFeed, encodeComposerDraft, followGenerationDefaults, } from '@theoremjs/web/client';
13
14
  import { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState, useSyncExternalStore, } from 'react';
14
15
  import { atStart } from "../mod.js";
15
16
  import { useActingAs } from "./lib/acting-as.js";
@@ -72,40 +73,45 @@ export function useLoadedStamp(answer) {
72
73
  setLoaded(now);
73
74
  return now;
74
75
  }
76
+ /** A side's chat as it stands, and as it changes. Null until the side is mounted. */
77
+ function useSideState(chat) {
78
+ const subscribe = useCallback((listener) => (chat ? chat.subscribe(listener) : () => { }), [chat]);
79
+ return useSyncExternalStore(subscribe, () => chat?.getState() ?? null);
80
+ }
75
81
  /**
76
- * One message sent to both sides, and which of them still answers it. A side rests when its turn
77
- * is done: the reply ended, and any question it stopped on was answered.
82
+ * The two sides' chats, and which of them still answers. A side rests when its turn is done: the
83
+ * reply ended, and any question it stopped on was answered.
78
84
  */
79
85
  function usePair() {
80
- const chats = useRef({ saved: null, edited: null });
81
- const [busy, setBusy] = useState([]);
82
- const done = useCallback((side) => {
83
- setBusy((sides) => sides.filter((other) => other !== side));
84
- }, []);
85
- const send = useCallback(async (text) => {
86
- const sent = SIDES.filter((side) => chats.current[side]);
87
- setBusy(sent);
88
- const answers = sent.map(async (side) => {
89
- // A side's send resolves once its reply is done, or at once when it could not take it.
90
- const added = await chats.current[side]?.send(text).catch(() => null);
91
- done(side);
92
- return [side, added ?? null];
86
+ const handles = useRef({ saved: null, edited: null });
87
+ const [chats, setChats] = useState({
88
+ saved: null,
89
+ edited: null,
90
+ });
91
+ const [refs] = useState(() => {
92
+ const ref = (side) => (handle) => {
93
+ handles.current[side] = handle;
94
+ const chat = handle?.controller ?? null;
95
+ setChats((now) => (now[side] === chat ? now : { ...now, [side]: chat }));
96
+ };
97
+ return { saved: ref('saved'), edited: ref('edited') };
98
+ });
99
+ const states = { saved: useSideState(chats.saved), edited: useSideState(chats.edited) };
100
+ const busy = SIDES.filter((side) => states[side] && states[side].phase !== 'idle');
101
+ const send = useCallback(async (text, options) => {
102
+ const sent = SIDES.flatMap((side) => {
103
+ const chat = handles.current[side]?.controller;
104
+ return chat ? [[side, chat]] : [];
93
105
  });
106
+ // A side's send resolves once its reply is done, or at once when it could not take it.
107
+ const answers = sent.map(async ([side, chat]) => [side, await chat.sendText(text, options).catch(() => null)]);
94
108
  return new Map(await Promise.all(answers));
95
- }, [done]);
109
+ }, []);
96
110
  const stop = useCallback(() => {
97
111
  for (const side of SIDES)
98
- chats.current[side]?.stop();
112
+ handles.current[side]?.stop();
99
113
  }, []);
100
- const [refs] = useState(() => ({
101
- saved: (handle) => {
102
- chats.current.saved = handle;
103
- },
104
- edited: (handle) => {
105
- chats.current.edited = handle;
106
- },
107
- }));
108
- return useMemo(() => ({ busy, send, stop, refs, chats }), [busy, send, stop, refs]);
114
+ return { busy, send, stop, refs, handles, chats, states };
109
115
  }
110
116
  /** Whether the files' side is put away, for every comparison in this tab. */
111
117
  const savedSide = { isHidden: false, listeners: new Set() };
@@ -172,10 +178,180 @@ export function SavedSide({ isCompared = true, children, }) {
172
178
  function NotRunning({ refusal, actions }) {
173
179
  return (_jsx(PaneFailure, { title: NOT_RUNNING[refusal.reason] ?? 'Your edits are not running.', actions: actions, children: _jsx(RefusalDetail, { refusal: refusal }) }));
174
180
  }
175
- /** The message both sides get, and the stop for both while either answers. */
176
- function SharedComposer({ handle, why, isBusy, onSend, onStop, }) {
177
- const [text, setText] = useState('');
178
- return (_jsxs(HStack, { gap: 2, vAlign: "end", padding: 3, children: [_jsx(StackItem, { size: "fill", children: _jsx(ChatComposerBar, { handle: handle, draftText: text, onDraftTextChange: setText, onSubmit: onSend, isDisabled: isBusy || why !== undefined, placeholder: why ?? 'Message both' }) }), isBusy && _jsx(Button, { label: "Stop", variant: "ghost", onClick: onStop })] }));
181
+ /** The phase the shared composer shows: streaming while either side streams, else gated while either waits. */
182
+ function pairPhase(states) {
183
+ if (states.some((state) => state.phase === 'streaming'))
184
+ return 'streaming';
185
+ return states.some((state) => state.phase === 'gated') ? 'gated' : 'idle';
186
+ }
187
+ function allowsSteering(state) {
188
+ return state.iface != null && 'allowSteering' in state.iface && state.iface.allowSteering;
189
+ }
190
+ /** Each side's pending messages, once each: both sides hold a shared message under one id. */
191
+ function pairPending(states) {
192
+ const byId = new Map(states.flatMap((state) => state.pendingMessages.map((message) => [message.id, message])));
193
+ return orderComposerPendingMessages([...byId.values()]);
194
+ }
195
+ /** Whether a side's running turn would take a steer now. */
196
+ const takesSteer = (state) => state.phase === 'streaming' && allowsSteering(state);
197
+ /**
198
+ * The one composer of both sides. It only types for them: each side does with what is sent what
199
+ * its own composer would. An idle side sends it, a busy one queues it; a steer goes to each side
200
+ * whose running turn takes one; and each side refuses a model or file its profile does not take.
201
+ */
202
+ function SharedComposer({ sides, edited, inputRef, }) {
203
+ const iface = edited.iface ?? undefined;
204
+ const [draftText, setDraftText] = useState('');
205
+ const [pendingFiles, setPendingFiles] = useState([]);
206
+ const [pendingVoice, setPendingVoice] = useState([]);
207
+ const [failure, setFailure] = useState(null);
208
+ const [pick, setPick] = useState({ isChosen: false });
209
+ // The pick follows the edited side's profile as a chat's own composer follows its profile.
210
+ if (iface && pick.of !== iface) {
211
+ const next = followGenerationDefaults(iface, pick, pick.of);
212
+ setPick({ ...next, of: iface, isChosen: pick.isChosen && next.model === pick.model });
213
+ }
214
+ const states = sides.map((side) => side.state);
215
+ const phase = pairPhase(states);
216
+ if (!iface)
217
+ return null;
218
+ // Unchosen, each side runs its own defaults: an edit to the defaults is what the two show.
219
+ const chosen = pick.isChosen ? { model: pick.model, effort: pick.effort } : {};
220
+ const options = () => ({ files: pendingFiles, voice: pendingVoice, ...chosen });
221
+ const message = async (kind) => createComposerPendingMessage({
222
+ kind,
223
+ draft: await encodeComposerDraft({ text: draftText, pendingFiles, pendingVoice }),
224
+ });
225
+ const clear = () => {
226
+ setDraftText('');
227
+ setPendingFiles([]);
228
+ setPendingVoice([]);
229
+ };
230
+ const takePick = (chat) => {
231
+ if (chosen.model !== undefined)
232
+ chat.setGeneration({ modelId: chosen.model, effort: chosen.effort });
233
+ };
234
+ /** Each side as its own composer would: an idle side sends, a busy one takes `kind`. */
235
+ const deliver = async (kind) => {
236
+ const text = draftText;
237
+ const sent = options();
238
+ let shared;
239
+ try {
240
+ shared = await message(kind === 'send_now' ? 'queue' : kind);
241
+ }
242
+ catch (error) {
243
+ // The draft stays in the composer, with why it could not go.
244
+ setFailure(clientFailure(error, iface.labels));
245
+ return;
246
+ }
247
+ setFailure(null);
248
+ clear();
249
+ for (const { chat, state } of sides) {
250
+ if (kind === 'steer') {
251
+ if (takesSteer(state))
252
+ void chat.pend(shared);
253
+ continue;
254
+ }
255
+ if (kind === 'stash') {
256
+ void chat.pend(shared);
257
+ continue;
258
+ }
259
+ // why: reading the attachments took time, and a side may have finished or started since.
260
+ if (chat.getState().phase === 'idle') {
261
+ void chat.sendText(text, sent);
262
+ continue;
263
+ }
264
+ takePick(chat);
265
+ void (kind === 'send_now' ? chat.sendNow(shared) : chat.pend(shared));
266
+ }
267
+ };
268
+ const each = (act) => {
269
+ for (const { chat } of sides)
270
+ act(chat);
271
+ };
272
+ const pending = pairPending(states);
273
+ return (_jsx(SharedDock, { children: _jsx(ChatComposerBar
274
+ // why: a steer goes only to a running turn, so one that no side would take is not offered.
275
+ , {
276
+ // why: a steer goes only to a running turn, so one that no side would take is not offered.
277
+ iface: {
278
+ ...iface,
279
+ ...('allowSteering' in iface
280
+ ? { allowSteering: sides.some(({ state }) => takesSteer(state)) }
281
+ : {}),
282
+ }, draftText: draftText, pendingFiles: pendingFiles, pendingVoice: pendingVoice, pendingMessages: pending, issues: [], phase: phase, failure: failure, selectedModel: pick.model, selectedEffort: pick.effort, placeholder: "Message both", inputRef: inputRef, onDraftTextChange: setDraftText, onFilesSelected: (files) => {
283
+ setPendingFiles((prev) => [...prev, ...files]);
284
+ }, onAttachmentRemove: (index) => {
285
+ setPendingFiles((prev) => prev.filter((_, at) => at !== index));
286
+ }, onVoiceStaged: (file) => {
287
+ setPendingVoice([file]);
288
+ }, onVoiceClear: () => {
289
+ setPendingVoice([]);
290
+ }, onSubmit: () => {
291
+ void deliver('queue');
292
+ }, onStop: () => {
293
+ each((chat) => {
294
+ chat.stop();
295
+ });
296
+ }, onMenuAction: (action) => {
297
+ void deliver(action);
298
+ }, onGenerationChange: (next) => {
299
+ setPick({ model: next.modelId, effort: next.effort, of: iface, isChosen: true });
300
+ }, slotChoices: edited.slots && {
301
+ ...edited.slots,
302
+ onChange: (name, value) => {
303
+ each((chat) => {
304
+ chat.pickSlot(name, value);
305
+ });
306
+ },
307
+ }, onPendingMove: (id, direction) => {
308
+ each((chat) => {
309
+ chat.movePending(id, direction);
310
+ });
311
+ }, onPendingRemove: (id) => {
312
+ each((chat) => {
313
+ chat.setPendingMessages((prev) => removeComposerPendingMessage(prev, id));
314
+ });
315
+ }, onPendingQueue: (id) => {
316
+ each((chat) => {
317
+ chat.queuePending(id);
318
+ });
319
+ }, onPendingRestore: (id) => {
320
+ void (async () => {
321
+ const restored = pending.find((held) => held.id === id);
322
+ if (!restored)
323
+ return;
324
+ // As a chat restores: what the composer holds is stashed first.
325
+ if (composerHasPayload(draftText, pendingFiles, pendingVoice))
326
+ await deliver('stash');
327
+ each((chat) => {
328
+ chat.setPendingMessages((prev) => removeComposerPendingMessage(prev, id));
329
+ });
330
+ const fields = composerFieldsFromDraft(restored.draft);
331
+ setDraftText(fields.text);
332
+ setPendingFiles(fields.files);
333
+ setPendingVoice(fields.voice);
334
+ })();
335
+ }, onPendingSendNow: (id) => {
336
+ for (const { chat, state } of sides) {
337
+ const held = state.pendingMessages.find((m) => m.id === id);
338
+ if (!held)
339
+ continue;
340
+ takePick(chat);
341
+ void chat.sendNow(held);
342
+ }
343
+ } }) }));
344
+ }
345
+ /**
346
+ * Where the shared composer sits: the width and inset of a chat's own dock.
347
+ * why: it sits outside both chats' layouts, so it brings the 12px sides and 24px below they give.
348
+ */
349
+ function SharedDock({ children }) {
350
+ return (_jsx(VStack, { paddingInline: 3, paddingBlockEnd: 6, children: _jsx(Center, { axis: "horizontal", width: "100%", children: _jsx(VStack, { width: "100%", maxWidth: DEFAULT_CHAT_MAX_WIDTH, children: children }) }) }));
351
+ }
352
+ /** The composer while the edits cannot take a message: it says why. */
353
+ function WaitingComposer({ handle, why }) {
354
+ return (_jsx(SharedDock, { children: _jsx(ChatComposerBar, { handle: handle, draftText: "", onDraftTextChange: () => { }, onSubmit: () => { }, isDisabled: true, placeholder: why }) }));
179
355
  }
180
356
  /** The agent as the files hold it: an edit may have renamed it, or made it another type. */
181
357
  function savedOf(tested, profileId) {
@@ -275,20 +451,32 @@ function useComparison({ project, profileId, tested, note, traces }) {
275
451
  }
276
452
  /**
277
453
  * The chat the page holds: a message goes to both sides while both are there and can take it, and
278
- * to the one side otherwise. It answers with what the edits said.
454
+ * to the one side otherwise. It answers with what the edits said, and its controller is theirs.
279
455
  */
280
- function useChatHandle(chatRef, pair, only, canSendBoth) {
281
- const { send, stop, chats } = pair;
282
- const sendBoth = useCallback(async (text) => (await send(text)).get('edited') ?? null, [send]);
456
+ function useChatHandle(chatRef, pair, only, canSendBoth, sharedInput) {
457
+ const { send, stop, handles } = pair;
283
458
  useImperativeHandle(chatRef, () => ({
284
- send: (text) => {
459
+ send: (text, options) => {
285
460
  if (only)
286
- return chats.current[only]?.send(text) ?? Promise.resolve(null);
287
- return canSendBoth ? sendBoth(text) : Promise.resolve(null);
461
+ return handles.current[only]?.send(text, options) ?? Promise.resolve(null);
462
+ if (!canSendBoth)
463
+ return Promise.resolve(null);
464
+ return send(text, options).then((answers) => answers.get('edited') ?? null);
288
465
  },
289
466
  stop,
290
- }), [only, canSendBoth, sendBoth, stop, chats]);
291
- return sendBoth;
467
+ focus: () => {
468
+ if (only)
469
+ handles.current[only]?.focus();
470
+ else
471
+ sharedInput.current?.focus();
472
+ },
473
+ get controller() {
474
+ const chat = handles.current[only ?? 'edited']?.controller;
475
+ if (!chat)
476
+ throw new Error('The chat is not open yet.');
477
+ return chat;
478
+ },
479
+ }), [only, canSendBoth, send, stop, handles, sharedInput]);
292
480
  }
293
481
  /**
294
482
  * A project's text or image profile, run by the studio's local server. While the builder has
@@ -303,7 +491,13 @@ export function ProjectChat(props) {
303
491
  const showsSaved = view.inFiles && !(view.isEditing && isSavedHidden);
304
492
  const isShared = view.isShared && showsSaved;
305
493
  const only = isShared ? undefined : showsSaved ? 'saved' : 'edited';
306
- const sendBoth = useChatHandle(chatRef, pair, only, !isBusy && isReady);
494
+ const sharedInput = useRef(null);
495
+ useChatHandle(chatRef, pair, only, !isBusy && isReady, sharedInput);
496
+ const shared = SIDES.flatMap((side) => {
497
+ const chat = pair.chats[side];
498
+ const state = pair.states[side];
499
+ return chat && state ? [{ chat, state }] : [];
500
+ });
307
501
  const common = {
308
502
  detectCodeLanguage: true,
309
503
  labels: STUDIO_LABELS,
@@ -319,7 +513,6 @@ export function ProjectChat(props) {
319
513
  // A new load is a new transport: the chat reads it in place and keeps its transcript.
320
514
  transport: transports.edited, conversation: view.conversations.current.edited ?? view.conversations.current.saved, onConversationChange: view.onChange.edited,
321
515
  // Under a refusal nothing reaches it: the edits it ran are not loaded.
322
- chatRef: refused ? undefined : pair.refs.edited })) }) }, "edited"))] }) }), isShared && (_jsx(SharedComposer, { handle: profileId, why: whyNot(refused !== undefined, isReady), isBusy: isBusy, onSend: (text) => {
323
- void sendBoth(text);
324
- }, onStop: pair.stop }))] }));
516
+ chatRef: refused ? undefined : pair.refs.edited })) }) }, "edited"))] }) }), isShared &&
517
+ (isReady && pair.states.edited ? (_jsx(SharedComposer, { sides: shared, edited: pair.states.edited, inputRef: sharedInput })) : (_jsx(WaitingComposer, { handle: profileId, why: whyNot(refused !== undefined, isReady) ?? 'Loading your edits' })))] }));
325
518
  }