fascicle 0.15.0 → 0.16.1
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/CHANGELOG.md +121 -0
- package/README.md +8 -8
- package/dist/acp.d.ts +9 -2
- package/dist/acp.js +1538 -1472
- package/dist/acp.js.map +1 -1
- package/dist/{adapters-DNnzeLxr.js → adapters-CDUzZlby.js} +35 -13
- package/dist/adapters-CDUzZlby.js.map +1 -0
- package/dist/adapters.d.ts +8 -1
- package/dist/adapters.js +1 -1
- package/dist/agents.d.ts +1 -1
- package/dist/agents.js +15 -8
- package/dist/agents.js.map +1 -1
- package/dist/bin/fascicle-viewer.js +4 -1
- package/dist/console-CdB4pcFO.js +37 -0
- package/dist/console-CdB4pcFO.js.map +1 -0
- package/dist/{core-CDrz0NM1.js → core-CErsxGF6.js} +246 -147
- package/dist/core-CErsxGF6.js.map +1 -0
- package/dist/diagram_bin.js +2 -2
- package/dist/diagram_bin.js.map +1 -1
- package/dist/{engine-ha9xmgwE.js → engine-CR8q2IqV.js} +173 -67
- package/dist/engine-CR8q2IqV.js.map +1 -0
- package/dist/index.d.ts +529 -73
- package/dist/index.js +440 -137
- package/dist/index.js.map +1 -1
- package/dist/{invoke-px31fffH.js → invoke-COaeZ-vy.js} +6 -5
- package/dist/invoke-COaeZ-vy.js.map +1 -0
- package/dist/{json_schema_to_standard-BTWD0J6p.js → json_schema_to_standard-C4F4lXHE.js} +9 -12
- package/dist/json_schema_to_standard-C4F4lXHE.js.map +1 -0
- package/dist/{leading_system-DfJLqpGi.js → leading_system-PoHzNHuV.js} +28 -8
- package/dist/leading_system-PoHzNHuV.js.map +1 -0
- package/dist/mcp.d.ts +3 -2
- package/dist/mcp.js +8 -4
- package/dist/mcp.js.map +1 -1
- package/dist/otel.js +10 -10
- package/dist/otel.js.map +1 -1
- package/dist/{search-CA_OqFeW.js → search-CpCJYMUm.js} +53 -6
- package/dist/search-CpCJYMUm.js.map +1 -0
- package/dist/search_worker.js +1 -1
- package/dist/stdio.js +7 -3
- package/dist/stdio.js.map +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +3 -3
- package/dist/testing.js.map +1 -1
- package/dist/{trajectory-Bm-mOtqw.d.ts → trajectory-BKGNxi7u.d.ts} +10 -9
- package/dist/{trajectory-BI-mrVFT.js → trajectory-DeURWIhj.js} +6 -5
- package/dist/trajectory-DeURWIhj.js.map +1 -0
- package/dist/{types-De-TVQxS.d.ts → types-Sw0oHW-_.d.ts} +6 -7
- package/dist/ui.d.ts +2 -1
- package/dist/ui.js +8 -1
- package/dist/ui.js.map +1 -1
- package/dist/viewer-app/assets/index-BYF5Dp7d.js +2 -0
- package/dist/viewer-app/index.html +2 -1
- package/dist/viewer.d.ts +26 -12
- package/dist/viewer.js +282 -63
- package/dist/viewer.js.map +1 -1
- package/package.json +5 -5
- package/dist/adapters-DNnzeLxr.js.map +0 -1
- package/dist/core-CDrz0NM1.js.map +0 -1
- package/dist/engine-ha9xmgwE.js.map +0 -1
- package/dist/invoke-px31fffH.js.map +0 -1
- package/dist/json_schema_to_standard-BTWD0J6p.js.map +0 -1
- package/dist/leading_system-DfJLqpGi.js.map +0 -1
- package/dist/search-CA_OqFeW.js.map +0 -1
- package/dist/trajectory-BI-mrVFT.js.map +0 -1
- package/dist/viewer-app/assets/index-Fnh5HKSU.js +0 -2
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"invoke-px31fffH.js","names":["ai_tool"],"sources":["../src/engine/providers/ai_sdk/telemetry.ts","../src/engine/providers/ai_sdk/invoke.ts"],"sourcesContent":["/**\n * AI SDK telemetry wiring, confined to the ai_sdk transport.\n *\n * `@ai-sdk/otel` is adopted strictly below the turn seam: it instruments one\n * turn inside this module, never the loop. The peer is loaded lazily and only\n * when telemetry is explicitly enabled, so the disabled default (every call\n * that does not opt in) pulls in nothing.\n *\n * This is the ONLY place `@ai-sdk/otel` is referenced. generate.ts and\n * create_engine.ts thread a plain `AiSdkTelemetrySettings` value through the\n * seam and stay SDK-agnostic; loop-level, transport-neutral tracing is the\n * separate `fascicle/otel` bridge.\n */\n\nimport type { AiSdkTelemetrySettings } from '../../types.js'\nimport { load_optional_peer } from '../types.js'\n\ntype OpenTelemetryCtor = new (options?: { tracer?: unknown }) => unknown\n\ntype AiSdkOtelModule = {\n readonly OpenTelemetry: OpenTelemetryCtor\n}\n\n/**\n * The subset of the AI SDK's telemetry option shape this module produces, using\n * the SDK's own (camelCase) keys. Cast onto `experimental_telemetry` at the\n * call site.\n */\nexport type AiSdkTelemetryPassthrough = {\n isEnabled: true\n integrations: unknown[]\n functionId?: string\n recordInputs?: boolean\n recordOutputs?: boolean\n metadata?: Readonly<Record<string, string | number | boolean>>\n}\n\n/**\n * Build the AI SDK's `experimental_telemetry` option from engine settings,\n * loading the `@ai-sdk/otel` peer only when telemetry is enabled.\n */\nexport async function build_ai_sdk_telemetry(\n settings: AiSdkTelemetrySettings | undefined,\n): Promise<AiSdkTelemetryPassthrough | undefined> {\n if (!settings?.enabled) return undefined\n const mod = await load_optional_peer<AiSdkOtelModule>('@ai-sdk/otel')\n const integration = new mod.OpenTelemetry(\n settings.tracer !== undefined ? { tracer: settings.tracer } : {},\n )\n const out: AiSdkTelemetryPassthrough = { isEnabled: true, integrations: [integration] }\n if (settings.function_id !== undefined) out.functionId = settings.function_id\n if (settings.record_inputs !== undefined) out.recordInputs = settings.record_inputs\n if (settings.record_outputs !== undefined) out.recordOutputs = settings.record_outputs\n if (settings.metadata !== undefined) out.metadata = settings.metadata\n return out\n}\n","/**\n * The ai_sdk transport: the engine's only Vercel AI SDK call site.\n *\n * Only this module imports from `ai` or invokes generateText / streamText.\n * generate.ts drives this transport through create_ai_sdk_turn and stays\n * SDK-agnostic; run_tool_loop sees the same neutral TurnResult a native\n * adapter produces. Enforced by rules/no-ai-import-outside-ai-sdk-provider.yml.\n *\n * Retry stays out of this module on purpose: generate.ts wraps the turn\n * returned here in the engine-owned retry_turn, exactly as it wraps a native\n * adapter's invoke_turn. This module owns request/response mapping only.\n */\n\nimport {\n generateText,\n NoObjectGeneratedError,\n Output,\n isStepCount,\n streamText,\n tool as ai_tool,\n type AssistantContent,\n type ContentPart,\n type ImagePart,\n type LanguageModel,\n type ModelMessage,\n type TextPart,\n type TextStreamPart,\n type ToolCallPart,\n type ToolSet,\n} from 'ai'\nimport type { ToolSchema } from '#schema'\nimport type {\n AiSdkTelemetrySettings,\n AssistantContentPart,\n FinishReason,\n Message,\n ProviderOptions,\n StreamChunk,\n Tool,\n TurnResult,\n UsageTotals,\n} from '../../types.js'\nimport { aborted_error } from '../../errors.js'\nimport { split_leading_system_run } from '../../leading_system.js'\nimport type { ChunkDispatcher } from '../../streaming.js'\nimport type { RawToolCall } from '../../tool_loop.js'\nimport {\n default_normalize_usage,\n type AiSdkProviderAdapter,\n type EffortTranslation,\n type RawProviderUsage,\n} from '../types.js'\nimport { is_own_reasoning } from '../native_shared.js'\nimport { build_ai_sdk_telemetry, type AiSdkTelemetryPassthrough } from './telemetry.js'\n\n// The SDK exports no name for an assistant reasoning part, so it is read off\n// the assistant content union.\ntype SdkReasoningPart = Extract<Exclude<AssistantContent, string>[number], { type: 'reasoning' }>\n\n/**\n * Attach a Fascicle part's provider_options to an SDK prompt part as its\n * providerOptions, the key the SDK reads a part's provider data back from.\n */\nfunction with_provider_options<part extends { providerOptions?: TextPart['providerOptions'] }>(\n sdk_part: part,\n provider_options: ProviderOptions | undefined,\n): part {\n if (provider_options === undefined) return sdk_part\n // ProviderOptions is the two-level provider map the SDK's shared provider\n // options spell with JSON values; the payloads are the SDK's own metadata.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return { ...sdk_part, providerOptions: provider_options as NonNullable<part['providerOptions']> }\n}\n\n/**\n * Map the AI SDK's finish reason string to the engine's FinishReason.\n */\nexport function map_finish_reason(raw: string | undefined): FinishReason {\n switch (raw) {\n case 'stop':\n return 'stop'\n case 'length':\n return 'length'\n case 'content-filter':\n case 'content_filter':\n return 'content_filter'\n case 'tool-calls':\n case 'tool_calls':\n return 'tool_calls'\n default:\n return 'stop'\n }\n}\n\n/**\n * Read a numeric field off an object by key, or undefined when it is absent or\n * not a number. The single typeof guard behind every usage-field read below.\n */\nfunction read_number(source: object, key: string): number | undefined {\n const value = Reflect.get(source, key)\n return typeof value === 'number' ? value : undefined\n}\n\n/**\n * Read the AI SDK's nested `inputTokenDetails` (cache read/write counts) onto\n * `raw`. Present-but-empty details still seed `input_token_details` so the\n * \"the SDK reported details\" signal survives even when both counts are absent.\n */\nfunction read_input_details(usage: object, raw: RawProviderUsage): void {\n const details = Reflect.get(usage, 'inputTokenDetails')\n if (details === null || typeof details !== 'object') return\n raw.input_token_details = {}\n const cache_read = read_number(details, 'cacheReadTokens')\n if (cache_read !== undefined) raw.input_token_details.cached_tokens = cache_read\n const cache_write = read_number(details, 'cacheWriteTokens')\n if (cache_write !== undefined) raw.input_token_details.cache_creation_input_tokens = cache_write\n}\n\n/**\n * Read the AI SDK's nested `outputTokenDetails` (reasoning-token count) onto\n * `raw`, seeding `output_token_details` whenever the details object is present.\n */\nfunction read_output_details(usage: object, raw: RawProviderUsage): void {\n const details = Reflect.get(usage, 'outputTokenDetails')\n if (details === null || typeof details !== 'object') return\n raw.output_token_details = {}\n const reasoning = read_number(details, 'reasoningTokens')\n if (reasoning !== undefined) raw.output_token_details.reasoning_tokens = reasoning\n}\n\n/**\n * Read the flattened snake_case usage fields some provider mocks return\n * directly. The `input_tokens`/`output_tokens` flats are fallbacks: they fill\n * in only when the camelCase read did not already set the same total.\n */\nfunction read_flat_usage(usage: object, raw: RawProviderUsage): void {\n const cached = read_number(usage, 'cached_input_tokens')\n if (cached !== undefined) raw.cached_input_tokens = cached\n const cache_write = read_number(usage, 'cache_write_tokens')\n if (cache_write !== undefined) raw.cache_write_tokens = cache_write\n const reasoning = read_number(usage, 'reasoning_tokens')\n if (reasoning !== undefined) raw.reasoning_tokens = reasoning\n const input_flat = read_number(usage, 'input_tokens')\n if (raw.input_tokens === undefined && input_flat !== undefined) raw.input_tokens = input_flat\n const output_flat = read_number(usage, 'output_tokens')\n if (raw.output_tokens === undefined && output_flat !== undefined) raw.output_tokens = output_flat\n}\n\n/**\n * Extract the usage fields `default_normalize_usage` understands from an AI\n * SDK usage object, tolerating both the SDK's camelCase shape and the\n * flattened snake_case fields some provider mocks return directly.\n */\nexport function to_raw_provider_usage(usage: unknown): RawProviderUsage {\n if (usage === null || typeof usage !== 'object') return {}\n const raw: RawProviderUsage = {}\n const input_tokens = read_number(usage, 'inputTokens')\n if (input_tokens !== undefined) raw.input_tokens = input_tokens\n const output_tokens = read_number(usage, 'outputTokens')\n if (output_tokens !== undefined) raw.output_tokens = output_tokens\n read_input_details(usage, raw)\n read_output_details(usage, raw)\n read_flat_usage(usage, raw)\n return raw\n}\n\n/**\n * Normalize an AI SDK `providerMetadata` value into the neutral\n * TurnResult.provider_reported shape.\n *\n * The SDK's metadata is already keyed by provider name, which is the shape\n * provider_reported documents, so the keys ride through untranslated and every\n * ai_sdk provider is served by this one seam: bedrock's guardrail `trace`,\n * anthropic's cache detail, openai's own fields. The payloads stay opaque\n * (callers narrow them at the use site), so this copies the top level and\n * inspects nothing below it. An absent or empty map returns undefined, keeping\n * \"the provider reported nothing\" spelled one way.\n */\nexport function to_provider_reported(metadata: unknown): Record<string, unknown> | undefined {\n if (metadata === null || typeof metadata !== 'object') return undefined\n const keys = Object.keys(metadata)\n if (keys.length === 0) return undefined\n const reported: Record<string, unknown> = {}\n for (const key of keys) reported[key] = Reflect.get(metadata, key)\n return reported\n}\n\n/**\n * Map Fascicle's Message[] to the AI SDK's ModelMessage[] shape. Each\n * assistant part's provider_options go back as its providerOptions, which is\n * where the SDK reads a signature or a thought signature back from, and a\n * reasoning part goes back only when it carries data under `metadata_key`,\n * the key the adapter's package writes (D3 own-reasoning-only).\n */\nexport function to_sdk_messages(\n messages: ReadonlyArray<Message>,\n metadata_key: string,\n): ModelMessage[] {\n const out: ModelMessage[] = []\n for (const m of messages) {\n if (m.role === 'system') {\n out.push({ role: 'system', content: m.content })\n continue\n }\n if (m.role === 'user') {\n if (typeof m.content === 'string') {\n out.push({ role: 'user', content: m.content })\n } else {\n const parts: Array<TextPart | ImagePart> = m.content.map((p) => {\n if (p.type === 'text') {\n return with_provider_options<TextPart>({ type: 'text', text: p.text }, p.provider_options)\n }\n const image_part: ImagePart = { type: 'image', image: p.image }\n if (p.media_type !== undefined) image_part.mediaType = p.media_type\n return with_provider_options(image_part, p.provider_options)\n })\n out.push({ role: 'user', content: parts })\n }\n continue\n }\n if (m.role === 'tool') {\n out.push({\n role: 'tool',\n content: [\n {\n type: 'tool-result',\n toolCallId: m.tool_call_id,\n toolName: m.name,\n output: { type: 'text', value: m.content },\n },\n ],\n })\n continue\n }\n // assistant\n if (typeof m.content === 'string') {\n out.push({ role: 'assistant', content: m.content })\n continue\n }\n const parts = m.content.flatMap((p): Array<TextPart | SdkReasoningPart | ToolCallPart> => {\n if (p.type === 'text') {\n return [with_provider_options<TextPart>({ type: 'text', text: p.text }, p.provider_options)]\n }\n if (p.type === 'reasoning') {\n // Another package's reasoning, or reasoning with no data, would draw a\n // warning or a refusal from this one.\n if (!is_own_reasoning(p, metadata_key)) return []\n return [\n with_provider_options<SdkReasoningPart>(\n { type: 'reasoning', text: p.text },\n p.provider_options,\n ),\n ]\n }\n return [\n with_provider_options<ToolCallPart>(\n { type: 'tool-call', toolCallId: p.id, toolName: p.name, input: p.input },\n p.provider_options,\n ),\n ]\n })\n out.push({ role: 'assistant', content: parts })\n }\n return out\n}\n\n/**\n * Hoist a leading run of system messages out of the SDK message list into the\n * AI SDK's top-level `system` option.\n *\n * Passing a `role: 'system'` entry inside `messages` makes the AI SDK treat it\n * as potentially attacker-controlled: it warns on every call (and newer `ai`\n * versions throw unless `allowSystemInMessages` is set). Fascicle's system\n * content is the developer's own prompt, and the SDK's own recommendation is to\n * deliver it through the top-level `instructions` option (v7's rename of the\n * former `system` option), which removes the warning at its source rather than\n * suppressing it.\n *\n * Only the *leading* run is hoisted (Fascicle's only shape: one or more system\n * messages, then the conversation). A system message that appears after a\n * non-system message keeps its position rather than being silently reordered to\n * the top, and the original list is returned untouched when hoisting would leave\n * `messages` empty, since the SDK rejects an empty messages array.\n */\nexport function split_leading_system(messages: ReadonlyArray<ModelMessage>): {\n system?: string\n messages: ModelMessage[]\n} {\n return split_leading_system_run(messages, (m) => m.content)\n}\n\n/**\n * Read a part's providerMetadata as provider_options, or undefined when it\n * carries none, so a part with nothing to send back stays bare.\n */\nfunction to_part_options(metadata: ProviderOptions | undefined): ProviderOptions | undefined {\n return metadata !== undefined && Object.keys(metadata).length > 0 ? metadata : undefined\n}\n\n/**\n * Map one SDK content part to an assistant part with its providerMetadata as\n * provider_options, or undefined for a kind with nothing to send back\n * (sources, files, tool results).\n */\nfunction to_turn_part(part: ContentPart<ToolSet>): AssistantContentPart | undefined {\n if (part.type === 'text') {\n return with_part_options({ type: 'text', text: part.text }, part.providerMetadata)\n }\n if (part.type === 'reasoning') {\n return with_part_options({ type: 'reasoning', text: part.text }, part.providerMetadata)\n }\n if (part.type === 'tool-call') {\n return with_part_options(\n { type: 'tool_call', id: part.toolCallId, name: part.toolName, input: part.input },\n part.providerMetadata,\n )\n }\n return undefined\n}\n\n/**\n * Give an assistant part the provider_options its metadata carries, leaving\n * the key off when there is none.\n */\nfunction with_part_options<part extends AssistantContentPart>(\n turn_part: part,\n metadata: ProviderOptions | undefined,\n): part {\n const provider_options = to_part_options(metadata)\n return provider_options === undefined ? turn_part : { ...turn_part, provider_options }\n}\n\n/**\n * Map an SDK step's content to TurnResult.content: its text, reasoning, and\n * tool calls in the order the provider sent them, each with its\n * providerMetadata as provider_options. Undefined when no part is reasoning\n * or carries data, so every other turn stays exactly what it was (D18).\n */\nexport function to_turn_content(\n content: ReadonlyArray<ContentPart<ToolSet>>,\n): AssistantContentPart[] | undefined {\n const parts = content.flatMap((part) => to_turn_part(part) ?? [])\n const carries = parts.some(\n (part) => part.type === 'reasoning' || part.provider_options !== undefined,\n )\n return carries ? parts : undefined\n}\n\n/**\n * Map Fascicle's Tool[] to the AI SDK's ToolSet.\n *\n * Returns undefined for an empty tool list so the caller can omit `tools`\n * from the call params entirely instead of passing an empty object.\n */\nexport function to_sdk_tools(tools: ReadonlyArray<Tool>): ToolSet | undefined {\n if (tools.length === 0) return undefined\n const entries: ToolSet = {}\n for (const t of tools) {\n entries[t.name] = ai_tool({\n description: t.description,\n inputSchema: t.input_schema,\n })\n }\n return entries\n}\n\n/**\n * Map one AI SDK stream part to the engine's StreamChunk shape, or undefined\n * for a part kind the engine does not model.\n */\nexport function map_stream_part_to_chunk(\n part: TextStreamPart<ToolSet>,\n step_index: number,\n): StreamChunk | undefined {\n switch (part.type) {\n case 'text-delta':\n return { kind: 'text', text: part.text, step_index }\n case 'reasoning-delta':\n return { kind: 'reasoning', text: part.text, step_index }\n case 'tool-input-start':\n return {\n kind: 'tool_call_start',\n id: part.id,\n name: part.toolName,\n step_index,\n }\n case 'tool-input-delta':\n return {\n kind: 'tool_call_input_delta',\n id: part.id,\n delta: part.delta,\n step_index,\n }\n case 'tool-call':\n return {\n kind: 'tool_call_end',\n id: part.toolCallId,\n input: part.input,\n step_index,\n }\n case 'finish-step':\n return {\n kind: 'step_finish',\n step_index,\n finish_reason: map_finish_reason(part.finishReason),\n usage: default_usage_from_sdk(part.usage),\n }\n default:\n // v7 parts with no engine StreamChunk kind (file, reasoning-file,\n // source, block framing) drop here on purpose: the engine models\n // text, reasoning, and tool traffic, not generated files.\n return undefined\n }\n}\n\n/**\n * Normalize a raw AI SDK usage object into UsageTotals for a streamed\n * step_finish chunk.\n */\nexport function default_usage_from_sdk(usage: unknown): UsageTotals {\n // Streamed step_finish chunks must carry the same cache/reasoning\n // granularity the step record gets via adapter.normalize_usage; every\n // built-in adapter routes through default_normalize_usage, so this keeps\n // the chunk surface consistent with the non-streamed result.\n return default_normalize_usage(to_raw_provider_usage(usage))\n}\n\n/**\n * The running TurnResult fields collect_stream builds as it consumes the SDK\n * stream: text and tool calls accrue across parts, while finish reason, usage,\n * and provider_reported are overwritten by the terminal finish-step.\n */\ntype StreamAccumulator = {\n text: string\n tool_calls: RawToolCall[]\n finish_reason: FinishReason\n raw_usage: RawProviderUsage\n provider_reported: Record<string, unknown> | undefined\n}\n\n/**\n * Fold one stream part's accumulated state into `acc`: text deltas append,\n * tool-call parts push a RawToolCall, and the finish-step overwrites finish\n * reason, usage, and provider_reported. The finish-step's providerMetadata is\n * the same value generateText returns on its result, which is what keeps a\n * streamed run's provider_reported identical to a plain run's. Parts with no\n * accumulated state (error, abort, stream framing) are the caller's to handle.\n */\nfunction accumulate_stream_part(part: TextStreamPart<ToolSet>, acc: StreamAccumulator): void {\n if (part.type === 'text-delta') {\n acc.text += part.text\n return\n }\n if (part.type === 'tool-call') {\n acc.tool_calls.push({\n id: part.toolCallId,\n name: part.toolName,\n input: part.input,\n })\n return\n }\n if (part.type === 'finish-step') {\n acc.finish_reason = map_finish_reason(part.finishReason)\n acc.raw_usage = to_raw_provider_usage(part.usage)\n acc.provider_reported = to_provider_reported(part.providerMetadata)\n }\n}\n\n/**\n * Run one streamText call, dispatching StreamChunks as parts arrive and\n * accumulating them into a TurnResult once the stream completes.\n */\nasync function collect_stream(\n params: Parameters<typeof streamText>[0],\n step_index: number,\n dispatcher: ChunkDispatcher,\n on_first_chunk: () => void,\n internal_controller: AbortController,\n adapter: AiSdkProviderAdapter,\n): Promise<TurnResult> {\n const stream_result = streamText(params)\n const acc: StreamAccumulator = {\n text: '',\n tool_calls: [],\n finish_reason: 'stop',\n raw_usage: {},\n provider_reported: undefined,\n }\n let first = true\n\n for await (const part of stream_result.stream) {\n accumulate_stream_part(part, acc)\n if (part.type === 'error') {\n throw part.error\n }\n if (part.type === 'abort') {\n throw new aborted_error('aborted', { step_index })\n }\n const chunk = map_stream_part_to_chunk(part, step_index)\n if (chunk === undefined) continue\n // Stamped on the first dispatched chunk, not the first stream part: the\n // SDK opens every stream with `start` and `start-step` framing before the\n // model has produced a token, and a stamp there would leave prefill inside\n // the decode window throughput() measures. This is also the native\n // transport's rule (build_native_invoke stamps in dispatch_chunk), so a\n // failure before the first token stays retryable on both.\n if (first) {\n first = false\n on_first_chunk()\n }\n try {\n await dispatcher.dispatch(chunk)\n } catch (err: unknown) {\n internal_controller.abort()\n throw err\n }\n }\n\n // The step's content settles once the stream has drained, so it is read\n // only after the loop and never on a failed stream.\n const content = to_turn_content(await stream_result.content)\n return {\n text: acc.text,\n tool_calls: acc.tool_calls,\n finish_reason: acc.finish_reason,\n usage: adapter.normalize_usage(acc.raw_usage),\n // Stryker disable next-line ConditionalExpression: an always-true spread only adds an explicit `provider_reported: undefined` key, which every reader of TurnResult treats identically to the absent key.\n ...(acc.provider_reported !== undefined ? { provider_reported: acc.provider_reported } : {}),\n ...(content !== undefined ? { content } : {}),\n }\n}\n\n/**\n * Run one generateText call and map its result into a TurnResult, recovering\n * a schema-validation failure from the SDK via recover_no_object_generated\n * instead of letting it throw.\n */\nasync function collect_non_stream(\n params: Parameters<typeof generateText>[0],\n adapter: AiSdkProviderAdapter,\n): Promise<TurnResult> {\n let result: Awaited<ReturnType<typeof generateText>>\n try {\n result = await generateText(params)\n } catch (err: unknown) {\n const recovered = recover_no_object_generated(err, adapter)\n if (recovered !== undefined) return recovered\n throw err\n }\n const tool_calls: RawToolCall[] = []\n for (const tc of result.toolCalls) {\n tool_calls.push({\n id: tc.toolCallId,\n name: tc.toolName,\n input: tc.input,\n })\n }\n const raw_usage = to_raw_provider_usage(result.usage)\n // result.providerMetadata rather than result.finalStep.providerMetadata: the\n // two are the same value under stopWhen isStepCount(1), and the flat field\n // exists across the whole `ai` ^7 peer range this package declares.\n const provider_reported = to_provider_reported(result.providerMetadata)\n const content = to_turn_content(result.content)\n return {\n text: result.text,\n tool_calls,\n finish_reason: map_finish_reason(result.finishReason),\n usage: adapter.normalize_usage(raw_usage),\n // Stryker disable next-line ConditionalExpression: see collect_stream; the always-true spread is unobservable through every TurnResult reader.\n ...(provider_reported !== undefined ? { provider_reported } : {}),\n ...(content !== undefined ? { content } : {}),\n }\n}\n\n/**\n * When `output` (structured output) is in play, `generateText` eagerly parses the\n * model's text against the schema and throws `NoObjectGeneratedError` if it\n * does not conform. That parse is the SDK's, not Fascicle's: turning it into a\n * thrown error would skip the engine's own schema-parse + repair loop (and the\n * error is not a retryable transient, so it would surface raw). Instead we\n * recover the model's raw text from the error and hand it back as a normal\n * turn result, so `parse_with_schema` re-validates it and the repair loop\n * engages exactly as it does for the prompt-based path. Returns undefined for\n * any other error so the caller rethrows.\n *\n * The recovered turn carries no provider_reported: the SDK's error exposes\n * text, usage, finishReason and response metadata, but not providerMetadata,\n * so there is nothing to read. The repair turn that follows reports normally.\n */\nfunction recover_no_object_generated(\n err: unknown,\n adapter: AiSdkProviderAdapter,\n): TurnResult | undefined {\n if (!NoObjectGeneratedError.isInstance(err)) return undefined\n const text_field = Reflect.get(err, 'text')\n const finish_field = Reflect.get(err, 'finishReason')\n const raw_usage = to_raw_provider_usage(Reflect.get(err, 'usage'))\n return {\n text: typeof text_field === 'string' ? text_field : '',\n tool_calls: [],\n finish_reason: map_finish_reason(typeof finish_field === 'string' ? finish_field : undefined),\n usage: adapter.normalize_usage(raw_usage),\n }\n}\n\ntype AiSdkCallParams = Parameters<typeof streamText>[0] & Parameters<typeof generateText>[0]\n\nexport type AiSdkTurnConfig = {\n readonly adapter: AiSdkProviderAdapter\n readonly model_id: string\n readonly dispatcher: ChunkDispatcher\n readonly tools: ReadonlyArray<Tool>\n readonly schema: ToolSchema | undefined\n readonly provider_options: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined\n readonly temperature: number | undefined\n readonly max_tokens: number | undefined\n readonly top_p: number | undefined\n readonly reasoning: EffortTranslation['reasoning']\n readonly telemetry: AiSdkTelemetrySettings | undefined\n}\n\nexport type AiSdkTurnArgs = {\n readonly step_index: number\n readonly messages: ReadonlyArray<Message>\n readonly abort: AbortSignal\n readonly stream: boolean\n readonly on_first_chunk: () => void\n}\n\nexport type AiSdkTurn = (args: AiSdkTurnArgs) => Promise<TurnResult>\n\n/**\n * Build the single-attempt SDK turn for one generate call: the\n * generateText/streamText call body behind the same neutral seam a native\n * adapter's invoke_turn implements. The built model is memoized across steps\n * of one generate call. No retry here: generate.ts wraps the returned turn in\n * the engine-owned retry_turn.\n */\nexport function create_ai_sdk_turn(cfg: AiSdkTurnConfig): AiSdkTurn {\n let model_instance: LanguageModel | undefined\n const get_model = async (): Promise<LanguageModel> => {\n if (model_instance === undefined) {\n const built = await cfg.adapter.build_model(cfg.model_id)\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n model_instance = built as LanguageModel\n }\n return model_instance\n }\n\n // Telemetry is resolved once per generate call and memoized across its steps,\n // mirroring get_model. build_ai_sdk_telemetry returns undefined immediately\n // (no peer load) unless telemetry is explicitly enabled, so the disabled\n // default costs nothing.\n let telemetry_options: AiSdkTelemetryPassthrough | undefined\n let telemetry_resolved = false\n const get_telemetry = async (): Promise<AiSdkTelemetryPassthrough | undefined> => {\n if (!telemetry_resolved) {\n telemetry_options = await build_ai_sdk_telemetry(cfg.telemetry)\n telemetry_resolved = true\n }\n return telemetry_options\n }\n\n const sdk_tools = to_sdk_tools(cfg.tools)\n\n // Native structured output: when a schema is requested and the provider\n // constrains decoding to it (the 'structured_output' capability), route\n // through the AI SDK's Output.object seam so the schema becomes the\n // provider's responseFormat (for example, Ollama's `format`) instead of a\n // prompt-for-JSON-then-scrape. Gated on no tools: forcing a JSON\n // responseFormat alongside tool calls breaks tool dispatch on most\n // providers, so tool runs keep the prompt-based schema path. The engine's\n // schema parse + repair loop still owns validation either way. This seam\n // is ai_sdk-only: a native adapter that constrains decoding honors\n // TurnRequest.schema inside its own invoke_turn.\n let output_spec: NonNullable<AiSdkCallParams['output']> | undefined\n if (\n cfg.schema !== undefined &&\n cfg.tools.length === 0 &&\n cfg.adapter.supports('structured_output')\n ) {\n // Output.object<T> is not structurally assignable to the SDK's default\n // Output<string, string> param slot, but the runtime shape is exactly\n // what generateText/streamText consume to set responseFormat.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n output_spec = Output.object({ schema: cfg.schema }) as NonNullable<\n AiSdkCallParams['output']\n >\n }\n\n // provider_options is Record<string, Record<string, unknown>>; the SDK\n // expects SharedV3ProviderOptions (Record<string, JSONObject>) which is\n // structurally compatible for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n const provider_options = cfg.provider_options as AiSdkCallParams['providerOptions']\n\n return async (args: AiSdkTurnArgs): Promise<TurnResult> => {\n const model = await get_model()\n const telemetry = await get_telemetry()\n const internal_controller = new AbortController()\n const cancel_on_user_abort = (): void => {\n internal_controller.abort(args.abort.reason)\n }\n if (args.abort.aborted) {\n internal_controller.abort(args.abort.reason)\n } else {\n args.abort.addEventListener('abort', cancel_on_user_abort, { once: true })\n }\n const { system: hoisted_system, messages: sdk_messages } = split_leading_system(\n to_sdk_messages(args.messages, cfg.adapter.metadata_key ?? cfg.adapter.name),\n )\n const base_params: AiSdkCallParams = {\n model,\n messages: sdk_messages,\n abortSignal: internal_controller.signal,\n stopWhen: isStepCount(1),\n // The engine owns retry via retry_turn in generate.ts; disable the AI\n // SDK's own retry (default 2) so it does not nest inside each of our\n // attempts and inflate provider round-trips / distort backoff.\n maxRetries: 0,\n }\n if (hoisted_system !== undefined) base_params.instructions = hoisted_system\n if (sdk_tools !== undefined) base_params.tools = sdk_tools\n if (output_spec !== undefined) base_params.output = output_spec\n if (provider_options !== undefined) base_params.providerOptions = provider_options\n if (cfg.temperature !== undefined) base_params.temperature = cfg.temperature\n if (cfg.max_tokens !== undefined) base_params.maxOutputTokens = cfg.max_tokens\n if (cfg.top_p !== undefined) base_params.topP = cfg.top_p\n // The SDK's own effort option; the provider package maps the level per\n // model, and leaving it out is the provider's default.\n if (cfg.reasoning !== undefined) base_params.reasoning = cfg.reasoning\n if (telemetry !== undefined) {\n // AiSdkTelemetryPassthrough uses the SDK's own telemetry keys; the slot's\n // generic (RUNTIME_CONTEXT/TOOLS) is erased for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n base_params.experimental_telemetry = telemetry as NonNullable<\n AiSdkCallParams['experimental_telemetry']\n >\n }\n\n try {\n if (args.stream) {\n return await collect_stream(\n base_params,\n args.step_index,\n cfg.dispatcher,\n args.on_first_chunk,\n internal_controller,\n cfg.adapter,\n )\n }\n return await collect_non_stream(base_params, cfg.adapter)\n } finally {\n args.abort.removeEventListener('abort', cancel_on_user_abort)\n }\n }\n}\n"],"mappings":";;;;;;;;AAyCA,eAAsB,uBACpB,UACgD;CAChD,IAAI,CAAC,UAAU,SAAS,OAAO,KAAA;CAK/B,MAAM,MAAiC;EAAE,WAAW;EAAM,cAAc,CAAC,KAHjD,OADN,mBAAoC,cAAc,GAAA,CACxC,cAC1B,SAAS,WAAW,KAAA,IAAY,EAAE,QAAQ,SAAS,OAAO,IAAI,CAAC,CAEkB,CAAC;CAAE;CACtF,IAAI,SAAS,gBAAgB,KAAA,GAAW,IAAI,aAAa,SAAS;CAClE,IAAI,SAAS,kBAAkB,KAAA,GAAW,IAAI,eAAe,SAAS;CACtE,IAAI,SAAS,mBAAmB,KAAA,GAAW,IAAI,gBAAgB,SAAS;CACxE,IAAI,SAAS,aAAa,KAAA,GAAW,IAAI,WAAW,SAAS;CAC7D,OAAO;AACT;;;;;;;;;;;;;;;;;;;ACQA,SAAS,sBACP,UACA,kBACM;CACN,IAAI,qBAAqB,KAAA,GAAW,OAAO;CAI3C,OAAO;EAAE,GAAG;EAAU,iBAAiB;CAAyD;AAClG;;;;AAKA,SAAgB,kBAAkB,KAAuC;CACvE,QAAQ,KAAR;EACE,KAAK,QACH,OAAO;EACT,KAAK,UACH,OAAO;EACT,KAAK;EACL,KAAK,kBACH,OAAO;EACT,KAAK;EACL,KAAK,cACH,OAAO;EACT,SACE,OAAO;CACX;AACF;;;;;AAMA,SAAS,YAAY,QAAgB,KAAiC;CACpE,MAAM,QAAQ,Q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I,QAAQ,IAAI,CAC7E;EACA,MAAM,cAA+B;GACnC;GACA,UAAU;GACV,aAAa,oBAAoB;GACjC,UAAU,YAAY,CAAC;GAIvB,YAAY;EACd;EACA,IAAI,mBAAmB,KAAA,GAAW,YAAY,eAAe;EAC7D,IAAI,cAAc,KAAA,GAAW,YAAY,QAAQ;EACjD,IAAI,gBAAgB,KAAA,GAAW,YAAY,SAAS;EACpD,IAAI,qBAAqB,KAAA,GAAW,YAAY,kBAAkB;EAClE,IAAI,IAAI,gBAAgB,KAAA,GAAW,YAAY,cAAc,IAAI;EACjE,IAAI,IAAI,eAAe,KAAA,GAAW,YAAY,kBAAkB,IAAI;EACpE,IAAI,IAAI,UAAU,KAAA,GAAW,YAAY,OAAO,IAAI;EAGpD,IAAI,IAAI,cAAc,KAAA,GAAW,YAAY,YAAY,IAAI;EAC7D,IAAI,cAAc,KAAA,GAIhB,YAAY,yBAAyB;EAKvC,IAAI;GACF,IAAI,KAAK,QACP,OAAO,MAAM,eACX,aACA,KAAK,YACL,IAAI,YACJ,KAAK,gBACL,qBACA,IAAI,OACN;GAEF,OAAO,MAAM,mBAAmB,aAAa,IAAI,OAAO;EAC1D,UAAU;GACR,KAAK,MAAM,oBAAoB,SAAS,oBAAoB;EAC9D;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"json_schema_to_standard-BTWD0J6p.js","names":[],"sources":["../src/schema/json_schema_to_standard.ts"],"sourcesContent":["/**\n * A Standard Schema over a plain JSON Schema, with no validator library behind\n * it.\n *\n * Built for inbound MCP tools, which advertise their input as JSON Schema, and\n * kept in the schema seam so any tool that declares its input that way can use\n * it without importing zod. A Fascicle `Tool` carries a `ToolSchema` that the\n * tool loop validates before `execute` and the engine emits back to the\n * provider as JSON Schema. Those are two faces of one object, so this bridge\n * builds both directly over the schema it is given: emission hands that schema\n * back unchanged, and validation walks it.\n *\n * The old MCP bridge converted the advertised schema into Zod so the provider\n * path could convert it back, a round trip that was lossy by construction.\n * Verbatim emission is strictly higher fidelity: whatever the schema declares\n * is what the model is told, including the constraints (`minLength`, `format`,\n * `pattern`) the Zod conversion dropped.\n *\n * Validation stays deliberately loose, unchanged from the Zod bridge's reach:\n * structure, types, enums, const, unions, and required keys are checked, value\n * constraints are not, extra keys pass through, and anything unrecognized\n * accepts. Whatever runs the call is the authority on its arguments (an MCP\n * server re-validates its own), so this check is a guard against an obviously\n * wrong call, not the contract.\n */\n\nimport { as_record, is_record } from './records.js'\nimport type { SchemaIssue, ToolSchema } from './types.js'\n\n/**\n * Builds a `ToolSchema` over a JSON Schema, such as an MCP server's advertised\n * tool input.\n *\n * The schema is snapshotted once, deeply, and both faces of the returned object\n * read that snapshot. A malformed or hostile schema degrades to the empty\n * schema during the snapshot rather than propagating an error, since an\n * arbitrary remote server's advertisement must never crash tool discovery, and\n * it leaves both faces describing the same thing: accept anything, emit\n * nothing.\n */\nexport function json_schema_to_standard(schema: unknown): ToolSchema {\n const advertised = snapshot(schema)\n return {\n '~standard': {\n version: 1,\n vendor: 'fascicle',\n validate: (value: unknown) => {\n const issues = check(advertised, value, [])\n return issues.length === 0 ? { value } : { issues }\n },\n jsonSchema: {\n // `target` is ignored in both directions: fascicle applies no transform,\n // so there is no re-targeting to do, and the dialect on the wire is\n // whichever one the server chose to advertise. Each call returns a fresh\n // copy because consumers mutate what they are handed (the AI SDK stamps\n // `additionalProperties` onto it in place), and a shared snapshot would\n // stop being verbatim after the first turn.\n input: () => clone_schema(advertised),\n output: () => clone_schema(advertised),\n },\n },\n }\n}\n\n/**\n * Deep-copies the advertised schema, or yields the empty schema when it is not\n * an object or cannot be read.\n *\n * Copying here means every later read walks plain data: a schema with throwing\n * accessors or a cycle fails once, at discovery, instead of on some later call.\n */\nfunction snapshot(schema: unknown): Record<string, unknown> {\n try {\n return clone_schema(as_record(schema) ?? {})\n } catch {\n return {}\n }\n}\n\n/**\n * Deep-copies one JSON Schema node.\n */\nfunction clone_schema(schema: Record<string, unknown>): Record<string, unknown> {\n const copy: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(schema)) copy[key] = clone_value(value)\n return copy\n}\n\n/**\n * Deep-copies a value inside a schema, recursing through arrays and objects and\n * returning every other value as is.\n */\nfunction clone_value(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(clone_value)\n return is_record(value) ? clone_schema(value) : value\n}\n\n/**\n * Checks one value against one JSON Schema node, returning the issues it\n * violated, or an empty array when it passes.\n *\n * A node that is not an object constrains nothing and accepts, which is what\n * makes a construct this bridge does not model degrade rather than reject.\n */\nfunction check(node: unknown, value: unknown, path: ReadonlyArray<PropertyKey>): SchemaIssue[] {\n const schema = as_record(node)\n if (schema === undefined) return []\n return check_keywords(schema, value, path) ?? check_shape(schema, value, path)\n}\n\n/**\n * Checks the keywords that stand on their own, returning `undefined` when the\n * node carries none of them.\n *\n * These are checked before `type` because they can appear without one and take\n * precedence when they do: a node with both `enum` and `type` is constrained by\n * the enum, which is the narrower of the two.\n */\nfunction check_keywords(\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] | undefined {\n if ('const' in schema) return check_const(schema['const'], value, path)\n if (Array.isArray(schema['enum'])) return check_enum(schema['enum'], value, path)\n if (Array.isArray(schema['anyOf'])) return check_any_of(schema['anyOf'], value, path)\n if (Array.isArray(schema['oneOf'])) return check_any_of(schema['oneOf'], value, path)\n if (Array.isArray(schema['allOf'])) return check_all_of(schema['allOf'], value, path)\n return undefined\n}\n\n/**\n * Checks the node's declared shape: its `type`, in either the single or the\n * array form.\n *\n * A node with no `type` but declared `properties` is still an object; a node\n * with neither says nothing structural and accepts.\n */\nfunction check_shape(\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n const type = schema['type']\n if (Array.isArray(type)) return check_type_union(type, schema, value, path)\n if (typeof type === 'string') return check_type(type, schema, value, path)\n if (is_record(schema['properties'])) return check_object(schema, value, path)\n return []\n}\n\n/**\n * Checks a `const`, which pins the value to one JSON literal.\n *\n * An object or array `const` accepts anything: matching it would mean a deep\n * comparison the server performs itself, and rejecting a valid argument is the\n * one failure mode this bridge must not have.\n */\nfunction check_const(\n expected: unknown,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (expected === null) return value === null ? [] : [issue('expected null', path)]\n if (\n typeof expected === 'string' ||\n typeof expected === 'number' ||\n typeof expected === 'boolean'\n ) {\n return value === expected ? [] : [issue(`expected ${JSON.stringify(expected)}`, path)]\n }\n return []\n}\n\n/**\n * Checks an `enum`, which pins the value to one of a list of JSON literals.\n * An empty enum constrains nothing and accepts.\n */\nfunction check_enum(\n values: unknown[],\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (values.length === 0) return []\n if (values.some((candidate) => check_const(candidate, value, path).length === 0)) return []\n return [issue(`expected one of ${values.map((v) => JSON.stringify(v)).join(', ')}`, path)]\n}\n\n/**\n * Checks an `anyOf` or `oneOf`, which passes when any branch passes.\n *\n * `oneOf` demands one match and only one; the bridge deliberately relaxes that\n * to at least one, since the distinction only ever rejects a value the server\n * would accept.\n *\n * A single-branch union reports that branch's own issues rather than a generic\n * \"no variant matched\", since with one variant there is no ambiguity about\n * which one failed.\n */\nfunction check_any_of(\n nodes: unknown[],\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (nodes.length === 0) return []\n if (nodes.length === 1) return check(nodes[0], value, path)\n if (nodes.some((node) => check(node, value, path).length === 0)) return []\n return [issue(`expected one of ${nodes.length} variants`, path)]\n}\n\n/**\n * Checks an `allOf`, which passes only when every branch passes.\n */\nfunction check_all_of(\n nodes: unknown[],\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n return nodes.flatMap((node) => check(node, value, path))\n}\n\n/**\n * Checks the array form of `type` (`[\"string\", \"null\"]`), which passes when the\n * value matches any listed type. The other keywords on the node apply to\n * whichever type matched, so each branch sees the whole node.\n */\nfunction check_type_union(\n types: unknown[],\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (types.length === 0) return []\n if (types.length === 1) return check_type(String(types[0]), schema, value, path)\n if (types.some((type) => check_type(String(type), schema, value, path).length === 0)) return []\n return [issue(`expected one of ${types.map(String).join(', ')}`, path)]\n}\n\n/**\n * The scalar `type` keywords, as predicates over the value.\n *\n * `number` rejects `NaN` and infinities because neither survives JSON, and\n * `integer` is the same check narrowed to whole values.\n */\nconst SCALAR_TYPES: Record<string, (value: unknown) => boolean> = {\n string: (value) => typeof value === 'string',\n number: (value) => Number.isFinite(value),\n integer: (value) => Number.isInteger(value),\n boolean: (value) => typeof value === 'boolean',\n null: (value) => value === null,\n}\n\n/**\n * Checks one `type` keyword. `object` and `array` recurse into the node's own\n * `properties` and `items`; everything else is a scalar predicate.\n *\n * An unrecognized type accepts, so a vendor extension cannot reject an argument\n * the server would take.\n */\nfunction check_type(\n type: string,\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (type === 'object') return check_object(schema, value, path)\n if (type === 'array') return check_array(schema, value, path)\n const matches = SCALAR_TYPES[type]\n if (matches === undefined) return []\n return matches(value) ? [] : [type_issue(type, value, path)]\n}\n\n/**\n * Checks an object against its `properties` and `required`.\n *\n * Keys the schema does not declare are left alone rather than rejected, so an\n * argument this bridge did not anticipate still reaches the server, which\n * re-validates and is the real authority. A `required` name with no entry in\n * `properties` is likewise not enforced: there is nothing to check it against.\n * Nor is a `required` that is not an array, which is malformed.\n */\nfunction check_object(\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (!is_record(value)) return [type_issue('object', value, path)]\n const properties = as_record(schema['properties']) ?? {}\n const required = schema['required']\n const issues: SchemaIssue[] = []\n for (const [key, property] of Object.entries(properties)) {\n const child = value[key]\n if (child === undefined) {\n if (Array.isArray(required) && required.includes(key)) {\n issues.push(issue('required', [...path, key]))\n }\n continue\n }\n issues.push(...check(property, child, [...path, key]))\n }\n return issues\n}\n\n/**\n * Checks an array against its `items`.\n *\n * A positional-tuple `items` (an array rather than a node) is not a record, so\n * every element accepts. Tuple schemas are rare in MCP tools and the server\n * re-validates them anyway.\n */\nfunction check_array(\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (!Array.isArray(value)) return [type_issue('array', value, path)]\n return value.flatMap((item, index) => check(schema['items'], item, [...path, index]))\n}\n\n/**\n * Builds a type-mismatch issue naming what was expected and what arrived.\n */\nfunction type_issue(\n expected: string,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue {\n return issue(`expected ${expected}, received ${describe(value)}`, path)\n}\n\n/**\n * Names a value's type the way a JSON Schema reader would, separating `null`\n * and arrays out of `typeof`'s `object`.\n */\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (Array.isArray(value)) return 'array'\n return typeof value\n}\n\n/**\n * Builds one issue, omitting the path entirely at the root so a failure about\n * the value as a whole does not report an empty path.\n */\nfunction issue(message: string, path: ReadonlyArray<PropertyKey>): SchemaIssue {\n return path.length === 0 ? { message } : { message, path: [...path] }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,wBAAwB,QAA6B;CACnE,MAAM,aAAa,SAAS,MAAM;CAClC,OAAO,EACL,aAAa;EACX,SAAS;EACT,QAAQ;EACR,WAAW,UAAmB;GAC5B,MAAM,SAAS,MAAM,YAAY,OAAO,CAAC,CAAC;GAC1C,OAAO,OAAO,WAAW,IAAI,EAAE,MAAM,IAAI,EAAE,OAAO;EACpD;EACA,YAAY;GAOV,aAAa,aAAa,UAAU;GACpC,cAAc,aAAa,UAAU;EACvC;CACF,EACF;AACF;;;;;;;;AASA,SAAS,SAAS,QAA0C;CAC1D,IAAI;EACF,OAAO,aAAa,UAA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AAM,UAAU,OAAO,CAAC,GAAG,MAAM,GAAG,CAAC,CAAC;CACvD;CACA,OAAO;AACT;;;;;;;;AASA,SAAS,YACP,QACA,OACA,MACe;CACf,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC,WAAW,SAAS,OAAO,IAAI,CAAC;CACnE,OAAO,MAAM,SAAS,MAAM,UAAU,MAAM,OAAO,UAAU,MAAM,CAAC,GAAG,MAAM,KAAK,CAAC,CAAC;AACtF;;;;AAKA,SAAS,WACP,UACA,OACA,MACa;CACb,OAAO,MAAM,YAAY,SAAS,aAAa,SAAS,KAAK,KAAK,IAAI;AACxE;;;;;AAMA,SAAS,SAAS,OAAwB;CACxC,IAAI,UAAU,MAAM,OAAO;CAC3B,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,OAAO,OAAO;AAChB;;;;;AAMA,SAAS,MAAM,SAAiB,MAA+C;CAC7E,OAAO,KAAK,WAAW,IAAI,EAAE,QAAQ,IAAI;EAAE;EAAS,MAAM,CAAC,GAAG,IAAI;CAAE;AACtE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"leading_system-DfJLqpGi.js","names":[],"sources":["../src/engine/errors.ts","../src/engine/providers/types.ts","../src/engine/providers/native_shared.ts","../src/engine/leading_system.ts"],"sourcesContent":["/**\n * Typed errors for the AI engine layer.\n *\n * This is the only source file in the engine module permitted to use the\n * `class` keyword. `Error` is a built-in and `instanceof` branching is how\n * the retry helper and composition-layer composers distinguish failure modes.\n * Every other engine file stays class-free.\n *\n * `aborted_error` is defined in the core module and re-exported here so that\n * `instanceof aborted_error` is true regardless of which layer surfaced it.\n * This is the one value-level import from core permitted in engine source;\n * see the ignores in `rules/no-core-value-import-in-engine.yml`.\n *\n * Every class declares an optional `path`: the chain of step ids the error\n * crossed while bubbling through the core runner's dispatch. The runner\n * attaches it via Reflect.set (`prepend_path` in core's runner.ts), so the\n * `declare` modifier types what arrives without emitting a field;\n * construction never sets it.\n */\n\nimport type { SchemaIssue } from '#schema'\nimport type { FinishReason } from './types.js'\n\nexport { aborted_error } from '#core'\n\nexport class rate_limit_error extends Error {\n readonly kind = 'rate_limit_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly retry_after_ms: number | undefined;\n readonly attempts: number;\n readonly status: number | undefined;\n constructor(\n message: string,\n metadata: { retry_after_ms?: number; attempts?: number; status?: number } = {},\n ) {\n super(message)\n this.name = 'rate_limit_error'\n this.retry_after_ms = metadata.retry_after_ms\n this.attempts = metadata.attempts ?? 0\n this.status = metadata.status\n }\n}\n\nexport class provider_error extends Error {\n readonly kind = 'provider_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly status: number | undefined;\n readonly body: string | undefined;\n readonly cause_kind: 'provider_5xx' | 'network' | 'unknown' | undefined;\n constructor(\n message: string,\n metadata: {\n status?: number\n body?: string\n cause_kind?: 'provider_5xx' | 'network' | 'unknown'\n } = {},\n ) {\n super(message)\n this.name = 'provider_error'\n this.status = metadata.status\n this.body = metadata.body\n this.cause_kind = metadata.cause_kind\n }\n}\n\n/**\n * Turn-timeout expiry. Thrown by the engine-owned retry_turn wrapper when a\n * single invoke_turn exceeds `turn_timeout_ms` before any chunk streamed.\n * Its `kind` is the RetryFailureKind wire value `'timeout'` (not the class\n * name) on purpose: that is the discriminant classify_retryable /\n * classify_provider_error already key on, so the shared classifier treats an\n * expiry as retryable without any timeout-specific branch. A mid-stream\n * expiry never reaches here; retry_turn converts it to a non-retryable\n * stream interruption first.\n */\nexport class turn_timeout_error extends Error {\n readonly kind = 'timeout' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly timeout_ms: number;\n readonly step_index: number | undefined;\n constructor(timeout_ms: number, step_index?: number) {\n super(`turn exceeded turn_timeout_ms budget of ${timeout_ms}ms`)\n this.name = 'turn_timeout_error'\n this.timeout_ms = timeout_ms\n this.step_index = step_index\n }\n}\n\nexport class schema_validation_error extends Error {\n readonly kind = 'schema_validation_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly schema_issues: ReadonlyArray<SchemaIssue>;\n readonly raw_text: string;\n constructor(message: string, schema_issues: ReadonlyArray<SchemaIssue>, raw_text: string) {\n super(message)\n this.name = 'schema_validation_error'\n this.schema_issues = schema_issues\n this.raw_text = raw_text\n }\n}\n\nexport class tool_error extends Error {\n readonly kind = 'tool_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly tool_name: string;\n readonly tool_call_id: string;\n override readonly cause: unknown;\n constructor(\n message: string,\n metadata: { tool_name: string; tool_call_id: string; cause: unknown },\n ) {\n super(message)\n this.name = 'tool_error'\n this.tool_name = metadata.tool_name\n this.tool_call_id = metadata.tool_call_id\n this.cause = metadata.cause\n }\n}\n\nexport class tool_approval_denied_error extends Error {\n readonly kind = 'tool_approval_denied_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly tool_name: string;\n readonly step_index: number;\n readonly tool_call_id: string;\n constructor(\n message: string,\n metadata: { tool_name: string; step_index: number; tool_call_id: string },\n ) {\n super(message)\n this.name = 'tool_approval_denied_error'\n this.tool_name = metadata.tool_name\n this.step_index = metadata.step_index\n this.tool_call_id = metadata.tool_call_id\n }\n}\n\nexport class model_required_error extends Error {\n readonly kind = 'model_required_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n constructor(\n message = 'no model specified: pass `model` to generate() or set `defaults.model` on the engine',\n ) {\n super(message)\n this.name = 'model_required_error'\n }\n}\n\n/**\n * A generate call named a provider the engine has no adapter for. Carries the\n * configured names, and the message repeats them, so a typo is visible from\n * the message alone rather than needing the engine config alongside it.\n */\nexport class provider_not_configured_error extends Error {\n readonly kind = 'provider_not_configured_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly provider: string;\n readonly configured: ReadonlyArray<string>;\n constructor(provider: string, configured: ReadonlyArray<string> = []) {\n const state = configured.length > 0 ? configured.join(', ') : 'none'\n super(\n `provider '${provider}' is not configured on this engine: pass it to create_engine({ providers }) (configured: ${state})`,\n )\n this.name = 'provider_not_configured_error'\n this.provider = provider\n this.configured = configured\n }\n}\n\n/**\n * No provider could be resolved for a generate call: several providers are\n * configured, the call named none, and no `defaults.provider` is set. Carries\n * the configured provider names so the message tells the caller exactly what\n * the engine can route to.\n */\nexport class provider_required_error extends Error {\n readonly kind = 'provider_required_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly configured: ReadonlyArray<string>;\n constructor(configured: ReadonlyArray<string>) {\n super(\n `no provider specified: pass \\`provider\\` to generate() or set \\`defaults.provider\\` (configured: ${configured.join(', ')})`,\n )\n this.name = 'provider_required_error'\n this.configured = configured\n }\n}\n\nexport class engine_config_error extends Error {\n readonly kind = 'engine_config_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly provider: string | undefined;\n constructor(message: string, provider?: string) {\n super(message)\n this.name = 'engine_config_error'\n this.provider = provider\n }\n}\n\nexport class on_chunk_error extends Error {\n readonly kind = 'on_chunk_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n override readonly cause: unknown;\n constructor(message: string, cause: unknown) {\n super(message)\n this.name = 'on_chunk_error'\n this.cause = cause\n }\n}\n\nexport class provider_capability_error extends Error {\n readonly kind = 'provider_capability_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly provider: string;\n readonly capability: string;\n constructor(provider: string, capability: string, detail?: string) {\n const suffix = detail !== undefined ? `: ${detail}` : ''\n super(`provider '${provider}' does not support '${capability}'${suffix}`)\n this.name = 'provider_capability_error'\n this.provider = provider\n this.capability = capability\n }\n}\n\nexport class engine_disposed_error extends Error {\n readonly kind = 'engine_disposed_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n constructor(message = 'engine has been disposed: build a new one with create_engine()') {\n super(message)\n this.name = 'engine_disposed_error'\n }\n}\n\nexport type ClaudeCliErrorReason =\n | 'binary_not_found'\n | 'auth_missing'\n | 'auth_expired'\n | 'api_key_missing'\n | 'startup_timeout'\n | 'stall_timeout'\n | 'no_result_event'\n | 'result_error'\n | 'subprocess_exit'\n | 'sandbox_unavailable'\n | 'engine_disposed'\n | 'parse_error'\n\nexport class claude_cli_error extends Error {\n readonly kind = 'claude_cli_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly reason: ClaudeCliErrorReason;\n readonly status: number | undefined;\n readonly stderr_snippet: string | undefined;\n constructor(\n reason: ClaudeCliErrorReason,\n message: string,\n metadata: { status?: number; stderr_snippet?: string } = {},\n ) {\n super(message)\n this.name = 'claude_cli_error'\n this.reason = reason\n this.status = metadata.status\n this.stderr_snippet = metadata.stderr_snippet\n }\n}\n\nexport class provider_auth_error extends Error {\n readonly kind = 'provider_auth_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly provider: string;\n readonly refresh_command: string | undefined;\n constructor(\n provider: string,\n message: string,\n metadata: { refresh_command?: string } = {},\n ) {\n super(message)\n this.name = 'provider_auth_error'\n this.provider = provider\n this.refresh_command = metadata.refresh_command\n }\n}\n\n/**\n * A generate call that set a schema finished for a reason other than 'stop'\n * (content_filter, length, max_steps, tool_calls), so no schema-validated\n * value exists and validation was never attempted. Carries the raw model text\n * and the last provider-reported payload, so a guardrail trace or other\n * block detail stays reachable from the catch. Distinct from\n * schema_validation_error, which covers a response that completed normally\n * and then failed validation after its repair attempts ran out.\n */\nexport class incomplete_generation_error extends Error {\n readonly kind = 'incomplete_generation_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly finish_reason: FinishReason;\n readonly raw_text: string;\n readonly provider_reported: Record<string, unknown> | undefined;\n constructor(\n finish_reason: FinishReason,\n raw_text: string,\n provider_reported?: Record<string, unknown>,\n ) {\n super(\n `generation finished with '${finish_reason}' before a schema-validated response was produced`,\n )\n this.name = 'incomplete_generation_error'\n this.finish_reason = finish_reason\n this.raw_text = raw_text\n this.provider_reported = provider_reported\n }\n}\n","/**\n * Shared provider-adapter shape.\n *\n * Each file under src/engine/providers/ exports a factory that accepts a\n * ProviderInit shape and returns a ProviderAdapter. Factories are\n * synchronous; build_model is async so SDK loading is deferred until a model\n * is actually needed. Missing peer dependencies surface as engine_config_error\n * on first build_model call with a clear message naming the missing peer.\n *\n * Only the ai_sdk transport module (providers/ai_sdk/invoke.ts) may import\n * from `ai` or invoke generateText/streamText. ai_sdk adapters build the\n * provider model and translate parameters; they do not orchestrate the call.\n */\n\nimport type {\n ResolvedModel,\n EffortLevel,\n GenerateOptions,\n GenerateResult,\n ProviderInit,\n TurnRequest,\n TurnResult,\n UsageTotals,\n} from '../types.js'\nimport { engine_config_error } from '../errors.js'\n\n/**\n * Which backend a provider factory returns: 'ai_sdk' wraps the Vercel AI SDK\n * provider package, 'native' talks to the provider's HTTP API directly. The\n * provider name stays the same across transports so pricing keys and usage\n * fields carry over; only the wire implementation changes.\n */\nexport type ProviderTransport = 'ai_sdk' | 'native'\n\n/**\n * Read the `transport` selector off a provider init. Defaults to 'ai_sdk';\n * anything but the two known backends throws at construction so a typo\n * fails loud instead of silently running the default.\n */\nexport function resolve_transport(\n init: ProviderInit,\n provider: string,\n): ProviderTransport {\n const raw = init['transport']\n if (raw === undefined || raw === 'ai_sdk') return 'ai_sdk'\n if (raw === 'native') return 'native'\n throw new engine_config_error(\n `${provider} provider: transport must be 'ai_sdk' or 'native', got ${JSON.stringify(raw)}`,\n provider,\n )\n}\n\nexport type EffortTranslation = {\n // Outer keys are provider names, inner records hold per-provider settings,\n // matching the two-level shape merge_provider_options expects.\n provider_options: Record<string, Record<string, unknown>>\n effort_ignored: boolean\n // A level for the AI SDK's own `reasoning` call option, which the provider\n // package maps per model. Left out, the SDK uses the provider's default.\n reasoning?: Exclude<EffortLevel, 'none'>\n}\n\n/**\n * Hand effort to the AI SDK's `reasoning` option and build no provider\n * options of its own, so the provider package maps each level per model from\n * the capability table it keeps (adaptive thinking or a budget for Claude,\n * `thinkingLevel` or a budget for Gemini, `reasoningEffort` for OpenAI).\n * `none` sends neither, which is the SDK's provider default. The anthropic,\n * bedrock, google, and openai ai_sdk adapters all translate this way.\n */\nexport function translate_effort_to_sdk_reasoning(effort: EffortLevel): EffortTranslation {\n if (effort === 'none') return { provider_options: {}, effort_ignored: false }\n return { provider_options: {}, effort_ignored: false, reasoning: effort }\n}\n\nexport type ProviderCapability =\n | 'text'\n | 'tools'\n | 'schema'\n | 'streaming'\n | 'image_input'\n | 'reasoning'\n // Provider performs native constrained decoding (the AI SDK responseFormat /\n // Output.object path), as opposed to the prompt-for-JSON-then-extract path.\n // Distinct from 'schema': every provider can satisfy a schema via repair, but\n // only some constrain the decode to it.\n | 'structured_output'\n\nexport type RawProviderUsage = {\n input_tokens?: number\n output_tokens?: number\n reasoning_tokens?: number\n cached_input_tokens?: number\n cache_write_tokens?: number\n // Vercel AI SDK v6 also surfaces details via *Details containers; adapters\n // accept the flattened shape above for testability.\n input_token_details?: {\n cached_tokens?: number\n cache_creation_input_tokens?: number\n }\n output_token_details?: {\n reasoning_tokens?: number\n }\n [k: string]: unknown\n}\n\nexport type AiSdkProviderAdapter = {\n readonly kind: 'ai_sdk'\n readonly name: string\n // The key the adapter's package writes providerMetadata under, which is\n // the only key a reasoning part may carry to be sent back (D26). Defaults\n // to `name`; a custom adapter over a built-in package (@ai-sdk/anthropic on\n // Vertex, say) can't take the built-in name, so it sets the package's key.\n readonly metadata_key?: string\n readonly build_model: (model_id: string) => Promise<unknown>\n readonly translate_effort: (effort: EffortLevel) => EffortTranslation\n readonly normalize_usage: (raw: RawProviderUsage | undefined) => UsageTotals\n readonly supports: (capability: ProviderCapability) => boolean\n}\n\n/**\n * Raw-HTTP transport: implements a single turn against a provider's own\n * API with zero `ai` / `@ai-sdk/*` in its module graph. generate.ts wraps\n * invoke_turn in retry + classification + abort, so a native adapter owns only\n * request/response mapping (and streaming via TurnRequest.dispatch_chunk); it\n * MUST NOT implement its own retry. classify_error optionally overrides the\n * shared classifier; dispose is optional (keep-alive agents, connection pools).\n */\nexport type NativeProviderAdapter = {\n readonly kind: 'native'\n readonly name: string\n readonly invoke_turn: (req: TurnRequest) => Promise<TurnResult>\n readonly supports: (capability: ProviderCapability) => boolean\n readonly dispose?: () => Promise<void>\n readonly classify_error?: (err: unknown) => unknown\n}\n\nexport type ExternalAgentAdapter = {\n readonly kind: 'external'\n readonly name: string\n readonly generate: <t>(\n opts: GenerateOptions<t>,\n resolved: ResolvedModel,\n ) => Promise<GenerateResult<t>>\n readonly dispose: () => Promise<void>\n readonly supports: (capability: ProviderCapability) => boolean\n}\n\nexport type ProviderAdapter =\n | AiSdkProviderAdapter\n | NativeProviderAdapter\n | ExternalAgentAdapter\n\nexport type ProviderFactory = (init: ProviderInit) => ProviderAdapter\n\n/**\n * Map raw provider usage to UsageTotals, the mapper most adapters share.\n *\n * Missing usage zeroes the totals. Optional fields (reasoning and cache\n * tokens) are set only when the raw payload carries them, reading the\n * flattened field first and the AI SDK's *_details container second.\n */\nexport function default_normalize_usage(\n raw: RawProviderUsage | undefined,\n): UsageTotals {\n if (raw === undefined) return { input_tokens: 0, output_tokens: 0 }\n const input_tokens = typeof raw.input_tokens === 'number' ? raw.input_tokens : 0\n const output_tokens = typeof raw.output_tokens === 'number' ? raw.output_tokens : 0\n const totals: UsageTotals = { input_tokens, output_tokens }\n if (typeof raw.reasoning_tokens === 'number') totals.reasoning_tokens = raw.reasoning_tokens\n else if (typeof raw.output_token_details?.reasoning_tokens === 'number') {\n totals.reasoning_tokens = raw.output_token_details.reasoning_tokens\n }\n if (typeof raw.cached_input_tokens === 'number') totals.cached_input_tokens = raw.cached_input_tokens\n else if (typeof raw.input_token_details?.cached_tokens === 'number') {\n totals.cached_input_tokens = raw.input_token_details.cached_tokens\n }\n if (typeof raw.cache_write_tokens === 'number') totals.cache_write_tokens = raw.cache_write_tokens\n else if (typeof raw.input_token_details?.cache_creation_input_tokens === 'number') {\n totals.cache_write_tokens = raw.input_token_details.cache_creation_input_tokens\n }\n return totals\n}\n\n/**\n * Usage mapper for local backends (Ollama, LM Studio) whose servers never\n * report cache or reasoning tokens: default-normalize, then strip those\n * fields so a stray *_details container cannot invent them.\n */\nexport function normalize_local_usage(raw: RawProviderUsage | undefined): UsageTotals {\n const base = default_normalize_usage(raw)\n delete base.cached_input_tokens\n delete base.cache_write_tokens\n delete base.reasoning_tokens\n return base\n}\n\n/**\n * Build the standard missing-peer error: names the package and the install\n * command so a missing peer is diagnosable from the message alone. Shared so\n * every optional-peer failure reads identically, whether the failing\n * `import()` names the peer directly (load_optional_peer below) or a local\n * module that reaches the peer through its own static import (the ai_sdk\n * turn seam in generate.ts, whose dynamic import must stay written in\n * generate.ts for its relative specifier to resolve correctly).\n */\nexport function missing_peer_error(peer_name: string, cause: unknown): Error {\n const detail = cause instanceof Error ? cause.message : JSON.stringify(cause)\n const message =\n `missing peer dependency '${peer_name}'. Install it with your package manager, e.g., \\`pnpm add ${peer_name}\\` or \\`npm install ${peer_name}\\`. Cause: ${detail}`\n return new Error(message, { cause })\n}\n\n/**\n * Dynamically import an optional peer dependency, rethrowing an import\n * failure via missing_peer_error so a missing peer is diagnosable from the\n * message alone.\n */\nexport async function load_optional_peer<t>(\n specifier: string,\n): Promise<t> {\n let mod: unknown\n try {\n mod = await import(specifier)\n } catch (err: unknown) {\n throw missing_peer_error(specifier, err)\n }\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return mod as t\n}\n","/**\n * Shared plumbing for the native (raw-HTTP) provider adapters.\n *\n * Everything here is wire-neutral: how a turn travels HTTP (POST, non-2xx\n * mapping, stream-vs-JSON dispatch), how streamed bytes become framed\n * payloads, and the engine-message folds the 1:1 wires share. Each adapter\n * keeps what is genuinely its own dialect (request bodies, response parsers,\n * stream aggregators) and delegates the rest here, so the three adapters\n * cannot drift apart on retry classification or stream draining. This module\n * imports nothing from `ai` or `@ai-sdk/*` and nothing from the adapters, so\n * every adapter can import it cycle-free.\n */\n\nimport type {\n AssistantContentPart,\n Message,\n ProviderInit,\n StreamChunk,\n TurnRequest,\n TurnResult,\n UserContentPart,\n} from '../types.js'\nimport { provider_auth_error, provider_error } from '../errors.js'\n\n/**\n * The message under a JSON error envelope's `error` key, or undefined when\n * the shape carries none worth surfacing.\n */\nfunction error_field_message(parsed: unknown): string | undefined {\n // Stryker disable next-line ConditionalExpression,LogicalOperator: the\n // caller's try/catch already funnels every non-object parse to the raw\n // snippet, so this guard only narrows unknown -> object for Reflect.get;\n // forcing it either way throws-and-catches to the same fallback (equivalent).\n if (parsed === null || typeof parsed !== 'object') return undefined\n const error: unknown = Reflect.get(parsed, 'error')\n if (typeof error === 'string' && error.length > 0) return error\n // Stryker disable next-line ConditionalExpression,LogicalOperator: same as\n // above -- a non-object error still reaches the raw-snippet fallback via the\n // catch or the message-not-a-string check, so both boundaries are equivalent.\n if (error === null || typeof error !== 'object') return undefined\n const message: unknown = Reflect.get(error, 'message')\n return typeof message === 'string' && message.length > 0 ? message : undefined\n}\n\n/**\n * Pull a human-readable message out of a non-2xx body. The native wires share\n * one envelope family: Anthropic sends `{ type: 'error', error: { message } }`,\n * OpenAI-style wires send `{ error: { message } }`, and Ollama sends\n * `{ error: \"message\" }` (with the nested shape appearing behind proxies), so\n * one parser accepts a string or a `{ message }` object under `error` and\n * falls back to the raw body, truncated to 300 chars.\n */\nfunction extract_error_message(body: string): string {\n if (body.length === 0) return '(empty body)'\n let message: string | undefined\n try {\n message = error_field_message(JSON.parse(body))\n } catch {\n // Not JSON; fall through to the raw snippet.\n }\n if (message !== undefined) return message\n return body.length > 300 ? `${body.slice(0, 300)}...` : body\n}\n\n/**\n * Map a non-2xx response to what the engine's retry stack expects: 401\n * becomes a typed provider_auth_error, 429/5xx keep `status` +\n * `responseHeaders` so classify_provider_error marks them retryable\n * (rate_limit honoring retry-after, provider_5xx), and any other 4xx is a\n * permanent provider_error that surfaces as-is.\n */\nasync function response_error(response: Response, provider: string): Promise<Error> {\n let body = ''\n try {\n body = await response.text()\n } catch {\n // Body is best-effort detail; classification needs only the status.\n }\n const detail = extract_error_message(body)\n const status = response.status\n if (status === 401) {\n return new provider_auth_error(\n provider,\n `${provider} authentication failed (401): ${detail}`,\n )\n }\n if (status === 429 || status >= 500) {\n const retry_after = response.headers.get('retry-after')\n return Object.assign(\n new Error(`${provider} API error ${status}: ${detail}`),\n { status },\n retry_after !== null ? { responseHeaders: { 'retry-after': retry_after } } : {},\n )\n }\n return new provider_error(`${provider} API error ${status}: ${detail}`, { status, body })\n}\n\n/**\n * A user abort surfaces as the fetch/reader AbortError; retry_turn converts\n * it via its own signal check, so it is rethrown untouched. Everything else\n * is a transport failure wrapped in the `kind: 'network'` shape the shared\n * classify_provider_error marks retryable.\n */\nfunction rethrow_network_failure(err: unknown, abort: AbortSignal, provider: string): never {\n if (abort.aborted) throw err\n const detail = err instanceof Error ? err.message : String(err)\n throw Object.assign(new Error(`${provider} native: network failure: ${detail}`), {\n kind: 'network',\n })\n}\n\n/**\n * Run one native turn over HTTP: POST the dialect's body, map a non-2xx to\n * the retry stack's shapes, and hand the response to the dialect's stream or\n * JSON consumer. `build_body` is called inside the network try/catch on\n * purpose, so a mapper that throws surfaces as a retryable network failure\n * rather than escaping the turn unclassified.\n */\nexport async function invoke_http_turn(\n req: TurnRequest,\n provider: string,\n request: {\n url: string\n headers: Record<string, string>\n build_body: () => Record<string, unknown>\n },\n consume: {\n stream: (response: Response) => Promise<TurnResult>\n parse: (payload: unknown) => TurnResult\n },\n): Promise<TurnResult> {\n let response: Response\n try {\n response = await fetch(request.url, {\n method: 'POST',\n headers: request.headers,\n body: JSON.stringify(request.build_body()),\n signal: req.abort,\n })\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort, provider)\n }\n if (!response.ok) throw await response_error(response, provider)\n if (req.stream) return consume.stream(response)\n const payload: unknown = await response.json()\n return consume.parse(payload)\n}\n\n/**\n * Drain a streaming response: decode bytes, reassemble framed payloads (SSE\n * events or NDJSON lines), and feed them to the dialect's aggregator, which\n * dispatches chunks through req.dispatch_chunk as they arrive. Transport\n * failures mid-read wrap as network errors; aggregator throws (malformed\n * frames, mid-stream error events, a rejecting on_chunk) pass through\n * untouched, with the reader cancelled so the connection is released.\n */\nexport async function consume_framed_stream(\n response: Response,\n req: TurnRequest,\n provider: string,\n framing: { push: (text: string) => string[]; flush: () => string[] },\n create_aggregator: (dispatch: (chunk: StreamChunk) => Promise<void>) => {\n handle: (data: string) => Promise<void>\n complete: () => TurnResult\n },\n): Promise<TurnResult> {\n const body = response.body\n if (body === null) {\n throw new provider_error(`${provider} native: streaming response has no body`)\n }\n const aggregator = create_aggregator(req.dispatch_chunk ?? (async (): Promise<void> => {}))\n const reader = body.getReader()\n const text_decoder = new TextDecoder()\n\n const next_bytes = async (): Promise<Uint8Array | undefined> => {\n let step: Awaited<ReturnType<typeof reader.read>>\n try {\n step = await reader.read()\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort, provider)\n }\n return step.done ? undefined : step.value\n }\n\n // Sequential awaits are the contract here: chunk order is an engine\n // invariant and each frame mutates aggregator state, so no parallelism.\n try {\n while (true) {\n const bytes = await next_bytes()\n if (bytes === undefined) break\n for (const data of framing.push(text_decoder.decode(bytes, { stream: true }))) {\n await aggregator.handle(data)\n }\n }\n } finally {\n // Frees the connection when an error exits the loop early; a no-op on a\n // fully drained stream.\n void reader.cancel().catch(() => {})\n }\n const tail = [...framing.push(text_decoder.decode()), ...framing.flush()]\n for (const data of tail) {\n await aggregator.handle(data)\n }\n return aggregator.complete()\n}\n\n/**\n * Incremental newline framing shared by the SSE and NDJSON decoders: buffer\n * decoded text across arbitrary chunk boundaries, hand each completed line\n * (CR trimmed) to `handle_line`, and on flush hand over an unterminated tail\n * line, then `on_flush` for state a decoder holds across lines (an SSE event\n * never closed by a blank line).\n */\nexport function create_line_splitter(\n handle_line: (line: string, out: string[]) => void,\n on_flush?: (out: string[]) => void,\n): { push: (text: string) => string[]; flush: () => string[] } {\n let buffer = ''\n\n const take_line = (raw: string, out: string[]): void => {\n handle_line(raw.endsWith('\\r') ? raw.slice(0, -1) : raw, out)\n }\n\n return {\n push(text: string): string[] {\n buffer += text\n const out: string[] = []\n let newline = buffer.indexOf('\\n')\n while (newline >= 0) {\n take_line(buffer.slice(0, newline), out)\n buffer = buffer.slice(newline + 1)\n newline = buffer.indexOf('\\n')\n }\n return out\n },\n flush(): string[] {\n const out: string[] = []\n if (buffer.length > 0) take_line(buffer, out)\n buffer = ''\n on_flush?.(out)\n return out\n },\n }\n}\n\n/**\n * Decode a tool call's wire `arguments` string into the engine's input value:\n * non-empty JSON parses (bad JSON is a provider_error naming the tool), and\n * an absent or empty value means `{}`, the shape some servers send for\n * no-argument calls. The Ollama wire's structured-object arguments are its\n * caller's business before this runs.\n */\nexport function parse_tool_call_arguments(\n raw_args: unknown,\n provider: string,\n tool_name: string,\n): unknown {\n if (typeof raw_args === 'string' && raw_args.length > 0) {\n try {\n return JSON.parse(raw_args)\n } catch {\n throw new provider_error(\n `${provider} native: tool_calls arguments for ${tool_name} is not valid JSON`,\n )\n }\n }\n return {}\n}\n\n/**\n * Fold engine messages into a wire's message array by role. Serves the wires\n * whose messages map 1:1 in place (chat/completions, Ollama's /api/chat); the\n * Messages API's system-hoisting and role-merging rules live in its own\n * mapper instead.\n */\nexport function map_messages_by_role<m>(\n messages: ReadonlyArray<Message>,\n wire: {\n system: (content: string) => m\n user: (content: string | UserContentPart[]) => m\n assistant: (content: string | AssistantContentPart[]) => m\n tool: (message: Extract<Message, { role: 'tool' }>) => m\n },\n): m[] {\n const out: m[] = []\n for (const message of messages) {\n switch (message.role) {\n case 'system':\n out.push(wire.system(message.content))\n break\n case 'user':\n out.push(wire.user(message.content))\n break\n case 'assistant':\n out.push(wire.assistant(message.content))\n break\n case 'tool':\n out.push(wire.tool(message))\n break\n }\n }\n return out\n}\n\ntype ReasoningPart = Extract<AssistantContentPart, { type: 'reasoning' }>\n\n/**\n * Whether a reasoning part is one this provider may send back: only a part\n * carrying data under the provider's own key goes. A part keyed for another\n * vendor stays behind, so a `fallback` never hands one vendor's signature to\n * another, and so does a part with no data, whose text alone is what a\n * signing wire refuses.\n */\nexport function is_own_reasoning(part: ReasoningPart, key: string): boolean {\n return part.provider_options?.[key] !== undefined\n}\n\n/**\n * Partition assistant content parts into the text runs, tool calls, and\n * reasoning the wire mappers serialize separately. `reasoning` holds only\n * the parts `provider` may send back, in order (see is_own_reasoning).\n */\nexport function split_assistant_parts(\n parts: ReadonlyArray<AssistantContentPart>,\n provider: string,\n): {\n texts: string[]\n tool_parts: Array<Extract<AssistantContentPart, { type: 'tool_call' }>>\n reasoning: ReasoningPart[]\n} {\n const texts: string[] = []\n const tool_parts: Array<Extract<AssistantContentPart, { type: 'tool_call' }>> = []\n const reasoning: ReasoningPart[] = []\n for (const part of parts) {\n if (part.type === 'text') texts.push(part.text)\n else if (part.type === 'tool_call') tool_parts.push(part)\n else if (is_own_reasoning(part, provider)) reasoning.push(part)\n }\n return { texts, tool_parts, reasoning }\n}\n\n/**\n * Read the api_key and base_url every OpenAI-compatible dialect starts from:\n * a missing or non-string api_key becomes '' (the core's empty-key guard owns\n * the throw), and an absent base_url falls back to the dialect's default.\n */\nexport function read_dialect_init(\n init: ProviderInit,\n default_base_url: string,\n): { api_key: string; base_url: string } {\n return {\n api_key: typeof init.api_key === 'string' ? init.api_key : '',\n base_url:\n typeof init.base_url === 'string' && init.base_url.length > 0\n ? init.base_url\n : default_base_url,\n }\n}\n","/**\n * Collapse a leading run of system messages into a single joined string,\n * returning the remaining messages.\n *\n * Both message paths hoist a leading system run out of their list the same way:\n * the engine-Message side (generate.ts split_leading_system_messages) hands the\n * run to a native adapter's TurnRequest.system, and the AI SDK side\n * (providers/ai_sdk/invoke.ts split_leading_system) hands it to the SDK's\n * top-level `instructions` option. Same guard, same '\\n\\n' join, and the same\n * \"return the list untouched when hoisting would leave `messages` empty\" rule,\n * since provider APIs reject an empty messages array. They differ only in the\n * element type and how a system message's text is read, so each caller supplies\n * `system_text`; the traversal and its guards live here once.\n */\nexport function split_leading_system_run<T extends { readonly role: string }>(\n messages: ReadonlyArray<T>,\n system_text: (message: Extract<T, { role: 'system' }>) => string,\n): { system?: string; messages: T[] } {\n let run_end = 0\n const system_parts: string[] = []\n while (run_end < messages.length) {\n const m = messages[run_end]\n if (!is_leading_system(m)) break\n system_parts.push(system_text(m))\n run_end += 1\n }\n const rest = messages.slice(run_end)\n if (system_parts.length === 0 || rest.length === 0) {\n return { messages: [...messages] }\n }\n return { system: system_parts.join('\\n\\n'), messages: rest }\n}\n\n/**\n * Narrow a possibly undefined message to the system member of its union.\n *\n * A cast-free type guard so `split_leading_system_run` can hand the narrowed\n * message straight to `system_text` without a `T`-eroding assertion; the\n * optional chain covers the out-of-bounds `undefined` the index access yields.\n */\nfunction is_leading_system<T extends { readonly role: string }>(\n m: T | undefined,\n): m is Extract<T, { role: 'system' }> {\n // Stryker disable next-line OptionalChaining: within the loop guard run_end < messages.length, m is always an in-bounds (defined) message, so m.role and m?.role read identically.\n return m?.role === 'system'\n}\n"],"mappings":";;AAyBA,IAAa,mBAAb,cAAsC,MAAM;CAC1C,OAAgB;CAEhB;CACA;CACA;CACA,YACE,SACA,WAA4E,CAAC,GAC7E;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,iBAAiB,SAAS;EAC/B,KAAK,WAAW,SAAS,YAAY;EACrC,KAAK,SAAS,SAAS;CACzB;AACF;AAEA,IAAa,iBAAb,cAAoC,MAAM;CACxC,OAAgB;CAEhB;CACA;CACA;CACA,YACE,SACA,WAII,CAAC,GACL;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS,SAAS;EACvB,KAAK,OAAO,SAAS;EACrB,KAAK,aAAa,SAAS;CAC7B;AACF;;;;;;;;;;;AAYA,IAAa,qBAAb,cAAwC,MAAM;CAC5C,OAAgB;CAEhB;CACA;CACA,YAAY,YAAoB,YAAqB;EACnD,MAAM,2CAA2C,WAAW,GAAG;EAC/D,KAAK,OAAO;EACZ,KAAK,aAAa;EAClB,KAAK,aAAa;CACpB;AACF;AAEA,IAAa,0BAAb,cAA6C,MAAM;CACjD,OAAgB;CAEhB;CACA;CACA,YAAY,SAAiB,eAA2C,UAAkB;EACxF,MAAM,OAAO;EACb,KAAK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ChC,OAAO,UAAU,SAAS,QAAQ;EAChC,MAAM,IAAI,SAAS;EACnB,IAAI,CAAC,kBAAkB,CAAC,GAAG;EAC3B,aAAa,KAAK,YAAY,CAAC,CAAC;EAChC,WAAW;CACb;CACA,MAAM,OAAO,SAAS,MAAM,OAAO;CACnC,IAAI,aAAa,WAAW,KAAK,KAAK,WAAW,GAC/C,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ,EAAE;CAEnC,OAAO;EAAE,QAAQ,aAAa,KAAK,MAAM;EAAG,UAAU;CAAK;AAC7D;;;;;;;;AASA,SAAS,kBACP,GACqC;CAErC,OAAO,GAAG,SAAS;AACrB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"search-CA_OqFeW.js","names":["LINE_WIDTH","ALL_FILES"],"sources":["../src/acp/tools/containment.ts","../src/acp/tools/read_file.ts","../src/acp/tools/list_files.ts","../src/acp/tools/search.ts"],"sourcesContent":["/**\n * Containment: the boundary the workspace file tools keep. A path, absolute\n * or relative to the session's `cwd`, is allowed only when its real path\n * lands under one of the session's roots, which are real paths themselves,\n * resolved once at `session/new`.\n *\n * Real paths on both sides are the point. A symlink inside the workspace\n * that points out of it is the classic escape, and checking the path as\n * written would let it through. A `cwd` behind a symlink (macOS's `/tmp` and\n * `/var` both are) would refuse every file in the project if the roots\n * stayed as the client sent them. A path that doesn't exist yet resolves\n * through its nearest existing ancestor, and a dangling symlink through its\n * target, so a path outside the roots is refused the same way whether or\n * not it exists.\n */\n\nimport { readlink, realpath, stat } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport type { AcpSession } from '../types.js'\n\n/** A path a tool may touch, both as the client names it and as the file system resolves it. */\nexport type ContainedPath = {\n /** Absolute, under the `cwd` the client sent: what the client and the model are shown. */\n readonly path: string\n /** Symlinks resolved: what the tool opens. */\n readonly real: string\n}\n\n/** The error codes that mean a path, or a directory on the way to it, doesn't exist. */\nconst MISSING: ReadonlySet<unknown> = new Set(['ENOENT', 'ENOTDIR'])\n\n/**\n * How many symlinks a missing path may pass through before resolving it\n * gives up. `path.resolve` folds `missing/..` away where the kernel would\n * fail on it, so a link such as `a -> missing/../a` would otherwise loop.\n */\nconst MAX_LINK_HOPS = 40\n\n/**\n * The code a Node file system error carries, such as `ENOENT`. Every\n * caller hands in an error from `node:fs`, which always has one.\n */\nexport function error_code(err: unknown): unknown {\n return Reflect.get(Object(err), 'code')\n}\n\n/**\n * Resolve one root the client sent to its real path, refusing a relative\n * path (which would resolve against wherever the agent was launched), a path\n * that doesn't exist, and a file.\n */\nasync function resolve_root(root: string): Promise<string> {\n if (!isAbsolute(root)) {\n throw new Error(`the workspace root ${root} is a relative path; send session/new with absolute paths`)\n }\n const real = await realpath(root).catch((err: unknown) => {\n throw new Error(\n `the workspace root ${root} can't be opened (${String(error_code(err))}); send session/new with a directory that exists`,\n )\n })\n if (!(await stat(real)).isDirectory()) {\n throw new Error(`the workspace root ${root} is a file; send session/new with a directory`)\n }\n return real\n}\n\n/**\n * Resolve a session's roots (its `cwd`, then each additional directory) to\n * their real paths, once, when the session starts. The error names the\n * first root that isn't an absolute path to an existing directory.\n */\nexport async function resolve_roots(roots: ReadonlyArray<string>): Promise<string[]> {\n return Promise.all(roots.map(resolve_root))\n}\n\n/**\n * Whether `target` is `root` or lies beneath it. Both are compared as they\n * are, so the caller hands in real paths for a containment check.\n */\nfunction is_within(root: string, target: string): boolean {\n return target === root || target.startsWith(root.endsWith(sep) ? root : `${root}${sep}`)\n}\n\n/**\n * A symlink's target as written, or `undefined` when the path isn't a\n * symlink or isn't there.\n */\nasync function link_target(path: string): Promise<string | undefined> {\n return readlink(path).catch(() => undefined)\n}\n\n/**\n * The real path of `path`, existing or not. A path that exists is the file\n * system's own answer. A missing one is its parent's real path plus its\n * name, unless it's a dangling symlink, whose real path is its target's:\n * writing through it would land there.\n */\nasync function real_path(path: string, hops_left: number): Promise<string> {\n try {\n return await realpath(path)\n } catch (err: unknown) {\n if (!MISSING.has(error_code(err))) throw err\n }\n const parent = await real_path(dirname(path), hops_left)\n const target = await link_target(path)\n if (target === undefined) return join(parent, basename(path))\n if (hops_left === 0) throw new Error(`${path} passes through too many symbolic links to resolve`)\n return real_path(resolve(parent, target), hops_left - 1)\n}\n\n/**\n * Check that a path a tool was handed lands inside the session's workspace,\n * and return it both ways. The refusal is an ordinary error naming the roots\n * in the client's terms, since the model reads it as a tool result and can\n * try a path that fits.\n */\nexport async function contain(session: AcpSession, requested: string): Promise<ContainedPath> {\n const path = resolve(session.cwd, requested)\n const real = await real_path(path, MAX_LINK_HOPS)\n if (session.roots.some((root) => is_within(root, real))) return { path, real }\n const allowed = [session.cwd, ...session.additional_directories].join(', ')\n throw new Error(`${requested} is outside the workspace; the file tools only reach paths under ${allowed}`)\n}\n\n/**\n * A path as a tool shows it to the model: relative to `cwd` when it's under\n * it, and absolute otherwise, as for a file in an additional directory.\n * Either form reads back through `contain`.\n */\nexport function shown_path(session: AcpSession, path: string): string {\n return is_within(session.cwd, path) ? relative(session.cwd, path) || '.' : path\n}\n","/**\n * read_file: read a text file in the workspace with its lines numbered, a\n * window at a time.\n *\n * A window stops at `read_limit_lines` and says where the next one starts,\n * and a line past LINE_WIDTH characters is cut with a marker, because a\n * minified bundle or a source map can be one line of megabytes and nothing\n * else keeps it out of the model's context. A file with a NUL byte in its\n * first 8 KB is refused as binary, the test `examples/pr-improve` uses. The\n * file streams line by line, so a window near the top of a huge file reads\n * only as far as it shows.\n */\n\nimport { open, stat } from 'node:fs/promises'\nimport type { FileHandle } from 'node:fs/promises'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain, error_code } from './containment.js'\n\n/** The longest line `read_file` returns whole, the width Claude Code's Read cuts at. */\nconst LINE_WIDTH = 2000\n\n/** How much of a file's head is checked for a NUL byte, the sign of a binary file. */\nconst BINARY_SNIFF_BYTES = 8192\n\n/** One read: the path as the model gave it, and the lines it covers. */\ntype ReadRequest = {\n readonly path: string\n readonly offset: number\n readonly limit: number\n}\n\n/**\n * Whether a value counts lines: a whole number of at least 1.\n */\nfunction is_count(value: unknown): value is number {\n return Number.isInteger(value) && Number(value) >= 1\n}\n\n/**\n * Read the call's window out of its input, with `limit` held to the cap.\n * The tool loop has already checked the types against the schema, but a\n * flow that wraps the tool can call `execute` directly, and the schema's\n * `minimum` is advice to the model rather than something the loop enforces.\n */\nfunction read_request(input: unknown, read_limit_lines: number): ReadRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { path, offset = 1, limit = read_limit_lines } = fields\n if (typeof path !== 'string') throw new Error('read_file needs a path, as a string')\n if (!is_count(offset) || !is_count(limit)) {\n throw new Error('read_file counts offset and limit in lines from 1, so each has to be a whole number of at least 1')\n }\n return { path, offset, limit: Math.min(limit, read_limit_lines) }\n}\n\n/**\n * Whether the file's first BINARY_SNIFF_BYTES hold a NUL byte. `search`\n * skips a file this calls binary, so the two tools agree on what is text.\n */\nexport async function is_binary(handle: FileHandle): Promise<boolean> {\n const head = Buffer.alloc(BINARY_SNIFF_BYTES)\n const { bytesRead } = await handle.read(head, 0, BINARY_SNIFF_BYTES, 0)\n return head.subarray(0, bytesRead).includes(0)\n}\n\n/**\n * One line as the model sees it: its number, a tab, and its text, cut at\n * LINE_WIDTH with a marker that says how long it was.\n */\nfunction numbered(line_number: number, line: string): string {\n const text =\n line.length > LINE_WIDTH ? `${line.slice(0, LINE_WIDTH)} [line cut at ${LINE_WIDTH} of ${line.length} characters]` : line\n return `${String(line_number).padStart(6)}\\t${text}`\n}\n\n/**\n * Number the window's lines, reading one line past it to learn whether the\n * file goes on, and say where to start the next read when it does.\n */\nasync function read_lines(handle: FileHandle, request: ReadRequest): Promise<string> {\n const last = request.offset + request.limit - 1\n const shown: string[] = []\n let count = 0\n let more = false\n // The binary check reads at an explicit position, which leaves the\n // handle's own position at the top, where these lines start.\n for await (const line of handle.readLines()) {\n count += 1\n if (count > last) {\n more = true\n break\n }\n if (count >= request.offset) shown.push(numbered(count, line))\n }\n if (count === 0) return `${request.path} is empty`\n if (shown.length === 0) {\n throw new Error(`offset ${request.offset} is past the end of ${request.path}, which has ${count} lines`)\n }\n const body = shown.join('\\n')\n if (!more) return body\n return `${body}\\n\\n[lines ${request.offset} to ${last} shown; the file goes on, so read on with offset ${last + 1}]`\n}\n\n/**\n * Read a contained file's window, refusing what isn't a regular text file.\n * The type is checked before the file opens, since opening a FIFO would\n * wait for a writer that never comes.\n */\nasync function read_contained(real: string, request: ReadRequest): Promise<string> {\n const info = await stat(real).catch((err: unknown) => {\n throw error_code(err) === 'ENOENT' ? new Error(`${request.path} doesn't exist`) : err\n })\n if (info.isDirectory()) throw new Error(`${request.path} is a directory; list_files shows what's in it`)\n if (!info.isFile()) throw new Error(`${request.path} isn't a regular file, so read_file can't read it`)\n const handle = await open(real)\n try {\n if (await is_binary(handle)) {\n throw new Error(`${request.path} is a binary file (it has a NUL byte in its first 8 KB), so read_file won't read it`)\n }\n return await read_lines(handle, request)\n } finally {\n await handle.close()\n }\n}\n\n/**\n * The `read_file` tool for one session: numbered lines from a file inside\n * its workspace, at most `read_limit_lines` per call.\n */\nexport function read_file_tool(session: AcpSession, read_limit_lines: number): Tool {\n return {\n name: 'read_file',\n description:\n `Read a text file in the workspace. Returns its lines numbered from 1, at most ${read_limit_lines} per call; ` +\n `pass offset (the first line to read) and limit to read part of a longer file. ` +\n `Lines over ${LINE_WIDTH} characters are cut. The path is absolute or relative to the workspace root.`,\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n path: { type: 'string', description: 'The file to read, absolute or relative to the workspace root' },\n offset: { type: 'integer', minimum: 1, description: 'The first line to read, counting from 1; default: 1' },\n limit: {\n type: 'integer',\n minimum: 1,\n description: `How many lines to read; default and most: ${read_limit_lines}`,\n },\n },\n required: ['path'],\n additionalProperties: false,\n }),\n execute: async (input) => {\n const request = read_request(input, read_limit_lines)\n const { real } = await contain(session, request.path)\n return read_contained(real, request)\n },\n }\n}\n","/**\n * list_files: list the workspace's files that match a glob.\n *\n * It walks the directory itself and matches each file with `path`'s\n * `matchesGlob`, rather than handing the walk to `fs/promises`' `glob`.\n * That `glob` steps through a symlinked directory whenever a pattern names\n * it, passes over its `exclude` callback for a pattern that names its\n * segments, swallows a directory it can't read, and, with an `exclude`\n * callback under Stryker's runner, dropped a whole directory it had already\n * listed. The walk here never follows a symlink and never enters an ignored\n * name, so every file it lists lies under the searched directory, which\n * `contain` has already placed inside a root, and its matches follow the\n * same glob rules as `glob`'s.\n */\n\nimport type { Dirent } from 'node:fs'\nimport { readdir, stat } from 'node:fs/promises'\nimport { isAbsolute, join, matchesGlob } from 'node:path'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain, shown_path } from './containment.js'\n\n/** What `list_files` matches when the call names no pattern. */\nconst ALL_FILES = '**/*'\n\n/** One listing: the glob, and the directory it runs in, as the model gave them. */\ntype ListRequest = {\n readonly pattern: string\n readonly path: string\n}\n\n/** What one walk needs besides the directory it's in. */\nexport type Walk = {\n readonly pattern: string\n readonly ignored: ReadonlySet<string>\n readonly abort: AbortSignal\n readonly found: string[]\n}\n\n/**\n * Read the call's pattern and directory out of its input, refusing a\n * pattern that reaches past the directory: it could never match, and the\n * model is better told to pass the directory as `path`.\n */\nfunction list_request(input: unknown): ListRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { pattern = ALL_FILES, path = '.' } = fields\n if (typeof pattern !== 'string' || typeof path !== 'string') {\n throw new Error('list_files takes its pattern and path as strings')\n }\n if (isAbsolute(pattern) || pattern.split(/[\\\\/]/).includes('..')) {\n throw new Error(\n `list_files matches its pattern under path, so ${pattern} can't be absolute or climb with ..; pass the directory as path instead`,\n )\n }\n return { pattern, path }\n}\n\n/**\n * Walk one directory, depth first: descend into each subdirectory and keep\n * each regular file that matches, skipping ignored names. A symlink is\n * neither a directory nor a file to a `readdir` entry, so the walk never\n * follows one. `search` walks with it too, so both tools see the same files.\n */\nexport async function walk(directory: string, below: string, work: Walk): Promise<void> {\n work.abort.throwIfAborted()\n const entries: Dirent[] = await readdir(directory, { withFileTypes: true })\n for (const entry of entries) {\n if (work.ignored.has(entry.name)) continue\n const relative = join(below, entry.name)\n if (entry.isDirectory()) await walk(join(directory, entry.name), relative, work)\n else if (entry.isFile() && matchesGlob(relative, work.pattern)) work.found.push(relative)\n }\n}\n\n/**\n * The files under the request's directory that match its pattern, in the\n * model's terms and sorted.\n */\nasync function matching_files(\n session: AcpSession,\n request: ListRequest,\n ignored: ReadonlySet<string>,\n abort: AbortSignal,\n): Promise<string[]> {\n const base = await contain(session, request.path)\n if (!(await stat(base.real)).isDirectory()) {\n throw new Error(`${request.path} is a file; list_files lists a directory, and read_file reads a file`)\n }\n const found: string[] = []\n await walk(base.real, '', { pattern: request.pattern, ignored, abort, found })\n return found.map((relative) => shown_path(session, join(base.path, relative))).toSorted()\n}\n\n/**\n * The files as the model reads them, one to a line, and past `limit` the\n * first `limit` of them with a note giving the total. The walk has already\n * found every match to sort them, so the total costs nothing to count.\n */\nfunction listing(files: ReadonlyArray<string>, limit: number): string {\n if (files.length <= limit) return files.join('\\n')\n const note = `[the first ${limit} of ${files.length} files; narrow pattern or path to see the rest]`\n return [...files.slice(0, limit), '', note].join('\\n')\n}\n\n/**\n * The `list_files` tool for one session: the files under a directory in\n * its workspace that match a glob, skipping the `ignore` names, at most\n * `limit` per call.\n */\nexport function list_files_tool(session: AcpSession, ignore: ReadonlyArray<string>, limit: number): Tool {\n const ignored = new Set(ignore)\n return {\n name: 'list_files',\n description: [\n `List the files in the workspace that match a glob pattern, one per line and at most ${limit} per call; a path under the workspace root is shown relative to it.`,\n `The pattern matches under path (default: the workspace root) and defaults to ${ALL_FILES}.`,\n 'As in a shell, * and ** skip names that start with a dot, so name the dot to list hidden files (.github/**/*).',\n ...(ignore.length === 0 ? [] : [`Skips ${ignore.join(', ')}.`]),\n ].join(' '),\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n pattern: { type: 'string', description: `A glob such as src/**/*.ts; default: ${ALL_FILES}` },\n path: {\n type: 'string',\n description: 'The directory to search, absolute or relative to the workspace root; default: the root',\n },\n },\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n const request = list_request(input)\n const files = await matching_files(session, request, ignored, ctx.abort)\n return files.length === 0 ? `no files match ${request.pattern} under ${request.path}` : listing(files, limit)\n },\n }\n}\n","/**\n * search: find the lines in the workspace's files that match a regular\n * expression.\n *\n * The pattern is the model's, and JavaScript's `RegExp` backtracks, so a\n * pattern such as `(a+)+$` against one long line can run for minutes. No\n * abort interrupts synchronous code, and one agent process serves every\n * session, so a search on the main thread could leave even `session/cancel`\n * unanswered. Each search runs in a worker thread instead, which the turn's\n * abort and a time budget can terminate mid-match. The worker is a thin\n * shell, `search_worker.ts`: what it runs is `search_files`, here, where\n * the tests call it on the main thread.\n *\n * The search walks the files itself, with `list_files`' walk, rather than\n * handing the work to `rg`, because the module keeps child processes to\n * `run_command`.\n */\n\nimport { open, stat } from 'node:fs/promises'\nimport { extname, join } from 'node:path'\nimport { Worker } from 'node:worker_threads'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain, shown_path } from './containment.js'\nimport { walk } from './list_files.js'\nimport { is_binary } from './read_file.js'\n\n/** What `search` matches when the call names no glob. */\nconst ALL_FILES = '**/*'\n\n/** The most matches one call returns. */\nconst MATCH_LIMIT = 100\n\n/**\n * The longest matching line shown whole. A longer one is shown as a window\n * this wide around its match, since a minified bundle is one line of\n * megabytes and every match in it would otherwise carry the whole line.\n */\nconst LINE_WIDTH = 500\n\n/** How much of a long line its window shows before the match. */\nconst LINE_LEAD = 100\n\n/**\n * The search worker, beside this module with its extension: `.ts` in the\n * source tree, where vitest and Stryker run it, and `.js` once built.\n */\nconst SEARCH_WORKER = new URL(`./search_worker${extname(import.meta.url)}`, import.meta.url)\n\n/** One search as the model asked for it. */\ntype SearchRequest = {\n readonly pattern: string\n readonly path: string\n readonly glob: string\n}\n\n/** One search as the worker runs it: plain data, since it crosses to another thread. */\ntype SearchJob = {\n /** The real path of the directory to walk, or of the one file to search. */\n readonly base: string\n readonly directory: boolean\n readonly pattern: string\n /** The glob as the walk matches it, relative to `base`. */\n readonly glob: string\n readonly ignore: ReadonlyArray<string>\n readonly limit: number\n}\n\n/**\n * One matching line: its file relative to the job's base (empty when the\n * base is that file), its number counting from 1, and its text.\n */\ntype SearchMatch = {\n readonly file: string\n readonly line: number\n readonly text: string\n}\n\n/** The matches, and whether the search stopped at its limit with more to find. */\ntype SearchResult = {\n readonly matches: ReadonlyArray<SearchMatch>\n readonly more: boolean\n}\n\n/**\n * Read the call's pattern, path, and glob out of its input. The pattern\n * compiles in the worker, which reports one that isn't a regular expression\n * with the engine's own message.\n */\nfunction search_request(input: unknown): SearchRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { pattern, path = '.', glob = ALL_FILES } = fields\n if (typeof pattern !== 'string' || typeof path !== 'string' || typeof glob !== 'string') {\n throw new Error('search needs a pattern, and takes its pattern, path, and glob as strings')\n }\n return { pattern, path, glob }\n}\n\n/**\n * The glob as the walk matches it. Like `rg --glob`, a glob without a slash\n * names files at any depth, so `*.ts` reaches `src/a.ts`, while one with a\n * slash matches the path under the searched directory.\n */\nfunction walk_glob(glob: string): string {\n return glob.includes('/') ? glob : `**/${glob}`\n}\n\n/**\n * The files a job searches, relative to its base: the one file, or every\n * file the walk keeps, sorted so the same search stops at the same match\n * every time.\n */\nasync function files_of(job: SearchJob): Promise<string[]> {\n if (!job.directory) return ['']\n const found: string[] = []\n // Nothing inside the worker cancels the walk: the turn's abort and the\n // budget terminate the whole thread instead.\n const abort = new AbortController().signal\n await walk(job.base, '', { pattern: job.glob, ignored: new Set(job.ignore), abort, found })\n return found.toSorted()\n}\n\n/**\n * A file's text, or nothing for a binary file, which then has no lines to\n * search.\n */\nasync function file_text(path: string): Promise<string> {\n const handle = await open(path)\n try {\n // The binary check reads at an explicit position, which leaves the\n // handle's own position at the top, where readFile starts.\n return (await is_binary(handle)) ? '' : await handle.readFile('utf8')\n } finally {\n await handle.close()\n }\n}\n\n/**\n * A text's lines without their endings, and without the empty one after a\n * final newline, which isn't a line of the file.\n */\nfunction lines_of(text: string): string[] {\n const lines = text.split(/\\r?\\n/)\n if (lines.at(-1) === '') lines.pop()\n return lines\n}\n\n/**\n * A matching line as `search` shows it: whole up to LINE_WIDTH characters,\n * and past that, a window that wide starting LINE_LEAD characters before\n * the match, kept inside the line, with the columns it covers.\n */\nfunction excerpt(line: string, at: number): string {\n if (line.length <= LINE_WIDTH) return line\n const start = Math.max(0, Math.min(at - LINE_LEAD, line.length - LINE_WIDTH))\n return `${line.slice(start, start + LINE_WIDTH)} [columns ${start + 1} to ${start + LINE_WIDTH} of ${line.length}]`\n}\n\n/**\n * Search a job's files, in order, for the lines its pattern matches,\n * stopping at the first match past the limit, which says there are more.\n * The search worker runs this, and the tests call it on the main thread,\n * where Stryker can switch its mutants on.\n */\nexport async function search_files(job: SearchJob): Promise<SearchResult> {\n const regex = new RegExp(job.pattern)\n const matches: SearchMatch[] = []\n for (const file of await files_of(job)) {\n for (const [index, line] of lines_of(await file_text(join(job.base, file))).entries()) {\n const found = regex.exec(line)\n if (found === null) continue\n if (matches.length === job.limit) return { matches, more: true }\n matches.push({ file, line: index + 1, text: excerpt(line, found.index) })\n }\n }\n return { matches, more: false }\n}\n\n/**\n * Run one job in a search worker. The turn's abort and the budget each\n * terminate the thread, mid-match if need be, which nothing could do to a\n * pattern running on the main thread. However the search ends, the abort\n * listener and the budget's timer go with it.\n */\nasync function in_worker(job: SearchJob, budget_ms: number, abort: AbortSignal): Promise<SearchResult> {\n abort.throwIfAborted()\n const worker = new Worker(SEARCH_WORKER, { workerData: job })\n const { promise, resolve, reject } = Promise.withResolvers<SearchResult>()\n const stop = (reason: unknown): void => {\n void worker.terminate()\n reject(reason)\n }\n const on_abort = (): void => {\n stop(abort.reason)\n }\n const over_budget = new Error(\n `search stopped after ${budget_ms / 1000} s without finishing: the pattern may backtrack without end, ` +\n 'as nested quantifiers such as (a+)+ can, or there may be too much to search; ' +\n 'simplify the pattern, or narrow path or glob',\n )\n const budget = setTimeout(stop, budget_ms, over_budget)\n abort.addEventListener('abort', on_abort)\n worker.once('message', resolve)\n worker.once('error', reject)\n try {\n return await promise\n } finally {\n clearTimeout(budget)\n abort.removeEventListener('abort', on_abort)\n }\n}\n\n/**\n * The matches as the model reads them, one `path:line: text` to a line, and\n * a note when the search stopped at its limit.\n */\nfunction report(session: AcpSession, base: string, request: SearchRequest, result: SearchResult): string {\n if (result.matches.length === 0) {\n return `no lines match ${request.pattern} under ${request.path} in files matching ${request.glob}`\n }\n const lines = result.matches.map(\n (match) => `${shown_path(session, join(base, match.file))}:${match.line}: ${match.text}`,\n )\n if (result.more) {\n lines.push('', `[the first ${result.matches.length} matches; narrow the pattern, path, or glob to see the rest]`)\n }\n return lines.join('\\n')\n}\n\n/**\n * The `search` tool for one session: the lines under a path in its\n * workspace that match a regular expression, skipping binary files and the\n * `ignore` names, at most MATCH_LIMIT per call, each search in a worker\n * that the turn's abort and `budget_ms` can terminate.\n */\nexport function search_tool(session: AcpSession, ignore: ReadonlyArray<string>, budget_ms: number): Tool {\n return {\n name: 'search',\n description: [\n `Search the workspace's files for lines that match a regular expression, at most ${MATCH_LIMIT} per call,`,\n 'each shown as path:line: text; a path under the workspace root is shown relative to it.',\n 'The pattern is a JavaScript regular expression matched against one line at a time; write (?i:...) for a part that ignores case.',\n 'path (default: the workspace root) is the directory to search, or a single file.',\n 'glob picks the files: without a slash it matches a file name at any depth (*.ts, *.{ts,tsx}),',\n 'and with one it matches the path under path (src/**/*.ts).',\n 'As in a shell, * and ** skip names that start with a dot, so name the dot to search hidden files (.github/**/*).',\n ignore.length === 0 ? 'Skips binary files.' : `Skips binary files and ${ignore.join(', ')}.`,\n ].join(' '),\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'A JavaScript regular expression, such as function\\\\s+\\\\w+' },\n path: {\n type: 'string',\n description: 'The directory or file to search, absolute or relative to the workspace root; default: the root',\n },\n glob: { type: 'string', description: `Which files to search, such as *.ts or src/**/*.ts; default: ${ALL_FILES}` },\n },\n required: ['pattern'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n const request = search_request(input)\n const base = await contain(session, request.path)\n const info = await stat(base.real)\n if (!info.isDirectory() && !info.isFile()) {\n throw new Error(`${request.path} isn't a directory or a regular file, so search can't read it`)\n }\n const job: SearchJob = {\n base: base.real,\n directory: info.isDirectory(),\n pattern: request.pattern,\n glob: walk_glob(request.glob),\n ignore,\n limit: MATCH_LIMIT,\n }\n return report(session, base.path, request, await in_worker(job, budget_ms, ctx.abort))\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,0BAAgC,IAAI,IAAI,CAAC,UAAU,SAAS,CAAC;;;;;;AAOnE,MAAM,gBAAgB;;;;;AAMtB,SAAgB,WAAW,KAAuB;CAChD,OAAO,QAAQ,IAAI,OAAO,GAAG,GAAG,MAAM;AACxC;;;;;;AAOA,eAAe,aAAa,MAA+B;CACzD,IAAI,CAAC,WAAW,IAAI,GAClB,MAAM,IAAI,MAAM,sBAAsB,KAAK,0DAA0D;CAEvG,MAAM,OAAO,MAAM,SAAS,IAAI,CAAC,CAAC,OAAO,QAAiB;EACxD,MAAM,IAAI,MACR,sBAAsB,KAAK,oBAAoB,OAAO,WAAW,GAAG,CAAC,EAAE,iDACzE;CACF,CAAC;CACD,IAAI,EAAE,MAAM,KAAK,IAAI,EAAA,CAAG,YAAY,GAClC,MAAM,IAAI,MAAM,sBAAsB,KAAK,8CAA8C;CAE3F,OAAO;AACT;;;;;;AAOA,eAAsB,cAAc,OAAiD;CACnF,OAAO,QAAQ,IAAI,MAAM,IAAI,YAAY,CAAC;AAC5C;;;;;AAMA,SAAS,UAAU,MAAc,QAA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
-
{"version":3,"file":"trajectory-BI-mrVFT.js","names":[],"sources":["../src/core/trajectory.ts"],"sourcesContent":["/**\n * Wire-format guards for trajectory events.\n *\n * `TrajectoryEvent` (in `types.ts`) is the loose internal type — any code that\n * calls `trajectory.record(event)` or `start_span(name, meta)` produces values\n * conforming to it. This file defines the *narrower* shapes that the studio\n * (and any other downstream consumer) can recognize in the wire stream:\n *\n * span_start: composer span open\n * span_end: composer span close\n * emit: user-emitted event from inside a step (ctx.emit)\n * run_end: terminal run event carrying the run's status, so a consumer\n * distinguishes done / failed / aborted / suspended without\n * inferring from silence\n * checkpoint: checkpoint store lookup outcome (hit / miss / read_error)\n * step_replayed: a step marked `side_effect` re-running before a resumed\n * run reached the gates it was resumed at\n * map_item_failed: an item of a `map` that settles threw, and its slot\n * holds the error instead of a value\n * <other>: anything else, recognized by `is_custom_trajectory_event`,\n * which only requires a string `kind`\n *\n * `parse_trajectory_event` is the wire gate, and it is deliberately permissive:\n * a value is a trajectory event iff it is a non-array object carrying a string\n * `kind`. The well-known guards layered on top are *recognizers*, not gates — a\n * `{ kind: 'span_start' }` line missing its `span_id` is still a valid event on\n * the wire, just not a `SpanStartEvent`. Anything stricter would have a viewer\n * drop lines a newer producer emits, which is the opposite of what a\n * forward-compatible wire format is for. `is_custom_trajectory_event` therefore\n * answers `true` for well-known kinds too: it is the fallback shape, not a\n * fifth disjoint case.\n *\n * Extra fields (`run_id`, `id`, provider-specific metadata) are neither\n * required nor stripped: a successful parse hands the value straight back, so a\n * parse / re-serialize round trip is lossless.\n */\n\nexport type SpanStartEvent = {\n readonly kind: 'span_start'\n readonly span_id: string\n readonly name: string\n} & { readonly [key: string]: unknown }\n\nexport type SpanEndEvent = {\n readonly kind: 'span_end'\n readonly span_id: string\n} & { readonly [key: string]: unknown }\n\nexport type EmitEvent = {\n readonly kind: 'emit'\n} & { readonly [key: string]: unknown }\n\nexport type RunEndStatus = 'done' | 'failed' | 'aborted' | 'suspended'\n\nexport type RunEndEvent = {\n readonly kind: 'run_end'\n readonly status: RunEndStatus\n} & { readonly [key: string]: unknown }\n\nexport type CheckpointStatus = 'hit' | 'miss' | 'read_error'\n\nexport type CheckpointEvent = {\n readonly kind: 'checkpoint'\n readonly status: CheckpointStatus\n readonly key: string\n} & { readonly [key: string]: unknown }\n\nexport type StepReplayedEvent = {\n readonly kind: 'step_replayed'\n readonly step_id: string\n readonly suspend_ids: ReadonlyArray<string>\n} & { readonly [key: string]: unknown }\n\nexport type MapItemFailedEvent = {\n readonly kind: 'map_item_failed'\n readonly step_id: string\n readonly index: number\n readonly error: string\n} & { readonly [key: string]: unknown }\n\nexport type CustomTrajectoryEvent = {\n readonly kind: string\n} & { readonly [key: string]: unknown }\n\nexport type ParsedTrajectoryEvent =\n | SpanStartEvent\n | SpanEndEvent\n | EmitEvent\n | RunEndEvent\n | CheckpointEvent\n | StepReplayedEvent\n | MapItemFailedEvent\n | CustomTrajectoryEvent\n\nexport type TrajectoryParseResult =\n | { readonly success: true; readonly data: ParsedTrajectoryEvent }\n | { readonly success: false; readonly error: Error }\n\n/**\n * The wire gate: a non-array object carrying a string `kind`.\n *\n * True for every well-known kind as well, since `custom` is the fallback shape\n * rather than a disjoint case.\n */\nexport function is_custom_trajectory_event(value: unknown): value is CustomTrajectoryEvent {\n if (typeof value !== 'object' || value === null) return false\n if (Array.isArray(value)) return false\n return typeof (value as { kind?: unknown }).kind === 'string'\n}\n\n/** A composer span open: both `span_id` and `name` must be present as strings. */\nexport function is_span_start_event(value: unknown): value is SpanStartEvent {\n if (!is_custom_trajectory_event(value)) return false\n if (value.kind !== 'span_start') return false\n return typeof value['span_id'] === 'string' && typeof value['name'] === 'string'\n}\n\n/** A composer span close: `span_id` must be present as a string, `name` need not be. */\nexport function is_span_end_event(value: unknown): value is SpanEndEvent {\n if (!is_custom_trajectory_event(value)) return false\n return value.kind === 'span_end' && typeof value['span_id'] === 'string'\n}\n\n/** A `ctx.emit` event: the kind alone identifies it, the payload is the caller's. */\nexport function is_emit_event(value: unknown): value is EmitEvent {\n return is_custom_trajectory_event(value) && value.kind === 'emit'\n}\n\nconst RUN_END_STATUSES: ReadonlySet<string> = new Set(['done', 'failed', 'aborted', 'suspended'])\n\n/**\n * A terminal run event: `status` must be one of the known run outcomes, so the\n * narrowed type's `status` union is truthful. An unknown future status still\n * passes the wire gate as a custom event.\n */\nexport function is_run_end_event(value: unknown): value is RunEndEvent {\n if (!is_custom_trajectory_event(value)) return false\n if (value.kind !== 'run_end') return false\n const status = value['status']\n return typeof status === 'string' && RUN_END_STATUSES.has(status)\n}\n\nconst CHECKPOINT_STATUSES: ReadonlySet<string> = new Set(['hit', 'miss', 'read_error'])\n\n/**\n * A checkpoint lookup event: `status` must be a known lookup outcome and `key`\n * the store key that was consulted, for the same truthful-narrowing reason as\n * `is_run_end_event`.\n */\nexport function is_checkpoint_event(value: unknown): value is CheckpointEvent {\n if (!is_custom_trajectory_event(value)) return false\n if (value.kind !== 'checkpoint') return false\n const status = value['status']\n if (typeof status !== 'string' || !CHECKPOINT_STATUSES.has(status)) return false\n return typeof value['key'] === 'string'\n}\n\n/**\n * A replay report: a step marked `side_effect` started before its resumed run\n * reached the gates in `suspend_ids`, so the work it does was already paid for\n * once. `step_id` names the step, and every gate id must be a string.\n */\nexport function is_step_replayed_event(value: unknown): value is StepReplayedEvent {\n if (!is_custom_trajectory_event(value)) return false\n if (value.kind !== 'step_replayed') return false\n const suspend_ids = value['suspend_ids']\n if (!Array.isArray(suspend_ids)) return false\n const ids: ReadonlyArray<unknown> = suspend_ids\n return typeof value['step_id'] === 'string' && ids.every((id) => typeof id === 'string')\n}\n\n/**\n * A failed item of a `map` that settles: `step_id` names the map, `index` is\n * the item's position in the map's input, and `error` is the message. An\n * error that carried a `kind` adds it as `error_kind`.\n */\nexport function is_map_item_failed_event(value: unknown): value is MapItemFailedEvent {\n if (!is_custom_trajectory_event(value)) return false\n if (value.kind !== 'map_item_failed') return false\n return (\n typeof value['step_id'] === 'string' &&\n Number.isInteger(value['index']) &&\n typeof value['error'] === 'string'\n )\n}\n\n/**\n * Parse one wire value into a trajectory event, `safeParse`-shaped.\n *\n * On success `data` is the value itself, not a copy, so nothing on the line is\n * dropped or reordered on the way through.\n */\nexport function parse_trajectory_event(value: unknown): TrajectoryParseResult {\n if (!is_custom_trajectory_event(value)) {\n return {\n success: false,\n error: new Error(\"not a trajectory event: expected an object with a string 'kind'\"),\n }\n }\n return { success: true, data: value }\n}\n"],"mappings":";;;;;;;AAwGA,SAAgB,2BAA2B,OAAgD;CACzF,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,OAAO,OAAQ,MAA6B,SAAS;AACvD;;AAGA,SAAgB,oBAAoB,OAAyC;CAC3E,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,IAAI,MAAM,SAAS,cAAc,OAAO;CACxC,OAAO,OAAO,MAAM,eAAe,YAAY,OAAO,MAAM,YAAY;AAC1E;;AAGA,SAAgB,kBAAkB,OAAuC;CACvE,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,OAAO,MAAM,SAAS,cAAc,OAAO,MAAM,eAAe;AAClE;;AAGA,SAAgB,cAAc,OAAoC;CAChE,OAAO,2BAA2B,KAAK,KAAK,MAAM,SAAS;AAC7D;AAEA,MAAM,mCAAwC,IAAI,IAAI;CAAC;CAAQ;CAAU;CAAW;AAAW,CAAC;;;;;;AAOhG,SAAgB,iBAAiB,OAAsC;CACrE,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,IAAI,MAAM,SAAS,WAAW,OAAO;CACrC,MAAM,SAAS,MAAM;CACrB,OAAO,OAAO,WAAW,YAAY,iBAAiB,IAAI,MAAM;AAClE;AAEA,MAAM,sCAA2C,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAY,CAAC;;;;;;AAOtF,SAAgB,oBAAoB,OAA0C;CAC5E,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,IAAI,MAAM,SAAS,cAAc,OAAO;CACxC,MAAM,SAAS,MAAM;CACrB,IAAI,OAAO,WAAW,YAAY,CAAC,oBAAoB,IAAI,MAAM,GAAG,OAAO;CAC3E,OAAO,OAAO,MAAM,WAAW;AACjC;;;;;;AAOA,SAAgB,uBAAuB,OAA4C;CACjF,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,IAAI,MAAM,SAAS,iBAAiB,OAAO;CAC3C,MAAM,cAAc,MAAM;CAC1B,IAAI,CAAC,MAAM,QAAQ,WAAW,GAAG,OAAO;CACxC,MAAM,MAA8B;CACpC,OAAO,OAAO,MAAM,eAAe,YAAY,IAAI,OAAO,OAAO,OAAO,OAAO,QAAQ;AACzF;;;;;;AAOA,SAAgB,yBAAyB,OAA6C;CACpF,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,IAAI,MAAM,SAAS,mBAAmB,OAAO;CAC7C,OACE,OAAO,MAAM,eAAe,YAC5B,OAAO,UAAU,MAAM,QAAQ,KAC/B,OAAO,MAAM,aAAa;AAE9B;;;;;;;AAQA,SAAgB,uBAAuB,OAAuC;CAC5E,IAAI,CAAC,2BAA2B,KAAK,GACnC,OAAO;EACL,SAAS;EACT,uBAAO,IAAI,MAAM,iEAAiE;CACpF;CAEF,OAAO;EAAE,SAAS;EAAM,MAAM;CAAM;AACtC"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return t(this.context.count)},getNextContextId(){return t(this.context.count++)}};function t(t){let n=String(t),r=n.length-1;return e.context.id+(r?String.fromCharCode(96+r):``)+n}function n(t){e.context=t}var r=(e,t)=>e===t,i=Symbol(`solid-track`),a={equals:r},o=null,s=oe,c=1,l=2,u={owned:null,cleanups:null,context:null,owner:null},d=null,f=null,p=null,m=null,h=null,g=0;function _(e,t){let n=p,r=d,i=e.length===0,a=t===void 0?r:t,o=i?u:{owned:null,cleanups:null,context:a?a.context:null,owner:a},s=i?e:()=>e(()=>S(()=>N(o)));d=o,p=null;try{return A(s,!0)}finally{p=n,d=r}}function v(e,t){t=t?Object.assign({},a,t):a;let n={value:e,observers:null,observerSlots:null,comparator:t.equals||void 0};return[ie.bind(n),e=>(typeof e==`function`&&(e=f&&f.running&&f.sources.has(n)?e(n.tValue):e(n.value)),T(n,e))]}function y(e,t,n){E(O(e,t,!1,c))}function b(e,t,n){s=j;let r=O(e,t,!1,c),i=w&&ne(w);i&&(r.suspense=i),(!n||!n.render)&&(r.user=!0),h?h.push(r):E(r)}function x(e,t,n){n=n?Object.assign({},a,n):a;let r=O(e,t,!0,0);return r.observers=null,r.observerSlots=null,r.comparator=n.equals||void 0,E(r),ie.bind(r)}function S(e){if(p===null)return e();let t=p;p=null;try{return e()}finally{p=t}}function ee(e){return d===null||(d.cleanups===null?d.cleanups=[e]:d.cleanups.push(e)),e}var[C,te]=v(!1);function ne(e){let t;return d&&d.context&&(t=d.context[e.id])!==void 0?t:e.defaultValue}function re(e){let t=x(e),n=x(()=>fe(t()));return n.toArray=()=>{let e=n();return Array.isArray(e)?e:e==null?[]:[e]},n}var w;function ie(){let e=f&&f.running;if(this.sources&&(e?this.tState:this.state)){if((e?this.tState:this.state)===c)E(this);else{let e=m;m=null,A(()=>M(this),!1),m=e}}if(p){let e=this.observers;if(!e||e[e.length-1]!==p){let t=e?e.length:0;p.sources?(p.sources.push(this),p.sourceSlots.push(t)):(p.sources=[this],p.sourceSlots=[t]),e?(e.push(p),this.observerSlots.push(p.sources.length-1)):(this.observers=[p],this.observerSlots=[p.sources.length-1])}}return e&&f.sources.has(this)?this.tValue:this.value}function T(e,t,n){let r=f&&f.running&&f.sources.has(e)?e.tValue:e.value;if(!e.comparator||!e.comparator(r,t)){if(f){let r=f.running;(r||!n&&f.sources.has(e))&&(f.sources.add(e),e.tValue=t),r||(e.value=t)}else e.value=t;e.observers&&e.observers.length&&A(()=>{for(let t=0;t<e.observers.length;t+=1){let n=e.observers[t],r=f&&f.running;r&&f.disposed.has(n)||((r?!n.tState:!n.state)&&(n.pure?m.push(n):h.push(n),n.observers&&se(n)),r?n.tState=c:n.state=c)}if(m.length>1e6)throw m=[],Error()},!1)}return t}function E(e){if(!e.fn)return;N(e);let t=g;D(e,f&&f.running&&f.sources.has(e)?e.tValue:e.value,t),f&&!f.running&&f.sources.has(e)&&queueMicrotask(()=>{A(()=>{f&&(f.running=!0),p=d=e,D(e,e.tValue,t),p=d=null},!1)})}function D(e,t,n){let r,i=d,a=p;p=d=e;try{r=e.fn(t)}catch(t){return e.pure&&(f&&f.running?(e.tState=c,e.tOwned&&e.tOwned.forEach(N),e.tOwned=void 0):(e.state=c,e.owned&&e.owned.forEach(N),e.owned=null)),e.updatedAt=n+1,de(t)}finally{p=a,d=i}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&`observers`in e?T(e,r,!0):f&&f.running&&e.pure?(f.sources.has(e)||(e.value=r),f.sources.add(e),e.tValue=r):e.value=r,e.updatedAt=n)}function O(e,t,n,r=c,i){let a={fn:e,state:r,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:d,context:d?d.context:null,pure:n};return f&&f.running&&(a.state=0,a.tState=r),d===null||d!==u&&(f&&f.running&&d.pure?d.tOwned?d.tOwned.push(a):d.tOwned=[a]:d.owned?d.owned.push(a):d.owned=[a]),a}function k(e){let t=f&&f.running;if((t?e.tState:e.state)===0)return;if((t?e.tState:e.state)===l)return M(e);if(e.suspense&&S(e.suspense.inFallback))return e.suspense.effects.push(e);let n=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<g);){if(t&&f.disposed.has(e))return;(t?e.tState:e.state)&&n.push(e)}for(let r=n.length-1;r>=0;r--){if(e=n[r],t){let t=e,i=n[r+1];for(;(t=t.owner)&&t!==i;)if(f.disposed.has(t))return}if((t?e.tState:e.state)===c)E(e);else if((t?e.tState:e.state)===l){let t=m;m=null,A(()=>M(e,n[0]),!1),m=t}}}function A(e,t){if(m)return e();let n=!1;t||(m=[]),h?n=!0:h=[],g++;try{let t=e();return ae(n),t}catch(e){n||(h=null),m=null,de(e)}}function ae(e){if(m&&=(oe(m),null),e)return;let t;if(f){if(!f.promises.size&&!f.queue.size){let e=f.sources,n=f.disposed;h.push.apply(h,f.effects),t=f.resolve;for(let e of h)`tState`in e&&(e.state=e.tState),delete e.tState;f=null,A(()=>{for(let e of n)N(e);for(let t of e){if(t.value=t.tValue,t.owned)for(let e=0,n=t.owned.length;e<n;e++)N(t.owned[e]);t.tOwned&&(t.owned=t.tOwned),delete t.tValue,delete t.tOwned,t.tState=0}te(!1)},!1)}else if(f.running){f.running=!1,f.effects.push.apply(f.effects,h),h=null,te(!0);return}}let n=h;h=null,n.length&&A(()=>s(n),!1),t&&t()}function oe(e){for(let t=0;t<e.length;t++)k(e[t])}function j(t){let r,i=0;for(r=0;r<t.length;r++){let e=t[r];e.user?t[i++]=e:k(e)}if(e.context){if(e.count){e.effects||=[],e.effects.push(...t.slice(0,i));return}n()}for(e.effects&&(e.done||!e.count)&&(t=[...e.effects,...t],i+=e.effects.length,delete e.effects),r=0;r<i;r++)k(t[r])}function M(e,t){let n=f&&f.running;n?e.tState=0:e.state=0;for(let r=0;r<e.sources.length;r+=1){let i=e.sources[r];if(i.sources){let e=n?i.tState:i.state;e===c?i!==t&&(!i.updatedAt||i.updatedAt<g)&&k(i):e===l&&M(i,t)}}}function se(e){let t=f&&f.running;for(let n=0;n<e.observers.length;n+=1){let r=e.observers[n];(t?!r.tState:!r.state)&&(t?r.tState=l:r.state=l,r.pure?m.push(r):h.push(r),r.observers&&se(r))}}function N(e){let t;if(e.sources)for(;e.sources.length;){let t=e.sources.pop(),n=e.sourceSlots.pop(),r=t.observers;if(r&&r.length){let e=r.pop(),i=t.observerSlots.pop();n<r.length&&(e.sourceSlots[i]=n,r[n]=e,t.observerSlots[n]=i)}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)N(e.tOwned[t]);delete e.tOwned}if(f&&f.running&&e.pure)ce(e,!0);else if(e.owned){for(t=e.owned.length-1;t>=0;t--)N(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}f&&f.running?e.tState=0:e.state=0}function ce(e,t){if(t||(e.tState=0,f.disposed.add(e)),e.owned)for(let t=0;t<e.owned.length;t++)ce(e.owned[t])}function le(e){return e instanceof Error?e:Error(typeof e==`string`?e:`Unknown error`,{cause:e})}function ue(e,t,n){try{for(let n of t)n(e)}catch(e){de(e,n&&n.owner||null)}}function de(e,t=d){let n=o&&t&&t.context&&t.context[o],r=le(e);if(!n)throw r;h?h.push({fn(){ue(r,n,t)},state:c}):ue(r,n,t)}function fe(e){if(typeof e==`function`&&!e.length)return fe(e());if(Array.isArray(e)){let t=[];for(let n=0;n<e.length;n++){let r=fe(e[n]);if(Array.isArray(r)){if(r.length<32768)t.push.apply(t,r);else for(let e=0;e<r.length;e++)t.push(r[e])}else t.push(r)}return t}return e}var pe=Symbol(`fallback`);function me(e){for(let t=0;t<e.length;t++)e[t]()}function he(e,t,n={}){let r=[],a=[],o=[],s=0,c=t.length>1?[]:null;return ee(()=>me(o)),()=>{let l=e()||[],u=l.length,d,f;return l[i],S(()=>{let e,t,i,m,h,g,v,y,b;if(u===0)s!==0&&(me(o),o=[],r=[],a=[],s=0,c&&=[]),n.fallback&&(r=[pe],a[0]=_(e=>(o[0]=e,n.fallback())),s=1);else if(s===0){for(a=Array(u),f=0;f<u;f++)r[f]=l[f],a[f]=_(p);s=u}else{for(i=Array(u),m=Array(u),c&&(h=Array(u)),g=0,v=Math.min(s,u);g<v&&r[g]===l[g];g++);for(v=s-1,y=u-1;v>=g&&y>=g&&r[v]===l[y];v--,y--)i[y]=a[v],m[y]=o[v],c&&(h[y]=c[v]);for(e=new Map,t=Array(y+1),f=y;f>=g;f--)b=l[f],d=e.get(b),t[f]=d===void 0?-1:d,e.set(b,f);for(d=g;d<=v;d++)b=r[d],f=e.get(b),f!==void 0&&f!==-1?(i[f]=a[d],m[f]=o[d],c&&(h[f]=c[d]),f=t[f],e.set(b,f)):o[d]();for(f=g;f<u;f++)f in i?(a[f]=i[f],o[f]=m[f],c&&(c[f]=h[f],c[f](f))):a[f]=_(p);a=a.slice(0,s=u),r=l.slice(0)}return a});function p(e){if(o[f]=e,c){let[e,n]=v(f);return c[f]=n,t(l[f],e)}return t(l[f])}}}function P(e,t){return S(()=>e(t||{}))}var ge=e=>`Stale read from <${e}>.`;function F(e){let t=`fallback`in e&&{fallback:()=>e.fallback};return x(he(()=>e.each,e.children,t||void 0))}function I(e){let t=e.keyed,n=x(()=>e.when,void 0,void 0),r=t?n:x(n,void 0,{equals:(e,t)=>!e==!t});return x(()=>{let i=r();if(i){let a=e.children;return typeof a==`function`&&a.length>0?S(()=>a(t?i:()=>{if(!S(r))throw ge(`Show`);return n()})):a}return e.fallback},void 0,void 0)}function _e(e){let t=re(()=>e.children),n=x(()=>{let e=t(),n=Array.isArray(e)?e:[e],r=()=>void 0;for(let e=0;e<n.length;e++){let t=e,i=n[e],a=r,o=x(()=>a()?void 0:i.when,void 0,void 0),s=i.keyed?o:x(o,void 0,{equals:(e,t)=>!e==!t});r=()=>a()||(s()?[t,o,i]:void 0)}return r});return x(()=>{let t=n()();if(!t)return e.fallback;let[r,i,a]=t,o=a.children;return typeof o==`function`&&o.length>0?S(()=>o(a.keyed?i():()=>{if(S(n)()?.[0]!==r)throw ge(`Match`);return i()})):o},void 0,void 0)}function ve(e){return e}var ye=e=>x(()=>e());function be(e,t,n){let r=n.length,i=t.length,a=r,o=0,s=0,c=t[i-1].nextSibling,l=null;for(;o<i||s<a;)if(t[o]===n[s])o++,s++;else{for(;t[i-1]===n[a-1];)i--,a--;if(i===o){let t=a<r?s?n[s-1].nextSibling:n[a-s]:c;for(;s<a;)e.insertBefore(n[s++],t)}else if(a===s)for(;o<i;)(!l||!l.has(t[o]))&&t[o].remove(),o++;else if(t[o]===n[a-1]&&n[s]===t[i-1]){let r=t[--i].nextSibling;e.insertBefore(n[s++],t[o++].nextSibling),e.insertBefore(n[--a],r),t[i]=n[a]}else{if(!l){l=new Map;let e=s;for(;e<a;)l.set(n[e],e++)}let r=l.get(t[o]);if(r!=null){if(s<r&&r<a){let c=o,u=1,d;for(;++c<i&&c<a&&(d=l.get(t[c]))!=null&&d===r+u;)u++;if(u>r-s){let i=t[o];for(;s<r;)e.insertBefore(n[s++],i)}else e.replaceChild(n[s++],t[o++])}else o++}else t[o++].remove()}}}var xe=`_$DX_DELEGATE`;function Se(e,t,n,r={}){let i;return _(r=>{i=r,t===document?e():z(t,e(),!n&&t.firstChild?null:void 0,n)},r.owner),()=>{i(),t.textContent=``}}function L(e,t,n,r){let i,a=()=>{let t=r?document.createElementNS(`http://www.w3.org/1998/Math/MathML`,`template`):document.createElement(`template`);return t.innerHTML=e,n?t.content.firstChild.firstChild:r?t.firstChild:t.content.firstChild},o=t?()=>S(()=>document.importNode(i||=a(),!0)):()=>(i||=a()).cloneNode(!0);return o.cloneNode=o,o}function Ce(e,t=window.document){let n=t[xe]||(t[xe]=new Set);for(let r=0,i=e.length;r<i;r++){let i=e[r];n.has(i)||(n.add(i),t.addEventListener(i,Ee))}}function R(e,t,n){Te(e)||(n==null?e.removeAttribute(t):e.setAttribute(t,n))}function we(e,t){Te(e)||(t==null?e.removeAttribute(`class`):e.className=t)}function z(e,t,n,r){if(n!==void 0&&!r&&(r=[]),typeof t!=`function`)return B(e,t,r,n);y(r=>B(e,t(),r,n),r)}function Te(t){return!!e.context&&!e.done&&(!t||t.isConnected)}function Ee(t){if(e.registry&&e.events&&e.events.find(([e,n])=>n===t))return;let n=t.target,r=`$$${t.type}`,i=t.target,a=t.currentTarget,o=e=>Object.defineProperty(t,"target",{configurable:!0,value:e}),s=()=>{let e=n[r];if(e&&!n.disabled){let i=n[`${r}Data`];if(i===void 0?e.call(n,t):e.call(n,i,t),t.cancelBubble)return}return n.host&&typeof n.host!=`string`&&!n.host._$host&&n.contains(t.target)&&o(n.host),!0},c=()=>{for(;s()&&(n=n._$host||n.parentNode||n.host););};Object.defineProperty(t,"currentTarget",{configurable:!0,get(){return n||document}}),e.registry&&!e.done&&(e.done=_$HY.done=!0);try{if(t.composedPath){let e=t.composedPath();o(e[0]);for(let t=0;t<e.length-2&&(n=e[t],s());t++){if(n._$host){n=n._$host,c();break}if(n.parentNode===a)break}}else c();o(i)}finally{t=n=null}}function B(e,t,n,r,i){let a=Te(e);if(a){!n&&(n=[...e.childNodes]);let t=[];for(let e=0;e<n.length;e++){let r=n[e];r.nodeType===8&&r.data.slice(0,2)===`!$`?r.remove():t.push(r)}n=t}for(;typeof n==`function`;)n=n();if(t===n)return n;let o=typeof t,s=r!==void 0;if(e=s&&n[0]&&n[0].parentNode||e,o===`string`||o===`number`){if(a||o===`number`&&(t=t.toString(),t===n))return n;if(s){let i=n[0];i&&i.nodeType===3?i.data!==t&&(i.data=t):i=document.createTextNode(t),n=V(e,n,r,i)}else n=n!==``&&typeof n==`string`?e.firstChild.data=t:e.textContent=t}else if(t==null||o===`boolean`){if(a)return n;n=V(e,n,r)}else if(o===`function`)return y(()=>{let i=t();for(;typeof i==`function`;)i=i();n=B(e,i,n,r)}),()=>n;else if(Array.isArray(t)){let o=[],c=n&&Array.isArray(n);if(De(o,t,n,i))return y(()=>n=B(e,o,n,r,!0)),()=>n;if(a){if(!o.length)return n;if(r===void 0)return n=[...e.childNodes];let t=o[0];if(t.parentNode!==e)return n;let i=[t];for(;(t=t.nextSibling)!==r;)i.push(t);return n=i}if(o.length===0){if(n=V(e,n,r),s)return n}else c?n.length===0?Oe(e,o,r):be(e,n,o):(n&&V(e),Oe(e,o));n=o}else if(t.nodeType){if(a&&t.parentNode)return n=s?[t]:t;if(Array.isArray(n)){if(s)return n=V(e,n,r,t);V(e,n,null,t)}else n==null||n===``||!e.firstChild?e.appendChild(t):e.replaceChild(t,e.firstChild);n=t}return n}function De(e,t,n,r){let i=!1;for(let a=0,o=t.length;a<o;a++){let o=t[a],s=n&&n[e.length],c;if(o!=null&&o!==!0&&o!==!1){if((c=typeof o)==`object`&&o.nodeType)e.push(o);else if(Array.isArray(o))i=De(e,o,s)||i;else if(c===`function`){if(r){for(;typeof o==`function`;)o=o();i=De(e,Array.isArray(o)?o:[o],Array.isArray(s)?s:[s])||i}else e.push(o),i=!0}else{let t=String(o);s&&s.nodeType===3&&s.data===t?e.push(s):e.push(document.createTextNode(t))}}}return i}function Oe(e,t,n=null){for(let r=0,i=t.length;r<i;r++)e.insertBefore(t[r],n)}function V(e,t,n,r){if(n===void 0)return e.textContent=``;let i=r||document.createTextNode(``);if(t.length){let r=!1;for(let a=t.length-1;a>=0;a--){let o=t[a];if(i!==o){let t=o.parentNode===e;!r&&!a?t?e.replaceChild(i,o):e.insertBefore(i,n):t&&o.remove()}else r=!0}}else e.insertBefore(i,n);return[i]}var ke=2e3,Ae=1e3;function je(e,t){let{speed:n,floor_ms:r,cap_ms:i}=t,a=[],o=0,s=null;for(let t of e){if(s!==null){let e=t-s,a=(e>0?Math.max(e,r):0)/n;o+=i===null?a:Math.min(a,i)}a.push(o),s=t}return{wall_times:a,wall_total_ms:o}}function Me(e,t){return je(e,{speed:t.speed,floor_ms:Ae,cap_ms:t.compress?ke:null})}function Ne(e,t,n){let{wall_times:r,wall_total_ms:i}=e,a=r.length;if(a===0)return{index:0,t_plus_ms:0,done:!0};let o=Math.max(0,n);if(o>=i)return{index:a-1,t_plus_ms:t[a-1]??0,done:!0};let s=0;for(let e=1;e<a&&!((r[e]??0)>o);e+=1)s=e;let c=r[s]??0,l=r[s+1]??i,u=t[s]??0,d=t[s+1]??u,f=(o-c)/(l-c);return{index:s,t_plus_ms:u+f*(d-u),done:!1}}var Pe={playing:!1,stepping:!1,speed:1,compress:!0,loop:!1,anchor_index:0,anchor_now_ms:0};function Fe(e,t,n,r){if(e.playing)return{...e,playing:!1};if(n<2)return e;let i=t===null||t>=n-1;return{...e,playing:!0,anchor_index:i?0:t,anchor_now_ms:r}}function Ie(e,t,n){let r=e.speed===1?2:e.speed===2?3:1;return Ke({...e,speed:r},t,n)}function Le(e,t,n){return Ke({...e,compress:!e.compress},t,n)}function Re(e){return e.stepping?{...e,stepping:!1}:{...e,stepping:!0,playing:!1}}function ze(e,t){return e===null||e>=t-1?0:e}function Be(e){return e.stepping?`NEXT`:e.playing?`PAUSE`:`PLAY`}function Ve(e){return{...e,loop:!e.loop}}function He(e,t,n){return Ke(e,t,n)}function Ue(e){return e.playing?{...e,playing:!1}:e}function We(e,t,n){return(e.wall_times[t.anchor_index]??0)+(n-t.anchor_now_ms)}function Ge(e,t,n){return e.playing&&n-t>=2500}function Ke(e,t,n){return e.playing?{...e,anchor_index:t,anchor_now_ms:n}:e}var qe=L(`<button type=button>`),Je=L(`<div class=playback data-testid=playback>`);function H(e){return(()=>{var t=qe();return t.$$click=()=>e.on_click(),z(t,()=>e.label),y(n=>{var r=e.play?`pb-button pb-button-play`:`pb-button`,i=e.testid,a=e.active?`true`:void 0;return r!==n.e&&we(t,n.e=r),i!==n.t&&R(t,`data-testid`,n.t=i),a!==n.a&&R(t,`data-active`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}function Ye(e){return(()=>{var t=Je();return z(t,P(H,{testid:`play-toggle`,get label(){return Be(e.playback)},play:!0,get on_click(){return e.on_play_chip}}),null),z(t,P(H,{testid:`step-toggle`,label:`STEP`,get active(){return e.playback.stepping},get on_click(){return e.on_toggle_step}}),null),z(t,P(H,{testid:`speed`,get label(){return`${e.playback.speed}X`},get on_click(){return e.on_cycle_speed}}),null),z(t,P(H,{testid:`compress-toggle`,label:`COMPRESS`,get active(){return e.playback.compress},get on_click(){return e.on_toggle_compress}}),null),z(t,P(H,{testid:`loop-toggle`,label:`LOOP`,get active(){return e.playback.loop},get on_click(){return e.on_toggle_loop}}),null),z(t,P(H,{testid:`density-toggle`,label:`DENSITY`,get active(){return e.density},get on_click(){return e.on_toggle_density}}),null),t})()}Ce([`click`]);function Xe(e){let{fold_t_plus_ms:t,run_over:n,connected:r,received_at_ms:i,now_ms:a}=e;return n||!r||i===null?t:t+Math.max(0,a-i)}var Ze=8,Qe=`·`.repeat(Ze);function $e(e){return e.slice(0,Ze)}function U(e){let t=Math.max(0,Math.floor(e));if(t<1e3)return`${t}MS`;if(t<6e4)return`${(Math.floor(t/10)/100).toFixed(2)}S`;let n=Math.floor(t/6e4),r=Math.floor(t%6e4/1e3);return`${n}M${String(r).padStart(2,`0`)}S`}function et(e){return`T+${U(e)}`}function tt(e){return e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function nt(e){return e===1?`RETRY`:`RETRIES`}var rt={text:`·`,role:`sep`};function it(e){return[{text:et(e.t_plus_ms),role:`value`},rt,{text:String(e.retries_absorbed),role:`value`},{text:`${nt(e.retries_absorbed)} ABSORBED`,role:`word`},rt,{text:`SCARS`,role:`word`},{text:String(e.scars),role:e.scars>0?`scar`:`value`},rt,{text:tt(e.cost_usd),role:`value`}]}var W={status:`pending`,occurrences:[],scarred:!1,suspended:!1,turn_retries:0,cost_usd:0,emits:0,checkpoint:null};function at(e){let t=new Map,n=new Map;return e!==null&&ot(e,t,n),{run_id:null,run_status:null,t0_ts:null,last_ts:null,retries_absorbed:0,scars:0,cost_usd:0,unattributed_usd:0,nodes:n,spans:new Map,open_spans:[],kinds:t}}function ot(e,t,n){t.has(e.id)||(t.set(e.id,e.kind),n.set(e.id,W));for(let r of e.children??[])ot(r,t,n)}function st(e){return e.t0_ts===null||e.last_ts===null?0:Math.max(0,e.last_ts-e.t0_ts)}function ct(e,t){if(!lt(t))return e;let n=t,r=ut(n,`ts`),i={...e,run_id:e.run_id??G(n,`run_id`),t0_ts:e.t0_ts??r,last_ts:r??e.last_ts};switch(n.kind){case`span_start`:return dt(i,n,r);case`span_end`:return ft(i,n,r);case`suspended`:return _t(i,n);case`emit`:return vt(i,n);case`checkpoint`:return bt(i,n);case`turn_retry`:return xt(i,n);case`cost`:return St(i,n);case`run_end`:return wt(i,n);default:return i}}function lt(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:typeof e.kind==`string`}function G(e,t){let n=e[t];return typeof n==`string`?n:null}function ut(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function dt(e,t,n){let r=G(t,`span_id`),i=G(t,`name`);if(r===null||i===null)return e;let a=G(t,`parent_span_id`),o=G(t,`id`),s=new Map(e.spans);s.set(r,{name:i,node_id:o,parent_span_id:a,open:!0,failed_descendant:!1,failed_joined_descendant:!1});let c={...e,spans:s,open_spans:[...e.open_spans,r]};if(o===null)return c;let l=e.nodes.get(o)??W,u={span_id:r,parent_span_id:a,status:`active`,started_ts:n,ended_ts:null,error:null},d=new Map(e.nodes);return d.set(o,Tt({...l,occurrences:[...l.occurrences,u],suspended:!1})),{...c,nodes:d}}function ft(e,t,n){let r=G(t,`span_id`);if(r===null)return e;let i=e.spans.get(r);if(i===void 0||!i.open)return e;let a=t.error!==void 0,o=pt(e,r,i,a),s=new Map(o.nodes),c=mt(o,r,i,a,n,G(t,`error`)),l={scars:o.scars,retries_absorbed:o.retries_absorbed};if(a){let e=ht(o,i,c,l);c=e.node,l={scars:e.scars,retries_absorbed:e.retries_absorbed}}return c!==void 0&&i.node_id!==null&&s.set(i.node_id,Tt(c)),a&&(l=gt(o,r,i,s,l)),{...o,nodes:s,...l}}function pt(e,t,n,r){let i=new Map(e.spans);if(i.set(t,{...n,open:!1}),r&&n.parent_span_id!==null){let e=i.get(n.parent_span_id);e!==void 0&&i.set(n.parent_span_id,{...e,failed_descendant:!0,failed_joined_descendant:e.failed_joined_descendant||n.node_id!==null||n.failed_joined_descendant})}return{...e,spans:i,open_spans:e.open_spans.filter(e=>e!==t)}}function mt(e,t,n,r,i,a){if(n.node_id===null)return;let o=e.nodes.get(n.node_id);if(o===void 0)return;let s=r?`failed`:`done`;return{...o,occurrences:o.occurrences.map(e=>e.span_id===t?{...e,status:s,ended_ts:i,error:a}:e)}}function ht(e,t,n,r){if(n?.suspended===!0)return{...r,node:n};if(Ot(e,t)){let e=+!t.failed_descendant;return{...r,retries_absorbed:r.retries_absorbed+e,node:n}}return n===void 0||t.failed_joined_descendant||n.scarred?{...r,node:n}:{...r,scars:r.scars+1,node:{...n,scarred:!0}}}function gt(e,t,n,r,i){if(Dt(e,n)!==`retry`||Ot(e,n))return i;let a=At(r,t);return a===null||a.node.scarred?i:(r.set(a.id,{...a.node,scarred:!0}),{scars:i.scars+1,retries_absorbed:Math.max(0,i.retries_absorbed-1)})}function _t(e,t){let n=G(t,`step_id`);if(n===null)return e;let r=e.nodes.get(n)??W,i=new Map(e.nodes);return i.set(n,Tt({...r,suspended:!0})),{...e,nodes:i}}function vt(e,t){let n=kt(e,G(t,`span_id`));if(n===null)return e;let r=e.nodes.get(n)??W,i=new Map(e.nodes);return i.set(n,{...r,emits:r.emits+1}),{...e,nodes:i}}function yt(e){return e===`hit`||e===`miss`||e===`read_error`}function bt(e,t){let n=G(t,`id`),r=G(t,`status`);if(n===null||r===null||!yt(r))return e;let i=e.nodes.get(n)??W,a=new Map(e.nodes);return a.set(n,{...i,checkpoint:r}),{...e,nodes:a}}function xt(e,t){let n=e.retries_absorbed+1,r=kt(e,G(t,`span_id`));if(r===null)return{...e,retries_absorbed:n};let i=e.nodes.get(r)??W,a=new Map(e.nodes);return a.set(r,{...i,turn_retries:i.turn_retries+1}),{...e,retries_absorbed:n,nodes:a}}function St(e,t){let n=ut(t,`total_usd`);if(n===null)return e;let r=e.cost_usd+n,i=kt(e,G(t,`span_id`));if(i===null)return{...e,cost_usd:r,unattributed_usd:e.unattributed_usd+n};let a=e.nodes.get(i)??W,o=new Map(e.nodes);return o.set(i,{...a,cost_usd:a.cost_usd+n}),{...e,cost_usd:r,nodes:o}}function Ct(e){return e===`done`||e===`failed`||e===`aborted`||e===`suspended`}function wt(e,t){let n=G(t,`status`);return n===null||!Ct(n)?e:{...e,run_status:n}}function Tt(e){return{...e,status:Et(e)}}function Et(e){if(e.suspended)return`suspended`;if(e.occurrences.some(e=>e.status===`active`))return`active`;let t=e.occurrences[e.occurrences.length-1];return t===void 0?`pending`:t.status===`failed`?`failed`:`done`}function Dt(e,t){if(t.node_id!==null){let n=e.kinds.get(t.node_id);if(n!==void 0)return n}return t.name}function Ot(e,t){let n=e.spans.size+1,r=t.parent_span_id;for(;r!==null&&n>0;){--n;let t=e.spans.get(r);if(t===void 0)return!1;if(t.open&&Dt(e,t)===`retry`)return!0;r=t.parent_span_id}return!1}function kt(e,t){let n=t??e.open_spans[e.open_spans.length-1]??null;if(n===null)return null;let r=e.spans.size+1,i=e.spans.get(n);for(;i!==void 0&&r>0;){if(--r,i.node_id!==null)return i.node_id;if(i.parent_span_id===null)return null;i=e.spans.get(i.parent_span_id)}return null}function At(e,t){for(let[n,r]of e){let e=r.occurrences[r.occurrences.length-1];if(e?.status===`failed`&&e.parent_span_id===t)return{id:n,node:r}}return null}var K={margin:72,branch_pitch:92,corner_radius:24,label_clear:16,name_drop:38,meta_drop:20,group_label_rise:52,group_tick_length:14,tick_pitch:30,comb_pitch:18,decade:10,decade_gap:8,node_pitch:128,entry_stub:28,lane_lead:56,junction_gap:36,junction_label_drop:37,loop_radius:46,basin_radius:32,basin_shoulder:108,basin_drop:92,group_text_indent:22,tick_lead:72,tick_reserve:160,puck_radius:7,junction_radius:5.5,terminus_radius:6.5,terminus_ring_radius:12,name_px:15,min_name_px:11},jt=K.min_name_px/K.name_px,Mt=10,Nt=4,Pt=11,Ft=K.name_drop+K.meta_drop+Nt,q=4,It=K.group_label_rise+Pt,Lt=K.label_clear+Pt,Rt=K.junction_label_drop+Nt,zt=K.basin_drop+q+Nt,Bt=40,Vt=40,Ht=8,Ut=new Set([`parallel`,`branch`,`adversarial`,`ensemble`,`tournament`,`consensus`]),Wt=new Set([`retry`,`loop`]);function Gt(e){let t={nodes:[],junctions:[],segments:[],group_labels:[],tick_lanes:[]};if(e===null)return{width:2*K.margin,height:2*K.margin,spine_y:K.margin,...t};let n=Kt(e),r=K.margin+n.above,i=K.margin+K.entry_stub;return t.segments.push({role:`entry`,from:null,to:n.id,path:`M ${K.margin} ${r} H ${i}`}),n.place(i,r,t,0),sn(t,n.exit_glyph),{width:i+n.width+K.margin,height:r+n.below+K.margin,spine_y:r,...t}}function Kt(e){let t=(e.children??[]).map(Kt);return Ut.has(e.kind)&&t.length>0?en(e,t):Wt.has(e.kind)?tn(e,t):e.kind===`fallback`&&t.length>=2?an(e,t):e.kind===`map`?on(e,t):t.length>0?{id:e.id,...Yt(t)}:Jt(e)}function qt(e){let t=e.config?.display_name;return typeof t==`string`&&t.length>0?t:e.id}function Jt(e){return{id:e.id,width:0,above:Mt,below:Ft,exit_glyph:e.id,place:(t,n,r,i)=>{let a=n+i+K.name_drop;r.nodes.push({id:e.id,kind:e.kind,label:qt(e),center:{x:t,y:n},radius:K.puck_radius,terminus:!1,name_anchor:{x:t,y:a},meta_anchor:{x:t,y:a+K.meta_drop}})}}}function Yt(e){let t=K.node_pitch*Math.max(0,e.length-1),n=e.reduce((e,t)=>e+t.width,t),r=null;for(let t of e)r=t.exit_glyph??r;return{width:n,above:e.reduce((e,t)=>Math.max(e,t.above),0),below:e.reduce((e,t)=>Math.max(e,t.below),0),exit_glyph:r,place:(t,n,r,i)=>{let a=t,o=null;for(let t of e)o!==null&&(r.segments.push({role:`line`,from:o.id,to:t.id,path:`M ${a} ${n} H ${a+K.node_pitch}`}),a+=K.node_pitch),t.place(a,n,r,i),a+=t.width,o=t}}}function Xt(e){let t=(e-1)/2,n=[];for(let r=0;r<e;r+=1){let e=r-t,i=Number.isInteger(e)?e:e+.5*Math.sign(e);n.push(i*K.branch_pitch)}return n}function Zt(e){let t=Xt(e.length),n=[],r=0,i=null;for(let[a,o]of e.entries()){let e=(t[a]??0)+r;if(i!==null){let t=i.box.below+o.above+K.label_clear,n=e-i.offset;n<t&&(r+=t-n,e+=t-n)}n.push(e),i={box:o,offset:e}}let a=Math.round(((n[0]??0)+(n[n.length-1]??0))/2);return n.map(e=>e-a)}function Qt(e,t,n,r){if(r===t)return`M ${e} ${t} H ${n}`;let i=K.corner_radius,a=e+i,o=r>t?1:-1;return`M ${e} ${t} Q ${a} ${t} ${a} ${t+o*i} L ${a} ${r-o*i} Q ${a} ${r} ${a+i} ${r} H ${n}`}function $t(e,t,n,r){let i=K.corner_radius;if(n===r)return`M ${e} ${r} H ${t+2*i}`;let a=t+i,o=n>r?-1:1;return`M ${e} ${n} H ${t} Q ${a} ${n} ${a} ${n+o*i} L ${a} ${r-o*i} Q ${a} ${r} ${a+i} ${r}`}function en(e,t){let n=Zt(t),r=2*K.corner_radius,i=t.reduce((e,t)=>Math.max(e,t.width),0),a=`${e.id}:junction`,o=n[0]??0,s=n[n.length-1]??0,c=t[0],l=t[t.length-1];return{id:e.id,width:r+K.lane_lead+i+K.lane_lead+r+K.junction_gap,above:-o+Math.max(c?.above??0,It),below:Math.max(s+(l?.below??0),Rt),exit_glyph:null,place:(s,c,l)=>{let u=s+r+K.lane_lead,d=u+i+K.lane_lead,f=d+r,p=f+K.junction_gap;for(let[r,i]of t.entries()){let t=c+(n[r]??0);l.segments.push({role:`branch_in`,from:e.id,to:i.id,path:Qt(s,c,u,t)}),i.place(u,t,l,0),l.segments.push({role:`branch_out`,from:i.id,to:a,path:$t(u+i.width,d,t,c)})}l.segments.push({role:`line`,from:e.id,to:a,path:`M ${f} ${c} H ${p}`}),l.junctions.push({id:a,owner:e.id,center:{x:p,y:c},radius:K.junction_radius,label_anchor:{x:p,y:c+K.junction_label_drop}});let m=c+o-K.group_label_rise;l.group_labels.push({owner:e.id,tick:{x:s+K.corner_radius,y:m-q},text_anchor:{x:s+K.corner_radius+K.group_text_indent,y:m}})}}}function tn(e,t){let n=Yt(t);if(n.width>0)return nn(e,n);let r=K.loop_radius,i=t[0]?.id??e.id;return{id:e.id,width:2*r,above:r+Lt,below:r+Ft,exit_glyph:n.exit_glyph,place:(t,a,o)=>{n.place(t,a,o,r);let s=t+2*r;o.segments.push({role:`loop_upper`,from:e.id,to:i,path:`M ${t} ${a} A ${r} ${r} 0 0 1 ${s} ${a}`}),o.segments.push({role:`loop_lower`,from:e.id,to:i,path:`M ${t} ${a} A ${r} ${r} 0 0 0 ${s} ${a}`});let c=a-r;o.group_labels.push({owner:e.id,tick:{x:s+K.label_clear,y:c-K.label_clear-q},text_anchor:{x:s+K.label_clear+K.group_text_indent,y:c-K.label_clear}})}}}function nn(e,t){let n=K.corner_radius,r=t.below+Vt;return{id:e.id,width:t.width,above:Math.max(t.above,It),below:r+Ht,exit_glyph:t.exit_glyph,place:(i,a,o)=>{t.place(i,a,o,0);let s=i+t.width,c=a+r;o.segments.push({role:`loop_return`,from:e.id,to:e.id,path:`M ${s} ${a} Q ${s+n} ${a} ${s+n} ${a+n} L ${s+n} ${c-n} Q ${s+n} ${c} ${s} ${c} H ${i} Q ${i-n} ${c} ${i-n} ${c-n} L ${i-n} ${a+n} Q ${i-n} ${a} ${i} ${a}`});let l=a-K.group_label_rise;o.group_labels.push({owner:e.id,tick:{x:i,y:l-q},text_anchor:{x:i+K.group_text_indent,y:l}})}}}function rn(e,t,n,r){let i=K.basin_radius,a=t+r,o=e+i,s=e+n-i;return`M ${e} ${t} Q ${o} ${t} ${o} ${t+i} L ${o} ${a-i} Q ${o} ${a} ${e+2*i} ${a} H ${e+n-2*i} Q ${s} ${a} ${s} ${a-i} L ${s} ${t+i} Q ${s} ${t} ${e+n} ${t}`}function an(e,t){let n=t[0];if(n===void 0)return Jt(e);let r=t.slice(1),i=[],a=K.basin_drop,o=null;for(let e of r)o!==null&&(a+=Math.max(K.basin_drop,o.below+e.above+K.label_clear)),i.push(a),o=e;let s=n.width+2*K.basin_shoulder,c=i[i.length-1]??K.basin_drop,l=r[r.length-1];return{id:e.id,width:s,above:n.above,below:c+Math.max(l?.below??0,zt),exit_glyph:n.exit_glyph,place:(t,a,o)=>{o.segments.push({role:`line`,from:e.id,to:n.id,path:`M ${t} ${a} H ${t+s}`}),n.place(t+K.basin_shoulder,a,o,0);for(let[n,c]of r.entries()){let r=i[n]??K.basin_drop;o.segments.push({role:`basin`,from:e.id,to:c.id,path:rn(t,a,s,r)}),c.place(t+(s-c.width)/2,a+r,o,0)}let l=a+c+K.basin_drop+q;o.group_labels.push({owner:e.id,tick:{x:t+Bt,y:l-q},text_anchor:{x:t+Bt+K.group_text_indent,y:l}})}}}function on(e,t){let n=Yt(t),r=n.width+K.tick_reserve,i=t[t.length-1]?.id??e.id;return{id:e.id,width:r,above:n.above,below:n.below,exit_glyph:n.exit_glyph,place:(t,a,o,s)=>{n.place(t,a,o,s),o.segments.push({role:`line`,from:i,to:e.id,path:`M ${t+n.width} ${a} H ${t+r}`}),o.tick_lanes.push({owner:e.id,y:a,x0:t+n.width+K.tick_lead,x1:t+r})}}}function sn(e,t){if(t!==null)for(let n=e.nodes.length-1;n>=0;--n){let r=e.nodes[n];if(r?.id===t){e.nodes[n]={...r,terminus:!0,radius:K.terminus_radius};return}}}function cn(e,t){if(!Number.isInteger(e)||e<=0)return{xs:[],decades:[],pitch:0};let n=e>K.decade,r=n?K.comb_pitch:K.tick_pitch,i=[];for(let t=0;t<e;t+=1){let e=n?Math.floor(t/K.decade):0;i.push(t*r+e*K.decade_gap)}return un({xs:i,decades:n?ln(i,e,r):[],pitch:r},t)}function ln(e,t,n){let r=[];for(let i=K.decade;i<=t;i+=K.decade){let t=e[i-1],a=e[i];if(t===void 0)break;r.push({value:i,x:a===void 0?t+n:(t+a)/2})}return r}function un(e,t){let n=e.xs[e.xs.length-1]??0;if(n<=t)return e;let r=t/n;return{xs:e.xs.map(e=>e*r),decades:e.decades.map(e=>({value:e.value,x:e.x*r})),pitch:e.pitch*r}}function dn(e,t,n){let r=Math.min(t/e.width,n/e.height),i=Math.max(Math.min(1,r),jt),a=e.width*i-t>.5,o=e.height*i-n>.5;return{scale:i,offset_x:a?0:(t-e.width*i)/2,offset_y:o?0:(n-e.height*i)/2,pan_x:a,pan_y:o}}var fn={structure:null,state:at(null)};function pn(e,t){if(mn(t)){let e=gn(t.structure);if(e!==null)return{structure:e,state:ct(at(e),t)}}let n=ct(e.state,t);return n===e.state?e:{structure:e.structure,state:n}}function mn(e){return hn(e)&&e.kind===`flow_structure`}function hn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gn(e){if(!hn(e))return null;let t=e.kind,n=e.id;if(typeof t!=`string`||typeof n!=`string`)return null;let r=e.children,i=Array.isArray(r)?r.map(gn).filter(e=>e!==null):[],a=e.config;return{kind:t,id:n,...hn(a)?{config:a}:{},...i.length===0?{}:{children:i}}}function _n(e){let t=new Map;return e!==null&&vn(e,t),t}function vn(e,t){t.has(e.id)||t.set(e.id,e.kind.toUpperCase());let n=e.children??[];for(let[r,i]of n.entries()){let n=yn(e,i,r);n!==null&&!t.has(i.id)&&t.set(i.id,n)}for(let e of n)vn(e,t)}function yn(e,t,n){switch(e.kind){case`map`:return`MAP`;case`loop`:return`LOOP`;case`retry`:return bn(e.config?.max_attempts);case`fallback`:return`${t.kind.toUpperCase()} · ${n===0?`PRIMARY`:`BACKUP`}`;default:return null}}function bn(e){let t=J(e);return t===null?`RETRY`:`RETRY · ${t} ${t===1?`ATTEMPT`:`ATTEMPTS`}`}function J(e){return typeof e!=`number`||!Number.isInteger(e)||e<=0?null:e}var xn=14,Sn=Math.PI/4,Cn=14,wn=-17,Tn=30,En=-156,Dn=279,On=22,kn=14,An=112,jn=44,Mn=12,Nn=24;function Pn(e,t){let n=Ln(e,t),r=_n(t.structure);return{nodes:e.nodes.map(e=>{let i=tr(n,e,r);return{glyph:e,meta:i.text,meta_fail:i.fail,status:$n(n,e.id),scar:nr(n,e.id)?null:Qn(t.state,e),emits:t.state.nodes.get(e.id)?.emits??0,checkpoint:n.checkpoint_hits.has(e.id)}}),junctions:e.junctions.map(e=>({glyph:e,label:`merge`,status:t.state.nodes.get(e.owner)?.status??`pending`})),group_labels:e.group_labels.map(e=>({anchor:e,text:sr(n,e.owner)})),segments:e.segments.map(e=>({segment:e,state:Hn(n,e)})),fail_marks:Zn(e,t.state),tick_lanes:Fn(e,n),cards:cr(e,n)}}function Fn(e,t){return e.tick_lanes.map(e=>{let n=t.nodes_by_id.get(e.owner)?.children?.[0],r=n===void 0?[]:Y(t.state,n.id),i=cn(r.length,e.x1-e.x0);return{owner:e.owner,ticks:r.map((t,n)=>({x:e.x0+(i.xs[n]??0),y:e.y,status:In(t.status)})),decades:i.decades.map(t=>({x:e.x0+t.x,y:e.y+Tn,value:t.value}))}})}function In(e){return e===`active`?`live`:e===`failed`?`failed`:`done`}function Ln(e,t){let n=new Map,r=new Map,i=new Map;t.structure!==null&&zn(t.structure,n,r,i);let a=new Map;for(let t of e.junctions)a.set(t.id,t.owner);let o=new Set;for(let t of e.segments)t.role===`loop_upper`&&o.add(t.to);let s=new Set;for(let e of r.values()){if(e.kind!==`fallback`)continue;let t=e.children?.[0];t!==void 0&&s.add(t.id)}return{state:t.state,parents:n,nodes_by_id:r,first_leaves:i,junction_owners:a,loop_leaves:o,fallback_primaries:s,checkpoint_hits:Rn(t.state,r,i)}}function Rn(e,t,n){let r=new Set;for(let i of t.values())i.kind===`checkpoint`&&e.nodes.get(i.id)?.checkpoint===`hit`&&r.add(n.get(i.id)??i.id);return r}function zn(e,t,n,r){n.has(e.id)||(n.set(e.id,e),r.set(e.id,Bn(e)));for(let i of e.children??[])t.has(i.id)||t.set(i.id,e.id),zn(i,t,n,r)}function Bn(e){let t=e;for(;t.children!==void 0&&t.children.length>0;){let e=t.children[0];if(e===void 0)break;t=e}return t.id}function Y(e,t){return e.nodes.get(t)?.occurrences??[]}function X(e){return e.some(e=>e.status===`active`)}function Vn(e,t){let n=Y(e,t);return n.length>0&&!X(n)}function Hn(e,t){switch(t.role){case`loop_upper`:return qn(e.state,t.from??t.to,t.to);case`loop_lower`:return Jn(e.state,t.to);case`loop_return`:return Xn(e,t.to)}let n=e.junction_owners.get(t.to);return n===void 0?t.from!==null&&Kn(e.parents,t.from,t.to)?Vn(e.state,t.to)?`traversed`:`unbuilt`:Un(e,t):Vn(e.state,n)?`traversed`:`unbuilt`}function Un(e,t){if(e.fallback_primaries.has(t.to)&&Wn(e.state,t.to))return`unbuilt`;let n=e.first_leaves.get(t.to)??t.to,r=Y(e.state,n);return r.length===0?`unbuilt`:X(r)&&!e.loop_leaves.has(n)&&!Gn(e.state,n)?`live`:`traversed`}function Wn(e,t){return e.nodes.get(t)?.scarred===!0}function Gn(e,t){return e.nodes.get(t)?.suspended===!0}function Kn(e,t,n){let r=e.size+1,i=t;for(;i!==void 0&&r>0;){if(--r,i===n)return!0;i=e.get(i)}return!1}function qn(e,t,n){let r=Y(e,n);return Yn(e,t,r)?`live`:r.length>0?`traversed`:`unbuilt`}function Jn(e,t){return Y(e,t).some(e=>e.status===`failed`)?`traversed`:`unbuilt`}function Yn(e,t,n){return X(Y(e,t))?X(n)?!0:n[n.length-1]?.status===`failed`:!1}function Xn(e,t){let n=e.nodes_by_id.get(t)?.children?.[0];if(n===void 0)return`unbuilt`;let r=Y(e.state,n.id),i=r.length>=2;return Yn(e.state,t,r)&&(i||!X(r))?`live`:i?`traversed`:`unbuilt`}function Zn(e,t){let n=[];for(let r of e.segments){if(r.role!==`loop_lower`)continue;let i=e.nodes.find(e=>e.id===r.to);if(i===void 0)continue;let a=Y(t,r.to).filter(e=>e.status===`failed`).length,o=i.center.x+K.loop_radius,s=K.loop_radius+xn;for(let e=0;e<a;e+=1){let t=Sn+Math.min(a-1-e,2)*Sn;n.push({x:o+Math.cos(t)*s,y:i.center.y+Math.sin(t)*s})}}return n}function Qn(e,t){return e.nodes.get(t.id)?.scarred===!0?{x:t.center.x+Cn,y:t.center.y+wn}:null}function $n(e,t){let n=e.state.nodes.get(t)?.status??`pending`;if(n!==`failed`)return n;let r=er(e,t);return r!==null&&X(Y(e.state,r.id))?`active`:n}function er(e,t){let n=e.parents.get(t);if(n===void 0)return null;let r=e.nodes_by_id.get(n);return r?.kind===`retry`?r:null}function tr(e,t,n){if(Gn(e.state,t.id))return{text:`SUSPENDED`,fail:null};let r=t.terminus?`TERMINUS`:n.get(t.id)??t.kind.toUpperCase(),i=Y(e.state,t.id);if(i.length===0)return{text:r,fail:null};let a=t.terminus?null:er(e,t.id);if(a!==null)return{text:ir(e.state,a,i),fail:null};if(!t.terminus&&nr(e,t.id))return rr(r,i);let o=i.length>=2?`${r} ×${i.length}`:r;return X(i)?{text:`${o} · RUNNING`,fail:null}:{text:ar(o,i),fail:null}}function nr(e,t){let n=e.parents.get(t);return n!==void 0&&e.nodes_by_id.get(n)?.kind===`map`}function rr(e,t){let n=t.length>=2?`${e} ×${t.length}`:e,r=t.filter(e=>e.status===`active`).length,i=t.filter(e=>e.status===`failed`).length,a=t.length>K.decade;return i>0||r>0&&a?{text:r>0?`${n} · ${r} LIVE`:n,fail:i>0?`${i} ✕`:null}:r>0?{text:`${n} · RUNNING`,fail:null}:{text:ar(n,t),fail:null}}function ir(e,t,n){let r=n[n.length-1]?.status===`failed`&&X(Y(e,t.id)),i=J(t.config?.max_attempts),a=n.length+ +!!r,o=`RETRY · ATT ${i===null?a:Math.min(a,i)}${i===null?``:`/${i}`}`;return X(n)||r?o:ar(o,n)}function ar(e,t){let n=or(t);return n===null?e:`${e} · ${U(n)}`}function or(e){let t=null,n=null;for(let r of e)r.started_ts!==null&&(t===null||r.started_ts<t)&&(t=r.started_ts),r.ended_ts!==null&&(n===null||r.ended_ts>n)&&(n=r.ended_ts);return t===null||n===null?null:Math.max(0,n-t)}function sr(e,t){let n=t.toUpperCase(),r=e.state.kinds.get(t)===`fallback`?` · ARMED`:``,i=Y(e.state,t);if(i.length===0||X(i))return`${n}${r}`;let a=or(i);return a===null?`${n}${r}`:`${n} · ${U(a)}`}function Z(e,t){return{role:e,spans:[{text:t,ember:!1}]}}function cr(e,t){let n=[];for(let r of e.nodes){let e=lr(t,r);e!==null&&n.push(mr(r,e))}return n}function lr(e,t){let n=e.state.nodes.get(t.id);return n===void 0?null:n.suspended?[Z(`title`,`SUSPENDED`),Z(`detail`,`AWAITING RESUME`)]:n.scarred&&!nr(e,t.id)?ur(n):dr(e,t.id,n.occurrences)}function ur(e){let t=pr(fr(e.occurrences)?.occurrence.error??null);return[Z(`title`,`PERMANENT FAILURE`),{role:`detail`,spans:t===null?[{text:`✕`,ember:!0}]:[{text:`✕`,ember:!0},{text:` ${t}`,ember:!1}]}]}function dr(e,t,n){let r=er(e,t);if(r===null||!X(Y(e.state,r.id)))return null;let i=n[n.length-1]?.status===`failed`;if(!i&&!X(n))return null;let a=J(r.config?.max_attempts),o=n.length+ +!!i,s=a===null?o:Math.min(o,a);if(s<2)return null;let c=[Z(`title`,`ATTEMPT ${s}${a===null?``:` OF ${a}`}`)],l=fr(n);if(l!==null){let e=pr(l.occurrence.error);c.push({role:`detail`,spans:[{text:`ATT ${l.attempt} `,ember:!1},{text:`✕`,ember:!0},...e===null?[]:[{text:` ${e}`,ember:!1}]]})}let u=J(r.config?.backoff_ms);return u!==null&&c.push(Z(`detail`,`BACKOFF ${U(u)} HONORED`)),c}function fr(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.status===`failed`)return{occurrence:n,attempt:t+1}}return null}function pr(e){if(e===null||e.length===0)return null;let t=e.toUpperCase();return t.length<=Nn?t:`${t.slice(0,23)}…`}function mr(e,t){let n=e.center.x+En<K.margin,r=e.center.x+(n?jn:En),i=e.center.y-Dn,a={x:r+(n?Mn:An),y:i+(t.length-1)*On+kn},o=hr(e.center,a);return{owner:e.id,lines:t.map((e,t)=>({x:r,y:i+t*On,role:e.role,spans:e.spans})),leader:`M ${a.x} ${a.y} L ${o.x} ${o.y}`,dot:o}}function hr(e,t){let n=t.x-e.x,r=t.y-e.y,i=Math.hypot(n,r);return i===0?{x:e.x,y:e.y-40}:{x:e.x+n/i*40,y:e.y+r/i*40}}function gr(e){let t=null,n=null,r=[],i=[];for(let a of e){let e=Dr(a);e!==null&&(t??=e,n=e);let o=t===null||n===null?0:Math.max(0,n-t);r.push(o),a.kind===`span_end`&&a.error!==void 0&&i.push(o)}let a=t===null||n===null?0:Math.max(0,n-t);return{count:r.length,span_ms:a,times:r,failures:i.map(e=>Er(e,a))}}function _r(e,t){let{times:n,span_ms:r,count:i}=e;if(i===0)return 0;let a=Q(t,0,i-1);return r>0?Q((n[a]??0)/r,0,1):i>1?a/(i-1):0}function vr(e,t){let{times:n,span_ms:r,count:i}=e;if(i===0)return 0;let a=Q(t,0,1);return r<=0?Math.round(a*(i-1)):Tr(n,a*r)}function yr(e,t){let n=Array.from({length:t},()=>0);if(e.count===0)return n;for(let r=0;r<e.count;r+=1){let i=Math.min(t-1,Math.floor(_r(e,r)*t));n[i]=(n[i]??0)+1}let r=Math.max(...n);return n.map(e=>e/r)}function br(e,t){let{times:n,count:r,span_ms:i}=e;if(r===0)return 0;if(i<=0)return xr(t,1,r);let a=Q(t,0,r-1);for(let e=a+1;e<r;e+=1)if(e===r-1||(n[e+1]??0)>(n[e]??0))return e;return a}function xr(e,t,n){return Q(e+Math.sign(t),0,Math.max(0,n-1))}function Sr(e,t,n){let{times:r,count:i}=e;if(i===0)return 0;let a=Q(t,0,i-1),o=r[a]??0;if(n>0){let e=o+1e3;for(let t=a+1;t<i;t+=1)if((r[t]??0)>=e)return t;return i-1}let s=o-1e3;for(let e=a-1;e>=0;--e)if((r[e]??0)<=s)return e;return 0}function Cr(e,t,n,r){if(e.count===0)return`ignore`;switch(n){case`ArrowRight`:return r?Sr(e,t,1):xr(t,1,e.count);case`ArrowLeft`:return r?Sr(e,t,-1):xr(t,-1,e.count);case`Home`:return 0;case`End`:return`live`;default:return`ignore`}}function wr(e,t){let n=fn,r=Q(t+1,0,e.length);for(let t=0;t<r;t+=1)n=pn(n,e[t]);return n}function Tr(e,t){let n=e.length;for(let r=0;r<e.length;r+=1)if((e[r]??0)>=t){n=r;break}if(n<=0)return 0;if(n>=e.length)return e.length-1;let r=n-1;return t-(e[r]??0)<=(e[n]??0)-t?r:n}function Er(e,t){return t>0?Q(e/t,0,1):0}function Dr(e){let t=e.ts;return typeof t==`number`&&Number.isFinite(t)?t:null}function Q(e,t,n){return Math.min(n,Math.max(t,e))}var Or=L(`<svg class=scrubber data-testid=scrubber height=40 fill=none><line class=scrub-spine-ahead y1=20 y2=20></line><line class=scrub-spine-traversed y1=20 y2=20></line><circle class=scrub-playhead data-testid=playhead cy=20 r=3.5></circle><rect class=scrub-band x=0 y=8 height=24>`),kr=L(`<svg><rect class=scrub-density y=15 height=10></svg>`,!1,!0,!1),Ar=L(`<svg><line class=scrub-fail y1=16 y2=24></svg>`,!1,!0,!1),$=4,jr=48,Mr=.3;function Nr(e){let t=()=>e.width-K.margin,n=()=>Math.max(0,t()-K.margin),r=e=>K.margin+e*n(),i=()=>r(Pr(e.fraction)),a=(t,n)=>{let r=n.width-2*K.margin,i=r<=0?0:(t-n.left-K.margin)/r;e.on_seek(Pr(i))},o=()=>e.density?yr(e.timeline,jr):[];return(()=>{var s=Or(),c=s.firstChild,l=c.nextSibling,u=l.nextSibling,d=u.nextSibling;return z(s,P(F,{get each(){return o()},children:(e,t)=>(()=>{var i=kr();return R(i,`opacity`,e*Mr),y(e=>{var a=r(t()/jr),o=n()/jr;return a!==e.e&&R(i,`x`,e.e=a),o!==e.t&&R(i,`width`,e.t=o),e},{e:void 0,t:void 0}),i})()}),c),z(s,P(F,{get each(){return e.timeline.failures},children:e=>[(()=>{var t=Ar();return y(n=>{var i=r(e)-$,a=r(e)+$;return i!==n.e&&R(t,`x1`,n.e=i),a!==n.t&&R(t,`x2`,n.t=a),n},{e:void 0,t:void 0}),t})(),(()=>{var t=Ar();return y(n=>{var i=r(e)+$,a=r(e)-$;return i!==n.e&&R(t,`x1`,n.e=i),a!==n.t&&R(t,`x2`,n.t=a),n},{e:void 0,t:void 0}),t})()]}),u),d.$$pointermove=e=>{e.currentTarget.hasPointerCapture(e.pointerId)&&a(e.clientX,e.currentTarget.getBoundingClientRect())},d.$$pointerdown=e=>{e.currentTarget.setPointerCapture(e.pointerId),a(e.clientX,e.currentTarget.getBoundingClientRect())},y(n=>{var r=i(),a=t(),o=K.margin,s=i(),f=i(),p=e.width;return r!==n.e&&R(c,`x1`,n.e=r),a!==n.t&&R(c,`x2`,n.t=a),o!==n.a&&R(l,`x1`,n.a=o),s!==n.o&&R(l,`x2`,n.o=s),f!==n.i&&R(u,`cx`,n.i=f),p!==n.n&&R(d,`width`,n.n=p),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),s})()}function Pr(e){return Math.min(1,Math.max(0,e))}Ce([`pointerdown`,`pointermove`]);var Fr=L(`<svg><circle class=scar-mask r=13></svg>`,!1,!0,!1),Ir=L(`<svg><circle class=scar-ring r=8.5></svg>`,!1,!0,!1),Lr=L(`<svg><path class=scar-mark></svg>`,!1,!0,!1),Rr=L(`<svg><path class=tick-fail></svg>`,!1,!0,!1),zr=L(`<svg><line class="tick tick-live-glow"></svg>`,!1,!0,!1),Br=L(`<svg><line class="tick tick-live"></svg>`,!1,!0,!1),Vr=L(`<svg><line class="tick tick-done"></svg>`,!1,!0,!1),Hr=L(`<svg><g class=seg-live data-state=live><path class="seg seg-live-outer"></path><path class="seg seg-live-inner"></path><path class="seg seg-live-march"></svg>`,!1,!0,!1),Ur=L(`<svg class=stage data-testid=stage fill=none><defs><radialGradient id=halo><stop offset=0% stop-color=#FFAC33 stop-opacity=0.5></stop><stop offset=45% stop-color=#FFAC33 stop-opacity=0.16></stop><stop offset=78% stop-color=#FFAC33 stop-opacity=0></stop></radialGradient><radialGradient id=bloom><stop offset=0% stop-color=#FFAC33 stop-opacity=0.055></stop><stop offset=70% stop-color=#FFAC33 stop-opacity=0></stop></radialGradient><filter id=glow-2 x=-60% y=-60% width=220% height=220%><feGaussianBlur stdDeviation=2></feGaussianBlur></filter><filter id=glow-4 x=-60% y=-60% width=220% height=220%><feGaussianBlur stdDeviation=4></feGaussianBlur></filter></defs><g><g class=scaffold data-testid=scaffold>`),Wr=L(`<svg><circle class=bloom></svg>`,!1,!0,!1),Gr=L(`<svg><path></svg>`,!1,!0,!1),Kr=L(`<svg><g class=tick-lane data-testid=tick-lane></svg>`,!1,!0,!1),qr=L(`<svg><text class=tick-decade></svg>`,!1,!0,!1),Jr=L(`<svg><circle class=halo></svg>`,!1,!0,!1),Yr=L(`<svg><circle class=puck-core r=2.5></svg>`,!1,!0,!1),Xr=L(`<svg><circle class=emit-bloom r=16></svg>`,!1,!0,!1),Zr=L(`<svg><circle class=terminus-ring></svg>`,!1,!0,!1),Qr=L(`<svg><tspan class=meta-check> ✓</svg>`,!1,!0,!1),$r=L(`<svg><g class=node data-testid=node><text class=node-name></text><text class=node-meta></svg>`,!1,!0,!1),ei=L(`<svg><circle class=puck></svg>`,!1,!0,!1),ti=L(`<svg><line class=pause-bar></svg>`,!1,!0,!1),ni=L(`<svg><tspan> · </svg>`,!1,!0,!1),ri=L(`<svg><tspan class=meta-fail></svg>`,!1,!0,!1),ii=L(`<svg><path class=fail-mark></svg>`,!1,!0,!1),ai=L(`<svg><g class=junction data-testid=junction><circle class=puck></circle><text class=junction-label></svg>`,!1,!0,!1),oi=L(`<svg><g class=group-label data-testid=group-label><line class=group-tick></line><text class=group-text></svg>`,!1,!0,!1),si=L(`<svg><g class=card data-testid=card><path class=card-leader></path><circle class=card-dot r=2.5></svg>`,!1,!0,!1),ci=L(`<svg><text></svg>`,!1,!0,!1),li=L(`<svg><tspan></svg>`,!1,!0,!1),ui=4.5,di=6,fi=4,pi=-32,mi=2.4,hi=3.2;function gi(e,t,n){return`M ${e-n} ${t-n} L ${e+n} ${t+n} M ${e+n} ${t-n} L ${e-n} ${t+n}`}function _i(e){return[(()=>{var t=Fr();return y(n=>{var r=e.center.x,i=e.center.y;return r!==n.e&&R(t,`cx`,n.e=r),i!==n.t&&R(t,`cy`,n.t=i),n},{e:void 0,t:void 0}),t})(),(()=>{var t=Ir();return y(n=>{var r=e.center.x,i=e.center.y,a=`rotate(${pi} ${e.center.x} ${e.center.y})`;return r!==n.e&&R(t,`cx`,n.e=r),i!==n.t&&R(t,`cy`,n.t=i),a!==n.a&&R(t,`transform`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})(),(()=>{var t=Lr();return y(()=>R(t,`d`,gi(e.mark.x,e.mark.y,ui))),t})()]}function vi(e){let t=()=>e.tick.y-di,n=()=>e.tick.y+di;return P(_e,{get children(){return[P(ve,{get when(){return e.tick.status===`failed`},get children(){var t=Rr();return y(()=>R(t,`d`,gi(e.tick.x,e.tick.y,fi))),t}}),P(ve,{get when(){return e.tick.status===`live`},get children(){return[(()=>{var r=zr();return y(i=>{var a=e.tick.x,o=t(),s=e.tick.x,c=n();return a!==i.e&&R(r,`x1`,i.e=a),o!==i.t&&R(r,`y1`,i.t=o),s!==i.a&&R(r,`x2`,i.a=s),c!==i.o&&R(r,`y2`,i.o=c),i},{e:void 0,t:void 0,a:void 0,o:void 0}),r})(),(()=>{var r=Br();return y(i=>{var a=e.tick.x,o=t(),s=e.tick.x,c=n();return a!==i.e&&R(r,`x1`,i.e=a),o!==i.t&&R(r,`y1`,i.t=o),s!==i.a&&R(r,`x2`,i.a=s),c!==i.o&&R(r,`y2`,i.o=c),i},{e:void 0,t:void 0,a:void 0,o:void 0}),r})()]}}),P(ve,{get when(){return e.tick.status===`done`},get children(){var r=Vr();return y(i=>{var a=e.tick.x,o=t(),s=e.tick.x,c=n();return a!==i.e&&R(r,`x1`,i.e=a),o!==i.t&&R(r,`y1`,i.t=o),s!==i.a&&R(r,`x2`,i.a=s),c!==i.o&&R(r,`y2`,i.o=c),i},{e:void 0,t:void 0,a:void 0,o:void 0}),r}})]}})}function yi(e){return(()=>{var t=Hr(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling;return y(a=>{var o=e.scene_segment.segment.role,s=e.scene_segment.segment.to,c=e.scene_segment.segment.path,l=e.scene_segment.segment.path,u=e.scene_segment.segment.path;return o!==a.e&&R(t,`data-role`,a.e=o),s!==a.t&&R(t,`data-to`,a.t=s),c!==a.a&&R(n,`d`,a.a=c),l!==a.o&&R(r,`d`,a.o=l),u!==a.i&&R(i,`d`,a.i=u),a},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),t})()}function bi(e){let t=x(()=>e.session.structure),n=x(()=>Gt(t())),r=x(()=>Pn(n(),e.session)),i=x(()=>r().nodes.filter(e=>e.status===`active`)),a=x(()=>dn(n(),e.viewport.width,e.viewport.height));return(()=>{var e=Ur(),t=e.firstChild.nextSibling,n=t.firstChild;return z(t,P(F,{get each(){return i()},children:e=>(()=>{var t=Wr();return R(t,`r`,215),y(n=>{var r=e.glyph.center.x,i=e.glyph.center.y;return r!==n.e&&R(t,`cx`,n.e=r),i!==n.t&&R(t,`cy`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n),z(n,P(F,{get each(){return r().segments},children:e=>P(I,{get when(){return e.state===`live`},get fallback(){return(()=>{var t=Gr();return y(n=>{var r=e.state===`traversed`?`seg seg-traversed`:`seg seg-unbuilt`,i=e.segment.path,a=e.segment.role,o=e.segment.to,s=e.state;return r!==n.e&&R(t,`class`,n.e=r),i!==n.t&&R(t,`d`,n.t=i),a!==n.a&&R(t,`data-role`,n.a=a),o!==n.o&&R(t,`data-to`,n.o=o),s!==n.i&&R(t,`data-state`,n.i=s),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),t})()},get children(){return P(yi,{scene_segment:e})}})})),z(t,P(F,{get each(){return r().tick_lanes},children:e=>(()=>{var t=Kr();return z(t,P(F,{get each(){return e.ticks},children:e=>P(vi,{tick:e})}),null),z(t,P(F,{get each(){return e.decades},children:e=>(()=>{var t=qr();return z(t,()=>e.value),y(n=>{var r=e.x,i=e.y;return r!==n.e&&R(t,`x`,n.e=r),i!==n.t&&R(t,`y`,n.t=i),n},{e:void 0,t:void 0}),t})()}),null),y(()=>R(t,`data-owner`,e.owner)),t})()}),null),z(t,P(F,{get each(){return i()},children:e=>(()=>{var t=Jr();return R(t,`r`,40),y(n=>{var r=e.glyph.center.x,i=e.glyph.center.y;return r!==n.e&&R(t,`cx`,n.e=r),i!==n.t&&R(t,`cy`,n.t=i),n},{e:void 0,t:void 0}),t})()}),null),z(t,P(F,{get each(){return r().nodes},children:e=>(()=>{var t=$r(),n=t.firstChild,r=n.nextSibling;return z(t,P(I,{get when(){return e.scar},get fallback(){return(()=>{var t=ei();return y(n=>{var r=e.glyph.center.x,i=e.glyph.center.y,a=e.status===`active`?e.glyph.radius+.5:e.glyph.radius;return r!==n.e&&R(t,`cx`,n.e=r),i!==n.t&&R(t,`cy`,n.t=i),a!==n.a&&R(t,`r`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()},children:t=>P(_i,{get center(){return e.glyph.center},get mark(){return t()}})}),n),z(t,P(I,{get when(){return e.status===`active`},get children(){var t=Yr();return y(n=>{var r=e.glyph.center.x,i=e.glyph.center.y;return r!==n.e&&R(t,`cx`,n.e=r),i!==n.t&&R(t,`cy`,n.t=i),n},{e:void 0,t:void 0}),t}}),n),z(t,P(I,{get when(){return e.status===`suspended`},get children(){return P(F,{each:[-2.4,mi],children:t=>(()=>{var n=ti();return y(r=>{var i=e.glyph.center.x+t,a=e.glyph.center.y-hi,o=e.glyph.center.x+t,s=e.glyph.center.y+hi;return i!==r.e&&R(n,`x1`,r.e=i),a!==r.t&&R(n,`y1`,r.t=a),o!==r.a&&R(n,`x2`,r.a=o),s!==r.o&&R(n,`y2`,r.o=s),r},{e:void 0,t:void 0,a:void 0,o:void 0}),n})()})}}),n),z(t,P(I,{keyed:!0,get when(){return ye(()=>e.emits>0)()?e.emits:null},get children(){var t=Xr();return y(n=>{var r=e.glyph.center.x,i=e.glyph.center.y;return r!==n.e&&R(t,`cx`,n.e=r),i!==n.t&&R(t,`cy`,n.t=i),n},{e:void 0,t:void 0}),t}}),n),z(t,P(I,{get when(){return e.glyph.terminus},get children(){var t=Zr();return y(n=>{var r=e.glyph.center.x,i=e.glyph.center.y,a=K.terminus_ring_radius;return r!==n.e&&R(t,`cx`,n.e=r),i!==n.t&&R(t,`cy`,n.t=i),a!==n.a&&R(t,`r`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t}}),n),z(n,()=>e.glyph.label),z(r,()=>e.meta,null),z(r,P(I,{get when(){return e.meta_fail},children:e=>[ni(),(()=>{var t=ri();return z(t,e),t})()]}),null),z(r,P(I,{get when(){return e.checkpoint},get children(){return Qr()}}),null),y(i=>{var a=e.status,o=e.scar===null?void 0:`true`,s=e.glyph.id,c=e.glyph.name_anchor.x,l=e.glyph.name_anchor.y,u=e.glyph.meta_anchor.x,d=e.glyph.meta_anchor.y;return a!==i.e&&R(t,`data-status`,i.e=a),o!==i.t&&R(t,`data-scar`,i.t=o),s!==i.a&&R(t,`data-node-id`,i.a=s),c!==i.o&&R(n,`x`,i.o=c),l!==i.i&&R(n,`y`,i.i=l),u!==i.n&&R(r,`x`,i.n=u),d!==i.s&&R(r,`y`,i.s=d),i},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),t})()}),null),z(t,P(F,{get each(){return r().fail_marks},children:e=>(()=>{var t=ii();return y(()=>R(t,`d`,gi(e.x,e.y,ui))),t})()}),null),z(t,P(F,{get each(){return r().junctions},children:e=>(()=>{var t=ai(),n=t.firstChild,r=n.nextSibling;return z(r,()=>e.label),y(i=>{var a=e.status,o=e.glyph.center.x,s=e.glyph.center.y,c=e.glyph.radius,l=e.glyph.label_anchor.x,u=e.glyph.label_anchor.y;return a!==i.e&&R(t,`data-status`,i.e=a),o!==i.t&&R(n,`cx`,i.t=o),s!==i.a&&R(n,`cy`,i.a=s),c!==i.o&&R(n,`r`,i.o=c),l!==i.i&&R(r,`x`,i.i=l),u!==i.n&&R(r,`y`,i.n=u),i},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),t})()}),null),z(t,P(F,{get each(){return r().group_labels},children:e=>(()=>{var t=oi(),n=t.firstChild,r=n.nextSibling;return z(r,()=>e.text),y(i=>{var a=e.anchor.owner,o=e.anchor.tick.x,s=e.anchor.tick.y,c=e.anchor.tick.x+K.group_tick_length,l=e.anchor.tick.y,u=e.anchor.text_anchor.x,d=e.anchor.text_anchor.y;return a!==i.e&&R(t,`data-owner`,i.e=a),o!==i.t&&R(n,`x1`,i.t=o),s!==i.a&&R(n,`y1`,i.a=s),c!==i.o&&R(n,`x2`,i.o=c),l!==i.i&&R(n,`y2`,i.i=l),u!==i.n&&R(r,`x`,i.n=u),d!==i.s&&R(r,`y`,i.s=d),i},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),t})()}),null),z(t,P(F,{get each(){return r().cards},children:e=>(()=>{var t=si(),n=t.firstChild,r=n.nextSibling;return z(t,P(F,{get each(){return e.lines},children:e=>(()=>{var t=ci();return z(t,P(F,{get each(){return e.spans},children:e=>(()=>{var t=li();return z(t,()=>e.text),y(()=>R(t,`class`,e.ember?`card-fail`:void 0)),t})()})),y(n=>{var r=e.role===`title`?`card-title`:`card-detail`,i=e.x,a=e.y;return r!==n.e&&R(t,`class`,n.e=r),i!==n.t&&R(t,`x`,n.t=i),a!==n.a&&R(t,`y`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),n),y(i=>{var a=e.owner,o=e.leader,s=e.dot.x,c=e.dot.y;return a!==i.e&&R(t,`data-owner`,i.e=a),o!==i.t&&R(n,`d`,i.t=o),s!==i.a&&R(r,`cx`,i.a=s),c!==i.o&&R(r,`cy`,i.o=c),i},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),null),y(()=>R(t,`transform`,`translate(${a().offset_x} ${a().offset_y}) scale(${a().scale})`)),e})()}var xi=L(`<span data-testid=status><i class=status-dot>`),Si=L(`<button type=button class=return-live data-testid=return-to-live>RETURN TO LIVE`),Ci=L(`<div class=canvas><header class=canvas-header><div class=run><span class=run-key>run</span><span class=run-id data-testid=run-id></span></div><div class=stats data-testid=stats>`),wi=L(`<span class="status status-replay"data-testid=status><i class=status-dot></i>REPLAY`),Ti=L(`<span>`),Ei={connecting:`CONNECTING`,live:`LIVE`,offline:`OFFLINE`};function Di(e){return(()=>{var t=xi();return t.firstChild,z(t,()=>Ei[e.status],null),y(()=>we(t,e.status===`live`?`status status-live`:`status status-offline`)),t})()}function Oi(e){let t=x(()=>it({t_plus_ms:e.play_t_plus_ms??Xe({fold_t_plus_ms:st(e.session.state),run_over:e.session.state.run_status!==null,connected:e.following&&e.status===`live`,received_at_ms:e.received_at_ms,now_ms:e.now_ms}),retries_absorbed:e.session.state.retries_absorbed,scars:e.session.state.scars,cost_usd:e.session.state.cost_usd}));return(()=>{var n=Ci(),r=n.firstChild.firstChild,i=r.firstChild.nextSibling,a=r.nextSibling;return z(i,(()=>{var t=ye(()=>e.session.state.run_id===null);return()=>t()?Qe:$e(e.session.state.run_id)})()),z(r,P(I,{get when(){return e.following},get fallback(){return wi()},get children(){return P(Di,{get status(){return e.status}})}}),null),z(r,P(I,{get when(){return!e.following},get children(){var t=Si();return t.$$click=()=>e.on_return_to_live(),t}}),null),z(a,P(F,{get each(){return t()},children:e=>(()=>{var t=Ti();return z(t,()=>e.text),y(()=>we(t,`stats-${e.role}`)),t})()})),z(n,P(bi,{get session(){return e.session},get viewport(){return e.viewport}}),null),z(n,P(I,{get when(){return e.timeline.count>0},get children(){return[P(Nr,{get timeline(){return e.timeline},get fraction(){return e.fraction},get width(){return e.viewport.width},get density(){return e.density},get on_seek(){return e.on_seek}}),P(Ye,{get playback(){return e.playback},get density(){return e.density},get on_play_chip(){return e.on_play_chip},get on_toggle_step(){return e.on_toggle_step},get on_cycle_speed(){return e.on_cycle_speed},get on_toggle_compress(){return e.on_toggle_compress},get on_toggle_loop(){return e.on_toggle_loop},get on_toggle_density(){return e.on_toggle_density}})]}}),null),y(()=>R(n,`data-chrome`,e.chrome_hidden?`hidden`:`visible`)),n})()}Ce([`click`]);function ki(e){let t;try{t=JSON.parse(e)}catch{return null}return Ai(t)?t:null}function Ai(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:typeof e.kind==`string`}function ji(e){let{url:t,open:n,on_frame:r,on_status:i}=e;i(`connecting`);let a=n(t);return a.addEventListener(`open`,()=>{i(`live`)}),a.addEventListener(`trajectory`,e=>{let t=ki(e.data);t!==null&&r(t)}),a.addEventListener(`close`,()=>{i(`offline`)}),a.addEventListener(`error`,()=>{i(`offline`)}),{close:()=>{a.close()}}}var Mi=`x-fascicle-cursor`;function Ni(e,t){let n=fn,r=[];for(let t of e.split(`
|
|
2
|
-
`)){if(t.length===0)continue;let e=ki(t);e!==null&&(n=pn(n,e),r.push(e))}return{session:n,frames:r,count:r.length,cursor:Math.max(r.length,t)}}function Pi(e){if(e===null)return 0;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:0}function Fi(e){return e>0?`/api/events?since=${e}`:`/api/events`}var Ii=`fascicle-viewer:density`;function Li(){try{return localStorage.getItem(Ii)===`on`}catch{return!1}}function Ri(e){try{localStorage.setItem(Ii,e?`on`:`off`)}catch{}}function zi(){let e=document.querySelector(`#root`);if(e===null)throw Error(`viewer app: #root is missing from index.html`);let[t,n]=v([]),[r,i]=v({session:fn,received_at_ms:null}),[a,o]=v(`connecting`),[s,c]=v(performance.now()),[l,u]=v(Vi()),[d,f]=v(null),[p,m]=v(Pe),[h,g]=v(Li()),[_,y]=v(performance.now());window.addEventListener(`resize`,()=>u(Vi()));let S=x(()=>gr(t())),ee=x(()=>d()===null),C=x(()=>d()??Math.max(0,S().count-1)),te=x(()=>d()===null?r().session:wr(t(),C())),ne=x(()=>d()===null?r().received_at_ms:null),re=x(()=>Me(S().times,p())),w=x(()=>{let e=p();return e.playing?Ne(re(),S().times,We(re(),e,s())):null}),ie=x(()=>Ge(p(),_(),s())),T=e=>{f(e),m(t=>He(t,e,s()))},E=e=>{T(vr(S(),e))},D=()=>{m(Ue),f(null)},O=()=>{m(e=>Fe(e,d(),S().count,s()))},k=()=>{let e=S();e.count!==0&&f(br(e,C()))},A=()=>{p().stepping?k():O()},ae=()=>{p().stepping||f(ze(d(),S().count)),m(Re)},oe=()=>{let e=!h();g(e),Ri(e)};window.addEventListener(`keydown`,e=>{if(e.key===` `){A(),e.preventDefault();return}let t=Cr(S(),C(),e.key,e.shiftKey);t!==`ignore`&&(t===`live`?D():T(t),e.preventDefault())});let j=()=>{y(performance.now())};window.addEventListener(`pointermove`,j),window.addEventListener(`pointerdown`,j),window.addEventListener(`keydown`,j);let M=e=>{c(e),requestAnimationFrame(M)};requestAnimationFrame(M),b(()=>{let e=w();e!==null&&(f(e.index),e.done&&m(e=>e.loop?{...e,anchor_index:0,anchor_now_ms:s()}:{...e,playing:!1}))}),Se(()=>P(Oi,{get session(){return te()},get status(){return a()},get viewport(){return l()},get received_at_ms(){return ne()},get now_ms(){return s()},get following(){return ee()},get timeline(){return S()},get fraction(){return _r(S(),C())},get playback(){return p()},get play_t_plus_ms(){return w()?.t_plus_ms??null},get chrome_hidden(){return ie()},get density(){return h()},on_seek:E,on_return_to_live:D,on_play_chip:A,on_toggle_step:ae,on_cycle_speed:()=>m(e=>Ie(e,C(),s())),on_toggle_compress:()=>m(e=>Le(e,C(),s())),on_toggle_loop:()=>m(Ve),on_toggle_density:oe}),e),Bi(n,i,o)}async function Bi(e,t,n){let r=0;try{let n=await fetch(`/api/trajectory`),i=Ni(await n.text(),Pi(n.headers.get(Mi)));r=i.cursor,i.count>0&&(e(i.frames),t({session:i.session,received_at_ms:performance.now()}))}catch{}ji({url:Fi(r),open:e=>new EventSource(e),on_status:n,on_frame:n=>{e(e=>[...e,n]),t(({session:e})=>({session:pn(e,n),received_at_ms:performance.now()}))}})}function Vi(){return{width:window.innerWidth,height:window.innerHeight}}zi();
|