@theoremjs/studio 0.3.5-next.933.gfc0e83b → 0.3.5-next.936.ga984349

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 (64) hide show
  1. package/README.md +1 -1
  2. package/package.json +4 -4
  3. package/page/assets/{BottomSheet-CFmWCLNs.js → BottomSheet-BnEb4FIt.js} +1 -1
  4. package/page/assets/{ConsoleFrame-sWIg1UlI.js → ConsoleFrame-DrpHfC9N.js} +1 -1
  5. package/page/assets/{ContextMenu-kJvPbe2l.js → ContextMenu-CQ4wCDA0.js} +2 -2
  6. package/page/assets/{DateInput-DFW6ZGmz.js → DateInput-CXT8JRWH.js} +1 -1
  7. package/page/assets/{DropdownMenu-kC1ynF9P.js → DropdownMenu-DZGQ0Uee.js} +2 -2
  8. package/page/assets/{Link-cEUGqR4E.js → Link-Dv6zIeat.js} +1 -1
  9. package/page/assets/{MenuBottomSheet-CXQHH9x8.js → MenuBottomSheet-CQ9ZexXb.js} +1 -1
  10. package/page/assets/{PowerSearchBottomSheet-DT2J58Od.js → PowerSearchBottomSheet-BiSB0QYs.js} +1 -1
  11. package/page/assets/{RankedBars-DBJRNmPe.js → RankedBars-DP6GtcXO.js} +1 -1
  12. package/page/assets/{SchemaFields-Cjm83Nt8.js → SchemaFields-CPYKsA4q.js} +1 -1
  13. package/page/assets/{ShapedData-DYOCaGlk.js → ShapedData-CKKImLdL.js} +1 -1
  14. package/page/assets/{TokenizerBottomSheet-BU9l3CaI.js → TokenizerBottomSheet-C0Up9fgz.js} +1 -1
  15. package/page/assets/{ToolResultCharts-CSyUS1-z.js → ToolResultCharts-DC1XXGbq.js} +1 -1
  16. package/page/assets/{Toolbar-BmuypKxW.js → Toolbar-CPHnkxGe.js} +1 -1
  17. package/page/assets/{TraceInspector-CPWC9lS8.js → TraceInspector-B7RGsmT0.js} +2 -2
  18. package/page/assets/{TraceOverview-DKAyP6oW.js → TraceOverview-Cc62BuWs.js} +3 -3
  19. package/page/assets/{_virtual_studio-type-sources-C6e3ZJtP.js → _virtual_studio-type-sources-mjgBn2Oq.js} +244 -46
  20. package/page/assets/browser-connection-ByVN8zLj.js +1 -0
  21. package/page/assets/browser-engine-C8oyevcF.js +16 -0
  22. package/page/assets/{browser-transport-BPAKt_cc.js → browser-transport-DM5OYMC7.js} +2 -2
  23. package/page/assets/{compile-oGEpwgkY.js → compile-Dpm_0jBP.js} +2 -2
  24. package/page/assets/encode-files-B1-I_sQm.js +1 -0
  25. package/page/assets/{export-agent-BcjOjktu.js → export-agent-DrStINWA.js} +1 -1
  26. package/page/assets/{getRadiusAndStrokeWidthFromDot-CuVjZhu8.js → getRadiusAndStrokeWidthFromDot-Dbl9FrzC.js} +1 -1
  27. package/page/assets/{guardrail-health-DzeSNMix.js → guardrail-health-WOTiJrJR.js} +2 -2
  28. package/page/assets/{guardrail-tester-BQ7BHdiW.js → guardrail-tester-Blg3lkvY.js} +1 -1
  29. package/page/assets/{index-hSIwfi4j.js → index-B_7X799H.js} +16 -16
  30. package/page/assets/{json-code-D6l475BW.js → json-code-Bk2TFAcZ.js} +1 -1
  31. package/page/assets/{labels-provider-D_7O3BSI.js → labels-provider-zFTJcXMk.js} +1 -1
  32. package/page/assets/{live-messages-DvMnxecr.js → live-messages-DUty9gDM.js} +1 -1
  33. package/page/assets/{prompt-row-OoetsUr1.js → prompt-row-Dw2EQXKt.js} +1 -1
  34. package/page/assets/reader-Q_pKlgc5.js +5 -0
  35. package/page/assets/registry-CNgPNMqQ.js +1 -0
  36. package/page/assets/{schema-DI2QKpYi.js → schema-CW04nV6r.js} +2 -2
  37. package/page/assets/{shaped-data-BxGL5na3.js → shaped-data-C_l29gBe.js} +17 -17
  38. package/page/assets/{stub-CY0cuGPg.js → stub-CXebNVt9.js} +1 -1
  39. package/page/assets/{studio-code-pane-CXo-J0fe.js → studio-code-pane-CA1ciH5H.js} +3 -3
  40. package/page/assets/{studio-console-BA7bGrU2.js → studio-console-nFuHKeGh.js} +1 -1
  41. package/page/assets/{studio-decision-C1U7AGDn.js → studio-decision-C7IW0I_P.js} +1 -1
  42. package/page/assets/{studio-embedding-DS7pVE5l.js → studio-embedding-VLv9pe2W.js} +1 -1
  43. package/page/assets/{studio-host-console-C3uC7P_C.js → studio-host-console-CIbYwxfr.js} +2 -2
  44. package/page/assets/{studio-live-DaQMlVSh.js → studio-live-BQdWFmlW.js} +1 -1
  45. package/page/assets/{studio-map-CqLgnQNk.js → studio-map-BWpFXC1W.js} +1 -1
  46. package/page/assets/{studio-media-CmbCThcX.js → studio-media-DcQ0YMpK.js} +1 -1
  47. package/page/assets/{studio-trace-replay-R8IQNP3s.js → studio-trace-replay-D-DFHZNh.js} +1 -1
  48. package/page/assets/{studio-type-checker-BQAMVf_u.js → studio-type-checker-Bnec_0A5.js} +1 -1
  49. package/page/assets/{tool-schema-Bfe2TkD-.js → tool-schema-D2XhgIQV.js} +1 -1
  50. package/page/assets/{trace-record--OEcC7x1.js → trace-record-D_urrJog.js} +1 -1
  51. package/page/assets/tree-b43adynw.js +3 -0
  52. package/page/assets/{turn-client-sADYJHV9.js → turn-client-C8_eHuOA.js} +2 -2
  53. package/page/assets/types-BWEkmZ2G.js +1 -0
  54. package/page/assets/{use-one-call-CJqcEomh.js → use-one-call-DLsLrsFN.js} +1 -1
  55. package/page/assets/{useDismissSearchOnTouchDrag-Cjqhp30f.js → useDismissSearchOnTouchDrag-BQv1scUD.js} +1 -1
  56. package/page/assets/{workspace-BrQUhBOf.js → workspace-DT3XVg2T.js} +1 -1
  57. package/page/index.html +21 -21
  58. package/page/assets/browser-connection-DzO00xRy.js +0 -1
  59. package/page/assets/browser-engine-BciA9NL-.js +0 -16
  60. package/page/assets/encode-files-Bn5i8t9U.js +0 -1
  61. package/page/assets/reader-Bz6rc3qr.js +0 -5
  62. package/page/assets/registry-Bjkfo9zx.js +0 -1
  63. package/page/assets/tree-CMulctlY.js +0 -3
  64. package/page/assets/types-7mVE39E8.js +0 -1
@@ -5320,7 +5320,7 @@ export interface ProviderLimits {
5320
5320
  export declare const providerLimitsSchema: z.ZodType<ProviderLimits>;
5321
5321
  `,"file:///node_modules/@theoremjs/agents/src/kernel/types.d.ts":`import type { ProviderCheckpoint, ProviderContinuationPolicy } from './checkpoint.js';
5322
5322
  import type { JsonObject } from './json.js';
5323
- import type { CompactionMeter, CompactionOutcome, CompactionTiming, ContextSender, ContinueStopKind, FieldMeta, KeySlot, KeyVault, LiveActivityHandling, LiveEndSensitivity, LiveStartSensitivity, MediaInputKind, ProfileType, SpeechAudioFormat, StreamMode, SummaryMode, ThinkingLevel, ToolLoadTier, TurnStage, TurnStopKind } from './schema.js';
5323
+ import type { CompactionMeter, CompactionOutcome, CompactionTiming, ContextSender, ContinueStopKind, FieldMeta, KeySlot, KeyVault, LiveActivityHandling, LiveEndSensitivity, LiveStartSensitivity, MediaInputKind, ProfileType, SpeechAudioFormat, StreamMode, SummaryMode, ThinkingLevel, ToolLoadTier, TurnInjectStage, TurnStage, TurnStopKind } from './schema.js';
5324
5324
  import type { StageHandler } from './stages.js';
5325
5325
  import type { ToolBackgroundService } from './tools/background.js';
5326
5326
  import type { GateDecision } from './tools/gate-answer.js';
@@ -5390,6 +5390,7 @@ export interface ProfileImageSpec {
5390
5390
  */
5391
5391
  includeText?: boolean;
5392
5392
  }
5393
+ import type { InboxItem, InboxPolicy } from '../conversation/types.js';
5393
5394
  import type { DecisionModelBinding, ModelBinding } from './protocols/binding.js';
5394
5395
  import type { ProviderHostOptions } from './protocols/runtime.js';
5395
5396
  export type { DecisionModelBinding, ModelBinding };
@@ -6354,16 +6355,6 @@ export interface TurnInput {
6354
6355
  voice?: TurnBlob[];
6355
6356
  /** The earlier messages of the conversation, when the host keeps them. */
6356
6357
  history?: TurnHistoryMessage[];
6357
- /**
6358
- * Background tool calls that settled after their turn, as the host stored them. The model reads
6359
- * each as a tool result, and this reply counts it as a remote read when the call was remote. Pass
6360
- * each one once: the turn emits it as a late_results event, so a history built from events holds
6361
- * it.
6362
- *
6363
- * @remarks Tool calls that settled after their turn, as the host stored them. Each counts as read
6364
- * in this reply.
6365
- */
6366
- lateResults?: ToolOperationOutcome[];
6367
6358
  /** A reply your host rejected and why, so that the model writes it again. */
6368
6359
  repair?: TurnRepairRequest;
6369
6360
  /**
@@ -6499,6 +6490,21 @@ export interface AgentRunRequest extends RunControls, ModelChoice {
6499
6490
  }
6500
6491
  /** A request to \`runTurn\`: the shared controls and the turn's input. */
6501
6492
  export interface TurnRequest extends AgentRunRequest {
6493
+ /**
6494
+ * Your function that gives the background tool calls that settled after their turn, as you
6495
+ * stored them. A text turn asks it when it opens, after each step whose calls settled, and once
6496
+ * the model has answered. The model reads each result as a tool result, and the turn counts it
6497
+ * as a remote read when the call was remote. A result lands once: one the conversation already
6498
+ * holds is not read again. Each landing is a late_results event, so a history built from events
6499
+ * holds it, and the event names the moment it landed. Once the model has answered, a landing
6500
+ * runs another step, so the model answers what it read.
6501
+ *
6502
+ * @remarks Asked only where the model reads what it gives: not mid-turn when the profile's
6503
+ * \`turnBehaviour.allowSteering\` is false, and not when another step would pass \`maxSteps\`. What
6504
+ * it gives at a moment it is not asked waits for a later turn. A throw is reported as
6505
+ * hook_failed, and the turn goes on without results.
6506
+ */
6507
+ lateResults?: LateResultsSource;
6502
6508
  /**
6503
6509
  * A session key a provider may use to route and cache this session's calls together.
6504
6510
  *
@@ -6564,19 +6570,33 @@ export interface TurnRequest extends AgentRunRequest {
6564
6570
  /** What the user sent for the turn. */
6565
6571
  input?: TurnInput;
6566
6572
  }
6573
+ /** Where a text turn asks for late results. */
6574
+ export interface LateResultsMoment {
6575
+ /**
6576
+ * \`pre_turn\` as the turn opens, \`post_tool\` after a step whose calls settled, \`before_end\` once
6577
+ * the model has answered.
6578
+ */
6579
+ stage: TurnInjectStage;
6580
+ /** The model steps the turn has taken; 0 as it opens. */
6581
+ step: number;
6582
+ /** The turn's \`host\`: what the app makes of the request. */
6583
+ host: unknown;
6584
+ signal?: AbortSignal;
6585
+ }
6586
+ /** Gives the late results a turn reads at a moment; see {@linkcode TurnRequest.lateResults}. */
6587
+ export type LateResultsSource = (moment: LateResultsMoment) => readonly ToolOperationOutcome[] | Promise<readonly ToolOperationOutcome[]>;
6567
6588
  /** A background call's end that the model has not read. */
6568
6589
  export interface LateResult {
6569
6590
  /** The id the session keeps the call under. */
6570
6591
  operationId: string;
6571
6592
  outcome: ToolOperationOutcome;
6572
6593
  }
6573
- /** A chat's ended results that no reply has read, as a {@linkcode LateResultsDecider} is asked. */
6574
- export interface LateResultsAsk {
6575
- /** The turn's \`host\`: what the app makes of the request. */
6576
- host: unknown;
6577
- /** The conversation reference the page holds. */
6578
- conversation: string;
6579
- results: readonly LateResult[];
6594
+ /**
6595
+ * A background call's end in a chat's inbox: the item a {@linkcode LateResultsDecider}'s policy
6596
+ * reads. Its \`id\` is the call's \`operationId\`.
6597
+ */
6598
+ export interface LateResultItem extends InboxItem<'late_result'> {
6599
+ outcome: ToolOperationOutcome;
6580
6600
  }
6581
6601
  /** A background call ended, and what Theorem lets the decider do about it. */
6582
6602
  export interface LateResultEnded {
@@ -6584,34 +6604,29 @@ export interface LateResultEnded {
6584
6604
  host: unknown;
6585
6605
  result: LateResult;
6586
6606
  /**
6587
- * Runs a reply to no message in \`conversation\`, as a page's wake does: the decider's \`give\` is
6588
- * asked with \`reason: 'wake'\`. It runs nothing while a reply waits on gates or answers a
6589
- * message, and a message posted meanwhile wins. The reference must stay the same across
6590
- * writes, so a store whose reference changes with each write cannot wake from the server.
6607
+ * Runs a reply to no message in \`conversation\`, as a page's wake does, for what the policy tells
6608
+ * at \`opening: 'wake'\`. While another reply holds the chat, that reply's hold tells what waits
6609
+ * as it ends, and this wake tries once more when the hold's lease runs out. The reference must
6610
+ * stay the same across writes, so a store whose reference changes with each write cannot wake
6611
+ * from the server.
6591
6612
  */
6592
6613
  wake(conversation: string): Promise<void>;
6593
6614
  /** Tells the pages open on the session to read the chat again. */
6594
6615
  notify(): Promise<void>;
6595
6616
  }
6596
6617
  /**
6597
- * Who tells the model that a background call ended. Theorem runs; the decider decides, and it
6598
- * keeps its own count of what it told, such as a cap or quiet hours.
6618
+ * Who tells the model that a background call ended. Theorem runs the replies under a hold of the
6619
+ * chat; the decider's policy chooses what each reply reads, and it keeps its own count of what it
6620
+ * told, such as a cap or quiet hours.
6599
6621
  */
6600
6622
  export interface LateResultsDecider {
6601
6623
  /**
6602
- * The results a reply gives the model, by \`operationId\`. \`reason\` is \`'message'\` for a reply to
6603
- * the person's message and \`'wake'\` for a reply to no message. Asked once for each reply, before
6604
- * its model runs. The model reads each result you return once. One you leave out stays for a
6605
- * later reply. A wake you give nothing runs no reply and leaves no mark.
6606
- */
6607
- give(ask: LateResultsAsk & {
6608
- reason: 'message' | 'wake';
6609
- }): readonly string[] | Promise<readonly string[]>;
6610
- /**
6611
- * Whether a page open on the chat wakes it now. Asked each time a page reads the chat, so it
6612
- * must change nothing. Say yes only when \`give\` would give something. Unset, no page wakes it.
6624
+ * What a reply reads now, and what no reply reads again. Asked as a reply opens, at its later
6625
+ * moments, as its hold ends (\`opening: 'follow_up'\`), and each time a page reads the chat
6626
+ * (\`opening: 'wake'\`, to say whether the page wakes it). It must change nothing. A result it
6627
+ * leaves waits for a later reply; one it gives up is reported once to \`onError\`.
6613
6628
  */
6614
- due?(ask: LateResultsAsk): boolean | Promise<boolean>;
6629
+ policy: InboxPolicy<LateResultItem>;
6615
6630
  /** A background call ended. Use \`wake\` to reply from the server, with no page open. */
6616
6631
  ended?(ended: LateResultEnded): void | Promise<void>;
6617
6632
  }
@@ -6636,8 +6651,8 @@ export interface TurnWiring {
6636
6651
  /**
6637
6652
  * Who tells the model that a background call ended, and when. Theorem runs the replies; this
6638
6653
  * decides. Unset, the model is never told: no page wakes the chat, and no reply reads a late
6639
- * result. \`pageWakes\` from \`@theoremjs/web/server\` lets the open page wake the chat, for an app
6640
- * with no server of its own.
6654
+ * result. \`tellEveryResult\` from \`@theoremjs/web/server\` tells each result to the first reply
6655
+ * that runs, and lets the open page wake the chat, for an app with no server of its own.
6641
6656
  */
6642
6657
  lateResultsDecider?: LateResultsDecider;
6643
6658
  }
@@ -6984,7 +6999,7 @@ import { z } from 'zod';
6984
6999
  import { type ErrorCopies, type GuardrailEvent } from '../guardrails/event-schemas.js';
6985
7000
  import type { ErrorKind } from '../guardrails/theorem-error.js';
6986
7001
  import { type JsonObject, type JsonValue } from './json.js';
6987
- import { AWAITING_USER_INPUT_STATUS, type CompactionMeter, type CompactionOutcome, type MediaInputKind, type StageApplyWarningCode, type ToolAccess, type ToolAuthType, type ToolPermission, type TurnStage, type TurnStopKind } from './schema.js';
7002
+ import { AWAITING_USER_INPUT_STATUS, type CompactionMeter, type CompactionOutcome, type MediaInputKind, type StageApplyWarningCode, type ToolAccess, type ToolAuthType, type ToolPermission, type TurnInjectStage, type TurnStage, type TurnStopKind } from './schema.js';
6988
7003
  export type { ErrorCopies, ErrorKind, GuardrailEvent };
6989
7004
  /** A text part of a history message. */
6990
7005
  export interface InteractionTextPart {
@@ -7260,7 +7275,7 @@ export type SessionEventOf<K extends SessionEventKind> = Extract<SessionEvent, {
7260
7275
  kind: K;
7261
7276
  }>;
7262
7277
  /** The host hooks whose crash the turn survives and reports as \`hook_failed\`. */
7263
- declare const HOOK_NAMES: readonly ["execution", "background", "onStage", "onEvent", "onAgentCall", "tools.preTool", "tools.t1Policy", "outputs.validation", "compaction.trigger"];
7278
+ declare const HOOK_NAMES: readonly ["execution", "background", "onStage", "lateResults", "onEvent", "onAgentCall", "tools.preTool", "tools.t1Policy", "outputs.validation", "compaction.trigger"];
7264
7279
  /** A host hook a \`hook_failed\` event names. */
7265
7280
  export type HookName = (typeof HOOK_NAMES)[number];
7266
7281
  /** Why a tool call failed, for the builder and for the user. */
@@ -7665,13 +7680,18 @@ export type TurnEvent = {
7665
7680
  reason: AttemptReason;
7666
7681
  }
7667
7682
  /**
7668
- * The message \`input.lateResults\` put in the conversation, role \`user\`. It enters a history built
7669
- * from events like any other message. \`operationIds\` are the calls whose results it holds.
7683
+ * The message \`lateResults\` put in the conversation, role \`user\`. It enters a history built from
7684
+ * events like any other message. \`operationIds\` are the calls whose results it holds; \`stage\` and
7685
+ * \`step\` are where it landed. \`inReply\` is true when it landed inside a reply: after the person's
7686
+ * message, mid-turn, or as a paused reply went on. Otherwise it opened the reply.
7670
7687
  */
7671
7688
  | {
7672
7689
  type: 'late_results';
7673
7690
  text: string;
7674
7691
  operationIds: string[];
7692
+ stage: TurnInjectStage;
7693
+ step: number;
7694
+ inReply: boolean;
7675
7695
  } | {
7676
7696
  type: 'media';
7677
7697
  media: {
@@ -9745,6 +9765,179 @@ export declare function retryAfterMs(headers: Headers, now?: number): number | u
9745
9765
  * taken, and the last answer or error goes back as it came. An abort ends the wait.
9746
9766
  */
9747
9767
  export declare function retryTransient(send: typeof fetch, wait?: Wait, timeLeft?: () => number): typeof fetch;
9768
+ `,"file:///node_modules/@theoremjs/agents/src/conversation/types.d.ts":`/**
9769
+ * The conversation layer's contract: what an app's storage gives the runner, and what the runner
9770
+ * gives the app's reply. One holder at a time reads a conversation's inbox; an item reaches the
9771
+ * model only through the holder, and is told once the reply that read it is saved.
9772
+ *
9773
+ * @module
9774
+ */
9775
+ import type { TurnInjectStage } from '../kernel/schema.js';
9776
+ /** A reply an item was handed to, which did not tell it. */
9777
+ export interface Handover {
9778
+ /** The hold the reply ran under. One hold can run several replies. */
9779
+ hold: string;
9780
+ /** The reply it was handed to. */
9781
+ reply: string;
9782
+ stage: TurnInjectStage;
9783
+ /** The model steps the reply had taken when it was handed; 0 as it opened. */
9784
+ step: number;
9785
+ /** Epoch milliseconds. */
9786
+ at: number;
9787
+ }
9788
+ /**
9789
+ * Something saved for a conversation that no saved reply has told: a call's late result, a due
9790
+ * reminder, a fact from outside. The app names the kinds.
9791
+ */
9792
+ export interface InboxItem<Kind extends string = string> {
9793
+ id: string;
9794
+ kind: Kind;
9795
+ /**
9796
+ * Each reply it was handed to that ended without telling it, oldest first. A reply that reads it
9797
+ * again can say what came of those earlier ones.
9798
+ */
9799
+ handovers: readonly Handover[];
9800
+ }
9801
+ /** What \`open\` finds: the conversation is now this hold's, or another hold has it until then. */
9802
+ export type Opened = {
9803
+ outcome: 'opened';
9804
+ } | {
9805
+ outcome: 'held';
9806
+ leasedUntil: number;
9807
+ };
9808
+ /** The items \`read\` returns, and the inbox's version as it read them. */
9809
+ export interface InboxRead<Item extends InboxItem> {
9810
+ items: readonly Item[];
9811
+ /** Moves each time an item arrives. \`release\` compares it. */
9812
+ version: string;
9813
+ }
9814
+ /** Where a reply takes items: the moment, and the reply's step. */
9815
+ export interface TakeAt {
9816
+ stage: TurnInjectStage;
9817
+ step: number;
9818
+ }
9819
+ /**
9820
+ * The app's storage for its conversations: one lock and one inbox each. An item arrives through the
9821
+ * app's own write, which moves the version. The reply's own save marks the items it told, in the
9822
+ * same write as the reply, and only while its hold still has the conversation.
9823
+ */
9824
+ export interface ConversationInbox<Item extends InboxItem = InboxItem> {
9825
+ /** Takes the conversation for \`hold\`, on a lease, or says until when another hold has it. */
9826
+ open(conversation: string, hold: string): Promise<Opened>;
9827
+ /**
9828
+ * Takes the conversation for \`hold\` from any hold that has it, as a person's message does. The
9829
+ * hold that had it can no longer renew, hand, or save, and what it was handed waits again.
9830
+ */
9831
+ takeOver(conversation: string, hold: string): Promise<void>;
9832
+ /** Extends \`hold\`'s lease. False when the hold no longer has the conversation. */
9833
+ renew(conversation: string, hold: string): Promise<boolean>;
9834
+ /**
9835
+ * The untold items no live hold has: those never handed, those given back, and those handed
9836
+ * under a hold whose lease ran out. Items a paused reply holds are not among them.
9837
+ */
9838
+ read(conversation: string): Promise<InboxRead<Item>>;
9839
+ /**
9840
+ * Hands \`ids\` to \`reply\` under \`hold\`, and returns the items it handed. Only the hold that has
9841
+ * the conversation can hand. The version does not move.
9842
+ */
9843
+ hand(conversation: string, hold: string, handover: Omit<Handover, 'hold' | 'at'>, ids: readonly string[]): Promise<readonly Item[]>;
9844
+ /**
9845
+ * Gives back the items \`reply\` read and did not tell, because it ended unsaved: an item it
9846
+ * resumed goes back to the reply that paused with it, and the rest wait for a later reply. Each
9847
+ * keeps the handover, so a later reply knows. The version does not move.
9848
+ */
9849
+ giveBack(conversation: string, hold: string, reply: string, ids: readonly string[]): Promise<void>;
9850
+ /**
9851
+ * Hands what a paused reply kept to \`handover.reply\`, as it goes on, and returns those items.
9852
+ * Only the hold that has the conversation can resume.
9853
+ */
9854
+ resume(conversation: string, hold: string, paused: string, handover: Omit<Handover, 'hold' | 'at'>): Promise<readonly Item[]>;
9855
+ /**
9856
+ * Gives up the items among \`ids\` that no live hold has: no reply reads them again. Returns
9857
+ * those it gave up. Only the hold that has the conversation can give up.
9858
+ */
9859
+ giveUp(conversation: string, hold: string, ids: readonly string[]): Promise<readonly Item[]>;
9860
+ /**
9861
+ * Lets the conversation go, only while the inbox is still at \`version\`. \`moved\` when an item
9862
+ * arrived since: \`hold\` keeps the conversation and reads again. \`lost\` when \`hold\` no longer
9863
+ * has it.
9864
+ */
9865
+ release(conversation: string, hold: string, version: string): Promise<'released' | 'moved' | 'lost'>;
9866
+ }
9867
+ /**
9868
+ * What opens a reply. A \`message\` or a \`wake\` opens the conversation under a new hold; a message
9869
+ * with \`takeOver\` takes it from any hold that has it. A \`follow_up\` runs under the hold a run
9870
+ * before it returned with \`continue\`.
9871
+ */
9872
+ export type ReplyStart = {
9873
+ opening: 'message';
9874
+ takeOver?: boolean;
9875
+ } | {
9876
+ opening: 'wake';
9877
+ } | {
9878
+ opening: 'follow_up';
9879
+ hold: string;
9880
+ };
9881
+ /** When the policy is asked: the moment, and what opened the reply. */
9882
+ export interface PolicyMoment extends TakeAt {
9883
+ /**
9884
+ * \`message\` for a reply to the person's message, \`wake\` for a reply to no message, and
9885
+ * \`follow_up\` at the end of a hold's reply, for items that arrived while it ran.
9886
+ */
9887
+ opening: 'message' | 'wake' | 'follow_up';
9888
+ }
9889
+ /**
9890
+ * What the policy chose among the items: those the model reads now, and those no reply will read.
9891
+ * The rest stay for later.
9892
+ */
9893
+ export interface PolicyChoice {
9894
+ tell: readonly string[];
9895
+ /** Items to give up, such as one a reply failed on too many times. They are reported once. */
9896
+ giveUp?: readonly string[];
9897
+ }
9898
+ /**
9899
+ * The app's rule for what may be told now. It must change nothing: the runner asks it again at
9900
+ * each moment.
9901
+ */
9902
+ export type InboxPolicy<Item extends InboxItem = InboxItem> = (items: readonly Item[], moment: PolicyMoment) => PolicyChoice | Promise<PolicyChoice>;
9903
+ /** One reply under a hold, as the runner gives it to the app. */
9904
+ export interface ReplyRun<Item extends InboxItem = InboxItem> {
9905
+ hold: string;
9906
+ reply: string;
9907
+ opening: PolicyMoment['opening'];
9908
+ /** The items the reply reads as it opens. */
9909
+ opened: readonly Item[];
9910
+ /** The items the reply reads at this later moment, handed to it as they are returned. */
9911
+ take(at: TakeAt): Promise<readonly Item[]>;
9912
+ /**
9913
+ * What the paused reply kept, handed to this reply as it goes on. If this reply ends without
9914
+ * telling them, they go back to the paused reply.
9915
+ */
9916
+ resume(paused: string): Promise<readonly Item[]>;
9917
+ /** Aborts once the hold no longer has the conversation: the reply must not save. */
9918
+ signal: AbortSignal;
9919
+ }
9920
+ /**
9921
+ * What one run of a conversation ended with. \`held\`: another hold has it, and tells what waits.
9922
+ * \`released\`: nothing waits that may be told now. \`continue\`: items wait that may be told now, and
9923
+ * the hold keeps the conversation for the caller's next reply. \`lost\`: the hold no longer has the
9924
+ * conversation, so another hold tells what waits. \`failure\` is what the reply threw: its items were given
9925
+ * back, and the caller reports it.
9926
+ */
9927
+ export type ConversationRun = {
9928
+ outcome: 'held';
9929
+ leasedUntil: number;
9930
+ } | {
9931
+ outcome: 'released';
9932
+ failure?: unknown;
9933
+ } | {
9934
+ outcome: 'continue';
9935
+ hold: string;
9936
+ failure?: unknown;
9937
+ } | {
9938
+ outcome: 'lost';
9939
+ failure?: unknown;
9940
+ };
9748
9941
  `,"file:///node_modules/@theoremjs/agents/src/kernel/tools/types.d.ts":`import type { z } from 'zod';
9749
9942
  import type { TurnDestinations } from '../../guardrails/destinations.js';
9750
9943
  import type { ResolveHost } from '../../guardrails/network.js';
@@ -14124,15 +14317,20 @@ export interface ToolDataRead {
14124
14317
  */
14125
14318
  declare function readToolData(content: string): ToolDataRead[];
14126
14319
  /**
14127
- * Whether a role \`user\` message holds tool results that \`input.lateResults\` opened. It is no one's
14320
+ * Whether a role \`user\` message holds tool results that \`TurnRequest.lateResults\` gave. It is no one's
14128
14321
  * word to the model. A person who types a fence only makes their own reply stricter.
14129
14322
  */
14130
14323
  declare function isLateResult(message: TurnHistoryMessage): boolean;
14131
- /** The history message \`input.lateResults\` opens; its metadata names the calls it holds. */
14132
- declare function lateResultsMessage(text: string, operationIds: readonly string[]): TurnHistoryMessage;
14324
+ /**
14325
+ * The history message \`TurnRequest.lateResults\` lands. Its metadata names the calls it holds, and
14326
+ * says when it landed inside a reply rather than opening one.
14327
+ */
14328
+ declare function lateResultsMessage(text: string, operationIds: readonly string[], inReply: boolean): TurnHistoryMessage;
14329
+ /** Whether \`message\` is a late result that landed inside a reply. Such a message opens no reply. */
14330
+ declare function landedInReply(message: TurnHistoryMessage): boolean;
14133
14331
  /** The calls whose late results a history message holds. */
14134
14332
  declare function lateResultIds(message: TurnHistoryMessage): string[];
14135
- export { isLateResult, lateResultIds, lateResultsMessage, readToolData, TOOL_CLOSE };
14333
+ export { isLateResult, landedInReply, lateResultIds, lateResultsMessage, readToolData, TOOL_CLOSE };
14136
14334
  `,"file:///node_modules/@theoremjs/agents/src/guardrails/tool-directives.d.ts":`import type { AdvisoryLevel } from './types.js';
14137
14335
  /**
14138
14336
  * What of a tool's text reads as an instruction to the agent: an order to set its instructions
@@ -0,0 +1 @@
1
+ import{E as e,d as t,x as n}from"./schemas-D7cgkv3L.js";import{H as r}from"./tool-schema-D2XhgIQV.js";import{$t as i,Ba as a,Cn as o,Da as s,Fi as c,Oa as l,Oi as u,Pi as ee,Qt as te,Sn as d,Ti as ne,Tn as f,Wa as re,Xa as ie,Y as ae,Zi as oe,ao as se,ba as ce,bn as le,ea as ue,fa as p,lo as m,na as de,nn as fe,ta as pe,uo as me,wi as h,xn as g,zi as _,zt as he}from"./shaped-data-C_l29gBe.js";import{c as v}from"./host-patterns-F-KZIzkF.js";import{D as ge,S as _e,g as y,k as ve,v as ye,w as be}from"./schema-CW04nV6r.js";import{a as xe,n as Se}from"./live-ingress-OuSlQ6q7.js";var Ce=2,we=4,Te=3,Ee=/(^|,)(\s*)("?)(?:([=@])|([+-])(?![0-9."]))/gm,De=/^[A-Za-z0-9+/]*={0,2}$/,Oe=new Set([`text/csv`,`text/plain`,`text/markdown`]);function b(e){let{maxFiles:t,maxBytes:n,maxTurnBytes:r,limitsByMime:i}=e;if(t&&n&&r)return{maxFiles:t,maxBytes:n,maxTurnBytes:r,limitsByMime:i}}function ke(e,t){if(t.limitsByMime){let n=f(e);if(t.limitsByMime[n])return t.limitsByMime[n];let[r]=n.split(`/`),i=`${r}/*`;if(t.limitsByMime[i])return t.limitsByMime[i]}return t.maxBytes}function x(e){return`uri`in e}function Ae(e){if(e.type===`speech`)throw new v(`request`,`Profile ${e.id} (speech) does not accept media input`);if(e.type===`live`)throw new v(`request`,`Profile ${e.id} (live) does not accept turn attachment input`);if(e.type===`host`||e.type===`decision`||e.type===`embedding`)throw new v(`request`,`Profile ${e.id} (${e.type}) does not accept turn input`);let t=b(e.inputs??{});if(!t)throw new v(`config`,`Profile ${e.id} must set maxFiles, maxBytes, and maxTurnBytes`);return t}function je(e){let t=0;return e.endsWith(`==`)?t=Ce:e.endsWith(`=`)&&(t=1),Math.floor(e.length*Te/we)-t}function Me(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return new TextDecoder(`latin1`).decode(e)}}function Ne(e){return e.replace(Ee,(e,...t)=>{let[n,r,i,a,o]=t;return`${n}${r}${i}'${a??``}${o??``}`})}function Pe(e,t,n){let r=Me(t);return e===`text/csv`&&(r=Ne(r)),new TextEncoder().encode(n.read(r))}function S(e,t){return t?{...e,fileName:t}:e}function C(e,t,n){return t.filter(t=>!g(e,t.mimeType)).map(e=>S({code:`mime_not_allowed`,params:{mimeType:e.mimeType,channel:n}},e.name))}function Fe(e,t){let n=[];e.length>t.maxFiles&&n.push({code:`too_many_files`,params:{maxFiles:t.maxFiles}});let r=0;for(let i of e){if(i.sizeBytes===void 0)continue;let e=ke(i.mimeType,t);i.sizeBytes>e&&n.push(S({code:`file_too_large`,params:{maxBytes:e}},i.name)),r+=i.sizeBytes}return r>t.maxTurnBytes&&n.push({code:`turn_too_large`,params:{maxTurnBytes:t.maxTurnBytes}}),n}function Ie(e,t,n){let r=[];return t.length>0&&!e.attachments&&r.push({code:`attachments_not_accepted`,params:{channel:`attachment`}}),n.length>0&&!e.voice&&r.push({code:`voice_not_accepted`,params:{channel:`voice`}}),r.length>0||t.length===0&&n.length===0?r:(e.attachments&&r.push(...C(e.attachments,t,`attachment`)),e.voice&&r.push(...C(e.voice,n,`voice`)),e.limits?[...r,...Fe([...t,...n],e.limits)]:[...r,{code:`limits_unconfigured`}])}var Le={mime_not_allowed:`attachments.mime_not_allowed`,too_many_files:`attachments.too_many_files`,too_many_of_kind:`attachments.too_many_of_kind`,file_too_large:`attachments.file_too_large`,turn_too_large:`attachments.turn_too_large`,attachments_not_accepted:`attachments.not_accepted`,voice_not_accepted:`attachments.not_accepted`,limits_unconfigured:`attachments.limits_unconfigured`};function Re(e){let t={};for(let[n,r]of Object.entries(e.params??{}))r!==void 0&&(t[n]=r);return e.fileName!==void 0&&(t.fileName=e.fileName),{key:Le[e.code],params:t}}function ze(e,t){let n=Re(e);return m(n.key,n.params,t)}function w(e){return new v(`input`,`attachments refused: ${e.map(e=>e.code).join(`, `)}`,{copy:e.map(Re)})}function T(e){if(!De.test(e))throw new v(`request`,`attachment data must be base64`);return je(e)}function E(e){let t={mimeType:e.mimeType,name:e.name};return x(e)||(t.sizeBytes=T(e.data)),t}function Be(e,t,n){if(!Ve(t,n))return;let r=Ae(e),i=Ie({attachments:d(e,`attachments`),voice:d(e,`voice`),limits:r},(t??[]).map(E),(n??[]).map(E));if(i.length>0)throw w(i)}function D(e,t){if(x(e))return e;let{mimeType:n,data:r}=e;if(!Oe.has(f(n)))return e;let i=Pe(n,s(r),t);return{...e,data:l(i)}}function Ve(e,t){return(e?.length??0)>0||(t?.length??0)>0}function He(e,t,n,r){return Be(e,t,n),{attachments:t?.length?t.map(e=>D(e,r.attachment)):t,voice:n?.length?n.map(e=>D(e,r.voice)):n}}function O(e){let t=Object.keys(e);return t.length===1?t[0]:void 0}function k(e){return e==null}function A(e){return k(e)||typeof e!=`object`||Array.isArray(e)?null:e}function j(e){let t=A(e);return!t||t.type!==void 0&&t.type!==`object`?null:t}function M(e){let t=e.required;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function N(e){let t=e.properties;return A(t)??{}}function Ue(e,t){return e?`${e}.${t}`:t}function P(e,t){t.push({path:e,error:`required field '${e}' is missing`})}async function We(e,t,n,r,i,a){if(!n)return;let o;try{o=await n(t,r)}catch(e){a.push(e),o={isValid:!1}}o.isValid||i.push({path:e,error:o.error||o.finding||`Validation failed for '${e}'`})}async function Ge(e){let{path:t,propSchema:n,child:r,isRequired:i,fields:a,options:o,failures:s,crashes:c}=e;if(k(r)){i&&P(t,s);return}await We(t,r,a?.[t],o,s,c);let l=j(n),u=l?A(r):null;l&&u&&await F(l,u,t,a,o,s,c)}async function F(e,t,n,r,i,a,o){let s=N(e),c=new Set(M(e)),l=new Set([...Object.keys(s),...c]),u=A(t);for(let e of l)await Ge({path:Ue(n,e),propSchema:s[e],child:u?.[e],isRequired:c.has(e),fields:r,options:i,failures:a,crashes:o})}async function Ke(e,t,n,r,i=[]){let a=j(e);if(!a)throw new v(`config`,`structured validation requires a JSON Schema object root`);let o=[];if(!A(t)){for(let e of M(a))P(e,o);return o}return await F(a,t,``,n,r,o,i),o}function qe(e,t){let n=e;for(let e of t.split(`.`)){let t=j(n);if(!t)return!1;let r=N(t);if(!Object.hasOwn(r,e)&&!M(t).includes(e))return!1;n=r[e]}return!0}function Je(e){return e.map(e=>e.error).join(`; `)}function I(e,t){let n=e;for(let e of t.split(`.`))n=A(n)?.[e];return n}function L(e,t,n){let[r,...i]=t.split(`.`),a=A(e)??{};return r===void 0?e:{...a,[r]:i.length?L(a[r],i.join(`.`),n):n}}async function Ye(e,t,n,r=[]){let i=[];for(let[a,o]of Object.entries(t??{})){let t=I(e,a);if(Array.isArray(t))for(let[e,s]of t.entries()){let t;try{t=await o.check(s,n)}catch(e){r.push(e),t={isValid:!1}}t.isValid||i.push({path:a,index:e,item:s,reason:t.error||t.finding||`Validation failed for '${a}'`,onFail:o.onFail})}}return i}function R(e,t){let n=e;for(let e of t.split(`.`)){let t=j(n);if(!t)return;n=N(t)[e]}let r=A(n);if(r?.type===`array`)return A(r.items)??void 0}function Xe(e,t,n,r){if(!n.provider?.trim()||!n.apiId?.trim())throw new v(`config`,m(`provider.binding_identity`))}function Ze(e){B(e.id,e.models),Y(e.id,e.observability),zt(e.id,e.inputs);for(let[t,n]of Object.entries(e.models))H(e.id,t,n);return{type:`embedding`,id:e.id,identity:{handle:e.identity.handle},models:e.models,defaultModel:V(e.id,e),allowModelSelect:e.allowModelSelect,inputs:e.inputs,guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function Qe(e){B(e.id,e.models),q(e.id,e.guardrails),Y(e.id,e.observability);for(let[t,n]of Object.entries(e.models))H(e.id,t,n);if(`text`in e.inputs&&e.inputs.text!==!1)throw new v(`config`,`Profile ${e.id}: a transcription takes a voice clip, so inputs.text must be false`);return{type:`transcription`,id:e.id,identity:{handle:e.identity.handle},...W(e),providerContinuation:void 0,maxSteps:void 0,inputs:{...e.inputs,text:!1},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function z(e,t,n,r){let i=r.safeParse(n);if(!i.success)throw new v(`config`,`Profile ${e} model '${t}': ${i.error.issues.map(e=>`${ae(e.path)}: ${e.message}`).join(`; `)}`)}function $e(e,t,n){if(z(e,t,n,i),Xe(e,t,n,`decision`),`retry`in n)throw new v(`config`,`Profile ${e} model '${t}': a decision binding takes no retry; a decision retries only a transient failure, by the kernel's rule`);if(n.timeoutMs!==void 0&&(!Number.isFinite(n.timeoutMs)||n.timeoutMs<=0))throw new v(`config`,`Profile ${e} model '${t}' timeoutMs must be > 0`)}function et(e){let t=e.models?O(e.models):void 0;if(!t)throw new v(`config`,`Profile ${e.id}: type 'decision' must declare exactly one model`);$e(e.id,t,e.models[t])}function tt(e){if(e.inputs.state!==`json`)throw new v(`config`,`Profile ${e.id}: decision inputs.state must be 'json'`);let t=e.inputs.maxStateBytes;if(t!==void 0&&!(Number.isInteger(t)&&t>0))throw new v(`config`,`Profile ${e.id}: decision inputs.maxStateBytes must be a positive integer`);if(!e.decision.contract.trim())throw new v(`config`,`Profile ${e.id}: decision.contract must be non-empty`)}function nt(e){return et(e),tt(e),Y(e.id,e.observability),{...e,identity:{handle:e.identity.handle}}}function rt(e){return e===void 0?{}:{parallel:e}}function it(e){return at(e.id,e.tools),Y(e.id,e.observability),{type:`host`,id:e.id,tools:{allow:e.tools.allow,...rt(e.tools.parallel)},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function at(e,t){if(!Array.isArray(t.allow))throw new v(`config`,`Profile ${e}: type 'host' must set tools.allow`)}function B(e,t){if(Object.keys(t).length===0)throw new v(`config`,`Profile ${e} must declare at least one model`)}function V(e,t){let n=t.defaultModel??O(t.models);if(!n)throw new v(`config`,`Profile ${e} must set defaultModel when more than one model is declared`);if(!t.models[n])throw new v(`config`,`Profile ${e} defaultModel '${n}' is not declared`);return n}function H(e,t,n){U(e,t,n),z(e,t,n,fe),U(e,t,n)}function U(e,t,n){let r=n.efforts;if(!r||Object.keys(r).length===0){if(n.defaultEffort||n.allowEffortSelect)throw new v(`config`,`Profile ${e} model '${t}': defaultEffort and allowEffortSelect require efforts`);return}for(let[n,i]of Object.entries(r))if(!_.includes(i))throw new v(`config`,`Profile ${e} model '${t}' effort '${n}': '${i}' is not a thinking level (${_.join(`, `)})`);let i=Object.keys(r),a=n.defaultEffort??(i.length===1?i[0]:void 0);if(!a)throw new v(`config`,`Profile ${e} model '${t}' must set defaultEffort when more than one effort is declared`);if(!r[a])throw new v(`config`,`Profile ${e} model '${t}' defaultEffort '${a}' is not declared`);if(n.allowEffortSelect&&i.length<2)throw new v(`config`,`Profile ${e} model '${t}' allowEffortSelect requires at least two efforts`)}function W(e){return{providerContinuation:e.providerContinuation?ce.parse(e.providerContinuation):{},models:e.models,defaultModel:V(e.id,e),allowModelSelect:e.allowModelSelect,maxSteps:e.maxSteps}}function G(e,t,n){if(n?.length){for(let r of n)if(!he(r))throw new v(`config`,`Profile ${e}: turnBehaviour.resumption.${t} may only include ContinueStopKind (${ne.join(` | `)}); got '${r}'`)}}function ot(e,t){t&&(G(e,`allowContinue`,t.allowContinue),G(e,`autoContinue`,t.autoContinue))}function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function st(e,t){let n=[e];for(let e of t)n=n.flatMap(t=>K(t)?e===`*`?Object.values(t):[t[e]]:[]);return n}var ct=Object.entries(ee).filter(([,e])=>e.required===!0).map(([e,t])=>[e,t.profileTypes]).sort(([e],[t])=>e.split(`.`).length-t.split(`.`).length);function lt(e){if(!K(e))throw new v(`config`,`Profile definition must be an object`);let t=typeof e.id==`string`&&e.id.trim()?e.id:void 0;if(!t)throw new v(`config`,`Profile definition must set id`);if(!c.find(t=>t===e.type))throw new v(`config`,`Profile ${t}: type must be one of ${c.join(`, `)}`)}function ut(e){let t=e.identity?.handle,n=[[`id`,e.id,64],[`identity.handle`,typeof t==`string`?t:``,32]];for(let[t,r,i]of n)if(!(Array.from(r).length<=i))throw new v(`config`,`Profile ${e.id.slice(0,64)}: ${t} must be at most ${i} characters`)}function dt(e){let{id:t,type:n}=e,r=e;for(let[e,i]of ct){if(i&&!i.includes(n))continue;let a=pe(e),o=st(r,a.slice(0,-1)),s=a[a.length-1];if(o.some(e=>{if(!K(e))return!1;let t=e[s];return t==null||t===``}))throw new v(`config`,`Profile ${t}: type '${n}' must set ${a.join(`.`)}`)}}function ft(e){let{id:t,type:n}=e;if(n!==`live`&&de(`inputs`).includes(n)&&e.inputs==null)throw new v(`config`,`Profile ${t}: type '${n}' must set inputs`)}function pt(e){let[t]=ue(e);if(!t)return;let{offValue:n,reason:r}=t.scope,i=n===void 0?``:` (other than ${n})`;throw new v(`config`,`Profile ${e.id}: type '${e.type}' must not set ${t.path}${i} — ${r}`)}function mt(e,t){let n=t.turnBehaviour;ot(e,n?.resumption)}function ht(e,t){let n=t=>new v(`config`,`Profile ${e}: ${t}`),r=t?.maxRetries;if(r!==void 0&&(!Number.isInteger(r)||r<0))throw n(`outputs.validation.maxRetries must be a non-negative integer`)}function q(e,t){let n=t=>new v(`config`,`Profile ${e}: ${t}`),r=Object.keys(t??{}).find(e=>!J.includes(e));if(r!==void 0)throw n(`guardrails.${r} is not a setting; it takes ${J.join(`, `)}`);_t(t?.blockedReply,n)}var J=[`quota`,`detect`,`blockedReply`,`network`,`taint`],gt=[`onBlock`,`maxRetries`];function _t(e,t){if(e===void 0)return;let n=Object.keys(e).find(e=>!gt.includes(e));if(n!==void 0)throw t(`guardrails.blockedReply.${n} is not a setting; it takes onBlock and maxRetries`);let{onBlock:r,maxRetries:i}=e;if(r!==void 0&&!a.includes(r))throw t(`guardrails.blockedReply.onBlock must be one of ${a.join(`, `)}`);if(i!==void 0&&(!Number.isInteger(i)||i<0))throw t(`guardrails.blockedReply.maxRetries must be a non-negative integer`)}function vt(e){let t=e.guardrails?.detect,n=e.type===`host`?p(`guardrails.detect`,t,re):p(`guardrails.detect`,t);if(n!==void 0)throw new v(`config`,`Profile ${e.id}: ${n}`)}function Y(e,t){try{let n=xe(t);if(!Number.isFinite(n.retainForDays))throw new v(`config`,`Profile ${e}: observability.retainForDays must be a finite number`);if(n.rotateAfterMiB<=0||!Number.isFinite(n.rotateAfterMiB))throw new v(`config`,`Profile ${e}: observability.rotateAfterMiB must be a positive number`)}catch(t){if(t instanceof v&&t.message.startsWith(`Profile `))throw t;let n=t instanceof Error?t.message:String(t);throw new v(ie(t),`Profile ${e}: ${n}`,{cause:t})}}function yt(e){if(e.type===`host`||e.type===`decision`||e.type===`speech`||e.type===`transcription`||e.type===`embedding`)return;let{options:t,system:n}=e.identity,r=n??``;_e(r,`Profile ${e.id} identity.system`);let i=be(r,t,e.inputs?.options);if(i)throw new v(`config`,`Profile ${e.id} identity.system: ${i}`)}function X(e){let t=bt(e),[n]=oe(e);if(n)throw new v(`config`,`Profile ${e.id}: ${n.path} ${n.message}`);return t}function bt(e){lt(e);for(let t of[`key`,`fallbackKey`,`protocol`,`provider`])if(t in e)throw new v(`config`,m(`provider.profile_configuration`,{profile:e.id,field:t}));pt(e),ft(e),dt(e),ut(e),e.labels&&me(e.labels,`Profile ${e.id}`);for(let t of se)if(e.labels?.[t]!==void 0)throw new v(`config`,`Profile ${e.id}: labels '${t}' is a host line, which a profile cannot change; set it with overrideLabels`);if(yt(e),vt(e),e.type===`host`)return it(e);if(e.type===`decision`)return nt(e);if(e.type===`embedding`)return Ze(e);if(e.type===`transcription`)return Qe(e);B(e.id,e.models),mt(e.id,e),q(e.id,e.guardrails),e.type===`text`&&ht(e.id,e.outputs?.validation),Y(e.id,e.observability);for(let[t,n]of Object.entries(e.models))H(e.id,t,n);let t=e.type===`speech`?{handle:e.identity.handle}:{handle:e.identity.handle,options:e.identity.options,system:e.identity.system},n=e.guardrails,r=e.observability,i=e.labels,a=W(e),o;switch(e.type){case`text`:o={type:`text`,id:e.id,identity:t,...a,tools:e.tools,inputs:e.inputs,outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i};break;case`image`:o={type:`image`,id:e.id,identity:t,...a,image:e.image,tools:e.tools,inputs:e.inputs,outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},Et(o.id,o.inputs.attachments?.accept),Tt(o.id,o.image);break;case`speech`:o={type:`speech`,id:e.id,identity:t,...a,speech:e.speech,outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i};break;case`live`:o={type:`live`,id:e.id,identity:t,...a,live:e.live,inputs:e.inputs,tools:{allow:e.tools.allow,...rt(e.tools.parallel)},turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},Se(o),Ot(o.id,o.live.contextCompression),Dt(o);break;default:throw new v(`config`,`Unknown profile type '${String(e)}'`)}return Ct(o),xt(o),St(o),o}function xt(e){let{maxSteps:t}=e;if(!(t===void 0||Number.isInteger(t)&&t>0))throw new v(`config`,`Profile ${e.id}: maxSteps must be a whole number of 1 or more; leave it out for the default of 20`)}function St(e){if(e.type===`text`&&e.turnBehaviour?.atStepLimit===`answer`&&e.maxSteps===1)throw new v(`config`,`Profile ${e.id}: turnBehaviour.atStepLimit 'answer' with maxSteps 1 leaves no step that can call a tool`)}function Ct(e){if(e.type===`live`)return;let t=e.outputs?.structured;if(!t||typeof t==`string`)return;let n=ve(e,t.by);if(!n)throw new v(`config`,`Profile ${e.id}: outputs.structured.by '${t.by}' is not one of the profile's options`);let r=ge(n),i=Object.keys(t.map).filter(e=>!r.includes(e));if(i.length)throw new v(`config`,`Profile ${e.id}: outputs.structured.map maps ${i.join(`, `)}, not a choice of option '${t.by}'`)}var wt={n:{ok:e=>Number.isInteger(e)&&e>=1,rule:`a whole number of 1 or more`},seed:{ok:Number.isInteger,rule:`a whole number`},outputCompression:{ok:e=>Number.isInteger(e)&&e>=0&&e<=100,rule:`a whole number from 0 to 100`}};function Tt(e,t){for(let[n,{ok:r,rule:i}]of Object.entries(wt)){let a=t[n];if(a!==void 0&&!r(a))throw new v(`config`,`Profile ${e}: image.${n} must be ${i}`)}t.references?.forEach((t,n)=>{let r=`Profile ${e}: image.references[${n}]`;if(le(t.mimeType)!==`image`)throw new v(`config`,`${r} must be an image, not '${t.mimeType}'`);if(!(x(t)?t.uri:t.data))throw new v(`config`,`${r} needs its bytes or its uri`)})}function Et(e,t){let n=t?.filter(e=>!g(u,e));if(n?.length)throw new v(`config`,`Profile ${e}: an image profile's attachments take images, video, and PDF only, not ${n.join(`, `)}`)}function Dt(e){let{greeting:t,resumed:n,sessionResumption:r}=e.live,i=`Profile ${e.id} live`;if(t!==void 0&&(typeof t!=`string`||!t.trim()))throw new v(`config`,`${i}.greeting must be a prompt; leave it out to wait`);if(!n)return;if(typeof n.prompt!=`string`||!n.prompt.trim())throw new v(`config`,`${i}.resumed.prompt must be a prompt`);let{afterMs:a}=n;if(a!==void 0&&!(Number.isFinite(a)&&a>=0))throw new v(`config`,`${i}.resumed.afterMs must be 0 or more milliseconds`);if(!r)throw new v(`config`,`${i}.resumed needs live.sessionResumption: without it no call resumes`)}function Ot(e,t){if(!t)return;let n=`Profile ${e} live.contextCompression`,r=t.triggerTokens,i=t.slidingWindow.targetTokens;if(Z(`${n}.triggerTokens`,r),Z(`${n}.slidingWindow.targetTokens`,i),r!==void 0&&i!==void 0&&i>=r)throw new v(`config`,`${n}: slidingWindow.targetTokens must be below triggerTokens`)}function Z(e,t){if(!(t===void 0||Number.isInteger(t)&&t>0))throw new v(`config`,`${e} must be a whole number above 0`)}function kt(e,t,n,r){let i=`Profile ${t.id} model ${n} compaction`;if(At(i,r),jt(i,r),r.profile===void 0){if(t.type!==`text`||t.inputs.text===!1)throw new v(`config`,`${i}: a profile that compacts itself must be a text profile that takes text`);return}let a=e.get(r.profile);if(!a)throw new v(`config`,`${i}: compaction profile '${r.profile}' must be registered before '${t.id}'`);if(a.type!==`text`||a.inputs.text===!1)throw new v(`config`,`${i}: compaction profile '${r.profile}' must be a text profile that takes text`)}function At(e,t){if(t.maxTokens<=0)throw new v(`config`,`${e}: maxTokens must be > 0`);if(t.compactAt<=0||t.compactAt>=1)throw new v(`config`,`${e}: compactAt must be in (0, 1)`)}function jt(e,t){if(t.previousExchanges<0)throw new v(`config`,`${e}: previousExchanges must be >= 0`);if(t.previousExchanges<1&&t.previousExchanges>=t.compactAt)throw new v(`config`,`${e}: previousExchanges as fraction (${t.previousExchanges}) must be < compactAt (${t.compactAt})`);if(t.previousExchanges>1&&!Number.isInteger(t.previousExchanges))throw new v(`config`,`${e}: previousExchanges >= 1 must be an integer`)}function Mt(e,t){for(let n of y(t))if(e.get(n)?.type===`builtin`)throw new v(`config`,t.type===`host`?`Profile ${t.id} lists builtin '${n}' in tools.allow — type 'host' never runs a model`:`Profile ${t.id} lists builtin '${n}' in tools.allow — declare it on models.*.builtInTools instead`)}function Nt(e,t){let n=ye(t)?.t2Loader;if(n){if(!y(t).includes(n))throw new v(`config`,`Profile ${t.id} tools.t2Loader '${n}' must also be listed in tools.allow`);if(e.get(n)?.type!==`function`)throw new v(`config`,`Profile ${t.id} tools.t2Loader '${n}' must be a registered type: 'function' tool`)}}function*Pt(e){for(let[t,n]of Object.entries(e.models))for(let e of n.builtInTools??[])yield{modelId:t,id:e}}function Ft(e,t){for(let{modelId:n,id:r}of Pt(t))if(e.get(r)?.type!==`builtin`)throw new v(`config`,`Profile ${t.id} model '${n}' lists '${r}' in builtInTools — not a registered builtin`)}function Q(e){let t=e.type===`text`?e.outputs?.structured:void 0;return t?typeof t==`string`?[t]:[...new Set([...Object.values(t.map),t.fallback])]:[]}function It(e,t){return t?.type===`text`?Q(t).flatMap(t=>{let n=e.find(t);return n?[n.jsonSchema]:[]}):[]}function Lt(e,t){let n=Q(t).map(n=>{let r=e.find(n);if(!r)throw new v(`config`,`Profile ${t.id}: outputs.structured names '${n}', which is not a registered schema; register it before the profile`);return r}),r=t.type===`text`?t.outputs?.validation:void 0,i=Object.keys(r?.fields??{}),a=Object.keys(r?.items??{});if(!i.length&&!a.length)return;if(!n.length)throw new v(`config`,`Profile ${t.id}: outputs.validation checks a structured reply, so it needs outputs.structured`);let o=a.filter(e=>!n.some(t=>R(t.jsonSchema,e)));if(o.length)throw new v(`config`,`Profile ${t.id}: outputs.validation.items has ${o.join(`, `)}, which no structured schema reaches as a list with an items schema`);let s=i.filter(e=>!n.some(t=>qe(t.jsonSchema,e)));if(s.length)throw new v(`config`,`Profile ${t.id}: outputs.validation.fields has ${s.join(`, `)}, which no structured schema reaches through object properties`)}function Rt(e){let t=o(e)?.context;if(!t)return;let n=h;if(t.from.length===0||t.from.some(e=>!n.includes(e)))throw new v(`config`,`Profile ${e.id}: inputs.context.from must list ${h.join(` or `)}`);if(!(Number.isInteger(t.maxChars)&&t.maxChars>0))throw new v(`config`,`Profile ${e.id}: inputs.context.maxChars must be a positive integer`)}function zt(e,t){if(!t)return;let{attachments:n,voice:r,maxFiles:i,maxBytes:a,maxTurnBytes:o,limitsByMime:s}=t,c={maxFiles:i,maxBytes:a,maxTurnBytes:o};if((n||r)&&Object.values(c).some(e=>e===void 0))throw new v(`config`,`Profile ${e} must set maxFiles, maxBytes, and maxTurnBytes`);for(let[e,t]of Object.entries(s??{}))c[`limitsByMime['${e}']`]=t;for(let[t,n]of Object.entries(c))if(n!==void 0&&!(Number.isInteger(n)&&n>0))throw new v(`config`,`Profile ${e}: inputs.${t} must be a positive integer`)}function Bt(e,t,n){let r=new Map,i=i=>{let a=X(i),s=n&&a.type!==`host`?{...a,models:Object.fromEntries(Object.entries(a.models).map(([e,t])=>[e,te(n.require(t.provider,t.apiId),t,a.type)]))}:a;if(Mt(e,s),Nt(e,s),s.type!==`host`&&s.type!==`decision`&&s.type!==`embedding`){Ft(e,s),zt(s.id,o(s)),Rt(s),Lt(t,s);for(let[e,t]of Object.entries(s.models))t.compaction&&kt(r,s,e,t.compaction)}r.set(s.id,s)};return{register:i,registerMany(e){for(let t of e)i(t)},get(e){let t=r.get(e);if(!t)throw new v(`config`,`Unknown profile '${e}'`);return t},find:e=>r.get(e),has:e=>r.has(e),list:()=>[...r.values()],clear:()=>r.clear()}}function Vt(e){let t=e?.trim()??``;if(t.startsWith(`AIza`))return`gemini`;if(t.startsWith(`sk-or-`))return`openrouter`}function Ht(e){let t;try{t=new URL(e.baseUrl)}catch{throw new v(`config`,`Enter a valid localhost URL.`)}if(![`http:`,`https:`].includes(t.protocol)||![`localhost`,`127.0.0.1`,`[::1]`].includes(t.hostname)||t.username||t.password||t.search||t.hash)throw new v(`config`,`Use a localhost URL without credentials, query parameters or a fragment.`);return{baseUrl:t.href.replace(/\/$/,``),fetch:(e,n)=>new URL(e instanceof Request?e.url:String(e)).origin===t.origin?fetch(e,{...n,redirect:`error`,credentials:`omit`}):Promise.reject(new v(`blocked`,`Local requests must stay on the configured origin.`))}}var Ut=n({data:t(n({id:e().min(1)}))});async function Wt(e,t){let n=Ht(e);if(!n?.fetch)throw new v(`config`,`Enter a local endpoint.`);let r=await n.fetch(`${n.baseUrl}/v1/models`,{signal:t,headers:{Accept:`application/json`}});if(!r.ok)throw new v(`network`,`Local model list returned HTTP ${r.status}.`);let i=Ut.safeParse(await r.json());if(!i.success)throw new v(`request`,`The endpoint returned an invalid model list.`);return[...new Set(i.data.data.map(e=>e.id))]}var Gt=`https://openrouter.ai/api/v1/models`,Kt=`https://openrouter.ai/api/v1/embeddings/models`,qt=[{id:`gemini-embedding-2-preview`,label:`Gemini Embeddings 2 (preview)`},{id:`gemini-embedding-001`,label:`Gemini Embedding 001`}],Jt=[{id:`liquid/lfm-2.5-embedding-350m:free`,label:`Liquid LFM 2.5 Embedding 350M (free)`},{id:`nvidia/nemotron-3-embed-1b:free`,label:`NVIDIA Nemotron 3 Embed 1B (free)`},{id:`nvidia/llama-nemotron-embed-vl-1b-v2:free`,label:`NVIDIA Llama Nemotron Embed VL 1B v2 (free)`}],Yt={text:`text`,image:`image`,speech:`speech`,transcription:`transcription`,live:void 0,embedding:void 0},Xt=n({data:t(n({id:e().min(1),name:e().optional(),architecture:n({output_modalities:t(e()).optional()}).optional()}))}),Zt=n({data:t(n({id:e().min(1),name:e().optional()}))}),Qt=n({models:t(n({name:e().min(1),displayName:e().optional(),supportedGenerationMethods:t(e()).optional()})).optional(),nextPageToken:e().optional()}),$t=5;async function $(e,t,n){let r=await fetch(t,{...n,redirect:`error`,credentials:`omit`});if(r.status===400||r.status===401||r.status===403)throw new v(`auth`,`${e} refused the key.`);if(!r.ok)throw new v(`network`,`${e} model list returned HTTP ${r.status}.`);return await r.json()}async function en(e,t,n,r){let i=n?.trim();if(t===`embedding`&&!i)return[...e===`openrouter`?Jt:qt];if(e===`openrouter`)return await tn(t,i,r);if(!i)throw new v(`auth`,`Choose a key to list Gemini models.`);return await rn(t,i,r)}async function tn(e,t,n){let r={signal:n,headers:{Accept:`application/json`,...t?{Authorization:[`Bearer`,t].join(` `)}:{}}};if(e===`embedding`){let e=Zt.safeParse(await $(`OpenRouter`,Kt,r));if(!e.success)throw new v(`bad_response`,`OpenRouter returned an invalid embedding model list.`);return e.data.data.map(e=>({id:e.id,label:e.name??e.id}))}let i=Yt[e];if(!i)return[];let a=Xt.safeParse(await $(`OpenRouter`,`${Gt}?output_modalities=${i}`,r));if(!a.success)throw new v(`bad_response`,`OpenRouter returned an invalid model list.`);return a.data.data.filter(e=>e.architecture?.output_modalities?.includes(i)??!0).map(e=>({id:e.id,label:e.name??e.id}))}var nn={live:`bidiGenerateContent`,embedding:`embedContent`};async function rn(e,t,n){let i=nn[e]??`generateContent`,a=[],o;for(let e=0;e<$t;e++){let e=new URL(r);e.searchParams.set(`pageSize`,`1000`),o&&e.searchParams.set(`pageToken`,o);let s=Qt.safeParse(await $(`Google`,e.href,{signal:n,headers:{Accept:`application/json`,"x-goog-api-key":t}}));if(!s.success)throw new v(`bad_response`,`Google returned an invalid model list.`);for(let e of s.data.models??[]){if(!e.supportedGenerationMethods?.includes(i))continue;let t=e.name.replace(/^models\//,``);a.push({id:t,label:e.displayName??t})}if(o=s.data.nextPageToken,!o)break}return a}function an(e){return[...new Set([e.key,e.fallbackKey,...Object.values(e.models??{}).flatMap(e=>[e.keySlot,e.fallbackKeySlot])].filter(e=>!!e))]}function on(e,t){return Object.fromEntries(e.map(e=>[e,Object.hasOwn(t,e)?t[e]:void 0]))}export{He as C,b as S,ze as _,an as a,T as b,X as c,Ke as d,Je as f,O as g,L as h,Ht as i,It as l,I as m,Wt as n,on as o,R as p,en as r,Bt as s,Vt as t,Ye as u,Ie as v,x,w as y};