@supersolutions/super-chat-core 0.4.3 → 0.5.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.
package/dist/index.d.ts CHANGED
@@ -296,8 +296,15 @@ type CalloutCard = {
296
296
  */
297
297
  type CitationsCard = {
298
298
  kind: "citations";
299
+ /**
300
+ * Lets prose point at this card: `[[1]](ref:<id>?cite=<item id or number>)`. Optional; without
301
+ * it the card is read as a list and nothing in the answer can point into it.
302
+ */
303
+ id?: string;
299
304
  title?: string;
300
305
  items: {
306
+ /** Names this source in a citation (`cite=<id>`). Optional: the 1-based position works too. */
307
+ id?: string;
301
308
  title: string;
302
309
  /** Publication, court, statute, dataset, site — whatever the source is. */
303
310
  source?: string;
@@ -1315,6 +1322,17 @@ type ToolApproval = {
1315
1322
  /** Marks an action that is hard to undo. */
1316
1323
  danger?: boolean;
1317
1324
  };
1325
+ /**
1326
+ * How a call of this tool reads in the transcript, in the words of the person reading it.
1327
+ * Plain functions of data to a string, with no markup; never shown to the model. Without it the
1328
+ * row shows the tool's name and, when opened, the raw input and output.
1329
+ */
1330
+ type ToolDisplay = {
1331
+ /** The call, such as `Search “clause 3”`. Replaces the tool's name on its row. */
1332
+ label?: (input: unknown) => string;
1333
+ /** The outcome, such as `4 results`. Shown after the label once the call has finished. */
1334
+ summary?: (output: unknown) => string;
1335
+ };
1318
1336
  type ToolDefinition = {
1319
1337
  name: string;
1320
1338
  description: string;
@@ -1346,6 +1364,8 @@ type ToolDefinition = {
1346
1364
  * Never shown to the model.
1347
1365
  */
1348
1366
  approval?: (input: unknown) => ToolApproval | undefined;
1367
+ /** How a call reads on its row in the transcript. Optional; see `ToolDisplay`. */
1368
+ display?: ToolDisplay;
1349
1369
  /** Ask the provider to enforce the schema (OpenAI strict mode). */
1350
1370
  strict?: boolean;
1351
1371
  /** Default card renderer key when the result carries no explicit card. */
@@ -2371,6 +2391,13 @@ type ToolCallOutcome = {
2371
2391
  unlockTools?: string[];
2372
2392
  ms: number;
2373
2393
  };
2394
+ /**
2395
+ * What the model reads when the person says no to an approval. The same words
2396
+ * go into the `{ error }` of the denied result and into the `reason` of the
2397
+ * answer a tool that asks for itself receives, so `userDeclined` (stop.ts) can
2398
+ * tell a person's "no" from a host that cannot ask.
2399
+ */
2400
+ declare const USER_DECLINED = "The user declined.";
2374
2401
  /** Shrink an error to something worth carrying in history. */
2375
2402
  declare function compactError(e: unknown): {
2376
2403
  error: string;
@@ -2677,10 +2704,31 @@ declare const tokenBudgetExceeded: (maxTotal: number) => StopCondition;
2677
2704
  * step cap, producing nothing but latency and spend.
2678
2705
  */
2679
2706
  declare const consecutiveFailures: (n: number) => StopCondition;
2680
- /** Stop when the user declined an interactive card — proceeding would ignore them. */
2707
+ /**
2708
+ * Whether an outcome is the person saying no, as opposed to a tool failing or a
2709
+ * host that cannot ask. Three shapes carry it:
2710
+ *
2711
+ * - an approval the runtime asked for (`side: "confirm"`): `failure: "denied"`
2712
+ * and the error is `USER_DECLINED`;
2713
+ * - a tool that asks for itself (`confirmation: "tool"`) and returns the
2714
+ * answer it was given: `{ cancelled: true }`;
2715
+ * - an interactive card from `visualize`: `{ response: { cancelled: true } }`.
2716
+ */
2717
+ declare function isUserDecline(outcome: ToolCallOutcome): boolean;
2718
+ /**
2719
+ * Stop the run as soon as the person has declined something.
2720
+ *
2721
+ * Opt-in. By default a decline is only a result the model reads ("The user
2722
+ * declined."): the run goes on, and the model decides what to do, usually to say
2723
+ * what was left undone and ask. Use this when your product treats a "no" as the
2724
+ * end of the turn. It is not in `DEFAULT_STOP_CONDITIONS`.
2725
+ */
2681
2726
  declare const userDeclined: StopCondition;
2682
2727
  declare function shouldStop(conditions: readonly StopCondition[] | undefined, ctx: StopContext): boolean;
2683
- /** A sane default set for an interactive chat agent. */
2728
+ /**
2729
+ * A sane default set for an interactive chat agent. A person's "no" is not here:
2730
+ * it is told to the model and the run continues (see `userDeclined`).
2731
+ */
2684
2732
  declare const DEFAULT_STOP_CONDITIONS: StopCondition[];
2685
2733
 
2686
2734
  type RunConfig = {
@@ -3142,4 +3190,4 @@ declare function createMcpSkill(serverName: string, defs: readonly ToolDefinitio
3142
3190
  */
3143
3191
  declare function elicitViaCard(requestCard: (spec: CardSpec) => Promise<unknown>): McpElicitHandler;
3144
3192
 
3145
- export { A2UI_VERSION, type A2uiMessage, ANTHROPIC_OFFICIAL_PROFILE, AgentError, type AgentErrorKind, type AppAction, type AppStateBinding, type AppStateSourceOptions, type AppliedEdit, BUILTIN_CARDS, type BindingScope, type BudgetShares, type BuiltContext, type BuiltinCard, type BuiltinCardKind, CARD_COMPONENT, CARD_ENTRY_PREFIX, CARD_KEY, CARD_PLACEMENTS, CARD_REF_LIMITS, CARD_REF_SCHEME, CallOptions, type CalloutCard, type Card, type CardAction, type CardCarrier, type CardKindDefinition, type CardPlacement, type CardRef, type CardRefEvent, type CardRefHost, type CardRefParse, type CardRefResult, CardRegistry, type CardSpec, type CardTone, type CardValidation, type CardValueFormat, type ChartAnnotation, type ChartCard, type ChartSeries, type ChecklistCard, type ChoiceCard, type CitationsCard, type CodeCard, type CompactionResult, type ComparisonCard, type ConfirmCard, ContentPart, ContextBuilder, type ContextBuilderOptions, type ContextLayer, type ContextSource, type ContextSourceInput, type ContextSourceResult, type ContextTrace, DEFAULT_PRESETS, DEFAULT_STOP_CONDITIONS, type DiffCard, type DirectTransportConfig, type DocumentCard, type DocumentEdit, type DocumentOutlineEntry, type DocumentQuoteRef, type DocumentSnapshot, type DocumentStore, type DocumentToolsOptions, type EditHunk, type EditRejection, type EditResult, type EditReviewCard, type EmailCard, type ExecuteToolOptions, type FileStore, FinishReason, type FormCard, type FormField, type FunnelCard, type GaugeCard, type GenerateImageToolOptions, GenerateResult, type GeneratedMedia, type GeneratedMediaKind, type ImageGenerationRequest, JSONSchema, JobHandle, JobStatus, type KeyValueCard, type LayerId, MAILTO_SAFE_LENGTH, MESSAGE_OVERHEAD_TOKENS, type MailtoLink, type MarkdownBlock, type MarkdownBlockKind, type MarkdownCard, type McpCallResult, McpClient, type McpClientConfig, type McpContent, type McpElicitHandler, type McpElicitRequest, type McpElicitResult, type McpImportOptions, McpRpcError, type McpServerInfo, type McpTool, type MediaCard, type MediaJobHandle, type MediaJobSnapshot, type MediaProvider, type MediaProviderCapabilities, MediaSource, type MemoryEntry, type MemorySourceOptions, type MemoryStore, Message, MessageRole, type MeterSink, type MeteringError, type MeteringRecord, type MeteringSource, type MeteringStatus, ModelInfo, NormalizedRequest, OPENAI_OFFICIAL_PROFILE, type OpenAIImageProviderConfig, PartialJsonParser, type PartialToolCall, type PresetName, type ProfileDirectTransportConfig, type ProgressCard, type ProgressStep, Provider, ProviderCapabilities, ProviderFileRef, type ProviderProfile, type ProviderProtocol, type ProxyEnvelope, type ProxyTransportConfig, QUOTES_METADATA_KEY, type QuoteDrift, type RepairResult, type ResolvedSkill, type RestThreadStoreConfig, type RetrievalDoc, type RetrievalSourceOptions, type RetrievedChunk, type Retriever, RetryPolicy, type RunConfig, type RunEvent, type RunMeteringRecord, type RunMode, type RunState, SSEDecoder, type SSEMessage, SURFACE_A2UI_CATALOG_ID, SURFACE_ARTIFACT_KIND, SURFACE_CARD_KIND, SURFACE_EVENT_METADATA_KEY, SURFACE_FORMAT_VERSION, SURFACE_GUIDE, SURFACE_LIMITS, SURFACE_PRIMITIVES, SURFACE_SKILL_ID, SURFACE_TOOL_NAMES, type SchemaCheckOptions, type SchemaProblem, type SerializedMultipartBody, type Skill, type SkillContext, type SkillMatch, type SkillMatcher, type SkillMode, SkillRegistry, type SkillRegistryOptions, type SkillSection, type SpeechGenerationRequest, type StatItem, type StatsCard, type StepMeteringRecord, type StopCondition, type StopContext, type StoredFile, type StoredThread, type Summarizer, type SurfaceAction, type SurfaceActivity, type SurfaceActivityState, type SurfaceAggregateOp, type SurfaceBinding, type SurfaceBuildContext, type SurfaceBuildResult, type SurfaceCardAnswer, SurfaceCatalogue, type SurfaceCatalogueOptions, type SurfaceComponent, type SurfaceComponentCategory, type SurfaceComponentDefinition, type SurfaceCondition, type SurfaceConditionOp, type SurfaceEventRecord, type SurfaceIssue, type SurfaceIssueCode, type SurfaceItemBinding, SurfaceLedger, type SurfaceOperation, type SurfacePathBinding, type SurfacePendingPart, type SurfaceQuery, type SurfaceQueryBinding, type SurfaceSpec, type SurfaceTemplateBinding, type SurfaceToolAuthorization, type SurfaceToolRunConfig, type SurfaceToolsOptions, type SurfaceValidationContext, type SurfaceWhere, type SurfaceWhereOp, THREAD_SCHEMA_VERSION, type TableCard, type TableColumn, type ThreadMeta, type ThreadStore, type TimelineCard, type TokenBudget, type TokenCounter, type ToolApproval, type ToolCallOutcome, type ToolCallRequest, ToolCallStatus, type ToolDefinition, type ToolExecutionContext, ToolFailureKind, type ToolLoading, type ToolLoadingHint, ToolRegistry, type ToolResolution, type ToolResult, type ToolResultExtras, type ToolSide, ToolSpec, type TraceEntry, type Transcript, type TranscriptionRequest, Transport, TransportRequest, type TreeCard, type TreeNode, type TurnLayoutOptions, type TurnSegment, type UnsafeFinding, Usage, type VideoGenerationRequest, type VisualizePlacement, type VisualizeToolOptions, afterTool, appendReasoning, appendText, applyEdits, applySurfaceOperations, approvalCard, assistantMessage, authorizeSurfaceTool, backoffDelay, base64ToBytes, bindingProblems, buildEml, buildMailto, buildSummaryPrompt, buildSurface, buildUrl, bytesToBase64, calloutCard, chartCard, check, checkQuoteDrift, checkSchema, checklistCard, childrenOf, choiceCard, citationsCard, codeCard, combineMeteringSources, compactError, compactHistory, comparisonCard, confirmCard, consecutiveFailures, countMessageTokens, countMessagesTokens, createAppActionTools, createAppStateSource, createBudget, createBuiltinTools, createDirectTransport, createDirectTransportForProfile, createDocumentTools, createEmailDraftTool, createGenerateImageTool, createHttpTransport, createKeywordRetriever, createLoadSkillTool, createLocalDocumentStore, createLocalFileStore, createLocalMemoryStore, createLocalThreadStore, createMcpSkill, createMemoryDocumentStore, createMemoryFileStore, createMemoryMemoryStore, createMemorySource, createMemoryThreadStore, createOpenAICompatibleProfile, createOpenAIImageProvider, createProviderFromProfile, createProxyTransport, createRememberTool, createRestThreadStore, createRetrievalSource, createSurfaceContextSource, createSurfaceSkill, createSurfaceTools, createUpdateCardTool, createVisualizeTool, deliverMetering, diffCard, documentCard, editReviewCard, elicitViaCard, emailCard, emlFilename, errorFromResponse, estimateJsonTokens, estimateTokens, evaluateSurfaceCondition, executeToolCall, executeToolCalls, file, findUnsafe, foldSurfaces, formCard, formatQuotes, formatTemplate, funnelCard, gaugeCard, generatedMediaUrl, getAt, hasTurnOrder, humanizeFieldName, hunksOf, image, importMcpTools, initialRunState, isAgentError, isCardCarrier, isCardPlacement, isScriptUrl, isSurfaceBinding, isSurfaceId, isSurfaceSpec, isTextPart, isToolCallPart, isToolResultPart, keyValueCard, kindFromStatus, lastUserText, latestLeaf, layoutTurn, linkLinear, makeCard, mapMcpResult, markdownCard, matchSkills, mediaCard, message, messageText, nextId, noToolCalls, normalizeProviderProfile, normalizeToolName, outlineOf, packByPriority, parseCardRef, parsePartialJson, parsePointer, parseRetryAfter, parseSSE, parseSSEJson, pathTo, previewSurface, progressCard, quoteDrift, quotesOf, reduceRunEvent, removeAt, renderSkill, repairToolArguments, resolvePartialCard, resolveSurfaceAction, resolveSurfaceValue, resolveToolLoading, runAgent, runSurfaceQuery, runSurfaceToolAction, safeCutIndex, safeSurfaceUrl, sanitizeSurfaceSpec, scoreSkill, searchBlocks, setAt, shouldStop, siblingsOf, spanOf, splitBlocks, statsCard, stepCountIs, stripCardPayload, stripUiOnlyParts, surfaceActionTools, surfaceCardId, tableCard, text, threadSnapshot, timelineCard, toA2uiMessages, toAgentError, tokenBudgetExceeded, tokenize, toolCall, toolCallsIn, toolResult, totalAllocated, treeCard, trimHistory, usageSource, userDeclined, userMessage, usesBinding, validateSurfaceAction, validateSurfaceComponent, validateSurfaceComponents, validateSurfaceGraph, withCard, withQuotes, withRetry };
3193
+ export { A2UI_VERSION, type A2uiMessage, ANTHROPIC_OFFICIAL_PROFILE, AgentError, type AgentErrorKind, type AppAction, type AppStateBinding, type AppStateSourceOptions, type AppliedEdit, BUILTIN_CARDS, type BindingScope, type BudgetShares, type BuiltContext, type BuiltinCard, type BuiltinCardKind, CARD_COMPONENT, CARD_ENTRY_PREFIX, CARD_KEY, CARD_PLACEMENTS, CARD_REF_LIMITS, CARD_REF_SCHEME, CallOptions, type CalloutCard, type Card, type CardAction, type CardCarrier, type CardKindDefinition, type CardPlacement, type CardRef, type CardRefEvent, type CardRefHost, type CardRefParse, type CardRefResult, CardRegistry, type CardSpec, type CardTone, type CardValidation, type CardValueFormat, type ChartAnnotation, type ChartCard, type ChartSeries, type ChecklistCard, type ChoiceCard, type CitationsCard, type CodeCard, type CompactionResult, type ComparisonCard, type ConfirmCard, ContentPart, ContextBuilder, type ContextBuilderOptions, type ContextLayer, type ContextSource, type ContextSourceInput, type ContextSourceResult, type ContextTrace, DEFAULT_PRESETS, DEFAULT_STOP_CONDITIONS, type DiffCard, type DirectTransportConfig, type DocumentCard, type DocumentEdit, type DocumentOutlineEntry, type DocumentQuoteRef, type DocumentSnapshot, type DocumentStore, type DocumentToolsOptions, type EditHunk, type EditRejection, type EditResult, type EditReviewCard, type EmailCard, type ExecuteToolOptions, type FileStore, FinishReason, type FormCard, type FormField, type FunnelCard, type GaugeCard, type GenerateImageToolOptions, GenerateResult, type GeneratedMedia, type GeneratedMediaKind, type ImageGenerationRequest, JSONSchema, JobHandle, JobStatus, type KeyValueCard, type LayerId, MAILTO_SAFE_LENGTH, MESSAGE_OVERHEAD_TOKENS, type MailtoLink, type MarkdownBlock, type MarkdownBlockKind, type MarkdownCard, type McpCallResult, McpClient, type McpClientConfig, type McpContent, type McpElicitHandler, type McpElicitRequest, type McpElicitResult, type McpImportOptions, McpRpcError, type McpServerInfo, type McpTool, type MediaCard, type MediaJobHandle, type MediaJobSnapshot, type MediaProvider, type MediaProviderCapabilities, MediaSource, type MemoryEntry, type MemorySourceOptions, type MemoryStore, Message, MessageRole, type MeterSink, type MeteringError, type MeteringRecord, type MeteringSource, type MeteringStatus, ModelInfo, NormalizedRequest, OPENAI_OFFICIAL_PROFILE, type OpenAIImageProviderConfig, PartialJsonParser, type PartialToolCall, type PresetName, type ProfileDirectTransportConfig, type ProgressCard, type ProgressStep, Provider, ProviderCapabilities, ProviderFileRef, type ProviderProfile, type ProviderProtocol, type ProxyEnvelope, type ProxyTransportConfig, QUOTES_METADATA_KEY, type QuoteDrift, type RepairResult, type ResolvedSkill, type RestThreadStoreConfig, type RetrievalDoc, type RetrievalSourceOptions, type RetrievedChunk, type Retriever, RetryPolicy, type RunConfig, type RunEvent, type RunMeteringRecord, type RunMode, type RunState, SSEDecoder, type SSEMessage, SURFACE_A2UI_CATALOG_ID, SURFACE_ARTIFACT_KIND, SURFACE_CARD_KIND, SURFACE_EVENT_METADATA_KEY, SURFACE_FORMAT_VERSION, SURFACE_GUIDE, SURFACE_LIMITS, SURFACE_PRIMITIVES, SURFACE_SKILL_ID, SURFACE_TOOL_NAMES, type SchemaCheckOptions, type SchemaProblem, type SerializedMultipartBody, type Skill, type SkillContext, type SkillMatch, type SkillMatcher, type SkillMode, SkillRegistry, type SkillRegistryOptions, type SkillSection, type SpeechGenerationRequest, type StatItem, type StatsCard, type StepMeteringRecord, type StopCondition, type StopContext, type StoredFile, type StoredThread, type Summarizer, type SurfaceAction, type SurfaceActivity, type SurfaceActivityState, type SurfaceAggregateOp, type SurfaceBinding, type SurfaceBuildContext, type SurfaceBuildResult, type SurfaceCardAnswer, SurfaceCatalogue, type SurfaceCatalogueOptions, type SurfaceComponent, type SurfaceComponentCategory, type SurfaceComponentDefinition, type SurfaceCondition, type SurfaceConditionOp, type SurfaceEventRecord, type SurfaceIssue, type SurfaceIssueCode, type SurfaceItemBinding, SurfaceLedger, type SurfaceOperation, type SurfacePathBinding, type SurfacePendingPart, type SurfaceQuery, type SurfaceQueryBinding, type SurfaceSpec, type SurfaceTemplateBinding, type SurfaceToolAuthorization, type SurfaceToolRunConfig, type SurfaceToolsOptions, type SurfaceValidationContext, type SurfaceWhere, type SurfaceWhereOp, THREAD_SCHEMA_VERSION, type TableCard, type TableColumn, type ThreadMeta, type ThreadStore, type TimelineCard, type TokenBudget, type TokenCounter, type ToolApproval, type ToolCallOutcome, type ToolCallRequest, ToolCallStatus, type ToolDefinition, type ToolDisplay, type ToolExecutionContext, ToolFailureKind, type ToolLoading, type ToolLoadingHint, ToolRegistry, type ToolResolution, type ToolResult, type ToolResultExtras, type ToolSide, ToolSpec, type TraceEntry, type Transcript, type TranscriptionRequest, Transport, TransportRequest, type TreeCard, type TreeNode, type TurnLayoutOptions, type TurnSegment, USER_DECLINED, type UnsafeFinding, Usage, type VideoGenerationRequest, type VisualizePlacement, type VisualizeToolOptions, afterTool, appendReasoning, appendText, applyEdits, applySurfaceOperations, approvalCard, assistantMessage, authorizeSurfaceTool, backoffDelay, base64ToBytes, bindingProblems, buildEml, buildMailto, buildSummaryPrompt, buildSurface, buildUrl, bytesToBase64, calloutCard, chartCard, check, checkQuoteDrift, checkSchema, checklistCard, childrenOf, choiceCard, citationsCard, codeCard, combineMeteringSources, compactError, compactHistory, comparisonCard, confirmCard, consecutiveFailures, countMessageTokens, countMessagesTokens, createAppActionTools, createAppStateSource, createBudget, createBuiltinTools, createDirectTransport, createDirectTransportForProfile, createDocumentTools, createEmailDraftTool, createGenerateImageTool, createHttpTransport, createKeywordRetriever, createLoadSkillTool, createLocalDocumentStore, createLocalFileStore, createLocalMemoryStore, createLocalThreadStore, createMcpSkill, createMemoryDocumentStore, createMemoryFileStore, createMemoryMemoryStore, createMemorySource, createMemoryThreadStore, createOpenAICompatibleProfile, createOpenAIImageProvider, createProviderFromProfile, createProxyTransport, createRememberTool, createRestThreadStore, createRetrievalSource, createSurfaceContextSource, createSurfaceSkill, createSurfaceTools, createUpdateCardTool, createVisualizeTool, deliverMetering, diffCard, documentCard, editReviewCard, elicitViaCard, emailCard, emlFilename, errorFromResponse, estimateJsonTokens, estimateTokens, evaluateSurfaceCondition, executeToolCall, executeToolCalls, file, findUnsafe, foldSurfaces, formCard, formatQuotes, formatTemplate, funnelCard, gaugeCard, generatedMediaUrl, getAt, hasTurnOrder, humanizeFieldName, hunksOf, image, importMcpTools, initialRunState, isAgentError, isCardCarrier, isCardPlacement, isScriptUrl, isSurfaceBinding, isSurfaceId, isSurfaceSpec, isTextPart, isToolCallPart, isToolResultPart, isUserDecline, keyValueCard, kindFromStatus, lastUserText, latestLeaf, layoutTurn, linkLinear, makeCard, mapMcpResult, markdownCard, matchSkills, mediaCard, message, messageText, nextId, noToolCalls, normalizeProviderProfile, normalizeToolName, outlineOf, packByPriority, parseCardRef, parsePartialJson, parsePointer, parseRetryAfter, parseSSE, parseSSEJson, pathTo, previewSurface, progressCard, quoteDrift, quotesOf, reduceRunEvent, removeAt, renderSkill, repairToolArguments, resolvePartialCard, resolveSurfaceAction, resolveSurfaceValue, resolveToolLoading, runAgent, runSurfaceQuery, runSurfaceToolAction, safeCutIndex, safeSurfaceUrl, sanitizeSurfaceSpec, scoreSkill, searchBlocks, setAt, shouldStop, siblingsOf, spanOf, splitBlocks, statsCard, stepCountIs, stripCardPayload, stripUiOnlyParts, surfaceActionTools, surfaceCardId, tableCard, text, threadSnapshot, timelineCard, toA2uiMessages, toAgentError, tokenBudgetExceeded, tokenize, toolCall, toolCallsIn, toolResult, totalAllocated, treeCard, trimHistory, usageSource, userDeclined, userMessage, usesBinding, validateSurfaceAction, validateSurfaceComponent, validateSurfaceComponents, validateSurfaceGraph, withCard, withQuotes, withRetry };
package/dist/index.js CHANGED
@@ -338,7 +338,7 @@ function quotesOf(metadata) {
338
338
 
339
339
  // src/transport/binary.ts
340
340
  var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
341
- var REVERSE = (() => {
341
+ var REVERSE = /* @__PURE__ */ (() => {
342
342
  const table = new Int16Array(128).fill(-1);
343
343
  for (let i = 0; i < ALPHABET.length; i += 1) table[ALPHABET.charCodeAt(i)] = i;
344
344
  return table;
@@ -2150,7 +2150,7 @@ function makeCard(spec, callId, id, placement) {
2150
2150
 
2151
2151
  // src/cards/card-ref.ts
2152
2152
  var CARD_REF_SCHEME = "ref";
2153
- var CARD_REF_LIMITS = Object.freeze({
2153
+ var CARD_REF_LIMITS = /* @__PURE__ */ Object.freeze({
2154
2154
  /** The whole link, in UTF-16 code units. */
2155
2155
  length: 512,
2156
2156
  /** The target (the card's id). */
@@ -2866,13 +2866,14 @@ var calloutCard = {
2866
2866
  };
2867
2867
  var citationsCard = {
2868
2868
  kind: "citations",
2869
- summary: "The sources behind what you just said. Use whenever a claim rests on specific documents \u2014 case law, statutes, papers, filings, articles, internal docs. Quote the passage relied on in `snippet`.",
2869
+ summary: "The sources behind what you just said. Use whenever a claim rests on specific documents \u2014 case law, statutes, papers, filings, articles, internal docs. Quote the passage relied on in `snippet`. To cite a source inside your answer, give the card an `id` and write `[[1]](ref:<card id>?cite=<item id or its number>)` where the claim is made; the reader can hover or press it to see the source.",
2870
2870
  estimateTokens: tokensOf,
2871
2871
  schema: {
2872
2872
  type: "object",
2873
2873
  required: ["kind", "items"],
2874
2874
  properties: {
2875
2875
  kind: { const: "citations" },
2876
+ id: { type: "string", description: "Short name, so the answer can cite into this card with ref:<id>?cite=<n>." },
2876
2877
  title: { type: "string" },
2877
2878
  items: {
2878
2879
  type: "array",
@@ -2880,6 +2881,7 @@ var citationsCard = {
2880
2881
  type: "object",
2881
2882
  required: ["title"],
2882
2883
  properties: {
2884
+ id: { type: "string", description: "Short name of this source for `cite=`; unique in the card." },
2883
2885
  title: { type: "string" },
2884
2886
  source: { type: "string", description: "Publication, court, statute, dataset, site." },
2885
2887
  url: { type: "string" },
@@ -2897,10 +2899,22 @@ var citationsCard = {
2897
2899
  if (failed(s)) return s;
2898
2900
  const items = check.arrayField(s, "items", "citations");
2899
2901
  if (failed(items)) return items;
2902
+ const named = /* @__PURE__ */ new Set();
2900
2903
  for (const i of items) {
2901
2904
  if (!isObj(i) || typeof i["title"] !== "string") {
2902
2905
  return { ok: false, error: "Each citation needs a `title`." };
2903
2906
  }
2907
+ if (i["id"] !== void 0) {
2908
+ if (typeof i["id"] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._~-]{0,63}$/.test(i["id"])) {
2909
+ return { ok: false, error: "A citation `id` is 1 to 64 letters, digits, dot, dash, underscore or tilde, starting with a letter or digit." };
2910
+ }
2911
+ if (named.has(i["id"])) return { ok: false, error: `Two citations share the id "${i["id"]}"; ids must be unique in a card.` };
2912
+ named.add(i["id"]);
2913
+ }
2914
+ }
2915
+ const cardId = s["id"];
2916
+ if (cardId !== void 0 && (typeof cardId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(cardId))) {
2917
+ return { ok: false, error: "citations.id is 1 to 128 letters, digits, dot, underscore, colon or dash, starting with a letter or digit." };
2904
2918
  }
2905
2919
  return ok;
2906
2920
  }
@@ -3615,7 +3629,7 @@ var TONES = ["neutral", "positive", "negative", "warning", "info"];
3615
3629
  var FORMATS2 = ["text", "number", "currency", "percent", "bytes", "duration", "datetime", "code"];
3616
3630
  var GAPS = ["none", "xs", "sm", "md", "lg"];
3617
3631
  var fixed = (schema) => ({ ...schema, "x-static": true });
3618
- var childIds = fixed({ type: "array", items: { type: "string" }, description: "Component ids, in display order." });
3632
+ var childIds = /* @__PURE__ */ fixed({ type: "array", items: { type: "string" }, description: "Component ids, in display order." });
3619
3633
  var childId = (description) => fixed({ type: "string", description });
3620
3634
  var boundValue = {
3621
3635
  type: "object",
@@ -3625,7 +3639,7 @@ var boundValue = {
3625
3639
  description: 'Two-way binding, e.g. { "$path": "/filters/region" }.',
3626
3640
  "x-static": true
3627
3641
  };
3628
- var CONDITION_SCHEMA = fixed({
3642
+ var CONDITION_SCHEMA = /* @__PURE__ */ fixed({
3629
3643
  type: "object",
3630
3644
  required: ["path"],
3631
3645
  properties: {
@@ -3635,7 +3649,7 @@ var CONDITION_SCHEMA = fixed({
3635
3649
  },
3636
3650
  additionalProperties: false
3637
3651
  });
3638
- var ACTION_SCHEMA = fixed({
3652
+ var ACTION_SCHEMA = /* @__PURE__ */ fixed({
3639
3653
  type: "object",
3640
3654
  required: ["type"],
3641
3655
  description: 'One of { "type": "set", "updates": [{ "path", "value" }] }, { "type": "tool", "tool", "args", "resultPath" }, { "type": "event", "name", "context" }.'
@@ -4793,6 +4807,7 @@ function approvalCard(tool, input, options = {}) {
4793
4807
 
4794
4808
  // src/runtime/execute-tools.ts
4795
4809
  var MAX_ERROR_CHARS = 400;
4810
+ var USER_DECLINED = "The user declined.";
4796
4811
  function compactError(e) {
4797
4812
  if (e instanceof AgentError) {
4798
4813
  return { error: e.message.slice(0, MAX_ERROR_CHARS), kind: e.kind };
@@ -4805,7 +4820,7 @@ async function confirmationRefusal(tool, call, opts) {
4805
4820
  if (tool.confirmation === "tool") return void 0;
4806
4821
  const answer = await opts.requestCard(call.callId, approvalCard(tool, call.input));
4807
4822
  if (opts.signal?.aborted) return "The run was stopped before this was approved.";
4808
- return answer?.confirmed === true ? void 0 : "The user declined.";
4823
+ return answer?.confirmed === true ? void 0 : USER_DECLINED;
4809
4824
  }
4810
4825
  var isToolResult = (v) => typeof v === "object" && v !== null && "output" in v && Object.keys(v).every((k) => ["output", "card", "failure", "cardId", "unlockTools", "placement"].includes(k));
4811
4826
  async function executeToolCall(call, opts) {
@@ -5872,14 +5887,20 @@ var consecutiveFailures = (n) => {
5872
5887
  return streak >= n;
5873
5888
  };
5874
5889
  };
5875
- var userDeclined = (ctx) => ctx.outcomes.some(
5876
- (o) => typeof o.output === "object" && o.output !== null && o.output.cancelled === true
5877
- );
5890
+ function isUserDecline(outcome2) {
5891
+ const output = outcome2.output;
5892
+ if (typeof output !== "object" || output === null) return false;
5893
+ const o = output;
5894
+ if (outcome2.failure === "denied" && o.error === USER_DECLINED) return true;
5895
+ if (o.cancelled === true) return true;
5896
+ return typeof o.response === "object" && o.response !== null && o.response.cancelled === true;
5897
+ }
5898
+ var userDeclined = (ctx) => ctx.outcomes.some(isUserDecline);
5878
5899
  function shouldStop(conditions, ctx) {
5879
5900
  if (!conditions?.length) return false;
5880
5901
  return conditions.some((c) => c(ctx));
5881
5902
  }
5882
- var DEFAULT_STOP_CONDITIONS = [consecutiveFailures(3), userDeclined];
5903
+ var DEFAULT_STOP_CONDITIONS = [/* @__PURE__ */ consecutiveFailures(3)];
5883
5904
 
5884
5905
  // src/runtime/run.ts
5885
5906
  async function* runAgent(messages, config) {
@@ -6129,7 +6150,7 @@ async function* runAgent(messages, config) {
6129
6150
  channel.push({ type: "awaiting-user", callId, card });
6130
6151
  const action = await config.onUserDecision(callId, card);
6131
6152
  channel.push({ type: "user-responded", callId, action });
6132
- return action.type === "cancel" || action.type === "dismiss" ? { cancelled: true, reason: "The user declined." } : action.value ?? { confirmed: true };
6153
+ return action.type === "cancel" || action.type === "dismiss" ? { cancelled: true, reason: USER_DECLINED } : action.value ?? { confirmed: true };
6133
6154
  } : void 0
6134
6155
  }).finally(() => channel.close());
6135
6156
  for await (const event of channel) yield event;
@@ -7212,6 +7233,7 @@ export {
7212
7233
  SurfaceLedger,
7213
7234
  THREAD_SCHEMA_VERSION,
7214
7235
  ToolRegistry,
7236
+ USER_DECLINED,
7215
7237
  afterTool,
7216
7238
  appendReasoning,
7217
7239
  appendText,
@@ -7330,6 +7352,7 @@ export {
7330
7352
  isTextPart,
7331
7353
  isToolCallPart,
7332
7354
  isToolResultPart,
7355
+ isUserDecline,
7333
7356
  keyValueCard,
7334
7357
  kindFromStatus,
7335
7358
  lastUserText,