@immediately-run/sdk 0.60.0 → 0.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/agentChatClient.d.cts +1 -0
  2. package/dist/agentChatClient.d.ts +1 -0
  3. package/dist/agentLoop.cjs +7 -1
  4. package/dist/agentLoop.cjs.map +1 -1
  5. package/dist/agentLoop.d.cts +21 -0
  6. package/dist/agentLoop.d.ts +21 -0
  7. package/dist/agentLoop.js +7 -1
  8. package/dist/agentLoop.js.map +1 -1
  9. package/dist/agentPause.cjs +68 -0
  10. package/dist/agentPause.cjs.map +1 -0
  11. package/dist/agentPause.d.cts +37 -0
  12. package/dist/agentPause.d.ts +37 -0
  13. package/dist/agentPause.js +45 -0
  14. package/dist/agentPause.js.map +1 -0
  15. package/dist/anchorClick.cjs +40 -0
  16. package/dist/anchorClick.cjs.map +1 -0
  17. package/dist/anchorClick.d.cts +23 -0
  18. package/dist/anchorClick.d.ts +23 -0
  19. package/dist/anchorClick.js +16 -0
  20. package/dist/anchorClick.js.map +1 -0
  21. package/dist/components/Link.cjs +4 -11
  22. package/dist/components/Link.cjs.map +1 -1
  23. package/dist/components/Link.d.cts +1 -1
  24. package/dist/components/Link.d.ts +1 -1
  25. package/dist/components/Link.js +3 -10
  26. package/dist/components/Link.js.map +1 -1
  27. package/dist/index.cjs +4 -0
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.cts +4 -2
  30. package/dist/index.d.ts +4 -2
  31. package/dist/index.js +2 -0
  32. package/dist/index.js.map +1 -1
  33. package/dist/llm.cjs +17 -1
  34. package/dist/llm.cjs.map +1 -1
  35. package/dist/llm.d.cts +34 -15
  36. package/dist/llm.d.ts +34 -15
  37. package/dist/llm.js +17 -1
  38. package/dist/llm.js.map +1 -1
  39. package/dist/openRepository.cjs +44 -0
  40. package/dist/openRepository.cjs.map +1 -0
  41. package/dist/openRepository.d.cts +36 -0
  42. package/dist/openRepository.d.ts +36 -0
  43. package/dist/openRepository.js +21 -0
  44. package/dist/openRepository.js.map +1 -0
  45. package/dist/platformLink.cjs +18 -3
  46. package/dist/platformLink.cjs.map +1 -1
  47. package/dist/platformLink.d.cts +33 -10
  48. package/dist/platformLink.d.ts +33 -10
  49. package/dist/platformLink.js +18 -3
  50. package/dist/platformLink.js.map +1 -1
  51. package/dist/protocolSchemes.cjs +1 -0
  52. package/dist/protocolSchemes.cjs.map +1 -1
  53. package/dist/protocolSchemes.d.cts +1 -0
  54. package/dist/protocolSchemes.d.ts +1 -0
  55. package/dist/protocolSchemes.js +2 -0
  56. package/dist/protocolSchemes.js.map +1 -1
  57. package/dist/recents.cjs +9 -1
  58. package/dist/recents.cjs.map +1 -1
  59. package/dist/recents.d.cts +6 -0
  60. package/dist/recents.d.ts +6 -0
  61. package/dist/recents.js +9 -1
  62. package/dist/recents.js.map +1 -1
  63. package/dist/region.cjs +22 -2
  64. package/dist/region.cjs.map +1 -1
  65. package/dist/region.d.cts +20 -1
  66. package/dist/region.d.ts +20 -1
  67. package/dist/region.js +18 -1
  68. package/dist/region.js.map +1 -1
  69. package/dist/urlUtils.cjs.map +1 -1
  70. package/dist/urlUtils.d.cts +6 -2
  71. package/dist/urlUtils.d.ts +6 -2
  72. package/dist/urlUtils.js.map +1 -1
  73. package/dist/version.cjs +1 -1
  74. package/dist/version.cjs.map +1 -1
  75. package/dist/version.d.cts +1 -1
  76. package/dist/version.d.ts +1 -1
  77. package/dist/version.js +1 -1
  78. package/dist/version.js.map +1 -1
  79. package/package.json +7 -3
package/dist/index.d.ts CHANGED
@@ -20,7 +20,7 @@ export { FormFactor, FormFactorClass, Orientation, getFormFactor, onFormFactorCh
20
20
  export { ChromeState, getChromeState, onChromeStateChange, useChromeState } from './chromeState.js';
21
21
  export { Workspace, getWorkspace, onWorkspaceChange, useWorkspace } from './workspace.js';
22
22
  export { HostAttention, HostAttentionKind, NO_HOST_ATTENTION, getHostAttention, onHostAttentionChange, useHostAttention } from './hostAttention.js';
23
- export { getRegion, useRegion } from './region.js';
23
+ export { getRegion, isRegionHidden, onRegionVisibilityChange, useRegion, useRegionHidden } from './region.js';
24
24
  export { Invite, MountQuery, MountRemoveReason, MountRule, RemovedMount, SandboxMount, SessionMount, SpaceError, acceptInvite, awaitMatchingMount, createSpace, declineInvite, findMount, getAppMountPath, getInvites, getMounts, getSessionMounts, importSettingsFromParent, listMyInvites, listPendingInvites, listSettingsApps, makeContentRef, mount, mountSpace, onInvitesChange, onMountsChange, onSessionMountsChange, openSettings, openSettingsOf, requestMount, requestSpace, resolveContentRef, resolveContentRefs, revokeInvite, unmountSpace, useInvites, useMounts, useSessionMounts, waitForMount } from './mounts.js';
25
25
  export { AnalyticsAck, AnalyticsPropValue, emitAnalyticsEvent, recordRoute, track, trackRoute } from './analytics.js';
26
26
  export { ContributeMode, ContributeOptions, ContributionEvent, ContributionResult, contribute } from './contribute.js';
@@ -31,7 +31,8 @@ export { HostFetchInit, HostFetchResponse, HostFetchStreamEvent, HostFetchStream
31
31
  export { FeedFetchResponse, FeedParams, feedFetch } from './feed.js';
32
32
  export { SecretError, SecretGrant, SecretHints, SecretQuery, SecretType, SecretView, getSecrets, onSecretsChange, requestAddSecret, requestSecret, revokeSecret, useSecrets } from './secrets.js';
33
33
  export { RecentProject, clearRecentProjects, listRecentProjects } from './recents.js';
34
- export { ChatDelta, ChatFeatures, ChatMessage, ChatProviderInfo, ChatProviderState, ChatRequest, ChatResult, ChatRole, ChatStopReason, ContentPart, ToolDef, chat, describeChat, describeChatState, normalizeProviderInfo, onChatProviderChange, onChatProviderStateChange, useChatProvider, useChatProviderState } from './llm.js';
34
+ export { OpenRepositoryError, OpenRepositoryErrorCode, RepositoryCoordinates, openRepository } from './openRepository.js';
35
+ export { ChatDelta, ChatExecutor, ChatFeatures, ChatMessage, ChatProviderInfo, ChatProviderState, ChatRequest, ChatResult, ChatRole, ChatStopReason, ChatTierModels, ContentPart, ToolDef, chat, describeChat, describeChatState, normalizeProviderInfo, onChatProviderChange, onChatProviderStateChange, useChatProvider, useChatProviderState } from './llm.js';
35
36
  export { BuildError, ConsoleEntry, ConsoleLevel, Diagnostics, DiagnosticsProvenance, getDiagnostics, onDiagnosticsChange, useDiagnostics } from './diagnostics.js';
36
37
  export { VcsActionError, VcsBranch, VcsChange, VcsPR, VcsState, getVcsState, onVcsStateChange, refreshDiff, refreshPRs, resetWorkingTree, useVcsState } from './vcs.js';
37
38
  export { FsChange, MountChange, getFsChange, onFsChange, useFsChange } from './onFsChange.js';
@@ -49,6 +50,7 @@ export { EvaluationContext, FileQueryResult, FilesMetadata, Metadata, MetadataQu
49
50
  export * from '@immediately-run/safe-content';
50
51
  export { AgentEvents, AgentMessage, AgentRole, AgentTool, COMPACTION_MARKER, ContentBlock, ImageBlock, ModelClient, ModelResponse, NUDGE_TEXT, ReasoningBlock, RunAgentOptions, StallReason, TextBlock, TokenUsage, ToolExecutor, ToolOutcome, ToolResultBlock, ToolUseBlock, compactTranscript, detectStall, estimateTokens, isContextOverflow, runAgent, shouldCompact } from './agentLoop.js';
51
52
  export { INTERRUPTED_TURN_TEXT, STEER_INTERRUPT_MARKER, STEER_MARKER, SteerController, SteerMessage, SteerMode, SteerSource, anySignal, parseSteer, steerWireText } from './agentSteering.js';
53
+ export { PauseController, PauseSource } from './agentPause.js';
52
54
  export { createChatModelClient } from './agentChatClient.js';
53
55
  export { HeadingSummary, METADATA_HEADINGS_KEY, METADATA_QUERY_TOOL_DESCRIPTOR, METADATA_QUERY_TOOL_NAME, MetadataQueryError, MetadataQueryInput, MetadataQueryRow, createMetadataQueryTool, executeMetadataQuery, globToRegExp, runMetadataQuery } from './metadataQueryTool.js';
54
56
  export { collectHeadings } from './collectHeadings.js';
package/dist/index.js CHANGED
@@ -33,6 +33,7 @@ export * from "./netFetch";
33
33
  export * from "./feed";
34
34
  export * from "./secrets";
35
35
  export * from "./recents";
36
+ export * from "./openRepository";
36
37
  export * from "./llm";
37
38
  export * from "./diagnostics";
38
39
  export * from "./vcs";
@@ -51,6 +52,7 @@ export * from "./sandboxTypes";
51
52
  export * from "./safeContent";
52
53
  export * from "./agentLoop";
53
54
  export * from "./agentSteering";
55
+ export * from "./agentPause";
54
56
  export * from "./agentChatClient";
55
57
  export * from "./metadataQueryTool";
56
58
  export * from "./collectHeadings";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './MDXProvider';\nexport * from './routing';\nexport * from './boot';\nexport * from './components/Include';\n// Only the component is public. `stripFrontmatter`/`appMountRelative` are module-level\n// exports so they can be unit-tested directly, NOT public API — the SDK's surface is\n// backwards-compatible forever, so an internal helper exported for a test's convenience is a\n// permanent commitment made for the wrong reason.\nexport { SafeInclude } from './components/SafeInclude';\nexport * from './sourceCache';\nexport * from './components/MDXComponents';\nexport * from './linkSpace';\nexport * from './bundle';\n// Deprecated `Corpus*` spellings of the above (R3-482); see `src/corpus.ts`.\nexport * from './corpus';\nexport * from './components/MountImage';\nexport * from './components/Routes';\nexport * from './hooks';\n// R3-276: the supported way for a viewer app to provide its own metadata store,\n// replacing a wholesale re-provision of `TinkerableContext` in app code.\nexport * from './metadataSource';\n// The deprecated injected-bundler adapters, re-exported so their deprecation notices\n// are visible in the published docs (R3-278; the window only narrows).\nexport { getInjectedMetadataEmitter, getInjectedMetadataSnapshot } from './injectedBundler';\nexport * from './auth';\nexport * from './theme';\nexport * from './editorContext';\nexport * from './editor';\nexport * from './formFactor';\nexport * from './chromeState';\nexport * from './workspace';\nexport * from './hostAttention';\nexport * from './region';\nexport * from './mounts';\nexport * from './analytics';\nexport * from './contribute';\nexport * from './catalog';\nexport * from './ipc';\nexport * from './dnd';\nexport * from './netFetch';\nexport * from './feed';\nexport * from './secrets';\nexport * from './recents'; // R3-485: the gated recent-projects read (page.home)\nexport * from './llm';\nexport * from './diagnostics';\nexport * from './vcs';\nexport * from './onFsChange';\nexport * from './fs';\nexport * from './debug';\nexport * from './tasks';\nexport * from './launch';\nexport * from './runtime';\nexport * from './irMarkers';\nexport * from './ready';\nexport * from './loading';\nexport * from './protocolStream';\nexport * from './protocolDeadline';\nexport * from './sandboxTypes';\nexport * from './safeContent';\n// R3-489 (GROVE_AGENT_SPEC): the embedded-agent seam every app shares — the tool-use\n// loop ported from agent-demo (`runAgent` over the host chat slot), the MDX metadata\n// query tool, the headings index collector, the deixis context block, and the fence\n// for corpus-derived bytes entering a loop.\nexport * from './agentLoop';\nexport * from './agentSteering';\nexport * from './agentChatClient';\nexport * from './metadataQueryTool';\nexport * from './collectHeadings';\nexport * from './agentContext';\nexport * from './fence';\nexport * from './platformLink';\n"],"mappings":";AAAA,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAKd,SAAS,mBAAmB;AAC5B,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAEd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAGd,cAAc;AAGd,SAAS,4BAA4B,mCAAmC;AACxE,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAKd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './MDXProvider';\nexport * from './routing';\nexport * from './boot';\nexport * from './components/Include';\n// Only the component is public. `stripFrontmatter`/`appMountRelative` are module-level\n// exports so they can be unit-tested directly, NOT public API — the SDK's surface is\n// backwards-compatible forever, so an internal helper exported for a test's convenience is a\n// permanent commitment made for the wrong reason.\nexport { SafeInclude } from './components/SafeInclude';\nexport * from './sourceCache';\nexport * from './components/MDXComponents';\nexport * from './linkSpace';\nexport * from './bundle';\n// Deprecated `Corpus*` spellings of the above (R3-482); see `src/corpus.ts`.\nexport * from './corpus';\nexport * from './components/MountImage';\nexport * from './components/Routes';\nexport * from './hooks';\n// R3-276: the supported way for a viewer app to provide its own metadata store,\n// replacing a wholesale re-provision of `TinkerableContext` in app code.\nexport * from './metadataSource';\n// The deprecated injected-bundler adapters, re-exported so their deprecation notices\n// are visible in the published docs (R3-278; the window only narrows).\nexport { getInjectedMetadataEmitter, getInjectedMetadataSnapshot } from './injectedBundler';\nexport * from './auth';\nexport * from './theme';\nexport * from './editorContext';\nexport * from './editor';\nexport * from './formFactor';\nexport * from './chromeState';\nexport * from './workspace';\nexport * from './hostAttention';\nexport * from './region';\nexport * from './mounts';\nexport * from './analytics';\nexport * from './contribute';\nexport * from './catalog';\nexport * from './ipc';\nexport * from './dnd';\nexport * from './netFetch';\nexport * from './feed';\nexport * from './secrets';\nexport * from './recents'; // R3-485: the gated recent-projects read (page.home)\nexport * from './openRepository'; // R3-476: host-mediated open-in-a-new-tab (route:read)\nexport * from './llm';\nexport * from './diagnostics';\nexport * from './vcs';\nexport * from './onFsChange';\nexport * from './fs';\nexport * from './debug';\nexport * from './tasks';\nexport * from './launch';\nexport * from './runtime';\nexport * from './irMarkers';\nexport * from './ready';\nexport * from './loading';\nexport * from './protocolStream';\nexport * from './protocolDeadline';\nexport * from './sandboxTypes';\nexport * from './safeContent';\n// R3-489 (GROVE_AGENT_SPEC): the embedded-agent seam every app shares — the tool-use\n// loop ported from agent-demo (`runAgent` over the host chat slot), the MDX metadata\n// query tool, the headings index collector, the deixis context block, and the fence\n// for corpus-derived bytes entering a loop.\nexport * from './agentLoop';\nexport * from './agentSteering';\nexport * from './agentPause';\nexport * from './agentChatClient';\nexport * from './metadataQueryTool';\nexport * from './collectHeadings';\nexport * from './agentContext';\nexport * from './fence';\nexport * from './platformLink';\n"],"mappings":";AAAA,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAKd,SAAS,mBAAmB;AAC5B,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAEd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAGd,cAAc;AAGd,SAAS,4BAA4B,mCAAmC;AACxE,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAKd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;","names":[]}
package/dist/llm.cjs CHANGED
@@ -35,10 +35,26 @@ function chat(req) {
35
35
  const { signal, ...params } = req;
36
36
  return (0, import_catalog.invokeStream)("llm:chat", params, signal);
37
37
  }
38
+ const EXECUTORS = ["browser-direct", "backend-proxied"];
39
+ const usableModels = (raw) => {
40
+ if (!raw || typeof raw !== "object") return void 0;
41
+ const { fast, smart } = raw;
42
+ return typeof fast === "string" && fast && typeof smart === "string" && smart ? { fast, smart } : void 0;
43
+ };
38
44
  function normalizeProviderInfo(provider) {
39
45
  if (!provider) return null;
46
+ const { displayName: rawName, executor: rawExecutor, models: rawModels, ...rest } = provider;
40
47
  const wire = provider.features;
41
- return { ...provider, features: { ...wire, reasoning: wire.reasoning === true } };
48
+ const executor = EXECUTORS.includes(rawExecutor) ? rawExecutor : void 0;
49
+ const displayName = typeof rawName === "string" && rawName ? rawName : void 0;
50
+ const models = usableModels(rawModels);
51
+ return {
52
+ ...rest,
53
+ features: { ...wire, reasoning: wire.reasoning === true },
54
+ ...displayName ? { displayName } : {},
55
+ ...executor ? { executor } : {},
56
+ ...models ? { models } : {}
57
+ };
42
58
  }
43
59
  let answered = false;
44
60
  const channel = (0, import_pushChannel.createPushChannel)({
package/dist/llm.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/llm.ts"],"sourcesContent":["// Provider-agnostic LLM chat — the `llm.chat@1` slot (SERVICE_PROVIDERS_SPEC;\n// LLM_AND_AGENTS_SPEC §8 D5).\n//\n// An app calls ONE chat slot and never worries about which provider the user has a\n// key for: the HOST resolves which vendor answers from the key the user holds\n// (`SecretView.boundOrigin`) plus their `preferredImplementation` choice, normalizes\n// the wire format, injects the key host-side at the §6 net:fetch point (the\n// look-at-nothing proxy), and streams normalized deltas back. The app never names a\n// vendor, never sees the key, and needs NO `net:fetch`/`secrets` grant of its own —\n// only the `llm:chat` capability (elevated, app-scoped: a fork earns it by consent).\n//\n// Inert until the host implements `protocol-llm` (the `chat` stream) + the\n// `llm-provider` describe channel; the contract ships here so apps (the file-explorer\n// summarize fork) can be written against it — exactly how `secrets.ts` shipped ahead\n// of `protocol-secrets`.\nimport { invokeStream } from './catalog';\nimport { createPushChannel } from './pushChannel';\nimport { LLM_PROVIDER, REQUEST_LLM_PROVIDER } from './generated/protocol';\n\n/** Who authored a {@link ChatMessage}. */\nexport type ChatRole = 'system' | 'user' | 'assistant' | 'tool';\n\n/** A part of a message. `image` is only honored when the resolved provider\n * advertises `features.vision` (§2.5); `tool-use`/`tool-result` only when it\n * advertises `features.tools` — branch on {@link describeChat} first. */\nexport type ContentPart =\n | { type: 'text'; text: string }\n | { type: 'image'; mimeType: string; data: string } // data: base64, no data: URL prefix\n // A tool call the model emitted on a prior `assistant` turn — replay it in the\n // conversation so a follow-up request carries the agentic history. Pairs with the\n // streamed `tool-call` {@link ChatDelta} that first surfaced it.\n | { type: 'tool-use'; id: string; name: string; input: Record<string, unknown> }\n // A block of the model's own REASONING from a prior `assistant` turn (R3-335).\n // Honored only when the resolved provider advertises `features.reasoning`.\n //\n // Echo these back. On some providers a reasoning block must be replayed — with its\n // `signature` intact and BEFORE the turn's text/tool-use — for the following turn to\n // be accepted at all; a loop that drops them is quietly lossy across turns in a way\n // that shows up as degraded output rather than an error. Pairs with the streamed\n // `reasoning` {@link ChatDelta}.\n | { type: 'reasoning'; text: string; signature?: string }\n // Reasoning the provider REDACTED: opaque bytes with no readable text, which still\n // have to be echoed back in place to keep the chain valid. Never render it.\n | { type: 'reasoning-redacted'; data: string }\n // The result of executing a `tool-use`, fed back so the model can continue. Carried\n // on a `user`/`tool`-role message; `toolCallId` matches the `tool-use` `id`.\n | { type: 'tool-result'; toolCallId: string; content: string; isError?: boolean };\n\n/** One message in a {@link ChatRequest}: a role plus its content parts. */\nexport interface ChatMessage {\n role: ChatRole;\n content: ContentPart[];\n}\n\n/** A tool the model may call — honored only when `features.tools`. */\nexport interface ToolDef {\n name: string;\n description?: string;\n /** JSON-Schema for the tool's arguments. */\n inputSchema: Record<string, unknown>;\n}\n\n/** A host-brokered chat completion request: the messages plus optional tools,\n * response format, and model hint (each honored per the provider's features). */\nexport interface ChatRequest {\n messages: ChatMessage[];\n /** Honored only when the resolved provider advertises `features.tools`. */\n tools?: ToolDef[];\n /** `'json'` honored only when `features.jsonMode`. Defaults to `'text'`. */\n responseFormat?: 'text' | 'json';\n maxTokens?: number;\n /** An ABSTRACT tier hint, never a vendor model id — the host maps it to a concrete\n * model on the resolved provider. Omit to take the provider's default. */\n modelHint?: 'fast' | 'smart';\n /** Abort the completion mid-stream. When it fires, the SDK sends the host a cancel\n * frame so the host aborts the upstream provider request and STOPS BILLING the\n * user's key — not merely stops the app-side iterator (LLM_AND_AGENTS_SPEC §3.3\n * \"abort the in-flight LLM request\", R3-224). Not sent over the wire (an\n * `AbortSignal` isn't serializable); handled SDK-side. */\n signal?: AbortSignal;\n}\n\n/** One streamed chunk. Consumers typically accumulate `text-delta`s. */\nexport type ChatDelta =\n | { type: 'text-delta'; text: string }\n | { type: 'tool-call'; id: string; name: string; input: unknown }\n // R3-335 — the model's reasoning as it streams. `reasoning-delta` carries the text\n // incrementally (render it live); the terminal `reasoning` carries the WHOLE block\n // plus the `signature` the provider may require on the echo, and is what a caller\n // should put back into the conversation. A provider without reasoning emits neither.\n | { type: 'reasoning-delta'; text: string }\n | { type: 'reasoning'; text: string; signature?: string }\n | { type: 'reasoning-redacted'; data: string }\n // Token accounting for the turn. `cacheReadTokens`/`cacheWriteTokens` are present\n // only on providers that report prompt caching (R3-336) — they are what makes a\n // caching claim verifiable rather than believed, and their ABSENCE is meaningful:\n // it says this provider reports nothing, not that nothing was cached.\n | {\n type: 'usage';\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n };\n\n/** Why generation stopped: natural `end`, `length` cap, a `tool` call, or content `filtered`. */\nexport type ChatStopReason = 'end' | 'length' | 'tool' | 'filtered';\n\n/** The terminal value of the {@link chat} stream. */\nexport interface ChatResult {\n stopReason: ChatStopReason;\n}\n\n/**\n * Stream a chat completion from whichever provider the user has configured.\n *\n * ```ts\n * let summary = '';\n * for await (const d of chat({ messages: [{ role: 'user', content: [{ type: 'text', text }] }] })) {\n * if (d.type === 'text-delta') summary += d.text;\n * }\n * ```\n *\n * Requires the `llm:chat` capability. If no provider is bound, the host first\n * draws the SP-7 connect-me gate itself (R3-456: the app never draws a\n * credential prompt — that is host chrome, SECRETS_SPEC S3):\n * - the user connects a key → the call retries once and streams normally;\n * - the user declines → the generator throws `code: 'cancelled'` (the same code\n * a declined powerbox produces — a working degraded state: catch it and\n * degrade, e.g. skip the AI feature);\n * - an older host without the gate throws `code: 'provider-not-configured'`.\n * A signed-out user throws `code: 'auth-required'`; an un-granted call throws\n * `forbidden`.\n */\nexport function chat(req: ChatRequest): AsyncGenerator<ChatDelta, ChatResult, void> {\n // Peel `signal` out of the request before it becomes wire params — an AbortSignal\n // can't cross the postMessage boundary as data; it drives the SDK-side cancel frame.\n const { signal, ...params } = req;\n return invokeStream<ChatDelta, ChatResult>('llm:chat', params as unknown as Record<string, unknown>, signal);\n}\n\n/** The resolved provider's advertised abilities (SERVICE_PROVIDERS_SPEC §2.5) — read\n * to branch/degrade (offer image upload only when `vision`). */\nexport interface ChatFeatures {\n vision: boolean;\n tools: boolean;\n jsonMode: boolean;\n /** R3-335: the provider emits reasoning blocks. Read it to decide whether to render\n * a thinking surface at all — an empty affordance on a provider that never thinks\n * is worse than none. Normalized to `false` by the channel when a host predating\n * R3-335 omits it, so this is never `undefined` in practice. */\n reasoning: boolean;\n maxContextTokens: number;\n}\n\n/** Info about the provider the host resolved for this app. `null` when no provider\n * is bound (SP-7: prompt the user to add a key before calling {@link chat}). */\nexport interface ChatProviderInfo {\n /** Opaque provider id, e.g. `llm.chat.anthropic` — never a vendor secret or model id. */\n providerId: string;\n /** True for Host-proxied providers (host-vouched, SP-9); false for app-level ones,\n * whose `features` are an untrusted claim. */\n hostVouched: boolean;\n features: ChatFeatures;\n // NOTE (R3-300): `displayName`, `executor` and the resolved per-tier `models` belong\n // here — an app rendering provider state wants all three. They are NOT added yet,\n // deliberately: this interface IS the `llm-provider` channel's declared value, so\n // adding a field is a WIRE change, and the wire is owned by\n // `@immediately-run/sandbox-protocol` (descriptor edit → publish → pin bump on both\n // sides). The protocol snapshot gate enforces exactly that, and it is right to. The\n // enrichment rides R3-307's publish, which already has to touch those descriptors —\n // one publish for two additions rather than two.\n}\n\n/**\n * Whether the host has told us about a provider yet, and if so whether one is bound.\n *\n * THREE states, because two is the bug (R3-300). `describeChat()` returns `null` both\n * when no provider is configured AND when the channel has not answered — so an app\n * cannot tell \"you need a key\" from \"ask again in a moment\", and consuming apps\n * rendered a misleading \"connect a key\" banner at users who had one. `unknown` is the\n * state before the host answers; it is not an error and not a prompt to act.\n *\n * **`unknown` is TRANSIENT — the host answers every frame** (R3-419;\n * `LLM_AND_AGENTS_SPEC §4.1` R-LLM-1..3). An app that does not hold `llm:chat` is not\n * met with silence: it is answered `not-configured`, the same terminal state as a user\n * with no key, because from the app's side those are the same fact — do not render a\n * provider, do offer the connect path. So it is correct to treat a `unknown` that\n * persists as a host bug rather than as a state to design around, and WRONG to render a\n * spinner with no timeout on it. (Before R3-419 the host withheld the channel entirely\n * from an ungranted frame, and `unknown` stood forever — that is the failure this note\n * exists to keep from being re-created on the app side.)\n */\nexport type ChatProviderState =\n | { status: 'unknown' }\n | { status: 'not-configured' }\n | { status: 'configured'; provider: ChatProviderInfo };\n\n// The `llm-provider` describe channel (Recipe A): the host pushes the resolved\n// provider info on change and replays it on register-frame, gated by `llm:chat`.\n// A message with no `provider` key is ignored; an explicit `null` means \"no provider\n// bound\", which is now REPRESENTABLE as distinct from \"not yet answered\".\n// The channel's VALUE stays exactly what the wire carries — `ChatProviderInfo | null` —\n// because the wire did not change here and the protocol snapshot gate reads this type as\n// the channel's shape. The three-state lives BESIDE it: `answered` records whether the host\n// has ever spoken on this channel, which is the one bit `null` cannot carry. Deriving the\n// state rather than widening the channel keeps the wire contract byte-identical, which it\n// is (SDK_PACKAGING_SPEC §9: the wire is additive-only, and this is not a wire change).\n/**\n * Fill in feature flags a host older than the field does not send (R3-335).\n *\n * `features.reasoning` arrived after `ChatFeatures` shipped, so a host predating it\n * omits the key. `undefined` reads as falsy everywhere EXCEPT a `'reasoning' in\n * features` check, which is exactly the kind of difference that produces one wrong\n * branch a year later — so it is normalized here, once, rather than left to every\n * caller. Absent means \"does not reason\": the fail-closed reading.\n *\n * Exported for its own test; not part of the public surface (`index.ts` re-exports\n * this module wholesale, so it is reachable — it is documented as internal rather\n * than hidden behind a lie).\n * @internal\n */\nexport function normalizeProviderInfo(provider: ChatProviderInfo | null): ChatProviderInfo | null {\n if (!provider) return null;\n // The wire value is whatever the host sent, which may predate `reasoning` — so read\n // it as partial rather than trusting the declared type, and decide the flag explicitly.\n const wire = provider.features as Partial<ChatFeatures>;\n return { ...provider, features: { ...wire, reasoning: wire.reasoning === true } as ChatFeatures };\n}\n\nlet answered = false;\nconst channel = createPushChannel<ChatProviderInfo | null>({\n pushType: LLM_PROVIDER,\n requestType: REQUEST_LLM_PROVIDER,\n initial: null,\n parse: (msg) => {\n if (!('provider' in msg)) return undefined;\n answered = true;\n return normalizeProviderInfo((msg.provider as ChatProviderInfo | null) ?? null);\n },\n});\n\n/** Derive the three-state from the wire value plus whether the host has answered. */\nconst stateOf = (provider: ChatProviderInfo | null): ChatProviderState =>\n !answered ? { status: 'unknown' } : provider ? { status: 'configured', provider } : { status: 'not-configured' };\n\n/**\n * The provider the host resolved for this app, or `null`.\n *\n * Kept for compatibility (`ways_of_working §6`, additive-only): it collapses `unknown`\n * and `not-configured` to `null`. Prefer {@link describeChatState} when the difference\n * matters — which is any time you would render \"connect a key\", because doing that in\n * the `unknown` state is exactly the false banner R3-300 fixes.\n */\nexport const describeChat = (): ChatProviderInfo | null => channel.get();\n\n/** The three-state read: `unknown` before the host answers, then configured or not. */\nexport const describeChatState = (): ChatProviderState => stateOf(channel.get());\n\n/** Subscribe to provider changes (key added/revoked, preference changed). Invoked\n * immediately with the current value, then on every change. Returns unsubscribe. */\nexport const onChatProviderChange = (listener: (provider: ChatProviderInfo | null) => void): (() => void) =>\n channel.onChange(listener);\n\n/** Subscribe to the three-state provider description. */\nexport const onChatProviderStateChange = (listener: (state: ChatProviderState) => void): (() => void) =>\n channel.onChange((p) => listener(stateOf(p)));\n\n/** React hook returning the resolved chat provider (or `null`), re-rendering on\n * change — gate the summarize affordance on `provider !== null`. */\nexport const useChatProvider = (): ChatProviderInfo | null => channel.use();\n\n/**\n * React hook returning the three-state description.\n *\n * Use this to render provider state honestly: show nothing (or a neutral placeholder)\n * while `unknown`, the connect affordance only on `not-configured`, and the provider's\n * name on `configured`.\n */\nexport const useChatProviderState = (): ChatProviderState => stateOf(channel.use());\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,qBAA6B;AAC7B,yBAAkC;AAClC,sBAAmD;AAqH5C,SAAS,KAAK,KAA+D;AAGlF,QAAM,EAAE,QAAQ,GAAG,OAAO,IAAI;AAC9B,aAAO,6BAAoC,YAAY,QAA8C,MAAM;AAC7G;AAmFO,SAAS,sBAAsB,UAA4D;AAChG,MAAI,CAAC,SAAU,QAAO;AAGtB,QAAM,OAAO,SAAS;AACtB,SAAO,EAAE,GAAG,UAAU,UAAU,EAAE,GAAG,MAAM,WAAW,KAAK,cAAc,KAAK,EAAkB;AAClG;AAEA,IAAI,WAAW;AACf,MAAM,cAAU,sCAA2C;AAAA,EACzD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AACd,QAAI,EAAE,cAAc,KAAM,QAAO;AACjC,eAAW;AACX,WAAO,sBAAuB,IAAI,YAAwC,IAAI;AAAA,EAChF;AACF,CAAC;AAGD,MAAM,UAAU,CAAC,aACf,CAAC,WAAW,EAAE,QAAQ,UAAU,IAAI,WAAW,EAAE,QAAQ,cAAc,SAAS,IAAI,EAAE,QAAQ,iBAAiB;AAU1G,MAAM,eAAe,MAA+B,QAAQ,IAAI;AAGhE,MAAM,oBAAoB,MAAyB,QAAQ,QAAQ,IAAI,CAAC;AAIxE,MAAM,uBAAuB,CAAC,aACnC,QAAQ,SAAS,QAAQ;AAGpB,MAAM,4BAA4B,CAAC,aACxC,QAAQ,SAAS,CAAC,MAAM,SAAS,QAAQ,CAAC,CAAC,CAAC;AAIvC,MAAM,kBAAkB,MAA+B,QAAQ,IAAI;AASnE,MAAM,uBAAuB,MAAyB,QAAQ,QAAQ,IAAI,CAAC;","names":[]}
1
+ {"version":3,"sources":["../src/llm.ts"],"sourcesContent":["// Provider-agnostic LLM chat — the `llm.chat@1` slot (SERVICE_PROVIDERS_SPEC;\n// LLM_AND_AGENTS_SPEC §8 D5).\n//\n// An app calls ONE chat slot and never worries about which provider the user has a\n// key for: the HOST resolves which vendor answers from the key the user holds\n// (`SecretView.boundOrigin`) plus their `preferredImplementation` choice, normalizes\n// the wire format, injects the key host-side at the §6 net:fetch point (the\n// look-at-nothing proxy), and streams normalized deltas back. The app never names a\n// vendor, never sees the key, and needs NO `net:fetch`/`secrets` grant of its own —\n// only the `llm:chat` capability (elevated, app-scoped: a fork earns it by consent).\n//\n// Inert until the host implements `protocol-llm` (the `chat` stream) + the\n// `llm-provider` describe channel; the contract ships here so apps (the file-explorer\n// summarize fork) can be written against it — exactly how `secrets.ts` shipped ahead\n// of `protocol-secrets`.\nimport { invokeStream } from './catalog';\nimport { createPushChannel } from './pushChannel';\nimport { LLM_PROVIDER, REQUEST_LLM_PROVIDER } from './generated/protocol';\n\n/** Who authored a {@link ChatMessage}. */\nexport type ChatRole = 'system' | 'user' | 'assistant' | 'tool';\n\n/** A part of a message. `image` is only honored when the resolved provider\n * advertises `features.vision` (§2.5); `tool-use`/`tool-result` only when it\n * advertises `features.tools` — branch on {@link describeChat} first. */\nexport type ContentPart =\n | { type: 'text'; text: string }\n | { type: 'image'; mimeType: string; data: string } // data: base64, no data: URL prefix\n // A tool call the model emitted on a prior `assistant` turn — replay it in the\n // conversation so a follow-up request carries the agentic history. Pairs with the\n // streamed `tool-call` {@link ChatDelta} that first surfaced it.\n | { type: 'tool-use'; id: string; name: string; input: Record<string, unknown> }\n // A block of the model's own REASONING from a prior `assistant` turn (R3-335).\n // Honored only when the resolved provider advertises `features.reasoning`.\n //\n // Echo these back. On some providers a reasoning block must be replayed — with its\n // `signature` intact and BEFORE the turn's text/tool-use — for the following turn to\n // be accepted at all; a loop that drops them is quietly lossy across turns in a way\n // that shows up as degraded output rather than an error. Pairs with the streamed\n // `reasoning` {@link ChatDelta}.\n | { type: 'reasoning'; text: string; signature?: string }\n // Reasoning the provider REDACTED: opaque bytes with no readable text, which still\n // have to be echoed back in place to keep the chain valid. Never render it.\n | { type: 'reasoning-redacted'; data: string }\n // The result of executing a `tool-use`, fed back so the model can continue. Carried\n // on a `user`/`tool`-role message; `toolCallId` matches the `tool-use` `id`.\n | { type: 'tool-result'; toolCallId: string; content: string; isError?: boolean };\n\n/** One message in a {@link ChatRequest}: a role plus its content parts. */\nexport interface ChatMessage {\n role: ChatRole;\n content: ContentPart[];\n}\n\n/** A tool the model may call — honored only when `features.tools`. */\nexport interface ToolDef {\n name: string;\n description?: string;\n /** JSON-Schema for the tool's arguments. */\n inputSchema: Record<string, unknown>;\n}\n\n/** A host-brokered chat completion request: the messages plus optional tools,\n * response format, and model hint (each honored per the provider's features). */\nexport interface ChatRequest {\n messages: ChatMessage[];\n /** Honored only when the resolved provider advertises `features.tools`. */\n tools?: ToolDef[];\n /** `'json'` honored only when `features.jsonMode`. Defaults to `'text'`. */\n responseFormat?: 'text' | 'json';\n maxTokens?: number;\n /** An ABSTRACT tier hint, never a vendor model id — the host maps it to a concrete\n * model on the resolved provider. Omit to take the provider's default. */\n modelHint?: 'fast' | 'smart';\n /** Abort the completion mid-stream. When it fires, the SDK sends the host a cancel\n * frame so the host aborts the upstream provider request and STOPS BILLING the\n * user's key — not merely stops the app-side iterator (LLM_AND_AGENTS_SPEC §3.3\n * \"abort the in-flight LLM request\", R3-224). Not sent over the wire (an\n * `AbortSignal` isn't serializable); handled SDK-side. */\n signal?: AbortSignal;\n}\n\n/** One streamed chunk. Consumers typically accumulate `text-delta`s. */\nexport type ChatDelta =\n | { type: 'text-delta'; text: string }\n | { type: 'tool-call'; id: string; name: string; input: unknown }\n // R3-335 — the model's reasoning as it streams. `reasoning-delta` carries the text\n // incrementally (render it live); the terminal `reasoning` carries the WHOLE block\n // plus the `signature` the provider may require on the echo, and is what a caller\n // should put back into the conversation. A provider without reasoning emits neither.\n | { type: 'reasoning-delta'; text: string }\n | { type: 'reasoning'; text: string; signature?: string }\n | { type: 'reasoning-redacted'; data: string }\n // Token accounting for the turn. `cacheReadTokens`/`cacheWriteTokens` are present\n // only on providers that report prompt caching (R3-336) — they are what makes a\n // caching claim verifiable rather than believed, and their ABSENCE is meaningful:\n // it says this provider reports nothing, not that nothing was cached.\n | {\n type: 'usage';\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n };\n\n/** Why generation stopped: natural `end`, `length` cap, a `tool` call, or content `filtered`. */\nexport type ChatStopReason = 'end' | 'length' | 'tool' | 'filtered';\n\n/** The terminal value of the {@link chat} stream. */\nexport interface ChatResult {\n stopReason: ChatStopReason;\n}\n\n/**\n * Stream a chat completion from whichever provider the user has configured.\n *\n * ```ts\n * let summary = '';\n * for await (const d of chat({ messages: [{ role: 'user', content: [{ type: 'text', text }] }] })) {\n * if (d.type === 'text-delta') summary += d.text;\n * }\n * ```\n *\n * Requires the `llm:chat` capability. If no provider is bound, the host first\n * draws the SP-7 connect-me gate itself (R3-456: the app never draws a\n * credential prompt — that is host chrome, SECRETS_SPEC S3):\n * - the user connects a key → the call retries once and streams normally;\n * - the user declines → the generator throws `code: 'cancelled'` (the same code\n * a declined powerbox produces — a working degraded state: catch it and\n * degrade, e.g. skip the AI feature);\n * - an older host without the gate throws `code: 'provider-not-configured'`.\n * A signed-out user throws `code: 'auth-required'`; an un-granted call throws\n * `forbidden`.\n */\nexport function chat(req: ChatRequest): AsyncGenerator<ChatDelta, ChatResult, void> {\n // Peel `signal` out of the request before it becomes wire params — an AbortSignal\n // can't cross the postMessage boundary as data; it drives the SDK-side cancel frame.\n const { signal, ...params } = req;\n return invokeStream<ChatDelta, ChatResult>('llm:chat', params as unknown as Record<string, unknown>, signal);\n}\n\n/** The resolved provider's advertised abilities (SERVICE_PROVIDERS_SPEC §2.5) — read\n * to branch/degrade (offer image upload only when `vision`). */\nexport interface ChatFeatures {\n vision: boolean;\n tools: boolean;\n jsonMode: boolean;\n /** R3-335: the provider emits reasoning blocks. Read it to decide whether to render\n * a thinking surface at all — an empty affordance on a provider that never thinks\n * is worse than none. Normalized to `false` by the channel when a host predating\n * R3-335 omits it, so this is never `undefined` in practice. */\n reasoning: boolean;\n maxContextTokens: number;\n}\n\n/** How the resolved provider's requests physically leave the browser. Read it to\n * DESCRIBE routing where that matters to the person (\"runs in your browser\" vs\n * \"routed through immediately.run\") — never to draw host chrome or a consent prompt,\n * which remain the host's (UI_AS_APPS §8 T15). */\nexport type ChatExecutor = 'browser-direct' | 'backend-proxied';\n\n/** The concrete model each abstract tier resolves to right now. */\nexport interface ChatTierModels {\n fast: string;\n smart: string;\n}\n\n/** Info about the provider the host resolved for this app. `null` when no provider\n * is bound (SP-7: prompt the user to add a key before calling {@link chat}). */\nexport interface ChatProviderInfo {\n /** Opaque provider id, e.g. `llm.chat.anthropic` — never a vendor secret or model id. */\n providerId: string;\n /** True for Host-proxied providers (host-vouched, SP-9); false for app-level ones,\n * whose `features` are an untrusted claim. */\n hostVouched: boolean;\n features: ChatFeatures;\n /** The provider's human name, e.g. `OpenRouter` — what to put in front of a person.\n * Absent on a host that predates the field: fall back to your own copy rather than\n * rendering the id, which is a platform identifier and not a name. */\n displayName?: string;\n /** How this provider's requests leave the browser. Absent on a host that predates the\n * field, which is NOT the same as `browser-direct` — say nothing about routing rather\n * than guess at it. */\n executor?: ChatExecutor;\n /**\n * The concrete model each {@link ChatRequest.modelHint} tier resolves to — what a\n * `smart` request would actually run, after the user's own preference.\n *\n * Read-only, and it does not weaken `LLM_AND_AGENTS_SPEC §0`: an app still names no\n * model, and {@link ChatRequest} still carries only the abstract hint. It is here so an\n * app can be HONEST about what answered — a transcript that says which model wrote a\n * reply, a warning that names the model about to be spent on — instead of showing a\n * blank where the platform knows the answer. The user picks the model in host settings;\n * the app reports it.\n *\n * Absent on a host that predates the field. It changes when the user changes their\n * preference, so read it through {@link onChatProviderChange} rather than caching it.\n */\n models?: ChatTierModels;\n}\n\n/**\n * Whether the host has told us about a provider yet, and if so whether one is bound.\n *\n * THREE states, because two is the bug (R3-300). `describeChat()` returns `null` both\n * when no provider is configured AND when the channel has not answered — so an app\n * cannot tell \"you need a key\" from \"ask again in a moment\", and consuming apps\n * rendered a misleading \"connect a key\" banner at users who had one. `unknown` is the\n * state before the host answers; it is not an error and not a prompt to act.\n *\n * **`unknown` is TRANSIENT — the host answers every frame** (R3-419;\n * `LLM_AND_AGENTS_SPEC §4.1` R-LLM-1..3). An app that does not hold `llm:chat` is not\n * met with silence: it is answered `not-configured`, the same terminal state as a user\n * with no key, because from the app's side those are the same fact — do not render a\n * provider, do offer the connect path. So it is correct to treat a `unknown` that\n * persists as a host bug rather than as a state to design around, and WRONG to render a\n * spinner with no timeout on it. (Before R3-419 the host withheld the channel entirely\n * from an ungranted frame, and `unknown` stood forever — that is the failure this note\n * exists to keep from being re-created on the app side.)\n */\nexport type ChatProviderState =\n | { status: 'unknown' }\n | { status: 'not-configured' }\n | { status: 'configured'; provider: ChatProviderInfo };\n\n// The `llm-provider` describe channel (Recipe A): the host pushes the resolved\n// provider info on change and replays it on register-frame, gated by `llm:chat`.\n// A message with no `provider` key is ignored; an explicit `null` means \"no provider\n// bound\", which is now REPRESENTABLE as distinct from \"not yet answered\".\n// The channel's VALUE stays exactly what the wire carries — `ChatProviderInfo | null` —\n// because the wire did not change here and the protocol snapshot gate reads this type as\n// the channel's shape. The three-state lives BESIDE it: `answered` records whether the host\n// has ever spoken on this channel, which is the one bit `null` cannot carry. Deriving the\n// state rather than widening the channel keeps the wire contract byte-identical, which it\n// is (SDK_PACKAGING_SPEC §9: the wire is additive-only, and this is not a wire change).\n/**\n * Reconcile what the host actually sent with what this SDK declares.\n *\n * `features.reasoning` arrived after `ChatFeatures` shipped, so a host predating it\n * omits the key. `undefined` reads as falsy everywhere EXCEPT a `'reasoning' in\n * features` check, which is exactly the kind of difference that produces one wrong\n * branch a year later — so it is normalized here, once, rather than left to every\n * caller. Absent means \"does not reason\": the fail-closed reading.\n *\n * `displayName`, `executor` and `models` arrived later still, and for them absence is a\n * REAL answer an app is told to handle (\"this host does not say\"), so they are left\n * absent rather than filled in. What is dropped is a value that is present but not\n * usable — an `executor` outside the union, a `models` missing a tier — because a\n * half-answer rendered as fact is worse than the honest blank the app already handles.\n *\n * Exported for its own test; not part of the public surface (`index.ts` re-exports\n * this module wholesale, so it is reachable — it is documented as internal rather\n * than hidden behind a lie).\n * @internal\n */\nconst EXECUTORS: readonly ChatExecutor[] = ['browser-direct', 'backend-proxied'];\n\nconst usableModels = (raw: unknown): ChatTierModels | undefined => {\n if (!raw || typeof raw !== 'object') return undefined;\n const { fast, smart } = raw as Partial<ChatTierModels>;\n return typeof fast === 'string' && fast && typeof smart === 'string' && smart ? { fast, smart } : undefined;\n};\n\nexport function normalizeProviderInfo(provider: ChatProviderInfo | null): ChatProviderInfo | null {\n if (!provider) return null;\n // The three later fields are taken OFF the value and put back only if usable — spreading\n // and then overwriting would leave an unusable key present, and `key in provider` is\n // exactly how an app is told to ask whether the host said anything.\n const { displayName: rawName, executor: rawExecutor, models: rawModels, ...rest } = provider;\n // The wire value is whatever the host sent, which may predate any of these fields — so\n // read it as partial rather than trusting the declared type, and decide each explicitly.\n const wire = provider.features as Partial<ChatFeatures>;\n const executor = EXECUTORS.includes(rawExecutor as ChatExecutor) ? (rawExecutor as ChatExecutor) : undefined;\n const displayName = typeof rawName === 'string' && rawName ? rawName : undefined;\n const models = usableModels(rawModels);\n return {\n ...rest,\n features: { ...wire, reasoning: wire.reasoning === true } as ChatFeatures,\n ...(displayName ? { displayName } : {}),\n ...(executor ? { executor } : {}),\n ...(models ? { models } : {}),\n };\n}\n\nlet answered = false;\nconst channel = createPushChannel<ChatProviderInfo | null>({\n pushType: LLM_PROVIDER,\n requestType: REQUEST_LLM_PROVIDER,\n initial: null,\n parse: (msg) => {\n if (!('provider' in msg)) return undefined;\n answered = true;\n return normalizeProviderInfo((msg.provider as ChatProviderInfo | null) ?? null);\n },\n});\n\n/** Derive the three-state from the wire value plus whether the host has answered. */\nconst stateOf = (provider: ChatProviderInfo | null): ChatProviderState =>\n !answered ? { status: 'unknown' } : provider ? { status: 'configured', provider } : { status: 'not-configured' };\n\n/**\n * The provider the host resolved for this app, or `null`.\n *\n * Kept for compatibility (`ways_of_working §6`, additive-only): it collapses `unknown`\n * and `not-configured` to `null`. Prefer {@link describeChatState} when the difference\n * matters — which is any time you would render \"connect a key\", because doing that in\n * the `unknown` state is exactly the false banner R3-300 fixes.\n */\nexport const describeChat = (): ChatProviderInfo | null => channel.get();\n\n/** The three-state read: `unknown` before the host answers, then configured or not. */\nexport const describeChatState = (): ChatProviderState => stateOf(channel.get());\n\n/** Subscribe to provider changes (key added/revoked, preference changed). Invoked\n * immediately with the current value, then on every change. Returns unsubscribe. */\nexport const onChatProviderChange = (listener: (provider: ChatProviderInfo | null) => void): (() => void) =>\n channel.onChange(listener);\n\n/** Subscribe to the three-state provider description. */\nexport const onChatProviderStateChange = (listener: (state: ChatProviderState) => void): (() => void) =>\n channel.onChange((p) => listener(stateOf(p)));\n\n/** React hook returning the resolved chat provider (or `null`), re-rendering on\n * change — gate the summarize affordance on `provider !== null`. */\nexport const useChatProvider = (): ChatProviderInfo | null => channel.use();\n\n/**\n * React hook returning the three-state description.\n *\n * Use this to render provider state honestly: show nothing (or a neutral placeholder)\n * while `unknown`, the connect affordance only on `not-configured`, and the provider's\n * name on `configured`.\n */\nexport const useChatProviderState = (): ChatProviderState => stateOf(channel.use());\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,qBAA6B;AAC7B,yBAAkC;AAClC,sBAAmD;AAqH5C,SAAS,KAAK,KAA+D;AAGlF,QAAM,EAAE,QAAQ,GAAG,OAAO,IAAI;AAC9B,aAAO,6BAAoC,YAAY,QAA8C,MAAM;AAC7G;AAoHA,MAAM,YAAqC,CAAC,kBAAkB,iBAAiB;AAE/E,MAAM,eAAe,CAAC,QAA6C;AACjE,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,EAAE,MAAM,MAAM,IAAI;AACxB,SAAO,OAAO,SAAS,YAAY,QAAQ,OAAO,UAAU,YAAY,QAAQ,EAAE,MAAM,MAAM,IAAI;AACpG;AAEO,SAAS,sBAAsB,UAA4D;AAChG,MAAI,CAAC,SAAU,QAAO;AAItB,QAAM,EAAE,aAAa,SAAS,UAAU,aAAa,QAAQ,WAAW,GAAG,KAAK,IAAI;AAGpF,QAAM,OAAO,SAAS;AACtB,QAAM,WAAW,UAAU,SAAS,WAA2B,IAAK,cAA+B;AACnG,QAAM,cAAc,OAAO,YAAY,YAAY,UAAU,UAAU;AACvE,QAAM,SAAS,aAAa,SAAS;AACrC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,UAAU,EAAE,GAAG,MAAM,WAAW,KAAK,cAAc,KAAK;AAAA,IACxD,GAAI,cAAc,EAAE,YAAY,IAAI,CAAC;AAAA,IACrC,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;AAAA,IAC/B,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,EAC7B;AACF;AAEA,IAAI,WAAW;AACf,MAAM,cAAU,sCAA2C;AAAA,EACzD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AACd,QAAI,EAAE,cAAc,KAAM,QAAO;AACjC,eAAW;AACX,WAAO,sBAAuB,IAAI,YAAwC,IAAI;AAAA,EAChF;AACF,CAAC;AAGD,MAAM,UAAU,CAAC,aACf,CAAC,WAAW,EAAE,QAAQ,UAAU,IAAI,WAAW,EAAE,QAAQ,cAAc,SAAS,IAAI,EAAE,QAAQ,iBAAiB;AAU1G,MAAM,eAAe,MAA+B,QAAQ,IAAI;AAGhE,MAAM,oBAAoB,MAAyB,QAAQ,QAAQ,IAAI,CAAC;AAIxE,MAAM,uBAAuB,CAAC,aACnC,QAAQ,SAAS,QAAQ;AAGpB,MAAM,4BAA4B,CAAC,aACxC,QAAQ,SAAS,CAAC,MAAM,SAAS,QAAQ,CAAC,CAAC,CAAC;AAIvC,MAAM,kBAAkB,MAA+B,QAAQ,IAAI;AASnE,MAAM,uBAAuB,MAAyB,QAAQ,QAAQ,IAAI,CAAC;","names":[]}
package/dist/llm.d.cts CHANGED
@@ -126,6 +126,16 @@ interface ChatFeatures {
126
126
  reasoning: boolean;
127
127
  maxContextTokens: number;
128
128
  }
129
+ /** How the resolved provider's requests physically leave the browser. Read it to
130
+ * DESCRIBE routing where that matters to the person ("runs in your browser" vs
131
+ * "routed through immediately.run") — never to draw host chrome or a consent prompt,
132
+ * which remain the host's (UI_AS_APPS §8 T15). */
133
+ type ChatExecutor = 'browser-direct' | 'backend-proxied';
134
+ /** The concrete model each abstract tier resolves to right now. */
135
+ interface ChatTierModels {
136
+ fast: string;
137
+ smart: string;
138
+ }
129
139
  /** Info about the provider the host resolved for this app. `null` when no provider
130
140
  * is bound (SP-7: prompt the user to add a key before calling {@link chat}). */
131
141
  interface ChatProviderInfo {
@@ -135,6 +145,29 @@ interface ChatProviderInfo {
135
145
  * whose `features` are an untrusted claim. */
136
146
  hostVouched: boolean;
137
147
  features: ChatFeatures;
148
+ /** The provider's human name, e.g. `OpenRouter` — what to put in front of a person.
149
+ * Absent on a host that predates the field: fall back to your own copy rather than
150
+ * rendering the id, which is a platform identifier and not a name. */
151
+ displayName?: string;
152
+ /** How this provider's requests leave the browser. Absent on a host that predates the
153
+ * field, which is NOT the same as `browser-direct` — say nothing about routing rather
154
+ * than guess at it. */
155
+ executor?: ChatExecutor;
156
+ /**
157
+ * The concrete model each {@link ChatRequest.modelHint} tier resolves to — what a
158
+ * `smart` request would actually run, after the user's own preference.
159
+ *
160
+ * Read-only, and it does not weaken `LLM_AND_AGENTS_SPEC §0`: an app still names no
161
+ * model, and {@link ChatRequest} still carries only the abstract hint. It is here so an
162
+ * app can be HONEST about what answered — a transcript that says which model wrote a
163
+ * reply, a warning that names the model about to be spent on — instead of showing a
164
+ * blank where the platform knows the answer. The user picks the model in host settings;
165
+ * the app reports it.
166
+ *
167
+ * Absent on a host that predates the field. It changes when the user changes their
168
+ * preference, so read it through {@link onChatProviderChange} rather than caching it.
169
+ */
170
+ models?: ChatTierModels;
138
171
  }
139
172
  /**
140
173
  * Whether the host has told us about a provider yet, and if so whether one is bound.
@@ -163,20 +196,6 @@ type ChatProviderState = {
163
196
  status: 'configured';
164
197
  provider: ChatProviderInfo;
165
198
  };
166
- /**
167
- * Fill in feature flags a host older than the field does not send (R3-335).
168
- *
169
- * `features.reasoning` arrived after `ChatFeatures` shipped, so a host predating it
170
- * omits the key. `undefined` reads as falsy everywhere EXCEPT a `'reasoning' in
171
- * features` check, which is exactly the kind of difference that produces one wrong
172
- * branch a year later — so it is normalized here, once, rather than left to every
173
- * caller. Absent means "does not reason": the fail-closed reading.
174
- *
175
- * Exported for its own test; not part of the public surface (`index.ts` re-exports
176
- * this module wholesale, so it is reachable — it is documented as internal rather
177
- * than hidden behind a lie).
178
- * @internal
179
- */
180
199
  declare function normalizeProviderInfo(provider: ChatProviderInfo | null): ChatProviderInfo | null;
181
200
  /**
182
201
  * The provider the host resolved for this app, or `null`.
@@ -206,4 +225,4 @@ declare const useChatProvider: () => ChatProviderInfo | null;
206
225
  */
207
226
  declare const useChatProviderState: () => ChatProviderState;
208
227
 
209
- export { type ChatDelta, type ChatFeatures, type ChatMessage, type ChatProviderInfo, type ChatProviderState, type ChatRequest, type ChatResult, type ChatRole, type ChatStopReason, type ContentPart, type ToolDef, chat, describeChat, describeChatState, normalizeProviderInfo, onChatProviderChange, onChatProviderStateChange, useChatProvider, useChatProviderState };
228
+ export { type ChatDelta, type ChatExecutor, type ChatFeatures, type ChatMessage, type ChatProviderInfo, type ChatProviderState, type ChatRequest, type ChatResult, type ChatRole, type ChatStopReason, type ChatTierModels, type ContentPart, type ToolDef, chat, describeChat, describeChatState, normalizeProviderInfo, onChatProviderChange, onChatProviderStateChange, useChatProvider, useChatProviderState };
package/dist/llm.d.ts CHANGED
@@ -126,6 +126,16 @@ interface ChatFeatures {
126
126
  reasoning: boolean;
127
127
  maxContextTokens: number;
128
128
  }
129
+ /** How the resolved provider's requests physically leave the browser. Read it to
130
+ * DESCRIBE routing where that matters to the person ("runs in your browser" vs
131
+ * "routed through immediately.run") — never to draw host chrome or a consent prompt,
132
+ * which remain the host's (UI_AS_APPS §8 T15). */
133
+ type ChatExecutor = 'browser-direct' | 'backend-proxied';
134
+ /** The concrete model each abstract tier resolves to right now. */
135
+ interface ChatTierModels {
136
+ fast: string;
137
+ smart: string;
138
+ }
129
139
  /** Info about the provider the host resolved for this app. `null` when no provider
130
140
  * is bound (SP-7: prompt the user to add a key before calling {@link chat}). */
131
141
  interface ChatProviderInfo {
@@ -135,6 +145,29 @@ interface ChatProviderInfo {
135
145
  * whose `features` are an untrusted claim. */
136
146
  hostVouched: boolean;
137
147
  features: ChatFeatures;
148
+ /** The provider's human name, e.g. `OpenRouter` — what to put in front of a person.
149
+ * Absent on a host that predates the field: fall back to your own copy rather than
150
+ * rendering the id, which is a platform identifier and not a name. */
151
+ displayName?: string;
152
+ /** How this provider's requests leave the browser. Absent on a host that predates the
153
+ * field, which is NOT the same as `browser-direct` — say nothing about routing rather
154
+ * than guess at it. */
155
+ executor?: ChatExecutor;
156
+ /**
157
+ * The concrete model each {@link ChatRequest.modelHint} tier resolves to — what a
158
+ * `smart` request would actually run, after the user's own preference.
159
+ *
160
+ * Read-only, and it does not weaken `LLM_AND_AGENTS_SPEC §0`: an app still names no
161
+ * model, and {@link ChatRequest} still carries only the abstract hint. It is here so an
162
+ * app can be HONEST about what answered — a transcript that says which model wrote a
163
+ * reply, a warning that names the model about to be spent on — instead of showing a
164
+ * blank where the platform knows the answer. The user picks the model in host settings;
165
+ * the app reports it.
166
+ *
167
+ * Absent on a host that predates the field. It changes when the user changes their
168
+ * preference, so read it through {@link onChatProviderChange} rather than caching it.
169
+ */
170
+ models?: ChatTierModels;
138
171
  }
139
172
  /**
140
173
  * Whether the host has told us about a provider yet, and if so whether one is bound.
@@ -163,20 +196,6 @@ type ChatProviderState = {
163
196
  status: 'configured';
164
197
  provider: ChatProviderInfo;
165
198
  };
166
- /**
167
- * Fill in feature flags a host older than the field does not send (R3-335).
168
- *
169
- * `features.reasoning` arrived after `ChatFeatures` shipped, so a host predating it
170
- * omits the key. `undefined` reads as falsy everywhere EXCEPT a `'reasoning' in
171
- * features` check, which is exactly the kind of difference that produces one wrong
172
- * branch a year later — so it is normalized here, once, rather than left to every
173
- * caller. Absent means "does not reason": the fail-closed reading.
174
- *
175
- * Exported for its own test; not part of the public surface (`index.ts` re-exports
176
- * this module wholesale, so it is reachable — it is documented as internal rather
177
- * than hidden behind a lie).
178
- * @internal
179
- */
180
199
  declare function normalizeProviderInfo(provider: ChatProviderInfo | null): ChatProviderInfo | null;
181
200
  /**
182
201
  * The provider the host resolved for this app, or `null`.
@@ -206,4 +225,4 @@ declare const useChatProvider: () => ChatProviderInfo | null;
206
225
  */
207
226
  declare const useChatProviderState: () => ChatProviderState;
208
227
 
209
- export { type ChatDelta, type ChatFeatures, type ChatMessage, type ChatProviderInfo, type ChatProviderState, type ChatRequest, type ChatResult, type ChatRole, type ChatStopReason, type ContentPart, type ToolDef, chat, describeChat, describeChatState, normalizeProviderInfo, onChatProviderChange, onChatProviderStateChange, useChatProvider, useChatProviderState };
228
+ export { type ChatDelta, type ChatExecutor, type ChatFeatures, type ChatMessage, type ChatProviderInfo, type ChatProviderState, type ChatRequest, type ChatResult, type ChatRole, type ChatStopReason, type ChatTierModels, type ContentPart, type ToolDef, chat, describeChat, describeChatState, normalizeProviderInfo, onChatProviderChange, onChatProviderStateChange, useChatProvider, useChatProviderState };
package/dist/llm.js CHANGED
@@ -6,10 +6,26 @@ function chat(req) {
6
6
  const { signal, ...params } = req;
7
7
  return invokeStream("llm:chat", params, signal);
8
8
  }
9
+ const EXECUTORS = ["browser-direct", "backend-proxied"];
10
+ const usableModels = (raw) => {
11
+ if (!raw || typeof raw !== "object") return void 0;
12
+ const { fast, smart } = raw;
13
+ return typeof fast === "string" && fast && typeof smart === "string" && smart ? { fast, smart } : void 0;
14
+ };
9
15
  function normalizeProviderInfo(provider) {
10
16
  if (!provider) return null;
17
+ const { displayName: rawName, executor: rawExecutor, models: rawModels, ...rest } = provider;
11
18
  const wire = provider.features;
12
- return { ...provider, features: { ...wire, reasoning: wire.reasoning === true } };
19
+ const executor = EXECUTORS.includes(rawExecutor) ? rawExecutor : void 0;
20
+ const displayName = typeof rawName === "string" && rawName ? rawName : void 0;
21
+ const models = usableModels(rawModels);
22
+ return {
23
+ ...rest,
24
+ features: { ...wire, reasoning: wire.reasoning === true },
25
+ ...displayName ? { displayName } : {},
26
+ ...executor ? { executor } : {},
27
+ ...models ? { models } : {}
28
+ };
13
29
  }
14
30
  let answered = false;
15
31
  const channel = createPushChannel({
package/dist/llm.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/llm.ts"],"sourcesContent":["// Provider-agnostic LLM chat — the `llm.chat@1` slot (SERVICE_PROVIDERS_SPEC;\n// LLM_AND_AGENTS_SPEC §8 D5).\n//\n// An app calls ONE chat slot and never worries about which provider the user has a\n// key for: the HOST resolves which vendor answers from the key the user holds\n// (`SecretView.boundOrigin`) plus their `preferredImplementation` choice, normalizes\n// the wire format, injects the key host-side at the §6 net:fetch point (the\n// look-at-nothing proxy), and streams normalized deltas back. The app never names a\n// vendor, never sees the key, and needs NO `net:fetch`/`secrets` grant of its own —\n// only the `llm:chat` capability (elevated, app-scoped: a fork earns it by consent).\n//\n// Inert until the host implements `protocol-llm` (the `chat` stream) + the\n// `llm-provider` describe channel; the contract ships here so apps (the file-explorer\n// summarize fork) can be written against it — exactly how `secrets.ts` shipped ahead\n// of `protocol-secrets`.\nimport { invokeStream } from './catalog';\nimport { createPushChannel } from './pushChannel';\nimport { LLM_PROVIDER, REQUEST_LLM_PROVIDER } from './generated/protocol';\n\n/** Who authored a {@link ChatMessage}. */\nexport type ChatRole = 'system' | 'user' | 'assistant' | 'tool';\n\n/** A part of a message. `image` is only honored when the resolved provider\n * advertises `features.vision` (§2.5); `tool-use`/`tool-result` only when it\n * advertises `features.tools` — branch on {@link describeChat} first. */\nexport type ContentPart =\n | { type: 'text'; text: string }\n | { type: 'image'; mimeType: string; data: string } // data: base64, no data: URL prefix\n // A tool call the model emitted on a prior `assistant` turn — replay it in the\n // conversation so a follow-up request carries the agentic history. Pairs with the\n // streamed `tool-call` {@link ChatDelta} that first surfaced it.\n | { type: 'tool-use'; id: string; name: string; input: Record<string, unknown> }\n // A block of the model's own REASONING from a prior `assistant` turn (R3-335).\n // Honored only when the resolved provider advertises `features.reasoning`.\n //\n // Echo these back. On some providers a reasoning block must be replayed — with its\n // `signature` intact and BEFORE the turn's text/tool-use — for the following turn to\n // be accepted at all; a loop that drops them is quietly lossy across turns in a way\n // that shows up as degraded output rather than an error. Pairs with the streamed\n // `reasoning` {@link ChatDelta}.\n | { type: 'reasoning'; text: string; signature?: string }\n // Reasoning the provider REDACTED: opaque bytes with no readable text, which still\n // have to be echoed back in place to keep the chain valid. Never render it.\n | { type: 'reasoning-redacted'; data: string }\n // The result of executing a `tool-use`, fed back so the model can continue. Carried\n // on a `user`/`tool`-role message; `toolCallId` matches the `tool-use` `id`.\n | { type: 'tool-result'; toolCallId: string; content: string; isError?: boolean };\n\n/** One message in a {@link ChatRequest}: a role plus its content parts. */\nexport interface ChatMessage {\n role: ChatRole;\n content: ContentPart[];\n}\n\n/** A tool the model may call — honored only when `features.tools`. */\nexport interface ToolDef {\n name: string;\n description?: string;\n /** JSON-Schema for the tool's arguments. */\n inputSchema: Record<string, unknown>;\n}\n\n/** A host-brokered chat completion request: the messages plus optional tools,\n * response format, and model hint (each honored per the provider's features). */\nexport interface ChatRequest {\n messages: ChatMessage[];\n /** Honored only when the resolved provider advertises `features.tools`. */\n tools?: ToolDef[];\n /** `'json'` honored only when `features.jsonMode`. Defaults to `'text'`. */\n responseFormat?: 'text' | 'json';\n maxTokens?: number;\n /** An ABSTRACT tier hint, never a vendor model id — the host maps it to a concrete\n * model on the resolved provider. Omit to take the provider's default. */\n modelHint?: 'fast' | 'smart';\n /** Abort the completion mid-stream. When it fires, the SDK sends the host a cancel\n * frame so the host aborts the upstream provider request and STOPS BILLING the\n * user's key — not merely stops the app-side iterator (LLM_AND_AGENTS_SPEC §3.3\n * \"abort the in-flight LLM request\", R3-224). Not sent over the wire (an\n * `AbortSignal` isn't serializable); handled SDK-side. */\n signal?: AbortSignal;\n}\n\n/** One streamed chunk. Consumers typically accumulate `text-delta`s. */\nexport type ChatDelta =\n | { type: 'text-delta'; text: string }\n | { type: 'tool-call'; id: string; name: string; input: unknown }\n // R3-335 — the model's reasoning as it streams. `reasoning-delta` carries the text\n // incrementally (render it live); the terminal `reasoning` carries the WHOLE block\n // plus the `signature` the provider may require on the echo, and is what a caller\n // should put back into the conversation. A provider without reasoning emits neither.\n | { type: 'reasoning-delta'; text: string }\n | { type: 'reasoning'; text: string; signature?: string }\n | { type: 'reasoning-redacted'; data: string }\n // Token accounting for the turn. `cacheReadTokens`/`cacheWriteTokens` are present\n // only on providers that report prompt caching (R3-336) — they are what makes a\n // caching claim verifiable rather than believed, and their ABSENCE is meaningful:\n // it says this provider reports nothing, not that nothing was cached.\n | {\n type: 'usage';\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n };\n\n/** Why generation stopped: natural `end`, `length` cap, a `tool` call, or content `filtered`. */\nexport type ChatStopReason = 'end' | 'length' | 'tool' | 'filtered';\n\n/** The terminal value of the {@link chat} stream. */\nexport interface ChatResult {\n stopReason: ChatStopReason;\n}\n\n/**\n * Stream a chat completion from whichever provider the user has configured.\n *\n * ```ts\n * let summary = '';\n * for await (const d of chat({ messages: [{ role: 'user', content: [{ type: 'text', text }] }] })) {\n * if (d.type === 'text-delta') summary += d.text;\n * }\n * ```\n *\n * Requires the `llm:chat` capability. If no provider is bound, the host first\n * draws the SP-7 connect-me gate itself (R3-456: the app never draws a\n * credential prompt — that is host chrome, SECRETS_SPEC S3):\n * - the user connects a key → the call retries once and streams normally;\n * - the user declines → the generator throws `code: 'cancelled'` (the same code\n * a declined powerbox produces — a working degraded state: catch it and\n * degrade, e.g. skip the AI feature);\n * - an older host without the gate throws `code: 'provider-not-configured'`.\n * A signed-out user throws `code: 'auth-required'`; an un-granted call throws\n * `forbidden`.\n */\nexport function chat(req: ChatRequest): AsyncGenerator<ChatDelta, ChatResult, void> {\n // Peel `signal` out of the request before it becomes wire params — an AbortSignal\n // can't cross the postMessage boundary as data; it drives the SDK-side cancel frame.\n const { signal, ...params } = req;\n return invokeStream<ChatDelta, ChatResult>('llm:chat', params as unknown as Record<string, unknown>, signal);\n}\n\n/** The resolved provider's advertised abilities (SERVICE_PROVIDERS_SPEC §2.5) — read\n * to branch/degrade (offer image upload only when `vision`). */\nexport interface ChatFeatures {\n vision: boolean;\n tools: boolean;\n jsonMode: boolean;\n /** R3-335: the provider emits reasoning blocks. Read it to decide whether to render\n * a thinking surface at all — an empty affordance on a provider that never thinks\n * is worse than none. Normalized to `false` by the channel when a host predating\n * R3-335 omits it, so this is never `undefined` in practice. */\n reasoning: boolean;\n maxContextTokens: number;\n}\n\n/** Info about the provider the host resolved for this app. `null` when no provider\n * is bound (SP-7: prompt the user to add a key before calling {@link chat}). */\nexport interface ChatProviderInfo {\n /** Opaque provider id, e.g. `llm.chat.anthropic` — never a vendor secret or model id. */\n providerId: string;\n /** True for Host-proxied providers (host-vouched, SP-9); false for app-level ones,\n * whose `features` are an untrusted claim. */\n hostVouched: boolean;\n features: ChatFeatures;\n // NOTE (R3-300): `displayName`, `executor` and the resolved per-tier `models` belong\n // here — an app rendering provider state wants all three. They are NOT added yet,\n // deliberately: this interface IS the `llm-provider` channel's declared value, so\n // adding a field is a WIRE change, and the wire is owned by\n // `@immediately-run/sandbox-protocol` (descriptor edit → publish → pin bump on both\n // sides). The protocol snapshot gate enforces exactly that, and it is right to. The\n // enrichment rides R3-307's publish, which already has to touch those descriptors —\n // one publish for two additions rather than two.\n}\n\n/**\n * Whether the host has told us about a provider yet, and if so whether one is bound.\n *\n * THREE states, because two is the bug (R3-300). `describeChat()` returns `null` both\n * when no provider is configured AND when the channel has not answered — so an app\n * cannot tell \"you need a key\" from \"ask again in a moment\", and consuming apps\n * rendered a misleading \"connect a key\" banner at users who had one. `unknown` is the\n * state before the host answers; it is not an error and not a prompt to act.\n *\n * **`unknown` is TRANSIENT — the host answers every frame** (R3-419;\n * `LLM_AND_AGENTS_SPEC §4.1` R-LLM-1..3). An app that does not hold `llm:chat` is not\n * met with silence: it is answered `not-configured`, the same terminal state as a user\n * with no key, because from the app's side those are the same fact — do not render a\n * provider, do offer the connect path. So it is correct to treat a `unknown` that\n * persists as a host bug rather than as a state to design around, and WRONG to render a\n * spinner with no timeout on it. (Before R3-419 the host withheld the channel entirely\n * from an ungranted frame, and `unknown` stood forever — that is the failure this note\n * exists to keep from being re-created on the app side.)\n */\nexport type ChatProviderState =\n | { status: 'unknown' }\n | { status: 'not-configured' }\n | { status: 'configured'; provider: ChatProviderInfo };\n\n// The `llm-provider` describe channel (Recipe A): the host pushes the resolved\n// provider info on change and replays it on register-frame, gated by `llm:chat`.\n// A message with no `provider` key is ignored; an explicit `null` means \"no provider\n// bound\", which is now REPRESENTABLE as distinct from \"not yet answered\".\n// The channel's VALUE stays exactly what the wire carries — `ChatProviderInfo | null` —\n// because the wire did not change here and the protocol snapshot gate reads this type as\n// the channel's shape. The three-state lives BESIDE it: `answered` records whether the host\n// has ever spoken on this channel, which is the one bit `null` cannot carry. Deriving the\n// state rather than widening the channel keeps the wire contract byte-identical, which it\n// is (SDK_PACKAGING_SPEC §9: the wire is additive-only, and this is not a wire change).\n/**\n * Fill in feature flags a host older than the field does not send (R3-335).\n *\n * `features.reasoning` arrived after `ChatFeatures` shipped, so a host predating it\n * omits the key. `undefined` reads as falsy everywhere EXCEPT a `'reasoning' in\n * features` check, which is exactly the kind of difference that produces one wrong\n * branch a year later — so it is normalized here, once, rather than left to every\n * caller. Absent means \"does not reason\": the fail-closed reading.\n *\n * Exported for its own test; not part of the public surface (`index.ts` re-exports\n * this module wholesale, so it is reachable — it is documented as internal rather\n * than hidden behind a lie).\n * @internal\n */\nexport function normalizeProviderInfo(provider: ChatProviderInfo | null): ChatProviderInfo | null {\n if (!provider) return null;\n // The wire value is whatever the host sent, which may predate `reasoning` — so read\n // it as partial rather than trusting the declared type, and decide the flag explicitly.\n const wire = provider.features as Partial<ChatFeatures>;\n return { ...provider, features: { ...wire, reasoning: wire.reasoning === true } as ChatFeatures };\n}\n\nlet answered = false;\nconst channel = createPushChannel<ChatProviderInfo | null>({\n pushType: LLM_PROVIDER,\n requestType: REQUEST_LLM_PROVIDER,\n initial: null,\n parse: (msg) => {\n if (!('provider' in msg)) return undefined;\n answered = true;\n return normalizeProviderInfo((msg.provider as ChatProviderInfo | null) ?? null);\n },\n});\n\n/** Derive the three-state from the wire value plus whether the host has answered. */\nconst stateOf = (provider: ChatProviderInfo | null): ChatProviderState =>\n !answered ? { status: 'unknown' } : provider ? { status: 'configured', provider } : { status: 'not-configured' };\n\n/**\n * The provider the host resolved for this app, or `null`.\n *\n * Kept for compatibility (`ways_of_working §6`, additive-only): it collapses `unknown`\n * and `not-configured` to `null`. Prefer {@link describeChatState} when the difference\n * matters — which is any time you would render \"connect a key\", because doing that in\n * the `unknown` state is exactly the false banner R3-300 fixes.\n */\nexport const describeChat = (): ChatProviderInfo | null => channel.get();\n\n/** The three-state read: `unknown` before the host answers, then configured or not. */\nexport const describeChatState = (): ChatProviderState => stateOf(channel.get());\n\n/** Subscribe to provider changes (key added/revoked, preference changed). Invoked\n * immediately with the current value, then on every change. Returns unsubscribe. */\nexport const onChatProviderChange = (listener: (provider: ChatProviderInfo | null) => void): (() => void) =>\n channel.onChange(listener);\n\n/** Subscribe to the three-state provider description. */\nexport const onChatProviderStateChange = (listener: (state: ChatProviderState) => void): (() => void) =>\n channel.onChange((p) => listener(stateOf(p)));\n\n/** React hook returning the resolved chat provider (or `null`), re-rendering on\n * change — gate the summarize affordance on `provider !== null`. */\nexport const useChatProvider = (): ChatProviderInfo | null => channel.use();\n\n/**\n * React hook returning the three-state description.\n *\n * Use this to render provider state honestly: show nothing (or a neutral placeholder)\n * while `unknown`, the connect affordance only on `not-configured`, and the provider's\n * name on `configured`.\n */\nexport const useChatProviderState = (): ChatProviderState => stateOf(channel.use());\n"],"mappings":";AAeA,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAClC,SAAS,cAAc,4BAA4B;AAqH5C,SAAS,KAAK,KAA+D;AAGlF,QAAM,EAAE,QAAQ,GAAG,OAAO,IAAI;AAC9B,SAAO,aAAoC,YAAY,QAA8C,MAAM;AAC7G;AAmFO,SAAS,sBAAsB,UAA4D;AAChG,MAAI,CAAC,SAAU,QAAO;AAGtB,QAAM,OAAO,SAAS;AACtB,SAAO,EAAE,GAAG,UAAU,UAAU,EAAE,GAAG,MAAM,WAAW,KAAK,cAAc,KAAK,EAAkB;AAClG;AAEA,IAAI,WAAW;AACf,MAAM,UAAU,kBAA2C;AAAA,EACzD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AACd,QAAI,EAAE,cAAc,KAAM,QAAO;AACjC,eAAW;AACX,WAAO,sBAAuB,IAAI,YAAwC,IAAI;AAAA,EAChF;AACF,CAAC;AAGD,MAAM,UAAU,CAAC,aACf,CAAC,WAAW,EAAE,QAAQ,UAAU,IAAI,WAAW,EAAE,QAAQ,cAAc,SAAS,IAAI,EAAE,QAAQ,iBAAiB;AAU1G,MAAM,eAAe,MAA+B,QAAQ,IAAI;AAGhE,MAAM,oBAAoB,MAAyB,QAAQ,QAAQ,IAAI,CAAC;AAIxE,MAAM,uBAAuB,CAAC,aACnC,QAAQ,SAAS,QAAQ;AAGpB,MAAM,4BAA4B,CAAC,aACxC,QAAQ,SAAS,CAAC,MAAM,SAAS,QAAQ,CAAC,CAAC,CAAC;AAIvC,MAAM,kBAAkB,MAA+B,QAAQ,IAAI;AASnE,MAAM,uBAAuB,MAAyB,QAAQ,QAAQ,IAAI,CAAC;","names":[]}
1
+ {"version":3,"sources":["../src/llm.ts"],"sourcesContent":["// Provider-agnostic LLM chat — the `llm.chat@1` slot (SERVICE_PROVIDERS_SPEC;\n// LLM_AND_AGENTS_SPEC §8 D5).\n//\n// An app calls ONE chat slot and never worries about which provider the user has a\n// key for: the HOST resolves which vendor answers from the key the user holds\n// (`SecretView.boundOrigin`) plus their `preferredImplementation` choice, normalizes\n// the wire format, injects the key host-side at the §6 net:fetch point (the\n// look-at-nothing proxy), and streams normalized deltas back. The app never names a\n// vendor, never sees the key, and needs NO `net:fetch`/`secrets` grant of its own —\n// only the `llm:chat` capability (elevated, app-scoped: a fork earns it by consent).\n//\n// Inert until the host implements `protocol-llm` (the `chat` stream) + the\n// `llm-provider` describe channel; the contract ships here so apps (the file-explorer\n// summarize fork) can be written against it — exactly how `secrets.ts` shipped ahead\n// of `protocol-secrets`.\nimport { invokeStream } from './catalog';\nimport { createPushChannel } from './pushChannel';\nimport { LLM_PROVIDER, REQUEST_LLM_PROVIDER } from './generated/protocol';\n\n/** Who authored a {@link ChatMessage}. */\nexport type ChatRole = 'system' | 'user' | 'assistant' | 'tool';\n\n/** A part of a message. `image` is only honored when the resolved provider\n * advertises `features.vision` (§2.5); `tool-use`/`tool-result` only when it\n * advertises `features.tools` — branch on {@link describeChat} first. */\nexport type ContentPart =\n | { type: 'text'; text: string }\n | { type: 'image'; mimeType: string; data: string } // data: base64, no data: URL prefix\n // A tool call the model emitted on a prior `assistant` turn — replay it in the\n // conversation so a follow-up request carries the agentic history. Pairs with the\n // streamed `tool-call` {@link ChatDelta} that first surfaced it.\n | { type: 'tool-use'; id: string; name: string; input: Record<string, unknown> }\n // A block of the model's own REASONING from a prior `assistant` turn (R3-335).\n // Honored only when the resolved provider advertises `features.reasoning`.\n //\n // Echo these back. On some providers a reasoning block must be replayed — with its\n // `signature` intact and BEFORE the turn's text/tool-use — for the following turn to\n // be accepted at all; a loop that drops them is quietly lossy across turns in a way\n // that shows up as degraded output rather than an error. Pairs with the streamed\n // `reasoning` {@link ChatDelta}.\n | { type: 'reasoning'; text: string; signature?: string }\n // Reasoning the provider REDACTED: opaque bytes with no readable text, which still\n // have to be echoed back in place to keep the chain valid. Never render it.\n | { type: 'reasoning-redacted'; data: string }\n // The result of executing a `tool-use`, fed back so the model can continue. Carried\n // on a `user`/`tool`-role message; `toolCallId` matches the `tool-use` `id`.\n | { type: 'tool-result'; toolCallId: string; content: string; isError?: boolean };\n\n/** One message in a {@link ChatRequest}: a role plus its content parts. */\nexport interface ChatMessage {\n role: ChatRole;\n content: ContentPart[];\n}\n\n/** A tool the model may call — honored only when `features.tools`. */\nexport interface ToolDef {\n name: string;\n description?: string;\n /** JSON-Schema for the tool's arguments. */\n inputSchema: Record<string, unknown>;\n}\n\n/** A host-brokered chat completion request: the messages plus optional tools,\n * response format, and model hint (each honored per the provider's features). */\nexport interface ChatRequest {\n messages: ChatMessage[];\n /** Honored only when the resolved provider advertises `features.tools`. */\n tools?: ToolDef[];\n /** `'json'` honored only when `features.jsonMode`. Defaults to `'text'`. */\n responseFormat?: 'text' | 'json';\n maxTokens?: number;\n /** An ABSTRACT tier hint, never a vendor model id — the host maps it to a concrete\n * model on the resolved provider. Omit to take the provider's default. */\n modelHint?: 'fast' | 'smart';\n /** Abort the completion mid-stream. When it fires, the SDK sends the host a cancel\n * frame so the host aborts the upstream provider request and STOPS BILLING the\n * user's key — not merely stops the app-side iterator (LLM_AND_AGENTS_SPEC §3.3\n * \"abort the in-flight LLM request\", R3-224). Not sent over the wire (an\n * `AbortSignal` isn't serializable); handled SDK-side. */\n signal?: AbortSignal;\n}\n\n/** One streamed chunk. Consumers typically accumulate `text-delta`s. */\nexport type ChatDelta =\n | { type: 'text-delta'; text: string }\n | { type: 'tool-call'; id: string; name: string; input: unknown }\n // R3-335 — the model's reasoning as it streams. `reasoning-delta` carries the text\n // incrementally (render it live); the terminal `reasoning` carries the WHOLE block\n // plus the `signature` the provider may require on the echo, and is what a caller\n // should put back into the conversation. A provider without reasoning emits neither.\n | { type: 'reasoning-delta'; text: string }\n | { type: 'reasoning'; text: string; signature?: string }\n | { type: 'reasoning-redacted'; data: string }\n // Token accounting for the turn. `cacheReadTokens`/`cacheWriteTokens` are present\n // only on providers that report prompt caching (R3-336) — they are what makes a\n // caching claim verifiable rather than believed, and their ABSENCE is meaningful:\n // it says this provider reports nothing, not that nothing was cached.\n | {\n type: 'usage';\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n };\n\n/** Why generation stopped: natural `end`, `length` cap, a `tool` call, or content `filtered`. */\nexport type ChatStopReason = 'end' | 'length' | 'tool' | 'filtered';\n\n/** The terminal value of the {@link chat} stream. */\nexport interface ChatResult {\n stopReason: ChatStopReason;\n}\n\n/**\n * Stream a chat completion from whichever provider the user has configured.\n *\n * ```ts\n * let summary = '';\n * for await (const d of chat({ messages: [{ role: 'user', content: [{ type: 'text', text }] }] })) {\n * if (d.type === 'text-delta') summary += d.text;\n * }\n * ```\n *\n * Requires the `llm:chat` capability. If no provider is bound, the host first\n * draws the SP-7 connect-me gate itself (R3-456: the app never draws a\n * credential prompt — that is host chrome, SECRETS_SPEC S3):\n * - the user connects a key → the call retries once and streams normally;\n * - the user declines → the generator throws `code: 'cancelled'` (the same code\n * a declined powerbox produces — a working degraded state: catch it and\n * degrade, e.g. skip the AI feature);\n * - an older host without the gate throws `code: 'provider-not-configured'`.\n * A signed-out user throws `code: 'auth-required'`; an un-granted call throws\n * `forbidden`.\n */\nexport function chat(req: ChatRequest): AsyncGenerator<ChatDelta, ChatResult, void> {\n // Peel `signal` out of the request before it becomes wire params — an AbortSignal\n // can't cross the postMessage boundary as data; it drives the SDK-side cancel frame.\n const { signal, ...params } = req;\n return invokeStream<ChatDelta, ChatResult>('llm:chat', params as unknown as Record<string, unknown>, signal);\n}\n\n/** The resolved provider's advertised abilities (SERVICE_PROVIDERS_SPEC §2.5) — read\n * to branch/degrade (offer image upload only when `vision`). */\nexport interface ChatFeatures {\n vision: boolean;\n tools: boolean;\n jsonMode: boolean;\n /** R3-335: the provider emits reasoning blocks. Read it to decide whether to render\n * a thinking surface at all — an empty affordance on a provider that never thinks\n * is worse than none. Normalized to `false` by the channel when a host predating\n * R3-335 omits it, so this is never `undefined` in practice. */\n reasoning: boolean;\n maxContextTokens: number;\n}\n\n/** How the resolved provider's requests physically leave the browser. Read it to\n * DESCRIBE routing where that matters to the person (\"runs in your browser\" vs\n * \"routed through immediately.run\") — never to draw host chrome or a consent prompt,\n * which remain the host's (UI_AS_APPS §8 T15). */\nexport type ChatExecutor = 'browser-direct' | 'backend-proxied';\n\n/** The concrete model each abstract tier resolves to right now. */\nexport interface ChatTierModels {\n fast: string;\n smart: string;\n}\n\n/** Info about the provider the host resolved for this app. `null` when no provider\n * is bound (SP-7: prompt the user to add a key before calling {@link chat}). */\nexport interface ChatProviderInfo {\n /** Opaque provider id, e.g. `llm.chat.anthropic` — never a vendor secret or model id. */\n providerId: string;\n /** True for Host-proxied providers (host-vouched, SP-9); false for app-level ones,\n * whose `features` are an untrusted claim. */\n hostVouched: boolean;\n features: ChatFeatures;\n /** The provider's human name, e.g. `OpenRouter` — what to put in front of a person.\n * Absent on a host that predates the field: fall back to your own copy rather than\n * rendering the id, which is a platform identifier and not a name. */\n displayName?: string;\n /** How this provider's requests leave the browser. Absent on a host that predates the\n * field, which is NOT the same as `browser-direct` — say nothing about routing rather\n * than guess at it. */\n executor?: ChatExecutor;\n /**\n * The concrete model each {@link ChatRequest.modelHint} tier resolves to — what a\n * `smart` request would actually run, after the user's own preference.\n *\n * Read-only, and it does not weaken `LLM_AND_AGENTS_SPEC §0`: an app still names no\n * model, and {@link ChatRequest} still carries only the abstract hint. It is here so an\n * app can be HONEST about what answered — a transcript that says which model wrote a\n * reply, a warning that names the model about to be spent on — instead of showing a\n * blank where the platform knows the answer. The user picks the model in host settings;\n * the app reports it.\n *\n * Absent on a host that predates the field. It changes when the user changes their\n * preference, so read it through {@link onChatProviderChange} rather than caching it.\n */\n models?: ChatTierModels;\n}\n\n/**\n * Whether the host has told us about a provider yet, and if so whether one is bound.\n *\n * THREE states, because two is the bug (R3-300). `describeChat()` returns `null` both\n * when no provider is configured AND when the channel has not answered — so an app\n * cannot tell \"you need a key\" from \"ask again in a moment\", and consuming apps\n * rendered a misleading \"connect a key\" banner at users who had one. `unknown` is the\n * state before the host answers; it is not an error and not a prompt to act.\n *\n * **`unknown` is TRANSIENT — the host answers every frame** (R3-419;\n * `LLM_AND_AGENTS_SPEC §4.1` R-LLM-1..3). An app that does not hold `llm:chat` is not\n * met with silence: it is answered `not-configured`, the same terminal state as a user\n * with no key, because from the app's side those are the same fact — do not render a\n * provider, do offer the connect path. So it is correct to treat a `unknown` that\n * persists as a host bug rather than as a state to design around, and WRONG to render a\n * spinner with no timeout on it. (Before R3-419 the host withheld the channel entirely\n * from an ungranted frame, and `unknown` stood forever — that is the failure this note\n * exists to keep from being re-created on the app side.)\n */\nexport type ChatProviderState =\n | { status: 'unknown' }\n | { status: 'not-configured' }\n | { status: 'configured'; provider: ChatProviderInfo };\n\n// The `llm-provider` describe channel (Recipe A): the host pushes the resolved\n// provider info on change and replays it on register-frame, gated by `llm:chat`.\n// A message with no `provider` key is ignored; an explicit `null` means \"no provider\n// bound\", which is now REPRESENTABLE as distinct from \"not yet answered\".\n// The channel's VALUE stays exactly what the wire carries — `ChatProviderInfo | null` —\n// because the wire did not change here and the protocol snapshot gate reads this type as\n// the channel's shape. The three-state lives BESIDE it: `answered` records whether the host\n// has ever spoken on this channel, which is the one bit `null` cannot carry. Deriving the\n// state rather than widening the channel keeps the wire contract byte-identical, which it\n// is (SDK_PACKAGING_SPEC §9: the wire is additive-only, and this is not a wire change).\n/**\n * Reconcile what the host actually sent with what this SDK declares.\n *\n * `features.reasoning` arrived after `ChatFeatures` shipped, so a host predating it\n * omits the key. `undefined` reads as falsy everywhere EXCEPT a `'reasoning' in\n * features` check, which is exactly the kind of difference that produces one wrong\n * branch a year later — so it is normalized here, once, rather than left to every\n * caller. Absent means \"does not reason\": the fail-closed reading.\n *\n * `displayName`, `executor` and `models` arrived later still, and for them absence is a\n * REAL answer an app is told to handle (\"this host does not say\"), so they are left\n * absent rather than filled in. What is dropped is a value that is present but not\n * usable — an `executor` outside the union, a `models` missing a tier — because a\n * half-answer rendered as fact is worse than the honest blank the app already handles.\n *\n * Exported for its own test; not part of the public surface (`index.ts` re-exports\n * this module wholesale, so it is reachable — it is documented as internal rather\n * than hidden behind a lie).\n * @internal\n */\nconst EXECUTORS: readonly ChatExecutor[] = ['browser-direct', 'backend-proxied'];\n\nconst usableModels = (raw: unknown): ChatTierModels | undefined => {\n if (!raw || typeof raw !== 'object') return undefined;\n const { fast, smart } = raw as Partial<ChatTierModels>;\n return typeof fast === 'string' && fast && typeof smart === 'string' && smart ? { fast, smart } : undefined;\n};\n\nexport function normalizeProviderInfo(provider: ChatProviderInfo | null): ChatProviderInfo | null {\n if (!provider) return null;\n // The three later fields are taken OFF the value and put back only if usable — spreading\n // and then overwriting would leave an unusable key present, and `key in provider` is\n // exactly how an app is told to ask whether the host said anything.\n const { displayName: rawName, executor: rawExecutor, models: rawModels, ...rest } = provider;\n // The wire value is whatever the host sent, which may predate any of these fields — so\n // read it as partial rather than trusting the declared type, and decide each explicitly.\n const wire = provider.features as Partial<ChatFeatures>;\n const executor = EXECUTORS.includes(rawExecutor as ChatExecutor) ? (rawExecutor as ChatExecutor) : undefined;\n const displayName = typeof rawName === 'string' && rawName ? rawName : undefined;\n const models = usableModels(rawModels);\n return {\n ...rest,\n features: { ...wire, reasoning: wire.reasoning === true } as ChatFeatures,\n ...(displayName ? { displayName } : {}),\n ...(executor ? { executor } : {}),\n ...(models ? { models } : {}),\n };\n}\n\nlet answered = false;\nconst channel = createPushChannel<ChatProviderInfo | null>({\n pushType: LLM_PROVIDER,\n requestType: REQUEST_LLM_PROVIDER,\n initial: null,\n parse: (msg) => {\n if (!('provider' in msg)) return undefined;\n answered = true;\n return normalizeProviderInfo((msg.provider as ChatProviderInfo | null) ?? null);\n },\n});\n\n/** Derive the three-state from the wire value plus whether the host has answered. */\nconst stateOf = (provider: ChatProviderInfo | null): ChatProviderState =>\n !answered ? { status: 'unknown' } : provider ? { status: 'configured', provider } : { status: 'not-configured' };\n\n/**\n * The provider the host resolved for this app, or `null`.\n *\n * Kept for compatibility (`ways_of_working §6`, additive-only): it collapses `unknown`\n * and `not-configured` to `null`. Prefer {@link describeChatState} when the difference\n * matters — which is any time you would render \"connect a key\", because doing that in\n * the `unknown` state is exactly the false banner R3-300 fixes.\n */\nexport const describeChat = (): ChatProviderInfo | null => channel.get();\n\n/** The three-state read: `unknown` before the host answers, then configured or not. */\nexport const describeChatState = (): ChatProviderState => stateOf(channel.get());\n\n/** Subscribe to provider changes (key added/revoked, preference changed). Invoked\n * immediately with the current value, then on every change. Returns unsubscribe. */\nexport const onChatProviderChange = (listener: (provider: ChatProviderInfo | null) => void): (() => void) =>\n channel.onChange(listener);\n\n/** Subscribe to the three-state provider description. */\nexport const onChatProviderStateChange = (listener: (state: ChatProviderState) => void): (() => void) =>\n channel.onChange((p) => listener(stateOf(p)));\n\n/** React hook returning the resolved chat provider (or `null`), re-rendering on\n * change — gate the summarize affordance on `provider !== null`. */\nexport const useChatProvider = (): ChatProviderInfo | null => channel.use();\n\n/**\n * React hook returning the three-state description.\n *\n * Use this to render provider state honestly: show nothing (or a neutral placeholder)\n * while `unknown`, the connect affordance only on `not-configured`, and the provider's\n * name on `configured`.\n */\nexport const useChatProviderState = (): ChatProviderState => stateOf(channel.use());\n"],"mappings":";AAeA,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAClC,SAAS,cAAc,4BAA4B;AAqH5C,SAAS,KAAK,KAA+D;AAGlF,QAAM,EAAE,QAAQ,GAAG,OAAO,IAAI;AAC9B,SAAO,aAAoC,YAAY,QAA8C,MAAM;AAC7G;AAoHA,MAAM,YAAqC,CAAC,kBAAkB,iBAAiB;AAE/E,MAAM,eAAe,CAAC,QAA6C;AACjE,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,EAAE,MAAM,MAAM,IAAI;AACxB,SAAO,OAAO,SAAS,YAAY,QAAQ,OAAO,UAAU,YAAY,QAAQ,EAAE,MAAM,MAAM,IAAI;AACpG;AAEO,SAAS,sBAAsB,UAA4D;AAChG,MAAI,CAAC,SAAU,QAAO;AAItB,QAAM,EAAE,aAAa,SAAS,UAAU,aAAa,QAAQ,WAAW,GAAG,KAAK,IAAI;AAGpF,QAAM,OAAO,SAAS;AACtB,QAAM,WAAW,UAAU,SAAS,WAA2B,IAAK,cAA+B;AACnG,QAAM,cAAc,OAAO,YAAY,YAAY,UAAU,UAAU;AACvE,QAAM,SAAS,aAAa,SAAS;AACrC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,UAAU,EAAE,GAAG,MAAM,WAAW,KAAK,cAAc,KAAK;AAAA,IACxD,GAAI,cAAc,EAAE,YAAY,IAAI,CAAC;AAAA,IACrC,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;AAAA,IAC/B,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,EAC7B;AACF;AAEA,IAAI,WAAW;AACf,MAAM,UAAU,kBAA2C;AAAA,EACzD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AACd,QAAI,EAAE,cAAc,KAAM,QAAO;AACjC,eAAW;AACX,WAAO,sBAAuB,IAAI,YAAwC,IAAI;AAAA,EAChF;AACF,CAAC;AAGD,MAAM,UAAU,CAAC,aACf,CAAC,WAAW,EAAE,QAAQ,UAAU,IAAI,WAAW,EAAE,QAAQ,cAAc,SAAS,IAAI,EAAE,QAAQ,iBAAiB;AAU1G,MAAM,eAAe,MAA+B,QAAQ,IAAI;AAGhE,MAAM,oBAAoB,MAAyB,QAAQ,QAAQ,IAAI,CAAC;AAIxE,MAAM,uBAAuB,CAAC,aACnC,QAAQ,SAAS,QAAQ;AAGpB,MAAM,4BAA4B,CAAC,aACxC,QAAQ,SAAS,CAAC,MAAM,SAAS,QAAQ,CAAC,CAAC,CAAC;AAIvC,MAAM,kBAAkB,MAA+B,QAAQ,IAAI;AASnE,MAAM,uBAAuB,MAAyB,QAAQ,QAAQ,IAAI,CAAC;","names":[]}
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var openRepository_exports = {};
20
+ __export(openRepository_exports, {
21
+ openRepository: () => openRepository
22
+ });
23
+ module.exports = __toCommonJS(openRepository_exports);
24
+ var import_sandboxUtils = require("./sandboxUtils");
25
+ var import_protocol = require("./generated/protocol");
26
+ var import_protocolSchemes = require("./protocolSchemes");
27
+ async function openRepository(coordinates) {
28
+ const { provider, namespace, repository } = coordinates;
29
+ const res = await (0, import_sandboxUtils.protocolRequest)(import_protocolSchemes.SCHEMES[import_protocol.PROTOCOL_OPENREPO], "open", [
30
+ { provider, namespace, repository }
31
+ ]);
32
+ if (!res || res.ok !== true) {
33
+ const err = new Error(
34
+ (res && "message" in res ? res.message : void 0) ?? "repository open refused"
35
+ );
36
+ err.code = (res && "code" in res ? res.code : void 0) ?? "unknown";
37
+ throw err;
38
+ }
39
+ }
40
+ // Annotate the CommonJS export names for ESM import in node:
41
+ 0 && (module.exports = {
42
+ openRepository
43
+ });
44
+ //# sourceMappingURL=openRepository.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/openRepository.ts"],"sourcesContent":["// Host-mediated \"open this repository in a new tab\" (R3-476).\n//\n// An app frame cannot open a first-party tab itself. A `window.open` from inside the\n// sandboxed frame inherits the sandbox — the opened tab runs at the same opaque origin and\n// cannot load the host — and `target=\"_top\"` would replace the app's own frame rather than\n// open a tab. So the app asks the host, and the host performs the open from its own context.\n//\n// The app names COORDINATES and nothing else. It cannot pass a URL, a route prefix or a\n// path: the host builds the destination from its own route grammar, so this call can only\n// ever reach one of the platform's own repository routes. That is the point of the shape —\n// an app that could spell the destination could open anything.\n//\n// Two more conditions hold on the host side, and neither is something this call can assert\n// for itself: the open needs the HOST document's live transient user activation (a real\n// click, which the host samples rather than believes), and one gesture opens exactly one\n// tab. Both surface here as ordinary coded refusals.\nimport { protocolRequest } from './sandboxUtils';\nimport { PROTOCOL_OPENREPO } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a repository lives. The same three fields a `RecentProject` carries — this is a\n * location the user may already have navigated to under their own authority. */\nexport interface RepositoryCoordinates {\n provider: string;\n namespace: string;\n repository: string;\n}\n\n/** Why the host refused to open a tab.\n *\n * - `invalid` — the coordinates are not three clean path segments.\n * - `no-activation` — no live user gesture on the host document. Call this from a click\n * handler; a timer or a boot path will always get this. A SECOND call inside one gesture\n * also lands here: `window.open` consumes the host's transient activation, so one click\n * buys exactly one tab and the next needs a real second click.\n * - `forbidden` — the app does not hold the baseline `route:read` capability.\n * - `unsupported` — this host has no repository-open surface wired.\n * - `unknown` — the host refused without naming a code. */\nexport type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface OpenRepositoryError extends Error {\n code: OpenRepositoryErrorCode;\n}\n\n/** The host's reply: the envelope resolves INSIDE the promise, so a refusal is a resolved\n * `{ ok: false }` rather than a rejection at the transport layer. */\ntype OpenRepositoryReply = { ok: true; url?: string } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to open a repository in a new browser tab.\n *\n * Resolves once the host has performed the open; it does not wait for — and cannot observe —\n * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`\n * when the host refuses.\n *\n * Call it directly from a user gesture. The host samples its own transient activation when\n * the request arrives, so anything that defers the call past the gesture (an `await` before\n * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are\n * worth retrying: each names a condition a retry cannot change.\n */\nexport async function openRepository(coordinates: RepositoryCoordinates): Promise<void> {\n const { provider, namespace, repository } = coordinates;\n const res = (await protocolRequest(SCHEMES[PROTOCOL_OPENREPO], 'open', [\n { provider, namespace, repository },\n ])) as OpenRepositoryReply;\n // The refusal resolves inside the reply, so `res.ok !== true` is the only failure test\n // there is — a bare-promise shape here would swallow every coded refusal as a success.\n if (!res || res.ok !== true) {\n const err = new Error(\n (res && 'message' in res ? res.message : undefined) ?? 'repository open refused',\n ) as OpenRepositoryError;\n err.code = ((res && 'code' in res ? res.code : undefined) as OpenRepositoryErrorCode) ?? 'unknown';\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,0BAAgC;AAChC,sBAAkC;AAClC,6BAAwB;AA0CxB,eAAsB,eAAe,aAAmD;AACtF,QAAM,EAAE,UAAU,WAAW,WAAW,IAAI;AAC5C,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,iCAAiB,GAAG,QAAQ;AAAA,IACrE,EAAE,UAAU,WAAW,WAAW;AAAA,EACpC,CAAC;AAGD,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI;AAAA,OACb,OAAO,aAAa,MAAM,IAAI,UAAU,WAAc;AAAA,IACzD;AACA,QAAI,QAAS,OAAO,UAAU,MAAM,IAAI,OAAO,WAA0C;AACzF,UAAM;AAAA,EACR;AACF;","names":[]}
@@ -0,0 +1,36 @@
1
+ /** Where a repository lives. The same three fields a `RecentProject` carries — this is a
2
+ * location the user may already have navigated to under their own authority. */
3
+ interface RepositoryCoordinates {
4
+ provider: string;
5
+ namespace: string;
6
+ repository: string;
7
+ }
8
+ /** Why the host refused to open a tab.
9
+ *
10
+ * - `invalid` — the coordinates are not three clean path segments.
11
+ * - `no-activation` — no live user gesture on the host document. Call this from a click
12
+ * handler; a timer or a boot path will always get this. A SECOND call inside one gesture
13
+ * also lands here: `window.open` consumes the host's transient activation, so one click
14
+ * buys exactly one tab and the next needs a real second click.
15
+ * - `forbidden` — the app does not hold the baseline `route:read` capability.
16
+ * - `unsupported` — this host has no repository-open surface wired.
17
+ * - `unknown` — the host refused without naming a code. */
18
+ type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';
19
+ interface OpenRepositoryError extends Error {
20
+ code: OpenRepositoryErrorCode;
21
+ }
22
+ /**
23
+ * Ask the host to open a repository in a new browser tab.
24
+ *
25
+ * Resolves once the host has performed the open; it does not wait for — and cannot observe —
26
+ * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`
27
+ * when the host refuses.
28
+ *
29
+ * Call it directly from a user gesture. The host samples its own transient activation when
30
+ * the request arrives, so anything that defers the call past the gesture (an `await` before
31
+ * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are
32
+ * worth retrying: each names a condition a retry cannot change.
33
+ */
34
+ declare function openRepository(coordinates: RepositoryCoordinates): Promise<void>;
35
+
36
+ export { type OpenRepositoryError, type OpenRepositoryErrorCode, type RepositoryCoordinates, openRepository };
@@ -0,0 +1,36 @@
1
+ /** Where a repository lives. The same three fields a `RecentProject` carries — this is a
2
+ * location the user may already have navigated to under their own authority. */
3
+ interface RepositoryCoordinates {
4
+ provider: string;
5
+ namespace: string;
6
+ repository: string;
7
+ }
8
+ /** Why the host refused to open a tab.
9
+ *
10
+ * - `invalid` — the coordinates are not three clean path segments.
11
+ * - `no-activation` — no live user gesture on the host document. Call this from a click
12
+ * handler; a timer or a boot path will always get this. A SECOND call inside one gesture
13
+ * also lands here: `window.open` consumes the host's transient activation, so one click
14
+ * buys exactly one tab and the next needs a real second click.
15
+ * - `forbidden` — the app does not hold the baseline `route:read` capability.
16
+ * - `unsupported` — this host has no repository-open surface wired.
17
+ * - `unknown` — the host refused without naming a code. */
18
+ type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';
19
+ interface OpenRepositoryError extends Error {
20
+ code: OpenRepositoryErrorCode;
21
+ }
22
+ /**
23
+ * Ask the host to open a repository in a new browser tab.
24
+ *
25
+ * Resolves once the host has performed the open; it does not wait for — and cannot observe —
26
+ * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`
27
+ * when the host refuses.
28
+ *
29
+ * Call it directly from a user gesture. The host samples its own transient activation when
30
+ * the request arrives, so anything that defers the call past the gesture (an `await` before
31
+ * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are
32
+ * worth retrying: each names a condition a retry cannot change.
33
+ */
34
+ declare function openRepository(coordinates: RepositoryCoordinates): Promise<void>;
35
+
36
+ export { type OpenRepositoryError, type OpenRepositoryErrorCode, type RepositoryCoordinates, openRepository };
@@ -0,0 +1,21 @@
1
+ import "./chunk-VHAA22YE.js";
2
+ import { protocolRequest } from "./sandboxUtils";
3
+ import { PROTOCOL_OPENREPO } from "./generated/protocol";
4
+ import { SCHEMES } from "./protocolSchemes";
5
+ async function openRepository(coordinates) {
6
+ const { provider, namespace, repository } = coordinates;
7
+ const res = await protocolRequest(SCHEMES[PROTOCOL_OPENREPO], "open", [
8
+ { provider, namespace, repository }
9
+ ]);
10
+ if (!res || res.ok !== true) {
11
+ const err = new Error(
12
+ (res && "message" in res ? res.message : void 0) ?? "repository open refused"
13
+ );
14
+ err.code = (res && "code" in res ? res.code : void 0) ?? "unknown";
15
+ throw err;
16
+ }
17
+ }
18
+ export {
19
+ openRepository
20
+ };
21
+ //# sourceMappingURL=openRepository.js.map