fascicle 0.17.8 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +25 -2
  3. package/dist/AGENTS.md +23 -11
  4. package/dist/acp.d.ts +3 -17
  5. package/dist/acp.js +25 -44
  6. package/dist/acp.js.map +1 -1
  7. package/dist/{adapters-CDUzZlby.js → adapters-CpKpDk7r.js} +9 -17
  8. package/dist/{adapters-CDUzZlby.js.map → adapters-CpKpDk7r.js.map} +1 -1
  9. package/dist/adapters.d.ts +1 -13
  10. package/dist/adapters.js +1 -1
  11. package/dist/agents.d.ts +3 -5
  12. package/dist/agents.js +2 -3
  13. package/dist/{console-CdB4pcFO.js → console-B1ozi_ii.js} +2 -3
  14. package/dist/{console-CdB4pcFO.js.map → console-B1ozi_ii.js.map} +1 -1
  15. package/dist/{core-Bfzt55Fl.js → core-BH7sWpEG.js} +34 -66
  16. package/dist/{core-Bfzt55Fl.js.map → core-BH7sWpEG.js.map} +1 -1
  17. package/dist/diagram_bin.d.ts +0 -2
  18. package/dist/diagram_bin.js +3 -5
  19. package/dist/diagram_bin.js.map +1 -1
  20. package/dist/{engine-D7ANZ8eq.js → engine-fOjYHcv6.js} +42 -79
  21. package/dist/{engine-D7ANZ8eq.js.map → engine-fOjYHcv6.js.map} +1 -1
  22. package/dist/index.d.ts +4 -98
  23. package/dist/index.js +27 -47
  24. package/dist/index.js.map +1 -1
  25. package/dist/{invoke-DnmWf8gE.js → invoke-7iu8db6V.js} +19 -12
  26. package/dist/{invoke-DnmWf8gE.js.map → invoke-7iu8db6V.js.map} +1 -1
  27. package/dist/{json_schema_to_standard-C4F4lXHE.js → json_schema_to_standard-BstoXjM8.js} +3 -4
  28. package/dist/{json_schema_to_standard-C4F4lXHE.js.map → json_schema_to_standard-BstoXjM8.js.map} +1 -1
  29. package/dist/{leading_system-CHSYz0h9.js → leading_system-BeQUSAim.js} +6 -10
  30. package/dist/{leading_system-CHSYz0h9.js.map → leading_system-BeQUSAim.js.map} +1 -1
  31. package/dist/{mcp-8mKK7eDY.js → mcp-CHJ88HiG.js} +9 -14
  32. package/dist/{mcp-8mKK7eDY.js.map → mcp-CHJ88HiG.js.map} +1 -1
  33. package/dist/mcp.d.ts +3 -11
  34. package/dist/mcp.js +2 -2
  35. package/dist/otel.d.ts +1 -5
  36. package/dist/otel.js +3 -6
  37. package/dist/otel.js.map +1 -1
  38. package/dist/{records-1HU7mWXf.js → records-Btlmvunj.js} +2 -3
  39. package/dist/{records-1HU7mWXf.js.map → records-Btlmvunj.js.map} +1 -1
  40. package/dist/{search-DjhdMsJ8.js → search-BZagxXtd.js} +7 -11
  41. package/dist/{search-DjhdMsJ8.js.map → search-BZagxXtd.js.map} +1 -1
  42. package/dist/search_worker.js +2 -3
  43. package/dist/stdio.d.ts +2 -6
  44. package/dist/stdio.js +5 -7
  45. package/dist/stdio.js.map +1 -1
  46. package/dist/testing.d.ts +2 -18
  47. package/dist/testing.js +12 -21
  48. package/dist/testing.js.map +1 -1
  49. package/dist/{trajectory-DeURWIhj.js → trajectory-CkCFZWNR.js} +2 -3
  50. package/dist/{trajectory-DeURWIhj.js.map → trajectory-CkCFZWNR.js.map} +1 -1
  51. package/dist/{trajectory-BKGNxi7u.d.ts → trajectory-Dt0-A7kb.d.ts} +1 -3
  52. package/dist/{types-CPqLZOEr.d.ts → types-BUXt_zgJ.d.ts} +1 -3
  53. package/dist/{types-BK0UW28o.d.ts → types-CvghbZ0x.d.ts} +1 -5
  54. package/dist/{types-C6PB2aP0.d.ts → types-Dk9tLpUq.d.ts} +3 -9
  55. package/dist/ui.d.ts +1 -3
  56. package/dist/ui.js +1 -2
  57. package/dist/viewer-app/assets/index-D8Tb3drm.js +4 -0
  58. package/dist/viewer-app/index.html +1 -1
  59. package/dist/viewer.d.ts +1 -11
  60. package/dist/viewer.js +8 -14
  61. package/dist/viewer.js.map +1 -1
  62. package/dist/web.d.ts +83 -0
  63. package/dist/web.js +2888 -0
  64. package/dist/web.js.map +1 -0
  65. package/package.json +34 -28
  66. package/dist/viewer-app/assets/index-YrQFld-l.js +0 -4
package/dist/otel.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"otel.js","names":["otel_metrics","otel_context"],"sources":["../src/otel/metrics.ts","../src/otel/trajectory_logger.ts"],"sourcesContent":["/**\n * Opt-in OpenTelemetry metrics derived from the trajectory stream.\n *\n * The bridge's spans answer \"what happened on this run\"; SRE dashboards ask\n * aggregate questions (\"p95 latency by model\", \"429s per minute\", \"tokens per\n * hour\"), which want real OTel metric instruments rather than a\n * spans-to-metrics pipeline. This recorder listens to the same trajectory\n * events the span bridge mirrors and records the GenAI semantic-convention\n * client histograms, plus three Fascicle-named instruments for the data the\n * conventions do not cover yet (cost, absorbed retries, cache traffic).\n *\n * Instruments and sources:\n * - `gen_ai.client.token.usage` ({token}) from `response_received`, one\n * point per direction via `gen_ai.token.type`.\n * - `fascicle.client.cache.token.usage` ({token}) from `response_received`'s\n * `cached_input_tokens` and `cache_write_tokens`, one point per direction\n * above zero via `fascicle.cache.direction` (`read` or `write`).\n * - `gen_ai.client.operation.duration` (s) from `response_received`\n * `duration_ms`, the model-only round trip.\n * - `gen_ai.client.operation.time_to_first_chunk` (s) from\n * `first_chunk_ms` on streamed turns.\n * - `gen_ai.execute_tool.duration` (s) from `tool_result`, tagged\n * `gen_ai.tool.name`.\n * - `fascicle.client.operation.cost` (usd) from the `cost` event's\n * `total_usd`.\n * - `fascicle.client.turn_retries` ({retry}) counter from `turn_retry`,\n * tagged `error.type` with the classified failure kind.\n *\n * Provider and model attributes come from the enclosing `engine.generate`\n * span's start meta, tracked on a stack with the same documented\n * approximation as the span bridge: concurrent generates sharing one logger\n * attribute to the innermost open call. The GenAI semantic conventions are\n * experimental, so a revision of them may rename an instrument this module\n * records.\n */\n\nimport {\n metrics as otel_metrics,\n type Attributes,\n type Counter,\n type Histogram,\n type Meter,\n} from '@opentelemetry/api'\nimport type { TrajectoryEvent } from '#core'\n\nexport type OtelMetricsOptions = {\n /**\n * Meter to create instruments on. Defaults to\n * `metrics.getMeter('fascicle')`, which resolves against the global\n * MeterProvider the host has registered.\n */\n readonly meter?: Meter\n}\n\n/**\n * The span-lifecycle + event listener the trajectory logger drives when\n * metrics are enabled.\n */\nexport type MetricsRecorder = {\n readonly on_start_span: (\n id: string,\n name: string,\n meta: Record<string, unknown> | undefined,\n ) => void\n readonly on_end_span: (id: string) => void\n readonly on_record: (event: TrajectoryEvent) => void\n}\n\n/** Semconv-suggested boundaries for the duration histograms, in seconds. */\nconst DURATION_BOUNDARIES = [\n 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48,\n 40.96, 81.92,\n]\n\n/** Semconv-suggested boundaries for the token-usage histogram. */\nconst TOKEN_BOUNDARIES = [\n 1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304,\n]\n\n/**\n * Read `key` off the loose event and return it only when it is a number.\n */\nfunction event_number(event: TrajectoryEvent, key: string): number | undefined {\n const value = event[key]\n return typeof value === 'number' ? value : undefined\n}\n\n/**\n * Read `key` off the loose event and return it only when it is a string.\n */\nfunction event_string(event: TrajectoryEvent, key: string): string | undefined {\n const value = event[key]\n return typeof value === 'string' ? value : undefined\n}\n\n/**\n * Create the metrics recorder: instruments are created once here, and every\n * recording stamps the provider/model of the innermost open generate call.\n */\nexport function create_metrics_recorder(options: OtelMetricsOptions): MetricsRecorder {\n const meter = options.meter ?? otel_metrics.getMeter('fascicle')\n\n const token_usage: Histogram = meter.createHistogram('gen_ai.client.token.usage', {\n unit: '{token}',\n description: 'Number of input and output tokens used per model turn',\n advice: { explicitBucketBoundaries: TOKEN_BOUNDARIES },\n })\n const operation_duration: Histogram = meter.createHistogram(\n 'gen_ai.client.operation.duration',\n {\n unit: 's',\n description: 'Model round-trip duration of the successful turn attempt',\n advice: { explicitBucketBoundaries: DURATION_BOUNDARIES },\n },\n )\n const time_to_first_chunk: Histogram = meter.createHistogram(\n 'gen_ai.client.operation.time_to_first_chunk',\n {\n unit: 's',\n description: 'Time from turn start to the first streamed chunk',\n advice: { explicitBucketBoundaries: DURATION_BOUNDARIES },\n },\n )\n const tool_duration: Histogram = meter.createHistogram('gen_ai.execute_tool.duration', {\n unit: 's',\n description: 'Tool execution duration',\n advice: { explicitBucketBoundaries: DURATION_BOUNDARIES },\n })\n const cache_token_usage: Histogram = meter.createHistogram('fascicle.client.cache.token.usage', {\n unit: '{token}',\n description: 'Number of input tokens read from or written to the prompt cache per model turn',\n advice: { explicitBucketBoundaries: TOKEN_BOUNDARIES },\n })\n const cost: Histogram = meter.createHistogram('fascicle.client.operation.cost', {\n unit: 'usd',\n description: 'Estimated cost per model turn',\n })\n const retries: Counter = meter.createCounter('fascicle.client.turn_retries', {\n unit: '{retry}',\n description: 'Provider turn attempts that failed and were retried',\n })\n\n // Open engine.generate calls in the order they started, each with the\n // identity its metric attributes carry; the last one is the innermost.\n const context_stack: Array<{ readonly id: string; readonly provider?: string; readonly model?: string }> = []\n\n const base_attributes = (): Attributes => {\n const attrs: Attributes = { 'gen_ai.operation.name': 'chat' }\n const top = context_stack[context_stack.length - 1]\n if (top?.provider !== undefined) attrs['gen_ai.provider.name'] = top.provider\n if (top?.model !== undefined) attrs['gen_ai.request.model'] = top.model\n return attrs\n }\n\n // A provider that caches reports zero counts on a turn that didn't, so a\n // direction records a point only above zero.\n const record_cache_tokens = (event: TrajectoryEvent, base: Attributes): void => {\n const reads = event_number(event, 'cached_input_tokens') ?? 0\n if (reads > 0) cache_token_usage.record(reads, { ...base, 'fascicle.cache.direction': 'read' })\n const writes = event_number(event, 'cache_write_tokens') ?? 0\n if (writes > 0) cache_token_usage.record(writes, { ...base, 'fascicle.cache.direction': 'write' })\n }\n\n const on_response_received = (event: TrajectoryEvent): void => {\n const base = base_attributes()\n record_cache_tokens(event, base)\n const input = event_number(event, 'input_tokens')\n if (input !== undefined) {\n token_usage.record(input, { ...base, 'gen_ai.token.type': 'input' })\n }\n const output = event_number(event, 'output_tokens')\n if (output !== undefined) {\n token_usage.record(output, { ...base, 'gen_ai.token.type': 'output' })\n }\n const duration_ms = event_number(event, 'duration_ms')\n if (duration_ms !== undefined) operation_duration.record(duration_ms / 1000, base)\n const first_chunk_ms = event_number(event, 'first_chunk_ms')\n if (first_chunk_ms !== undefined) {\n time_to_first_chunk.record(first_chunk_ms / 1000, base)\n }\n }\n\n return {\n on_start_span(id, name, meta) {\n if (name !== 'engine.generate') return\n const provider = meta?.['provider']\n const model = meta?.['model_id']\n context_stack.push({\n id,\n ...(typeof provider === 'string' ? { provider } : {}),\n ...(typeof model === 'string' ? { model } : {}),\n })\n },\n on_end_span(id) {\n // Removed by id, since interleaved generates need not end in the\n // reverse of the order they started.\n const idx = context_stack.findIndex((entry) => entry.id === id)\n if (idx !== -1) context_stack.splice(idx, 1)\n },\n on_record(event) {\n if (event.kind === 'response_received') {\n on_response_received(event)\n return\n }\n if (event.kind === 'tool_result') {\n const duration_ms = event_number(event, 'duration_ms')\n if (duration_ms === undefined) return\n const name = event_string(event, 'name')\n tool_duration.record(duration_ms / 1000, {\n ...base_attributes(),\n ...(name !== undefined ? { 'gen_ai.tool.name': name } : {}),\n })\n return\n }\n if (event.kind === 'cost') {\n const total_usd = event_number(event, 'total_usd')\n if (total_usd !== undefined) cost.record(total_usd, base_attributes())\n return\n }\n if (event.kind === 'turn_retry') {\n const failure_kind = event_string(event, 'failure_kind')\n retries.add(1, {\n ...base_attributes(),\n ...(failure_kind !== undefined ? { 'error.type': failure_kind } : {}),\n })\n }\n },\n }\n}\n","/**\n * OpenTelemetry bridge for Fascicle trajectory events.\n *\n * `create_otel_trajectory_logger` returns a plain TrajectoryLogger that turns\n * the engine's own span + event stream into OpenTelemetry spans: the\n * `engine.generate` span becomes an OTel root span, each `engine.generate.step`\n * a child span, and every `record`ed event (tool_call, tool_result, cost, ...)\n * an OTel span event on the currently open span. It is transport-neutral: the\n * spans come from events the engine already emits, so native and external\n * transports get traces without any AI-SDK involvement.\n *\n * `@opentelemetry/api` is imported ONLY under `src/otel/` (this module and\n * metrics.ts), outside `src/engine/` on purpose: engine code outside\n * `providers/` imports no npm package (rules/no-engine-npm-dep.yml), and an\n * app that never imports `fascicle/otel` pulls in zero OTel packages at\n * runtime.\n *\n * Nesting is resolved two ways, in order: an explicit `parent_span_id` on the\n * start meta (how the composition runner threads composer-span parenthood) wins;\n * otherwise the currently open span (top of the open stack) is the parent. This\n * is exact for the sequential engine flow (generate → step → step) and for\n * runner-nested spans; genuinely interleaved sibling spans that carry no\n * `parent_span_id` (concurrent branches sharing one logger) fall back to stack\n * order, which is this bridge's one documented approximation.\n */\n\nimport {\n context as otel_context,\n trace,\n SpanStatusCode,\n type AttributeValue,\n type Attributes,\n type Context,\n type Span,\n type Tracer,\n} from '@opentelemetry/api'\nimport type { TrajectoryEvent, TrajectoryLogger } from '#core'\nimport { create_metrics_recorder, type OtelMetricsOptions } from './metrics.js'\n\nexport type OtelTrajectoryLoggerOptions = {\n /**\n * Tracer to open spans on. Defaults to `trace.getTracer('fascicle')`, which\n * resolves against whatever global TracerProvider the host has registered.\n */\n readonly tracer?: Tracer\n /**\n * Prefix for span + event attributes derived from event metadata, keeping\n * them out of the OTel semantic-convention namespace. Defaults to `fascicle.`.\n */\n readonly attribute_prefix?: string\n /**\n * Opt-in metric instruments recorded from the same trajectory stream the\n * spans mirror (GenAI semconv client histograms plus Fascicle's cost and\n * retry instruments; see metrics.ts). `true` uses the global MeterProvider's\n * `fascicle` meter; an object supplies a custom Meter. Off by default so the\n * bridge stays a pure tracer for hosts without a metrics pipeline.\n */\n readonly metrics?: boolean | OtelMetricsOptions\n}\n\n// Event/meta keys that are bridge plumbing, not span attributes.\nconst INTERNAL_KEYS: ReadonlySet<string> = new Set(['kind', 'span_id', 'parent_span_id'])\n\n/**\n * JSON-stringify `value`, falling back to `String(value)` when `stringify`\n * throws or returns `undefined`, as it does for functions and symbols.\n */\nfunction safe_json(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\n/**\n * Convert a JS value into an OTel-compatible attribute value.\n *\n * Primitives and homogeneous primitive arrays pass through unchanged;\n * anything else falls back to `safe_json`; `null`/`undefined` drop out\n * entirely (returning `undefined`) so the caller can omit the attribute.\n */\nfunction to_attribute_value(value: unknown): AttributeValue | undefined {\n if (value === null || value === undefined) return undefined\n const kind = typeof value\n if (kind === 'string' || kind === 'number' || kind === 'boolean') {\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return value as AttributeValue\n }\n if (Array.isArray(value)) {\n if (value.every((v) => typeof v === 'string')) return value\n if (value.every((v) => typeof v === 'number')) return value\n if (value.every((v) => typeof v === 'boolean')) return value\n return safe_json(value)\n }\n return safe_json(value)\n}\n\n/**\n * True for a plain object value (not null, not an array): the shape span-meta\n * flattening applies to.\n */\nfunction is_plain_object(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * Spread one object-valued span-meta field into dotted attribute keys\n * (`usage` + `input_tokens` becomes `<prefix>usage.input_tokens`), with\n * deeper nesting falling back to `to_attribute_value`'s JSON form.\n */\nfunction flatten_into(\n attrs: Attributes,\n key: string,\n value: Record<string, unknown>,\n prefix: string,\n): void {\n for (const [inner_key, inner_value] of Object.entries(value)) {\n const attr = to_attribute_value(inner_value)\n if (attr !== undefined) attrs[`${prefix}${key}.${inner_key}`] = attr\n }\n}\n\n/**\n * Build an OTel `Attributes` object from event/meta fields.\n *\n * Skips the bridge's internal plumbing keys (`kind`, `span_id`,\n * `parent_span_id`) and prefixes the rest with `prefix` so they stay out of\n * OTel's semantic-convention namespace.\n *\n * With `flatten`, an object-valued field spreads one level into dotted keys\n * (`usage: { input_tokens: 5 }` becomes `<prefix>usage.input_tokens = 5`), so\n * span metadata like usage and model_resolved lands as numeric attributes a\n * dashboard can aggregate rather than a JSON string it cannot query. Flattening\n * applies to span meta only, never to `record`ed events: an event may carry\n * arbitrary payloads (a tool call's input, a salvage blob) where\n * attribute-per-key would explode cardinality and leak structure, so those\n * keep the JSON-string fallback.\n */\nfunction to_attributes(\n meta: Readonly<Record<string, unknown>> | undefined,\n prefix: string,\n flatten = false,\n): Attributes {\n const attrs: Attributes = {}\n if (meta === undefined) return attrs\n for (const [key, value] of Object.entries(meta)) {\n if (INTERNAL_KEYS.has(key)) continue\n if (flatten && is_plain_object(value)) {\n flatten_into(attrs, key, value, prefix)\n continue\n }\n const attr = to_attribute_value(value)\n if (attr !== undefined) attrs[`${prefix}${key}`] = attr\n }\n return attrs\n}\n\n/**\n * The engine events that carry a captured payload, and the field that holds\n * it: a turn's request, the reply's parts, and the body that went on the\n * wire. A `ctx.emit` event carries its own keys and isn't one of them.\n */\nconst CAPTURED_FIELDS: ReadonlyMap<string, string> = new Map([\n ['request_sent', 'request'],\n ['response_received', 'content'],\n ['request_wire', 'body'],\n])\n\n/**\n * A recorded event's attributes. A captured payload, which grows with the\n * conversation, is left out and recorded as `<prefix>capture.bytes`, the\n * UTF-8 length of its JSON, since an attribute has to stay small.\n */\nfunction event_attributes(event: TrajectoryEvent, prefix: string): Attributes {\n const field = CAPTURED_FIELDS.get(event.kind)\n // Stryker disable next-line ConditionalExpression: with the first test gone, `undefined in event` looks for a key named \"undefined\", which no event of another kind carries, so it returns here all the same.\n if (field === undefined || !(field in event)) return to_attributes(event, prefix)\n const { [field]: payload, ...rest } = event\n return {\n ...to_attributes(rest, prefix),\n [`${prefix}capture.bytes`]: Buffer.byteLength(safe_json(payload)),\n }\n}\n\ntype OpenSpan = { readonly span: Span; readonly context: Context }\n\n/**\n * Create a `TrajectoryLogger` that mirrors spans and events onto\n * OpenTelemetry, using `options.tracer` (or the global `fascicle` tracer).\n *\n * Parent resolution favors an explicit `parent_span_id` on the start meta;\n * otherwise it falls back to the currently open span on an internal stack.\n */\nexport function create_otel_trajectory_logger(\n options: OtelTrajectoryLoggerOptions = {},\n): TrajectoryLogger {\n const tracer = options.tracer ?? trace.getTracer('fascicle')\n const prefix = options.attribute_prefix ?? 'fascicle.'\n const metrics_recorder =\n options.metrics === undefined || options.metrics === false\n ? undefined\n : create_metrics_recorder(options.metrics === true ? {} : options.metrics)\n const open = new Map<string, OpenSpan>()\n const stack: string[] = []\n let counter = 0\n\n const top_context = (): Context | undefined => {\n const top = stack[stack.length - 1]\n if (top === undefined) return undefined\n return open.get(top)?.context\n }\n\n const parent_context = (meta: Record<string, unknown> | undefined): Context => {\n const explicit = meta?.['parent_span_id']\n if (typeof explicit === 'string') {\n const parent = open.get(explicit)\n if (parent !== undefined) return parent.context\n }\n return top_context() ?? otel_context.active()\n }\n\n const target_for_event = (event: TrajectoryEvent): Span | undefined => {\n if (typeof event.span_id === 'string') {\n const target = open.get(event.span_id)\n if (target !== undefined) return target.span\n }\n const top = stack[stack.length - 1]\n return top !== undefined ? open.get(top)?.span : undefined\n }\n\n return {\n start_span(name, meta) {\n const parent = parent_context(meta)\n const span = tracer.startSpan(\n name,\n { attributes: to_attributes(meta, prefix, true) },\n parent,\n )\n counter += 1\n const id = `fascicle-otel-${counter}`\n open.set(id, { span, context: trace.setSpan(parent, span) })\n stack.push(id)\n metrics_recorder?.on_start_span(id, name, meta)\n return id\n },\n end_span(id, meta) {\n metrics_recorder?.on_end_span(id)\n const entry = open.get(id)\n if (entry === undefined) return\n const { span } = entry\n span.setAttributes(to_attributes(meta, prefix, true))\n const error = meta?.['error']\n if (typeof error === 'string' && error.length > 0) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: error })\n }\n span.end()\n open.delete(id)\n const idx = stack.lastIndexOf(id)\n if (idx !== -1) stack.splice(idx, 1)\n },\n record(event) {\n metrics_recorder?.on_record(event)\n const span = target_for_event(event)\n if (span === undefined) return\n const name = typeof event.kind === 'string' ? event.kind : 'event'\n span.addEvent(name, event_attributes(event, prefix))\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;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logger.ts"],"sourcesContent":["/**\n * Opt-in OpenTelemetry metrics derived from the trajectory stream.\n *\n * The bridge's spans answer \"what happened on this run\"; SRE dashboards ask\n * aggregate questions (\"p95 latency by model\", \"429s per minute\", \"tokens per\n * hour\"), which want real OTel metric instruments rather than a\n * spans-to-metrics pipeline. This recorder listens to the same trajectory\n * events the span bridge mirrors and records the GenAI semantic-convention\n * client histograms, plus three Fascicle-named instruments for the data the\n * conventions do not cover yet (cost, absorbed retries, cache traffic).\n *\n * Instruments and sources:\n * - `gen_ai.client.token.usage` ({token}) from `response_received`, one\n * point per direction via `gen_ai.token.type`.\n * - `fascicle.client.cache.token.usage` ({token}) from `response_received`'s\n * `cached_input_tokens` and `cache_write_tokens`, one point per direction\n * above zero via `fascicle.cache.direction` (`read` or `write`).\n * - `gen_ai.client.operation.duration` (s) from `response_received`\n * `duration_ms`, the model-only round trip.\n * - `gen_ai.client.operation.time_to_first_chunk` (s) from\n * `first_chunk_ms` on streamed turns.\n * - `gen_ai.execute_tool.duration` (s) from `tool_result`, tagged\n * `gen_ai.tool.name`.\n * - `fascicle.client.operation.cost` (usd) from the `cost` event's\n * `total_usd`.\n * - `fascicle.client.turn_retries` ({retry}) counter from `turn_retry`,\n * tagged `error.type` with the classified failure kind.\n *\n * Provider and model attributes come from the enclosing `engine.generate`\n * span's start meta, tracked on a stack with the same documented\n * approximation as the span bridge: concurrent generates sharing one logger\n * attribute to the innermost open call. The GenAI semantic conventions are\n * experimental, so a revision of them may rename an instrument this module\n * records.\n */\n\nimport {\n metrics as otel_metrics,\n type Attributes,\n type Counter,\n type Histogram,\n type Meter,\n} from '@opentelemetry/api'\nimport type { TrajectoryEvent } from '#core'\n\nexport type OtelMetricsOptions = {\n /**\n * Meter to create instruments on. Defaults to\n * `metrics.getMeter('fascicle')`, which resolves against the global\n * MeterProvider the host has registered.\n */\n readonly meter?: Meter\n}\n\n/**\n * The span-lifecycle + event listener the trajectory logger drives when\n * metrics are enabled.\n */\nexport type MetricsRecorder = {\n readonly on_start_span: (\n id: string,\n name: string,\n meta: Record<string, unknown> | undefined,\n ) => void\n readonly on_end_span: (id: string) => void\n readonly on_record: (event: TrajectoryEvent) => void\n}\n\n/** Semconv-suggested boundaries for the duration histograms, in seconds. */\nconst DURATION_BOUNDARIES = [\n 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48,\n 40.96, 81.92,\n]\n\n/** Semconv-suggested boundaries for the token-usage histogram. */\nconst TOKEN_BOUNDARIES = [\n 1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304,\n]\n\n/**\n * Read `key` off the loose event and return it only when it is a number.\n */\nfunction event_number(event: TrajectoryEvent, key: string): number | undefined {\n const value = event[key]\n return typeof value === 'number' ? value : undefined\n}\n\n/**\n * Read `key` off the loose event and return it only when it is a string.\n */\nfunction event_string(event: TrajectoryEvent, key: string): string | undefined {\n const value = event[key]\n return typeof value === 'string' ? value : undefined\n}\n\n/**\n * Create the metrics recorder: instruments are created once here, and every\n * recording stamps the provider/model of the innermost open generate call.\n */\nexport function create_metrics_recorder(options: OtelMetricsOptions): MetricsRecorder {\n const meter = options.meter ?? otel_metrics.getMeter('fascicle')\n\n const token_usage: Histogram = meter.createHistogram('gen_ai.client.token.usage', {\n unit: '{token}',\n description: 'Number of input and output tokens used per model turn',\n advice: { explicitBucketBoundaries: TOKEN_BOUNDARIES },\n })\n const operation_duration: Histogram = meter.createHistogram(\n 'gen_ai.client.operation.duration',\n {\n unit: 's',\n description: 'Model round-trip duration of the successful turn attempt',\n advice: { explicitBucketBoundaries: DURATION_BOUNDARIES },\n },\n )\n const time_to_first_chunk: Histogram = meter.createHistogram(\n 'gen_ai.client.operation.time_to_first_chunk',\n {\n unit: 's',\n description: 'Time from turn start to the first streamed chunk',\n advice: { explicitBucketBoundaries: DURATION_BOUNDARIES },\n },\n )\n const tool_duration: Histogram = meter.createHistogram('gen_ai.execute_tool.duration', {\n unit: 's',\n description: 'Tool execution duration',\n advice: { explicitBucketBoundaries: DURATION_BOUNDARIES },\n })\n const cache_token_usage: Histogram = meter.createHistogram('fascicle.client.cache.token.usage', {\n unit: '{token}',\n description: 'Number of input tokens read from or written to the prompt cache per model turn',\n advice: { explicitBucketBoundaries: TOKEN_BOUNDARIES },\n })\n const cost: Histogram = meter.createHistogram('fascicle.client.operation.cost', {\n unit: 'usd',\n description: 'Estimated cost per model turn',\n })\n const retries: Counter = meter.createCounter('fascicle.client.turn_retries', {\n unit: '{retry}',\n description: 'Provider turn attempts that failed and were retried',\n })\n\n // Open engine.generate calls in the order they started, each with the\n // identity its metric attributes carry; the last one is the innermost.\n const context_stack: Array<{ readonly id: string; readonly provider?: string; readonly model?: string }> = []\n\n const base_attributes = (): Attributes => {\n const attrs: Attributes = { 'gen_ai.operation.name': 'chat' }\n const top = context_stack[context_stack.length - 1]\n if (top?.provider !== undefined) attrs['gen_ai.provider.name'] = top.provider\n if (top?.model !== undefined) attrs['gen_ai.request.model'] = top.model\n return attrs\n }\n\n // A provider that caches reports zero counts on a turn that didn't, so a\n // direction records a point only above zero.\n const record_cache_tokens = (event: TrajectoryEvent, base: Attributes): void => {\n const reads = event_number(event, 'cached_input_tokens') ?? 0\n if (reads > 0) cache_token_usage.record(reads, { ...base, 'fascicle.cache.direction': 'read' })\n const writes = event_number(event, 'cache_write_tokens') ?? 0\n if (writes > 0) cache_token_usage.record(writes, { ...base, 'fascicle.cache.direction': 'write' })\n }\n\n const on_response_received = (event: TrajectoryEvent): void => {\n const base = base_attributes()\n record_cache_tokens(event, base)\n const input = event_number(event, 'input_tokens')\n if (input !== undefined) {\n token_usage.record(input, { ...base, 'gen_ai.token.type': 'input' })\n }\n const output = event_number(event, 'output_tokens')\n if (output !== undefined) {\n token_usage.record(output, { ...base, 'gen_ai.token.type': 'output' })\n }\n const duration_ms = event_number(event, 'duration_ms')\n if (duration_ms !== undefined) operation_duration.record(duration_ms / 1000, base)\n const first_chunk_ms = event_number(event, 'first_chunk_ms')\n if (first_chunk_ms !== undefined) {\n time_to_first_chunk.record(first_chunk_ms / 1000, base)\n }\n }\n\n return {\n on_start_span(id, name, meta) {\n if (name !== 'engine.generate') return\n const provider = meta?.['provider']\n const model = meta?.['model_id']\n context_stack.push({\n id,\n ...(typeof provider === 'string' ? { provider } : {}),\n ...(typeof model === 'string' ? { model } : {}),\n })\n },\n on_end_span(id) {\n // Removed by id, since interleaved generates need not end in the\n // reverse of the order they started.\n const idx = context_stack.findIndex((entry) => entry.id === id)\n if (idx !== -1) context_stack.splice(idx, 1)\n },\n on_record(event) {\n if (event.kind === 'response_received') {\n on_response_received(event)\n return\n }\n if (event.kind === 'tool_result') {\n const duration_ms = event_number(event, 'duration_ms')\n if (duration_ms === undefined) return\n const name = event_string(event, 'name')\n tool_duration.record(duration_ms / 1000, {\n ...base_attributes(),\n ...(name !== undefined ? { 'gen_ai.tool.name': name } : {}),\n })\n return\n }\n if (event.kind === 'cost') {\n const total_usd = event_number(event, 'total_usd')\n if (total_usd !== undefined) cost.record(total_usd, base_attributes())\n return\n }\n if (event.kind === 'turn_retry') {\n const failure_kind = event_string(event, 'failure_kind')\n retries.add(1, {\n ...base_attributes(),\n ...(failure_kind !== undefined ? { 'error.type': failure_kind } : {}),\n })\n }\n },\n }\n}\n","/**\n * OpenTelemetry bridge for Fascicle trajectory events.\n *\n * `create_otel_trajectory_logger` returns a plain TrajectoryLogger that turns\n * the engine's own span + event stream into OpenTelemetry spans: the\n * `engine.generate` span becomes an OTel root span, each `engine.generate.step`\n * a child span, and every `record`ed event (tool_call, tool_result, cost, ...)\n * an OTel span event on the currently open span. It is transport-neutral: the\n * spans come from events the engine already emits, so native and external\n * transports get traces without any AI-SDK involvement.\n *\n * `@opentelemetry/api` is imported ONLY under `src/otel/` (this module and\n * metrics.ts), outside `src/engine/` on purpose: engine code outside\n * `providers/` imports no npm package (rules/no-engine-npm-dep.yml), and an\n * app that never imports `fascicle/otel` pulls in zero OTel packages at\n * runtime.\n *\n * Nesting is resolved two ways, in order: an explicit `parent_span_id` on the\n * start meta (how the composition runner threads composer-span parenthood) wins;\n * otherwise the currently open span (top of the open stack) is the parent. This\n * is exact for the sequential engine flow (generate → step → step) and for\n * runner-nested spans; genuinely interleaved sibling spans that carry no\n * `parent_span_id` (concurrent branches sharing one logger) fall back to stack\n * order, which is this bridge's one documented approximation.\n */\n\nimport {\n context as otel_context,\n trace,\n SpanStatusCode,\n type Attributes,\n type Context,\n type Span,\n type Tracer,\n} from '@opentelemetry/api'\nimport type { TrajectoryEvent, TrajectoryLogger } from '#core'\nimport { create_metrics_recorder, type OtelMetricsOptions } from './metrics.js'\n\nexport type OtelTrajectoryLoggerOptions = {\n /**\n * Tracer to open spans on. Defaults to `trace.getTracer('fascicle')`, which\n * resolves against whatever global TracerProvider the host has registered.\n */\n readonly tracer?: Tracer\n /**\n * Prefix for span + event attributes derived from event metadata, keeping\n * them out of the OTel semantic-convention namespace. Defaults to `fascicle.`.\n */\n readonly attribute_prefix?: string\n /**\n * Opt-in metric instruments recorded from the same trajectory stream the\n * spans mirror (GenAI semconv client histograms plus Fascicle's cost and\n * retry instruments; see metrics.ts). `true` uses the global MeterProvider's\n * `fascicle` meter; an object supplies a custom Meter. Off by default so the\n * bridge stays a pure tracer for hosts without a metrics pipeline.\n */\n readonly metrics?: boolean | OtelMetricsOptions\n}\n\n// Event/meta keys that are bridge plumbing, not span attributes.\nconst INTERNAL_KEYS: ReadonlySet<string> = new Set(['kind', 'span_id', 'parent_span_id'])\n\n/**\n * JSON-stringify `value`, falling back to `String(value)` when `stringify`\n * throws or returns `undefined`, as it does for functions and symbols.\n */\nfunction safe_json(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\n/**\n * The attribute values the bridge writes, a primitive or a homogeneous array\n * of one, which every `@opentelemetry/api` release in the peer range accepts.\n * From 1.10 the API also takes complex values, which backends aren't\n * expected to index.\n */\ntype SimpleAttributeValue = string | number | boolean | string[] | number[] | boolean[]\n\n/**\n * Convert a JS value into an OTel-compatible attribute value.\n *\n * Primitives and homogeneous primitive arrays pass through unchanged;\n * anything else falls back to `safe_json`; `null`/`undefined` drop out\n * entirely (returning `undefined`) so the caller can omit the attribute.\n */\nfunction to_attribute_value(value: unknown): SimpleAttributeValue | undefined {\n if (value === null || value === undefined) return undefined\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value\n if (Array.isArray(value)) {\n if (value.every((v) => typeof v === 'string')) return value\n if (value.every((v) => typeof v === 'number')) return value\n if (value.every((v) => typeof v === 'boolean')) return value\n return safe_json(value)\n }\n return safe_json(value)\n}\n\n/**\n * True for a plain object value (not null, not an array): the shape span-meta\n * flattening applies to.\n */\nfunction is_plain_object(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * Spread one object-valued span-meta field into dotted attribute keys\n * (`usage` + `input_tokens` becomes `<prefix>usage.input_tokens`), with\n * deeper nesting falling back to `to_attribute_value`'s JSON form.\n */\nfunction flatten_into(\n attrs: Attributes,\n key: string,\n value: Record<string, unknown>,\n prefix: string,\n): void {\n for (const [inner_key, inner_value] of Object.entries(value)) {\n const attr = to_attribute_value(inner_value)\n if (attr !== undefined) attrs[`${prefix}${key}.${inner_key}`] = attr\n }\n}\n\n/**\n * Build an OTel `Attributes` object from event/meta fields.\n *\n * Skips the bridge's internal plumbing keys (`kind`, `span_id`,\n * `parent_span_id`) and prefixes the rest with `prefix` so they stay out of\n * OTel's semantic-convention namespace.\n *\n * With `flatten`, an object-valued field spreads one level into dotted keys\n * (`usage: { input_tokens: 5 }` becomes `<prefix>usage.input_tokens = 5`), so\n * span metadata like usage and model_resolved lands as numeric attributes a\n * dashboard can aggregate rather than a JSON string it cannot query. Flattening\n * applies to span meta only, never to `record`ed events: an event may carry\n * arbitrary payloads (a tool call's input, a salvage blob) where\n * attribute-per-key would explode cardinality and leak structure, so those\n * keep the JSON-string fallback.\n */\nfunction to_attributes(\n meta: Readonly<Record<string, unknown>> | undefined,\n prefix: string,\n flatten = false,\n): Attributes {\n const attrs: Attributes = {}\n if (meta === undefined) return attrs\n for (const [key, value] of Object.entries(meta)) {\n if (INTERNAL_KEYS.has(key)) continue\n if (flatten && is_plain_object(value)) {\n flatten_into(attrs, key, value, prefix)\n continue\n }\n const attr = to_attribute_value(value)\n if (attr !== undefined) attrs[`${prefix}${key}`] = attr\n }\n return attrs\n}\n\n/**\n * The engine events that carry a captured payload, and the field that holds\n * it: a turn's request, the reply's parts, and the body that went on the\n * wire. A `ctx.emit` event carries its own keys and isn't one of them.\n */\nconst CAPTURED_FIELDS: ReadonlyMap<string, string> = new Map([\n ['request_sent', 'request'],\n ['response_received', 'content'],\n ['request_wire', 'body'],\n])\n\n/**\n * A recorded event's attributes. A captured payload, which grows with the\n * conversation, is left out and recorded as `<prefix>capture.bytes`, the\n * UTF-8 length of its JSON, since an attribute has to stay small.\n */\nfunction event_attributes(event: TrajectoryEvent, prefix: string): Attributes {\n const field = CAPTURED_FIELDS.get(event.kind)\n // Stryker disable next-line ConditionalExpression: with the first test gone, `undefined in event` looks for a key named \"undefined\", which no event of another kind carries, so it returns here all the same.\n if (field === undefined || !(field in event)) return to_attributes(event, prefix)\n const { [field]: payload, ...rest } = event\n return {\n ...to_attributes(rest, prefix),\n [`${prefix}capture.bytes`]: Buffer.byteLength(safe_json(payload)),\n }\n}\n\ntype OpenSpan = { readonly span: Span; readonly context: Context }\n\n/**\n * Create a `TrajectoryLogger` that mirrors spans and events onto\n * OpenTelemetry, using `options.tracer` (or the global `fascicle` tracer).\n *\n * Parent resolution favors an explicit `parent_span_id` on the start meta;\n * otherwise it falls back to the currently open span on an internal stack.\n */\nexport function create_otel_trajectory_logger(\n options: OtelTrajectoryLoggerOptions = {},\n): TrajectoryLogger {\n const tracer = options.tracer ?? trace.getTracer('fascicle')\n const prefix = options.attribute_prefix ?? 'fascicle.'\n const metrics_recorder =\n options.metrics === undefined || options.metrics === false\n ? undefined\n : create_metrics_recorder(options.metrics === true ? {} : options.metrics)\n const open = new Map<string, OpenSpan>()\n const stack: string[] = []\n let counter = 0\n\n const top_context = (): Context | undefined => {\n const top = stack[stack.length - 1]\n if (top === undefined) return undefined\n return open.get(top)?.context\n }\n\n const parent_context = (meta: Record<string, unknown> | undefined): Context => {\n const explicit = meta?.['parent_span_id']\n if (typeof explicit === 'string') {\n const parent = open.get(explicit)\n if (parent !== undefined) return parent.context\n }\n return top_context() ?? otel_context.active()\n }\n\n const target_for_event = (event: TrajectoryEvent): Span | undefined => {\n if (typeof event.span_id === 'string') {\n const target = open.get(event.span_id)\n if (target !== undefined) return target.span\n }\n const top = stack[stack.length - 1]\n return top !== undefined ? open.get(top)?.span : undefined\n }\n\n return {\n start_span(name, meta) {\n const parent = parent_context(meta)\n const span = tracer.startSpan(\n name,\n { attributes: to_attributes(meta, prefix, true) },\n parent,\n )\n counter += 1\n const id = `fascicle-otel-${counter}`\n open.set(id, { span, context: trace.setSpan(parent, span) })\n stack.push(id)\n metrics_recorder?.on_start_span(id, name, meta)\n return id\n },\n end_span(id, meta) {\n metrics_recorder?.on_end_span(id)\n const entry = open.get(id)\n if (entry === undefined) return\n const { span } = entry\n span.setAttributes(to_attributes(meta, prefix, true))\n const error = meta?.['error']\n if (typeof error === 'string' && error.length > 0) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: error })\n }\n span.end()\n open.delete(id)\n const idx = stack.lastIndexOf(id)\n if (idx !== -1) stack.splice(idx, 1)\n },\n record(event) {\n metrics_recorder?.on_record(event)\n const span = target_for_event(event)\n if (span === undefined) return\n const name = typeof event.kind === 'string' ? event.kind : 'event'\n span.addEvent(name, event_attributes(event, prefix))\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,MAAM,sBAAsB;CAC1B;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAO;CACnE;CAAO;AACT;;AAGA,MAA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L,WAAW,MAAM,MAAM;GACrB,MAAM,SAAS,eAAe,IAAI;GAClC,MAAM,OAAO,OAAO,UAClB,MACA,EAAE,YAAY,cAAc,MAAM,QAAQ,IAAI,EAAE,GAChD,MACF;GACA,WAAW;GACX,MAAM,KAAK,iBAAiB;GAC5B,KAAK,IAAI,IAAI;IAAE;IAAM,SAAS,MAAM,QAAQ,QAAQ,IAAI;GAAE,CAAC;GAC3D,MAAM,KAAK,EAAE;GACb,kBAAkB,cAAc,IAAI,MAAM,IAAI;GAC9C,OAAO;EACT;EACA,SAAS,IAAI,MAAM;GACjB,kBAAkB,YAAY,EAAE;GAChC,MAAM,QAAQ,KAAK,IAAI,EAAE;GACzB,IAAI,UAAU,KAAA,GAAW;GACzB,MAAM,EAAE,SAAS;GACjB,KAAK,cAAc,cAAc,MAAM,QAAQ,IAAI,CAAC;GACpD,MAAM,QAAQ,OAAO;GACrB,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,GAC9C,KAAK,UAAU;IAAE,MAAM,eAAe;IAAO,SAAS;GAAM,CAAC;GAE/D,KAAK,IAAI;GACT,KAAK,OAAO,EAAE;GACd,MAAM,MAAM,MAAM,YAAY,EAAE;GAChC,IAAI,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;EACrC;EACA,OAAO,OAAO;GACZ,kBAAkB,UAAU,KAAK;GACjC,MAAM,OAAO,iBAAiB,KAAK;GACnC,IAAI,SAAS,KAAA,GAAW;GACxB,MAAM,OAAO,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO;GAC3D,KAAK,SAAS,MAAM,iBAAiB,OAAO,MAAM,CAAC;EACrD;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- //#region src/schema/records.ts
1
+ // src/schema/records.ts
2
2
  /**
3
3
  * Small shared guards for reading untyped JSON. They live beside the JSON
4
4
  * Schema bridge that needs them and are exported, so MCP's client and result
@@ -16,7 +16,6 @@ function is_record(value) {
16
16
  function as_record(value) {
17
17
  return is_record(value) ? value : void 0;
18
18
  }
19
- //#endregion
20
19
  export { is_record as n, as_record as t };
21
20
 
22
- //# sourceMappingURL=records-1HU7mWXf.js.map
21
+ //# sourceMappingURL=records-Btlmvunj.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"records-1HU7mWXf.js","names":[],"sources":["../src/schema/records.ts"],"sourcesContent":["/**\n * Small shared guards for reading untyped JSON. They live beside the JSON\n * Schema bridge that needs them and are exported, so MCP's client and result\n * mapping read payloads through the same copy rather than carrying their own.\n */\n\n/**\n * Narrows a value to a plain object: non-null, `typeof` object, not an array.\n */\nexport function is_record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Returns the value when it is a plain object, otherwise `undefined`.\n */\nexport function as_record(value: unknown): Record<string, unknown> | undefined {\n return is_record(value) ? value : undefined\n}\n"],"mappings":";;;;;;;;;AASA,SAAgB,UAAU,OAAkD;CAC1E,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;AAKA,SAAgB,UAAU,OAAqD;CAC7E,OAAO,UAAU,KAAK,IAAI,QAAQ,KAAA;AACpC"}
1
+ {"version":3,"file":"records-Btlmvunj.js","names":[],"sources":["../src/schema/records.ts"],"sourcesContent":["/**\n * Small shared guards for reading untyped JSON. They live beside the JSON\n * Schema bridge that needs them and are exported, so MCP's client and result\n * mapping read payloads through the same copy rather than carrying their own.\n */\n\n/**\n * Narrows a value to a plain object: non-null, `typeof` object, not an array.\n */\nexport function is_record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Returns the value when it is a plain object, otherwise `undefined`.\n */\nexport function as_record(value: unknown): Record<string, unknown> | undefined {\n return is_record(value) ? value : undefined\n}\n"],"mappings":";;;;;;;;;AASA,SAAgB,UAAU,OAAkD;CAC1E,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;AAKA,SAAgB,UAAU,OAAqD;CAC7E,OAAO,UAAU,KAAK,IAAI,QAAQ,KAAA;AACpC"}
@@ -1,9 +1,9 @@
1
- import { t as as_record } from "./records-1HU7mWXf.js";
2
- import { t as json_schema_to_standard } from "./json_schema_to_standard-C4F4lXHE.js";
1
+ import { t as as_record } from "./records-Btlmvunj.js";
2
+ import { t as json_schema_to_standard } from "./json_schema_to_standard-BstoXjM8.js";
3
3
  import { open, readdir, readlink, realpath, stat } from "node:fs/promises";
4
4
  import { basename, dirname, extname, isAbsolute, join, matchesGlob, relative, resolve, sep } from "node:path";
5
5
  import { Worker } from "node:worker_threads";
6
- //#region src/acp/tools/containment.ts
6
+ // src/acp/tools/containment.ts
7
7
  /**
8
8
  * Containment: the boundary the workspace file tools keep. A path, absolute
9
9
  * or relative to the session's `cwd`, is allowed only when its real path
@@ -159,8 +159,7 @@ async function contain_writable(session, requested, tool) {
159
159
  function shown_path(session, path) {
160
160
  return is_within(session.cwd, path) ? relative(session.cwd, path) || "." : path;
161
161
  }
162
- //#endregion
163
- //#region src/acp/tools/read_file.ts
162
+ // src/acp/tools/read_file.ts
164
163
  /**
165
164
  * read_file: read a text file in the workspace with its lines numbered, a
166
165
  * window at a time.
@@ -294,8 +293,7 @@ function read_file_tool(session, read_limit_lines) {
294
293
  }
295
294
  };
296
295
  }
297
- //#endregion
298
- //#region src/acp/tools/list_files.ts
296
+ // src/acp/tools/list_files.ts
299
297
  /** What `list_files` matches when the call names no pattern. */
300
298
  const ALL_FILES$1 = "**/*";
301
299
  /**
@@ -395,8 +393,7 @@ function list_files_tool(session, ignore, limit) {
395
393
  }
396
394
  };
397
395
  }
398
- //#endregion
399
- //#region src/acp/tools/search.ts
396
+ // src/acp/tools/search.ts
400
397
  /**
401
398
  * search: find the lines in the workspace's files that match a regular
402
399
  * expression.
@@ -623,7 +620,6 @@ function search_tool(session, ignore, budget_ms) {
623
620
  }
624
621
  };
625
622
  }
626
- //#endregion
627
623
  export { read_file_tool as a, resolve_roots as c, is_binary as i, shown_path as l, search_tool as n, contain_writable as o, list_files_tool as r, error_code as s, search_files as t };
628
624
 
629
- //# sourceMappingURL=search-DjhdMsJ8.js.map
625
+ //# sourceMappingURL=search-BZagxXtd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"search-DjhdMsJ8.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 * The writes keep a stricter boundary inside the roots: nothing under a\n * `.git` or a `node_modules`. Git runs what its directory holds (a hook,\n * `core.fsmonitor`), a package manager runs what `node_modules` holds\n * (`.bin`, an install script), and a change in either never shows in\n * `git diff`, so an edit there would be code that runs unseen. No mode lifts\n * it, since Accept edits and Auto write without asking.\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 names a write never reaches through, wherever under a root they sit:\n * a nested repository's `.git` counts, and so does a worktree's, which is a\n * file pointing git at its real directory.\n */\nconst GUARDED_NAMES: ReadonlySet<string> = new Set(['.git', 'node_modules'])\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 segment as a file system that ignores case, or Windows, which also\n * drops trailing dots and spaces, compares it, so `.GIT` and `.git.` name\n * the same directory as `.git` wherever they do.\n */\nfunction folded(segment: string): string {\n return segment.toLowerCase().replace(/[. ]+$/u, '')\n}\n\n/**\n * The first of GUARDED_NAMES on the way down to `path` from any root it lies\n * under, or `undefined` when there is none.\n */\nfunction guarded_segment(roots: ReadonlyArray<string>, path: string): string | undefined {\n for (const root of roots) {\n if (!is_within(root, path)) continue\n const found = relative(root, path).split(sep).map(folded).find((name) => GUARDED_NAMES.has(name))\n if (found !== undefined) return found\n }\n return undefined\n}\n\n/**\n * Check a path a write was handed the way `contain` does, then refuse one\n * that reaches `.git` or `node_modules` under a root. The path is checked as\n * written, against the roots in the client's terms, and as its symlinks\n * resolve, against the real ones, so a `.git` that is a symlink and a\n * symlink into `.git` are both refused. `tool` names the tool asking, for\n * the refusal, which points the model at `run_command`, the tool that asks\n * before it acts in Manual and in Accept edits.\n */\nexport async function contain_writable(session: AcpSession, requested: string, tool: string): Promise<ContainedPath> {\n const target = await contain(session, requested)\n const roots = [...session.roots, ...[session.cwd, ...session.additional_directories].map((dir) => resolve(dir))]\n const segment = guarded_segment(roots, target.path) ?? guarded_segment(roots, target.real)\n if (segment === undefined) return target\n throw new Error(\n `${requested} reaches ${segment}, where ${tool} never writes, since what's there can run on the user's next command without showing in git diff; if it has to change, use run_command`,\n )\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 file streams line by line, so a\n * window near the top of a huge file reads 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 read_only: true,\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, can drop a whole directory it has 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 read_only: true,\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 read_only: true,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,0BAAgC,IAAI,IAAI,CAAC,UAAU,SAAS,CAAC;;;;;;AAOnE,MAAM,gBAAgB;;;;;;AAOtB,MAAM,gCAAqC,IAAI,IAAI,CAAC,QAAQ,cAAc,CAAC;;;;;AAM3E,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,QAAyB;CACxD,OAAO,WAAW,QAAQ,OAAO,WAAW,KAAK,SAAS,GAAG,IAAI,OAAO,GAAG,OAAO,KAAK;AACzF;;;;;AAMA,eAAe,YAAY,MAA2C;CACpE,OAAO,SAAS,IAAI,CAAC,CAAC,YAAY,KAAA,CAAS;AAC7C;;;;;;;AAQA,eAAe,UAAU,MAAc,WA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MAAM;KAAU,aAAa,gEAAgE;IAAY;GACnH;GACA,UAAU,CAAC,SAAS;GACpB,sBAAsB;EACxB,CAAC;EACD,WAAW;EACX,SAAS,OAAO,OAAO,QAAQ;GAC7B,MAAM,UAAU,eAAe,KAAK;GACpC,MAAM,OAAO,MAAM,QAAQ,SAAS,QAAQ,IAAI;GAChD,MAAM,OAAO,MAAM,KAAK,KAAK,IAAI;GACjC,IAAI,CAAC,KAAK,YAAY,KAAK,CAAC,KAAK,OAAO,GACtC,MAAM,IAAI,MAAM,GAAG,QAAQ,KAAK,8DAA8D;GAEhG,MAAM,MAAiB;IACrB,MAAM,KAAK;IACX,WAAW,KAAK,YAAY;IAC5B,SAAS,QAAQ;IACjB,MAAM,UAAU,QAAQ,IAAI;IAC5B;IACA,OAAO;GACT;GACA,OAAO,OAAO,SAAS,KAAK,MAAM,SAAS,MAAM,UAAU,KAAK,WAAW,IAAI,KAAK,CAAC;EACvF;CACF;AACF"}
1
+ {"version":3,"file":"search-BZagxXtd.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 * The writes keep a stricter boundary inside the roots: nothing under a\n * `.git` or a `node_modules`. Git runs what its directory holds (a hook,\n * `core.fsmonitor`), a package manager runs what `node_modules` holds\n * (`.bin`, an install script), and a change in either never shows in\n * `git diff`, so an edit there would be code that runs unseen. No mode lifts\n * it, since Accept edits and Auto write without asking.\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 names a write never reaches through, wherever under a root they sit:\n * a nested repository's `.git` counts, and so does a worktree's, which is a\n * file pointing git at its real directory.\n */\nconst GUARDED_NAMES: ReadonlySet<string> = new Set(['.git', 'node_modules'])\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 segment as a file system that ignores case, or Windows, which also\n * drops trailing dots and spaces, compares it, so `.GIT` and `.git.` name\n * the same directory as `.git` wherever they do.\n */\nfunction folded(segment: string): string {\n return segment.toLowerCase().replace(/[. ]+$/u, '')\n}\n\n/**\n * The first of GUARDED_NAMES on the way down to `path` from any root it lies\n * under, or `undefined` when there is none.\n */\nfunction guarded_segment(roots: ReadonlyArray<string>, path: string): string | undefined {\n for (const root of roots) {\n if (!is_within(root, path)) continue\n const found = relative(root, path).split(sep).map(folded).find((name) => GUARDED_NAMES.has(name))\n if (found !== undefined) return found\n }\n return undefined\n}\n\n/**\n * Check a path a write was handed the way `contain` does, then refuse one\n * that reaches `.git` or `node_modules` under a root. The path is checked as\n * written, against the roots in the client's terms, and as its symlinks\n * resolve, against the real ones, so a `.git` that is a symlink and a\n * symlink into `.git` are both refused. `tool` names the tool asking, for\n * the refusal, which points the model at `run_command`, the tool that asks\n * before it acts in Manual and in Accept edits.\n */\nexport async function contain_writable(session: AcpSession, requested: string, tool: string): Promise<ContainedPath> {\n const target = await contain(session, requested)\n const roots = [...session.roots, ...[session.cwd, ...session.additional_directories].map((dir) => resolve(dir))]\n const segment = guarded_segment(roots, target.path) ?? guarded_segment(roots, target.real)\n if (segment === undefined) return target\n throw new Error(\n `${requested} reaches ${segment}, where ${tool} never writes, since what's there can run on the user's next command without showing in git diff; if it has to change, use run_command`,\n )\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 file streams line by line, so a\n * window near the top of a huge file reads 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 read_only: true,\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, can drop a whole directory it has 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 read_only: true,\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 read_only: true,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,0BAAgC,IAAI,IAAI,CAAC,UAAU,SAAS,CAAC;;;;;;AAOnE,MAAM,gBAAgB;;;;;;AAOtB,MAAM,gCAAqC,IAAI,IAAI,CAAC,QAAQ,cAAc,CAAC;;;;;AAM3E,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,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,QAAQ,OAAO,6DAA6D;CAElH,OAAO,MAAM,KAAK,IAAI;AACxB;;;;;;;AAQA,SAAgB,YAAY,SAAqB,QAA+B,WAAyB;CACvG,OAAO;EACL,MAAM;EACN,aAAa;GACX,mFAAmF,YAAY;GAC/F;GACA;GACA;GACA;GACA;GACA;GACA,OAAO,WAAW,IAAI,wBAAwB,0BAA0B,OAAO,KAAK,IAAI,EAAE;EAC5F,CAAC,CAAC,KAAK,GAAG;EACV,cAAc,wBAAwB;GACpC,MAAM;GACN,YAAY;IACV,SAAS;KAAE,MAAM;KAAU,aAAa;IAA4D;IACpG,MAAM;KACJ,MAAM;KACN,aAAa;IACf;IACA,MAAM;KAAE,MAAM;KAAU,aAAa,gEAAgE;IAAY;GACnH;GACA,UAAU,CAAC,SAAS;GACpB,sBAAsB;EACxB,CAAC;EACD,WAAW;EACX,SAAS,OAAO,OAAO,QAAQ;GAC7B,MAAM,UAAU,eAAe,KAAK;GACpC,MAAM,OAAO,MAAM,QAAQ,SAAS,QAAQ,IAAI;GAChD,MAAM,OAAO,MAAM,KAAK,KAAK,IAAI;GACjC,IAAI,CAAC,KAAK,YAAY,KAAK,CAAC,KAAK,OAAO,GACtC,MAAM,IAAI,MAAM,GAAG,QAAQ,KAAK,8DAA8D;GAEhG,MAAM,MAAiB;IACrB,MAAM,KAAK;IACX,WAAW,KAAK,YAAY;IAC5B,SAAS,QAAQ;IACjB,MAAM,UAAU,QAAQ,IAAI;IAC5B;IACA,OAAO;GACT;GACA,OAAO,OAAO,SAAS,KAAK,MAAM,SAAS,MAAM,UAAU,KAAK,WAAW,IAAI,KAAK,CAAC;EACvF;CACF;AACF"}
@@ -1,6 +1,6 @@
1
- import { t as search_files } from "./search-DjhdMsJ8.js";
1
+ import { t as search_files } from "./search-BZagxXtd.js";
2
2
  import { parentPort, workerData } from "node:worker_threads";
3
- //#region src/acp/tools/search_worker.ts
3
+ // src/acp/tools/search_worker.ts
4
4
  /**
5
5
  * The search worker: one search, run off the main thread so the turn's
6
6
  * abort and the time budget can terminate it mid-match.
@@ -13,7 +13,6 @@ import { parentPort, workerData } from "node:worker_threads";
13
13
  * thread's `error` event carries the error back.
14
14
  */
15
15
  parentPort?.postMessage(await search_files(workerData));
16
- //#endregion
17
16
  export {};
18
17
 
19
18
  //# sourceMappingURL=search_worker.js.map
package/dist/stdio.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { c as Step, h as TrajectoryLogger } from "./types-CPqLZOEr.js";
2
- import { t as AnySchema } from "./types-BK0UW28o.js";
3
- //#region src/stdio/execute_stdio.d.ts
1
+ import { c as Step, h as TrajectoryLogger } from "./types-BUXt_zgJ.js";
2
+ import { t as AnySchema } from "./types-CvghbZ0x.js";
4
3
  type RunStdioOptions<i, o> = {
5
4
  readonly input_schema?: AnySchema<i>;
6
5
  readonly output_schema?: AnySchema<o>;
@@ -38,8 +37,6 @@ type StdioIo = {
38
37
  * carries an authoritative result" true even when disposal fails.
39
38
  */
40
39
  export declare function execute_stdio<i, o>(flow: Step<i, o>, options: RunStdioOptions<i, o>, io: StdioIo): Promise<StdioOutcome>;
41
- //#endregion
42
- //#region src/stdio/run_stdio.d.ts
43
40
  /**
44
41
  * Runs a flow as the stdio agent contract against the real process streams,
45
42
  * then exits with the outcome's code.
@@ -49,6 +46,5 @@ export declare function execute_stdio<i, o>(flow: Step<i, o>, options: RunStdioO
49
46
  * detail.
50
47
  */
51
48
  export declare function run_stdio<i, o>(flow: Step<i, o>, options?: RunStdioOptions<i, o>): Promise<void>;
52
- //#endregion
53
49
  export type { RunStdioOptions, StdioFailure, StdioIo, StdioOutcome };
54
50
  //# sourceMappingURL=stdio.d.ts.map
package/dist/stdio.js CHANGED
@@ -1,8 +1,8 @@
1
- import { C as validate_schema, w as run } from "./core-Bfzt55Fl.js";
2
- import { r as stderr_logger } from "./adapters-CDUzZlby.js";
3
- import { t as route_console_to_stderr } from "./console-CdB4pcFO.js";
1
+ import { t as route_console_to_stderr } from "./console-B1ozi_ii.js";
2
+ import { C as validate_schema, w as run } from "./core-BH7sWpEG.js";
3
+ import { r as stderr_logger } from "./adapters-CpKpDk7r.js";
4
4
  import { text } from "node:stream/consumers";
5
- //#region src/stdio/execute_stdio.ts
5
+ // src/stdio/execute_stdio.ts
6
6
  /**
7
7
  * The stdio agent contract, minus the process.
8
8
  *
@@ -204,8 +204,7 @@ function to_json_safe(value) {
204
204
  return;
205
205
  }
206
206
  }
207
- //#endregion
208
- //#region src/stdio/run_stdio.ts
207
+ // src/stdio/run_stdio.ts
209
208
  /**
210
209
  * Process glue for the stdio agent contract.
211
210
  *
@@ -258,7 +257,6 @@ function write_flushed(stream, chunk) {
258
257
  });
259
258
  });
260
259
  }
261
- //#endregion
262
260
  export { execute_stdio, run_stdio };
263
261
 
264
262
  //# sourceMappingURL=stdio.js.map
package/dist/stdio.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"stdio.js","names":[],"sources":["../src/stdio/execute_stdio.ts","../src/stdio/run_stdio.ts"],"sourcesContent":["/**\n * The stdio agent contract, minus the process.\n *\n * `execute_stdio` is everything `run_stdio` does (read, parse, validate, run,\n * validate, serialize, dispose), expressed over an injected `StdioIo` and\n * returning a `StdioOutcome` instead of touching `process.*` or exiting. The\n * split keeps the contract's branching unit-testable; the thin glue in\n * `run_stdio.ts` owns the real streams and the exit.\n *\n * The governing invariant: code 0 if and only if stdout carries an\n * authoritative result. That is why the engine is disposed before the output\n * is written (a teardown failure on the success path yields code 1 and no\n * stdout) and why every failure class short-circuits before `write_output`.\n * Code 1 means the flow did not produce a result (including a forwarded\n * SIGINT/SIGTERM aborting the run, or a failed delivery); code 2 means the\n * contract itself was violated (unparseable stdin, schema mismatch in either\n * direction, unserializable result).\n */\n\nimport { validate_schema, type AnySchema } from '#schema'\nimport { run } from '#core'\nimport type { Step, TrajectoryLogger } from '#core'\nimport { stderr_logger } from '#adapters'\n\nexport type RunStdioOptions<i, o> = {\n readonly input_schema?: AnySchema<i>\n readonly output_schema?: AnySchema<o>\n // Structural on purpose: anything with an async dispose qualifies, and the\n // stdio module never imports the engine layer.\n readonly engine?: { readonly dispose: () => Promise<void> }\n readonly trajectory?: TrajectoryLogger\n readonly abort?: AbortSignal\n}\n\nexport type StdioFailure = {\n readonly error: string\n readonly stage?:\n | 'read'\n | 'parse'\n | 'validate_input'\n | 'run'\n | 'validate_output'\n | 'serialize'\n | 'write'\n | 'dispose'\n readonly cause?: unknown\n}\n\nexport type StdioOutcome =\n | { readonly code: 0 }\n | { readonly code: 1 | 2; readonly failure: StdioFailure }\n\nexport type StdioIo = {\n readonly read_input: () => Promise<string>\n // Resolves once the bytes are flushed to the OS, so the caller may exit.\n readonly write_output: (text: string) => Promise<void>\n readonly error_stream: { write(chunk: string): unknown }\n}\n\n/**\n * Runs the stdio agent contract over injected `io`: read input, run the\n * flow, dispose the engine, write output, and return the outcome as a\n * value.\n *\n * Disposes the engine before writing output so a teardown failure on the\n * success path yields code 1 and no stdout, keeping \"code 0 means stdout\n * carries an authoritative result\" true even when disposal fails.\n */\nexport async function execute_stdio<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o>,\n io: StdioIo,\n): Promise<StdioOutcome> {\n const produced = await produce_output(flow, options, io)\n const dispose_failure = await dispose_engine(options.engine)\n if (produced.kind === 'failed') return { code: produced.code, failure: produced.failure }\n if (dispose_failure !== null) return { code: 1, failure: dispose_failure }\n try {\n await io.write_output(`${produced.json}\\n`)\n } catch (err) {\n return { code: 1, failure: make_failure('write', err) }\n }\n return { code: 0 }\n}\n\ntype ProduceResult =\n | { readonly kind: 'ok'; readonly json: string }\n | { readonly kind: 'failed'; readonly code: 1 | 2; readonly failure: StdioFailure }\n\n/**\n * Reads stdin, parses and validates it against the input schema, runs the\n * flow, then validates and serializes the result.\n *\n * Returns a tagged result instead of throwing so `execute_stdio` can dispose\n * the engine and choose the right exit code regardless of which stage\n * failed.\n */\nasync function produce_output<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o>,\n io: StdioIo,\n): Promise<ProduceResult> {\n let raw: string\n try {\n raw = await io.read_input()\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('read', err) }\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('parse', err) }\n }\n\n let input: i\n if (options.input_schema !== undefined) {\n const checked = await validate_schema(options.input_schema, parsed)\n if (!checked.ok) {\n return {\n kind: 'failed',\n code: 2,\n failure: {\n error: 'input failed schema validation',\n stage: 'validate_input',\n cause: to_json_safe(checked.issues),\n },\n }\n }\n input = checked.value\n } else {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n input = parsed as i\n }\n\n const trajectory = options.trajectory ?? stderr_logger({ stream: io.error_stream })\n\n let result: o\n try {\n result = await run(flow, input, {\n trajectory,\n ...(options.abort !== undefined ? { abort: options.abort } : {}),\n })\n } catch (err) {\n return { kind: 'failed', code: 1, failure: make_failure('run', err) }\n }\n\n let output: unknown = result\n if (options.output_schema !== undefined) {\n const checked = await validate_schema(options.output_schema, result)\n if (!checked.ok) {\n return {\n kind: 'failed',\n code: 2,\n failure: {\n error: 'flow result failed schema validation',\n stage: 'validate_output',\n cause: to_json_safe(checked.issues),\n },\n }\n }\n output = checked.value\n }\n\n let json: string | undefined\n try {\n json = JSON.stringify(output)\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('serialize', err) }\n }\n if (json === undefined) {\n return {\n kind: 'failed',\n code: 2,\n failure: { error: 'flow result is not JSON-serializable', stage: 'serialize' },\n }\n }\n return { kind: 'ok', json }\n}\n\n/**\n * Disposes the caller's engine when one was supplied, returning a\n * `StdioFailure` if disposal throws and `null` otherwise.\n */\nasync function dispose_engine(\n engine: RunStdioOptions<never, never>['engine'],\n): Promise<StdioFailure | null> {\n if (engine === undefined) return null\n try {\n await engine.dispose()\n return null\n } catch (err) {\n return make_failure('dispose', err)\n }\n}\n\n/**\n * Builds a `StdioFailure` for the given stage from a thrown value.\n */\nfunction make_failure(stage: NonNullable<StdioFailure['stage']>, err: unknown): StdioFailure {\n const cause = safe_cause(err)\n return {\n error: err instanceof Error ? err.message : String(err),\n stage,\n ...(cause !== undefined ? { cause } : {}),\n }\n}\n\n/**\n * Reduces a thrown value to a JSON-safe cause for `StdioFailure`.\n *\n * An `Error` is reduced to its `name`, `message`, and the `path` property the\n * runner stamps on it as it bubbles up through nested steps; anything else is\n * passed through `to_json_safe`.\n */\nfunction safe_cause(err: unknown): unknown {\n if (err instanceof Error) {\n const path = Reflect.get(err, 'path')\n return {\n name: err.name,\n message: err.message,\n ...(Array.isArray(path) ? { path: to_json_safe(path) } : {}),\n }\n }\n return to_json_safe(err)\n}\n\n/**\n * Round-trips a value through `JSON.stringify`/`parse` so it is safe to\n * embed in a `StdioFailure` that the glue will serialize again.\n *\n * Never throws and never returns a value that would make that later\n * serialization throw or silently vanish: a circular reference or a BigInt\n * becomes `undefined` instead.\n */\nfunction to_json_safe(value: unknown): unknown {\n try {\n const json = JSON.stringify(value)\n if (json === undefined) return undefined\n return JSON.parse(json) as unknown\n } catch {\n return undefined\n }\n}\n","/**\n * Process glue for the stdio agent contract.\n *\n * Binds `execute_stdio` to the real process: stdin to EOF in, exactly one JSON\n * document on stdout out, trajectory on stderr, exit code as the verdict\n * (0 = result on stdout is authoritative, 1 = flow failure, 2 = contract\n * violation). On a non-zero exit the LAST stderr line is the `StdioFailure`\n * as a single JSON object, so parents that want machine-readable detail take\n * the tail line.\n *\n * Final writes await the write callback before `process.exit`: on pipes,\n * exiting with buffered data truncates it, and a large JSON result is exactly\n * the risk case. Signal handlers stay at the runner's default (installed): a\n * single-shot child must die when the parent forwards SIGINT. The console's\n * stdout methods go to stderr for the life of the process, as under\n * `serve_acp`, so a stray log can't land ahead of the result.\n *\n * Excluded from mutation testing as process/IO glue (see stryker.config.mjs);\n * the spawn-based contract tests in `__tests__/e2e/` exercise it for real.\n */\n\nimport { text } from 'node:stream/consumers'\nimport type { Step } from '#core'\nimport { route_console_to_stderr } from '#process'\nimport { execute_stdio } from './execute_stdio.js'\nimport type { RunStdioOptions } from './execute_stdio.js'\n\n/**\n * Runs a flow as the stdio agent contract against the real process streams,\n * then exits with the outcome's code.\n *\n * On a non-zero outcome, writes the `StdioFailure` as the last line on\n * stderr so a parent process can take the tail line as machine-readable\n * detail.\n */\nexport async function run_stdio<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o> = {},\n): Promise<void> {\n // Leave stdout to the one result document, so a stray log can't land ahead\n // of it while the run still exits 0.\n route_console_to_stderr(console, process.stderr)\n const outcome = await execute_stdio(flow, options, {\n read_input: () => text(process.stdin),\n write_output: (chunk) => write_flushed(process.stdout, chunk),\n error_stream: process.stderr,\n })\n if (outcome.code !== 0) {\n try {\n await write_flushed(process.stderr, `${JSON.stringify(outcome.failure)}\\n`)\n } catch {\n // stderr is gone; the exit code still carries the verdict.\n }\n }\n process.exit(outcome.code)\n}\n\n/**\n * Writes a chunk to a stream and resolves only once it is flushed, so the\n * caller can safely exit the process afterward without truncating output.\n */\nfunction write_flushed(stream: NodeJS.WriteStream, chunk: string): Promise<void> {\n return new Promise((resolve, reject) => {\n stream.write(chunk, (err) => {\n if (err) reject(err)\n else resolve()\n })\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,eAAsB,cACpB,MACA,SACA,IACuB;CACvB,MAAM,WAAW,MAAM,eAAe,MAAM,SAAS,EAAE;CACvD,MAAM,kBAAkB,MAAM,eAAe,QAAQ,MAAM;CAC3D,IAAI,SAAS,SAAS,UAAU,OAAO;EAAE,MAAM,SAAS;EAAM,SAAS,SAAS;CAAQ;CACxF,IAAI,oBAAoB,MAAM,OAAO;EAAE,MAAM;EAAG,SAAS;CAAgB;CACzE,IAAI;EACF,MAAM,GAAG,aAAa,GAAG,SAAS,KAAK,GAAG;CAC5C,SAAS,KAAK;EACZ,OAAO;GAAE,MAAM;GAAG,SAAS,aAAa,SAAS,GAAG;EAAE;CACxD;CACA,OAAO,EAAE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M,UAAU,MAAM,cAAc,MAAM,SAAS;EACjD,kBAAkB,KAAK,QAAQ,KAAK;EACpC,eAAe,UAAU,cAAc,QAAQ,QAAQ,KAAK;EAC5D,cAAc,QAAQ;CACxB,CAAC;CACD,IAAI,QAAQ,SAAS,GACnB,IAAI;EACF,MAAM,cAAc,QAAQ,QAAQ,GAAG,KAAK,UAAU,QAAQ,OAAO,EAAE,GAAG;CAC5E,QAAQ,CAER;CAEF,QAAQ,KAAK,QAAQ,IAAI;AAC3B;;;;;AAMA,SAAS,cAAc,QAA4B,OAA8B;CAC/E,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,OAAO,MAAM,QAAQ,QAAQ;GAC3B,IAAI,KAAK,OAAO,GAAG;QACd,QAAQ;EACf,CAAC;CACH,CAAC;AACH"}
1
+ {"version":3,"file":"stdio.js","names":[],"sources":["../src/stdio/execute_stdio.ts","../src/stdio/run_stdio.ts"],"sourcesContent":["/**\n * The stdio agent contract, minus the process.\n *\n * `execute_stdio` is everything `run_stdio` does (read, parse, validate, run,\n * validate, serialize, dispose), expressed over an injected `StdioIo` and\n * returning a `StdioOutcome` instead of touching `process.*` or exiting. The\n * split keeps the contract's branching unit-testable; the thin glue in\n * `run_stdio.ts` owns the real streams and the exit.\n *\n * The governing invariant: code 0 if and only if stdout carries an\n * authoritative result. That is why the engine is disposed before the output\n * is written (a teardown failure on the success path yields code 1 and no\n * stdout) and why every failure class short-circuits before `write_output`.\n * Code 1 means the flow did not produce a result (including a forwarded\n * SIGINT/SIGTERM aborting the run, or a failed delivery); code 2 means the\n * contract itself was violated (unparseable stdin, schema mismatch in either\n * direction, unserializable result).\n */\n\nimport { validate_schema, type AnySchema } from '#schema'\nimport { run } from '#core'\nimport type { Step, TrajectoryLogger } from '#core'\nimport { stderr_logger } from '#adapters'\n\nexport type RunStdioOptions<i, o> = {\n readonly input_schema?: AnySchema<i>\n readonly output_schema?: AnySchema<o>\n // Structural on purpose: anything with an async dispose qualifies, and the\n // stdio module never imports the engine layer.\n readonly engine?: { readonly dispose: () => Promise<void> }\n readonly trajectory?: TrajectoryLogger\n readonly abort?: AbortSignal\n}\n\nexport type StdioFailure = {\n readonly error: string\n readonly stage?:\n | 'read'\n | 'parse'\n | 'validate_input'\n | 'run'\n | 'validate_output'\n | 'serialize'\n | 'write'\n | 'dispose'\n readonly cause?: unknown\n}\n\nexport type StdioOutcome =\n | { readonly code: 0 }\n | { readonly code: 1 | 2; readonly failure: StdioFailure }\n\nexport type StdioIo = {\n readonly read_input: () => Promise<string>\n // Resolves once the bytes are flushed to the OS, so the caller may exit.\n readonly write_output: (text: string) => Promise<void>\n readonly error_stream: { write(chunk: string): unknown }\n}\n\n/**\n * Runs the stdio agent contract over injected `io`: read input, run the\n * flow, dispose the engine, write output, and return the outcome as a\n * value.\n *\n * Disposes the engine before writing output so a teardown failure on the\n * success path yields code 1 and no stdout, keeping \"code 0 means stdout\n * carries an authoritative result\" true even when disposal fails.\n */\nexport async function execute_stdio<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o>,\n io: StdioIo,\n): Promise<StdioOutcome> {\n const produced = await produce_output(flow, options, io)\n const dispose_failure = await dispose_engine(options.engine)\n if (produced.kind === 'failed') return { code: produced.code, failure: produced.failure }\n if (dispose_failure !== null) return { code: 1, failure: dispose_failure }\n try {\n await io.write_output(`${produced.json}\\n`)\n } catch (err) {\n return { code: 1, failure: make_failure('write', err) }\n }\n return { code: 0 }\n}\n\ntype ProduceResult =\n | { readonly kind: 'ok'; readonly json: string }\n | { readonly kind: 'failed'; readonly code: 1 | 2; readonly failure: StdioFailure }\n\n/**\n * Reads stdin, parses and validates it against the input schema, runs the\n * flow, then validates and serializes the result.\n *\n * Returns a tagged result instead of throwing so `execute_stdio` can dispose\n * the engine and choose the right exit code regardless of which stage\n * failed.\n */\nasync function produce_output<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o>,\n io: StdioIo,\n): Promise<ProduceResult> {\n let raw: string\n try {\n raw = await io.read_input()\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('read', err) }\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('parse', err) }\n }\n\n let input: i\n if (options.input_schema !== undefined) {\n const checked = await validate_schema(options.input_schema, parsed)\n if (!checked.ok) {\n return {\n kind: 'failed',\n code: 2,\n failure: {\n error: 'input failed schema validation',\n stage: 'validate_input',\n cause: to_json_safe(checked.issues),\n },\n }\n }\n input = checked.value\n } else {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n input = parsed as i\n }\n\n const trajectory = options.trajectory ?? stderr_logger({ stream: io.error_stream })\n\n let result: o\n try {\n result = await run(flow, input, {\n trajectory,\n ...(options.abort !== undefined ? { abort: options.abort } : {}),\n })\n } catch (err) {\n return { kind: 'failed', code: 1, failure: make_failure('run', err) }\n }\n\n let output: unknown = result\n if (options.output_schema !== undefined) {\n const checked = await validate_schema(options.output_schema, result)\n if (!checked.ok) {\n return {\n kind: 'failed',\n code: 2,\n failure: {\n error: 'flow result failed schema validation',\n stage: 'validate_output',\n cause: to_json_safe(checked.issues),\n },\n }\n }\n output = checked.value\n }\n\n let json: string | undefined\n try {\n json = JSON.stringify(output)\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('serialize', err) }\n }\n if (json === undefined) {\n return {\n kind: 'failed',\n code: 2,\n failure: { error: 'flow result is not JSON-serializable', stage: 'serialize' },\n }\n }\n return { kind: 'ok', json }\n}\n\n/**\n * Disposes the caller's engine when one was supplied, returning a\n * `StdioFailure` if disposal throws and `null` otherwise.\n */\nasync function dispose_engine(\n engine: RunStdioOptions<never, never>['engine'],\n): Promise<StdioFailure | null> {\n if (engine === undefined) return null\n try {\n await engine.dispose()\n return null\n } catch (err) {\n return make_failure('dispose', err)\n }\n}\n\n/**\n * Builds a `StdioFailure` for the given stage from a thrown value.\n */\nfunction make_failure(stage: NonNullable<StdioFailure['stage']>, err: unknown): StdioFailure {\n const cause = safe_cause(err)\n return {\n error: err instanceof Error ? err.message : String(err),\n stage,\n ...(cause !== undefined ? { cause } : {}),\n }\n}\n\n/**\n * Reduces a thrown value to a JSON-safe cause for `StdioFailure`.\n *\n * An `Error` is reduced to its `name`, `message`, and the `path` property the\n * runner stamps on it as it bubbles up through nested steps; anything else is\n * passed through `to_json_safe`.\n */\nfunction safe_cause(err: unknown): unknown {\n if (err instanceof Error) {\n const path = Reflect.get(err, 'path')\n return {\n name: err.name,\n message: err.message,\n ...(Array.isArray(path) ? { path: to_json_safe(path) } : {}),\n }\n }\n return to_json_safe(err)\n}\n\n/**\n * Round-trips a value through `JSON.stringify`/`parse` so it is safe to\n * embed in a `StdioFailure` that the glue will serialize again.\n *\n * Never throws and never returns a value that would make that later\n * serialization throw or silently vanish: a circular reference or a BigInt\n * becomes `undefined` instead.\n */\nfunction to_json_safe(value: unknown): unknown {\n try {\n const json = JSON.stringify(value)\n if (json === undefined) return undefined\n return JSON.parse(json) as unknown\n } catch {\n return undefined\n }\n}\n","/**\n * Process glue for the stdio agent contract.\n *\n * Binds `execute_stdio` to the real process: stdin to EOF in, exactly one JSON\n * document on stdout out, trajectory on stderr, exit code as the verdict\n * (0 = result on stdout is authoritative, 1 = flow failure, 2 = contract\n * violation). On a non-zero exit the LAST stderr line is the `StdioFailure`\n * as a single JSON object, so parents that want machine-readable detail take\n * the tail line.\n *\n * Final writes await the write callback before `process.exit`: on pipes,\n * exiting with buffered data truncates it, and a large JSON result is exactly\n * the risk case. Signal handlers stay at the runner's default (installed): a\n * single-shot child must die when the parent forwards SIGINT. The console's\n * stdout methods go to stderr for the life of the process, as under\n * `serve_acp`, so a stray log can't land ahead of the result.\n *\n * Excluded from mutation testing as process/IO glue (see stryker.config.mjs);\n * the spawn-based contract tests in `__tests__/e2e/` exercise it for real.\n */\n\nimport { text } from 'node:stream/consumers'\nimport type { Step } from '#core'\nimport { route_console_to_stderr } from '#process'\nimport { execute_stdio } from './execute_stdio.js'\nimport type { RunStdioOptions } from './execute_stdio.js'\n\n/**\n * Runs a flow as the stdio agent contract against the real process streams,\n * then exits with the outcome's code.\n *\n * On a non-zero outcome, writes the `StdioFailure` as the last line on\n * stderr so a parent process can take the tail line as machine-readable\n * detail.\n */\nexport async function run_stdio<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o> = {},\n): Promise<void> {\n // Leave stdout to the one result document, so a stray log can't land ahead\n // of it while the run still exits 0.\n route_console_to_stderr(console, process.stderr)\n const outcome = await execute_stdio(flow, options, {\n read_input: () => text(process.stdin),\n write_output: (chunk) => write_flushed(process.stdout, chunk),\n error_stream: process.stderr,\n })\n if (outcome.code !== 0) {\n try {\n await write_flushed(process.stderr, `${JSON.stringify(outcome.failure)}\\n`)\n } catch {\n // stderr is gone; the exit code still carries the verdict.\n }\n }\n process.exit(outcome.code)\n}\n\n/**\n * Writes a chunk to a stream and resolves only once it is flushed, so the\n * caller can safely exit the process afterward without truncating output.\n */\nfunction write_flushed(stream: NodeJS.WriteStream, chunk: string): Promise<void> {\n return new Promise((resolve, reject) => {\n stream.write(chunk, (err) => {\n if (err) reject(err)\n else resolve()\n })\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,eAAsB,cACpB,MACA,SACA,IACuB;CACvB,MAAM,WAAW,MAAM,eAAe,MAAM,SAAS,EAAE;CACvD,MAAM,kBAAkB,MAAM,eAAe,QAAQ,MAAM;CAC3D,IAAI,SAAS,SAAS,UAAU,OAAO;EAAE,MAAM,SAAS;EAAM,SAAS,SAAS;CAAQ;CACxF,IAAI,oBAAoB,MAAM,OAAO;EAAE,MAAM;EAAG,SAAS;CAAgB;CACzE,IAAI;EACF,MAAM,GAAG,aAAa,GAAG,SAAS,KAAK,GAAG;CAC5C,SAAS,KAAK;EACZ,OAAO;GAAE,MAAM;GAAG,SAAS,aAAa,SAAS,GAAG;EAAE;CACxD;CACA,OAAO,EAAE,MAAM,EAAE;AACnB;;;;;;;;;AAcA,eAA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