zidane 8.2.1 → 8.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp-cli.js +8 -8
- package/dist/{acp-D7Pr8NGt.js → acp-oYRjlh71.js} +6 -6
- package/dist/{acp-D7Pr8NGt.js.map → acp-oYRjlh71.js.map} +1 -1
- package/dist/acp.d.ts +2 -2
- package/dist/acp.js +1 -1
- package/dist/{agent-DecDtKA_.js → agent-CBQglXtH.js} +9 -379
- package/dist/agent-CBQglXtH.js.map +1 -0
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +1 -1
- package/dist/{builtin-artifact-kinds-B_OEgf8b.js → builtin-artifact-kinds-BmorPkgz.js} +36 -9
- package/dist/builtin-artifact-kinds-BmorPkgz.js.map +1 -0
- package/dist/chat/pure.d.ts +4 -4
- package/dist/chat/pure.js +6 -6
- package/dist/chat.d.ts +4 -4
- package/dist/chat.js +15 -15
- package/dist/{cli-shared-Dx4vmif6.js → cli-shared-E5m_pI8A.js} +2 -2
- package/dist/{cli-shared-Dx4vmif6.js.map → cli-shared-E5m_pI8A.js.map} +1 -1
- package/dist/{client-core-imHuBWV3.d.ts → client-core-EEEX_u6D.d.ts} +24 -5
- package/dist/{client-core-imHuBWV3.d.ts.map → client-core-EEEX_u6D.d.ts.map} +1 -1
- package/dist/{connection-loop-CdHt3iQi.d.ts → connection-loop-CpgfUmuw.d.ts} +3 -3
- package/dist/{connection-loop-CdHt3iQi.d.ts.map → connection-loop-CpgfUmuw.d.ts.map} +1 -1
- package/dist/contexts/daytona.d.ts +1 -1
- package/dist/contexts/e2b.d.ts +1 -1
- package/dist/{credentials-Dti61yoi.js → credentials-B9DfBJP9.js} +11 -7
- package/dist/credentials-B9DfBJP9.js.map +1 -0
- package/dist/daemon-cli.js +2 -2
- package/dist/{dispatcher-vy3J6JMA.js → dispatcher-Bv9-c6I2.js} +28 -14
- package/dist/dispatcher-Bv9-c6I2.js.map +1 -0
- package/dist/{engine-BN6PjWAW.js → engine-XmoPPB6U.js} +5 -5
- package/dist/{engine-BN6PjWAW.js.map → engine-XmoPPB6U.js.map} +1 -1
- package/dist/{eval-BaJtxLCW.js → eval-CfQlBR81.js} +2 -2
- package/dist/{eval-BaJtxLCW.js.map → eval-CfQlBR81.js.map} +1 -1
- package/dist/eval.d.ts +1 -1
- package/dist/eval.js +1 -1
- package/dist/{executor-CT4oUkg6.js → executor-BhthPE1q.js} +3 -3
- package/dist/{executor-CT4oUkg6.js.map → executor-BhthPE1q.js.map} +1 -1
- package/dist/{extensions-BKt7lxxv.js → extensions-BgBwogRW.js} +114 -113
- package/dist/extensions-BgBwogRW.js.map +1 -0
- package/dist/extensions.d.ts +1 -1
- package/dist/extensions.js +2 -2
- package/dist/{fold-rules-BYedvsH7.d.ts → fold-rules-DSypi36k.d.ts} +2 -2
- package/dist/{fold-rules-BYedvsH7.d.ts.map → fold-rules-DSypi36k.d.ts.map} +1 -1
- package/dist/google-O6pRnddf.js +881 -0
- package/dist/google-O6pRnddf.js.map +1 -0
- package/dist/{headless-Ebd1ZEzC.js → headless-R4pbpTkm.js} +3 -3
- package/dist/{headless-Ebd1ZEzC.js.map → headless-R4pbpTkm.js.map} +1 -1
- package/dist/headless.d.ts +1 -1
- package/dist/headless.js +1 -1
- package/dist/{host-scoped-settings-Cy_zbmB_.js → host-scoped-settings-C-Nmb6vr.js} +2 -2
- package/dist/{host-scoped-settings-Cy_zbmB_.js.map → host-scoped-settings-C-Nmb6vr.js.map} +1 -1
- package/dist/{host-signals-Cx2IAbHh.js → host-signals-BFudPyCT.js} +5 -5
- package/dist/{host-signals-Cx2IAbHh.js.map → host-signals-BFudPyCT.js.map} +1 -1
- package/dist/{index-pc71ADi6.d.ts → index-AqRZ3gEz.d.ts} +71 -4
- package/dist/index-AqRZ3gEz.d.ts.map +1 -0
- package/dist/{index-Bt_G2Z_2.d.ts → index-CDS7YdUC.d.ts} +5 -5
- package/dist/{index-Bt_G2Z_2.d.ts.map → index-CDS7YdUC.d.ts.map} +1 -1
- package/dist/{index-CidMTcxS.d.ts → index-DyQyDLX1.d.ts} +167 -10
- package/dist/index-DyQyDLX1.d.ts.map +1 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +15 -15
- package/dist/ipc/remote.d.ts +5 -5
- package/dist/ipc/remote.js +3 -3
- package/dist/ipc.d.ts +5 -5
- package/dist/ipc.js +7 -7
- package/dist/{links-DSZ4uQ5w.js → links-rFaWqS2Y.js} +10 -10
- package/dist/{links-DSZ4uQ5w.js.map → links-rFaWqS2Y.js.map} +1 -1
- package/dist/{mcp-allowlist-BQ5MvhHi.js → mcp-allowlist-CLXweyxk.js} +14 -3
- package/dist/mcp-allowlist-CLXweyxk.js.map +1 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/{oauth-BSqXgads.js → oauth-7_48zR7n.js} +226 -40
- package/dist/oauth-7_48zR7n.js.map +1 -0
- package/dist/{openai-dTmPxM6T.js → openai-Rh6u5NXF.js} +121 -2
- package/dist/openai-Rh6u5NXF.js.map +1 -0
- package/dist/{openrouter-CtZbQDa0.js → openrouter-Dg0yaI-o.js} +91 -2
- package/dist/openrouter-Dg0yaI-o.js.map +1 -0
- package/dist/output/stream-json.d.ts +1 -1
- package/dist/output/terminal.d.ts +1 -1
- package/dist/plugins.d.ts +1 -1
- package/dist/{presets-EzlHyFSi.js → presets-DXeHsd24.js} +3 -3
- package/dist/{presets-EzlHyFSi.js.map → presets-DXeHsd24.js.map} +1 -1
- package/dist/presets.d.ts +1 -1
- package/dist/presets.js +1 -1
- package/dist/{prompts-D2lPHLOV.d.ts → prompts-DmY13jvF.d.ts} +2 -1
- package/dist/prompts-DmY13jvF.d.ts.map +1 -0
- package/dist/protocol-BIv1Yuvl.js.map +1 -1
- package/dist/providers/anthropic.d.ts +1 -1
- package/dist/providers/arcee.d.ts +1 -1
- package/dist/providers/baseten.d.ts +1 -1
- package/dist/providers/cerebras.d.ts +1 -1
- package/dist/providers/google.d.ts +1 -1
- package/dist/providers/google.js +1 -784
- package/dist/providers/local.d.ts +1 -1
- package/dist/providers/neuralwatt.d.ts +1 -1
- package/dist/providers/openai-compat.d.ts +1 -1
- package/dist/providers/openai.d.ts +1 -1
- package/dist/providers/openai.js +1 -1
- package/dist/providers/openrouter.d.ts +1 -1
- package/dist/providers/openrouter.js +1 -1
- package/dist/providers/xai.d.ts +1 -1
- package/dist/providers/xai.js +1 -101
- package/dist/providers.d.ts +2 -2
- package/dist/providers.js +6 -5
- package/dist/{registry-BBaEgTsX.js → registry-eourRLY2.js} +3 -3
- package/dist/{registry-BBaEgTsX.js.map → registry-eourRLY2.js.map} +1 -1
- package/dist/{remote-hosts-bO7wOt44.js → remote-hosts-DY2J07ut.js} +4 -4
- package/dist/{remote-hosts-bO7wOt44.js.map → remote-hosts-DY2J07ut.js.map} +1 -1
- package/dist/restate.d.ts +1 -1
- package/dist/{secret-shapes-Cda65uDH.js → secret-shapes-BjW4l6U0.js} +17 -3
- package/dist/secret-shapes-BjW4l6U0.js.map +1 -0
- package/dist/session/sqlite.d.ts +1 -1
- package/dist/{session-factory-BazyVdzj.js → session-factory-CMwIXE-7.js} +5 -5
- package/dist/{session-factory-BazyVdzj.js.map → session-factory-CMwIXE-7.js.map} +1 -1
- package/dist/session.d.ts +1 -1
- package/dist/{settings-keys-zYaer8DY.js → settings-keys-CPdmkTz7.js} +3 -3
- package/dist/{settings-keys-zYaer8DY.js.map → settings-keys-CPdmkTz7.js.map} +1 -1
- package/dist/{shell-path-od9XHRPt.js → shell-path-B8b3EOtK.js} +3 -3
- package/dist/{shell-path-od9XHRPt.js.map → shell-path-B8b3EOtK.js.map} +1 -1
- package/dist/{skills-use-D68a1gyZ.js → skills-use-CssTEaIj.js} +375 -2
- package/dist/skills-use-CssTEaIj.js.map +1 -0
- package/dist/skills.d.ts +1 -1
- package/dist/store-L01W0gGI.js.map +1 -1
- package/dist/{system-freeze-DXvJpveP.js → system-freeze-Um9ZJiPo.js} +24 -9
- package/dist/system-freeze-Um9ZJiPo.js.map +1 -0
- package/dist/{todo-edits-CmqNFvLJ.js → todo-edits-BERpCRPj.js} +3 -3
- package/dist/{todo-edits-CmqNFvLJ.js.map → todo-edits-BERpCRPj.js.map} +1 -1
- package/dist/tools/fetch-url.d.ts +1 -1
- package/dist/tools/prompts.d.ts +1 -1
- package/dist/tools/prompts.js +7 -0
- package/dist/tools/prompts.js.map +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/{tools-9Dpm8F-f.js → tools-pZVFIJ_K.js} +273 -2
- package/dist/tools-pZVFIJ_K.js.map +1 -0
- package/dist/tools.d.ts +3 -3
- package/dist/tools.js +4 -4
- package/dist/{transcript-anchors-B3TFJqr_.js → transcript-anchors-jHrg-r-H.js} +10 -10
- package/dist/{transcript-anchors-B3TFJqr_.js.map → transcript-anchors-jHrg-r-H.js.map} +1 -1
- package/dist/{transcript-reconcile-BC2DbTmp.js → transcript-reconcile-CPdrNbbR.js} +19 -2
- package/dist/{transcript-reconcile-BC2DbTmp.js.map → transcript-reconcile-CPdrNbbR.js.map} +1 -1
- package/dist/tui.d.ts +7 -7
- package/dist/tui.js +25 -23
- package/dist/tui.js.map +1 -1
- package/dist/{turn-operations-CIFoOebZ.d.ts → turn-operations-DuGtKuc_.d.ts} +10 -3
- package/dist/turn-operations-DuGtKuc_.d.ts.map +1 -0
- package/dist/{types-iFLlZKd0.d.ts → types-C0PJmBaO.d.ts} +2 -2
- package/dist/{types-iFLlZKd0.d.ts.map → types-C0PJmBaO.d.ts.map} +1 -1
- package/dist/types-JzccL5GE.js +24 -0
- package/dist/types-JzccL5GE.js.map +1 -0
- package/dist/types.d.ts +2 -2
- package/dist/{url-BTH-HE9Y.js → url-D8KZ7Edw.js} +2 -2
- package/dist/{url-BTH-HE9Y.js.map → url-D8KZ7Edw.js.map} +1 -1
- package/dist/{version-4T82xRxQ.js → version-bd3DQJkc.js} +2 -2
- package/dist/{version-4T82xRxQ.js.map → version-bd3DQJkc.js.map} +1 -1
- package/dist/wire-DH77Z-rr.js +80 -0
- package/dist/wire-DH77Z-rr.js.map +1 -0
- package/dist/{workspace-exec-stream-By8na6vz.js → workspace-exec-stream-CyfYgqAh.js} +4 -4
- package/dist/{workspace-exec-stream-By8na6vz.js.map → workspace-exec-stream-CyfYgqAh.js.map} +1 -1
- package/dist/{write-file-B4vi3SvQ.js → write-file-QYrcDdl3.js} +3 -3
- package/dist/{write-file-B4vi3SvQ.js.map → write-file-QYrcDdl3.js.map} +1 -1
- package/dist/{ws-CS312Jpx.js → ws-CURQ2igk.js} +5 -5
- package/dist/{ws-CS312Jpx.js.map → ws-CURQ2igk.js.map} +1 -1
- package/dist/{ws-client-wWka-Jku.js → ws-client-BVljYbdb.js} +3 -3
- package/dist/{ws-client-wWka-Jku.js.map → ws-client-BVljYbdb.js.map} +1 -1
- package/dist/xai-CStTwCV2.js +182 -0
- package/dist/xai-CStTwCV2.js.map +1 -0
- package/docs/ARCHITECTURE.md +1 -0
- package/docs/ARTIFACTS.md +1 -1
- package/docs/EXTENSIONS.md +9 -5
- package/package.json +2 -2
- package/dist/agent-DecDtKA_.js.map +0 -1
- package/dist/builtin-artifact-kinds-B_OEgf8b.js.map +0 -1
- package/dist/credentials-Dti61yoi.js.map +0 -1
- package/dist/dispatcher-vy3J6JMA.js.map +0 -1
- package/dist/extensions-BKt7lxxv.js.map +0 -1
- package/dist/index-CidMTcxS.d.ts.map +0 -1
- package/dist/index-pc71ADi6.d.ts.map +0 -1
- package/dist/mcp-allowlist-BQ5MvhHi.js.map +0 -1
- package/dist/oauth-BSqXgads.js.map +0 -1
- package/dist/openai-dTmPxM6T.js.map +0 -1
- package/dist/openrouter-CtZbQDa0.js.map +0 -1
- package/dist/prompts-D2lPHLOV.d.ts.map +0 -1
- package/dist/providers/google.js.map +0 -1
- package/dist/providers/xai.js.map +0 -1
- package/dist/secret-shapes-Cda65uDH.js.map +0 -1
- package/dist/skills-use-D68a1gyZ.js.map +0 -1
- package/dist/system-freeze-DXvJpveP.js.map +0 -1
- package/dist/tools-9Dpm8F-f.js.map +0 -1
- package/dist/turn-operations-CIFoOebZ.d.ts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"google-O6pRnddf.js","names":["catalogLookup"],"sources":["../src/providers/images/google.ts","../src/providers/google.ts"],"sourcesContent":["/**\n * Gemini image generation on the Gemini API (Google AI Studio):\n * `generateContent` with `responseModalities: ['TEXT', 'IMAGE']`. Reference\n * images go in as `inlineData` parts. One image per request, so a request for\n * several sends several in parallel.\n */\n\nimport type { ImageModelInfo, ProviderImageResponse, ProviderImages } from './types'\nimport type { ImageFetch } from './wire'\nimport { imageCount, imageHttpError, repeatRequest } from './wire'\n\nconst BASE_URL = 'https://generativelanguage.googleapis.com/v1beta'\n\n/** Gemini image models on the Gemini API. */\nexport const GOOGLE_IMAGE_MODELS: readonly ImageModelInfo[] = [\n { id: 'gemini-3.1-flash-image', name: 'Gemini 3.1 Flash Image', input: ['text', 'image'] },\n { id: 'gemini-3-pro-image', name: 'Gemini 3 Pro Image', input: ['text', 'image'] },\n { id: 'gemini-3.1-flash-lite-image', name: 'Gemini 3.1 Flash Lite Image', input: ['text', 'image'] },\n { id: 'gemini-2.5-flash-image', name: 'Gemini 2.5 Flash Image', input: ['text', 'image'] },\n]\n\ninterface GenerateContentResponse {\n candidates?: Array<{\n finishReason?: string\n content?: { parts?: Array<{ text?: string, inlineData?: { mimeType?: string, data?: string } }> }\n }>\n promptFeedback?: { blockReason?: string }\n}\n\n/**\n * Gemini image generation as a {@link ProviderImages}. Unavailable while `resolveKey` returns `undefined`.\n *\n * @param options - Key resolver and test overrides.\n * @param options.resolveKey - Returns the Gemini API key, or `undefined` when none is set. Called on every request.\n * @param options.fetch - Fetch override, for tests.\n */\nexport function googleImages(options: { resolveKey: () => string | undefined, fetch?: ImageFetch }): ProviderImages {\n const doFetch = options.fetch ?? fetch\n return {\n defaultModel: GOOGLE_IMAGE_MODELS[0]!.id,\n models: GOOGLE_IMAGE_MODELS,\n availability: () => options.resolveKey()\n ? { available: true }\n : { available: false, reason: 'Gemini image generation needs a Gemini API key (GEMINI_API_KEY).' },\n async generate(request, signal) {\n const key = options.resolveKey()\n if (!key)\n throw new Error('Gemini image generation needs a Gemini API key. Set GEMINI_API_KEY, or add a key in the Google Gemini provider settings.')\n const body = {\n contents: [{\n role: 'user',\n parts: [\n { text: request.prompt },\n ...(request.references ?? []).map(ref => ({ inlineData: { mimeType: ref.mediaType, data: ref.data } })),\n ],\n }],\n generationConfig: {\n responseModalities: ['TEXT', 'IMAGE'],\n ...(request.aspectRatio ? { imageConfig: { aspectRatio: request.aspectRatio } } : {}),\n },\n }\n const once = async (): Promise<ProviderImageResponse> => {\n const res = await doFetch(`${BASE_URL}/models/${encodeURIComponent(request.model)}:generateContent`, {\n method: 'POST',\n headers: { 'x-goog-api-key': key, 'content-type': 'application/json' },\n body: JSON.stringify(body),\n signal,\n })\n if (!res.ok)\n throw await imageHttpError('Gemini', res)\n const json = await res.json() as GenerateContentResponse\n if (json.promptFeedback?.blockReason)\n throw new Error(`Gemini refused the prompt (${json.promptFeedback.blockReason}).`)\n const candidate = json.candidates?.[0]\n const parts = candidate?.content?.parts ?? []\n const images = parts.flatMap(part => part.inlineData?.data\n ? [{ mediaType: part.inlineData.mimeType ?? 'image/png', data: part.inlineData.data }]\n : [])\n const text = parts.flatMap(part => part.text ? [part.text] : []).join('\\n').trim()\n if (images.length === 0) {\n const reason = candidate?.finishReason && candidate.finishReason !== 'STOP' ? ` (${candidate.finishReason})` : ''\n throw new Error(`Gemini returned no image${reason}${text ? `: ${text}` : '.'}`)\n }\n return { images, model: request.model, ...(text ? { text } : {}) }\n }\n return repeatRequest(imageCount(request.count), once)\n },\n }\n}\n","/**\n * Google Gemini providers, on pi-ai's Google streams.\n *\n * - {@link google}: the Gemini API (Google AI Studio), authenticated by an\n * API key.\n * - {@link googleVertex}: Vertex AI, authenticated by Google Cloud\n * credentials (gcloud Application Default Credentials or a credentials\n * file) or a Vertex API key.\n *\n * - {@link googleCompatible}: the same plumbing over another Gemini-wire\n * backend (an extension's transport, models and auth).\n *\n * Gemini signs its reasoning: thought signatures ride on text parts, thought\n * parts and function calls, and Gemini 3 rejects a tool-use step whose\n * function calls come back without theirs. pi-ai sends nothing in their\n * place, so these providers persist them on the blocks that carried them\n * (`signature`, `signatureProducer`) and replay them only to the route that\n * issued them, whatever the model: Google's guidance is to resend a session's\n * thought blocks as received, model switches included.\n */\nimport type {\n AssistantMessageEventStream,\n AssistantMessage as PiAssistantMessage,\n JsonObject as PiJsonObject,\n Message as PiMessage,\n Model as PiModel,\n ThinkingBudgets as PiThinkingBudgets,\n Tool as PiTool,\n Usage as PiUsage,\n SimpleStreamOptions,\n TranscriptContext,\n} from '@earendil-works/pi-ai'\nimport type { GoogleVertexOptions } from '@earendil-works/pi-ai/api/google-vertex'\nimport type { Provider, ProviderCapabilities, StreamCallbacks, StreamOptions, ToolSpec, TurnResult } from '.'\nimport type { ClassifiedError } from '../errors'\nimport type { GeminiSignatureScope, SessionContentBlock, SessionMessage, ToolResultDocumentContent, TurnFinishReason, TurnUsage } from '../types'\nimport type { ModelCostRates } from './cost'\nimport type { ModelCatalog } from './model-catalog'\nimport type { OAuthParams } from './oauth'\nimport { mkdtempSync, rmSync, writeFileSync } from 'node:fs'\nimport { lstat, readdir, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { normalizeContext } from '@earendil-works/pi-ai'\nimport { getBuiltinModel } from '@earendil-works/pi-ai/providers/all'\nimport { classifyErrorPrelude, classifyProviderLimit, isRetryableHttpStatus, matchesContextExceeded, matchesToolPairingError, providerLimitReason } from '../errors'\nimport { unsupportedMediaError } from '../prompt'\nimport { reasoningWireAction, SYNTHETIC_TOOL_RESULT_PLACEHOLDER } from '../session/messages'\nimport { systemNotesAsText } from '../system-notes'\nimport { renderSystemForWire } from '../system-prompt'\nimport { assertResolvedMediaBlock, documentBlockMarker } from '../types'\nimport { fillEstimatedCost } from './cost'\nimport { GOOGLE_VERTEX_OAUTH_ID } from './google-oauth'\nimport { googleImages } from './images/google'\nimport { lookupModel as catalogLookup, mergeCatalogEntry } from './model-catalog'\nimport { pinnedAccountMissingError, readAccountOAuthCredential, readOAuthCredentials, resolveOAuthApiKey } from './oauth'\nimport { assistantMessage, toolResultsMessage, userMessage } from './openai-compat'\nimport { sanitizeToolSpecs } from './schema-sanitize'\nimport { createToolNameBoundary } from './tool-name-boundary'\n\n/** Zidane provider (and signature route) names of the two Google backends. */\nexport type GoogleRouteName = 'google' | 'google-vertex'\n\ntype GoogleApi = 'google-generative-ai' | 'google-vertex'\n/**\n * pi-ai model record on a Gemini wire. A {@link googleCompatible} backend\n * builds its own with `api: 'google-generative-ai'` (the wire pi-ai's Gemini\n * converters speak) and its own `provider`.\n */\nexport type GoogleWireModel = PiModel<GoogleApi>\ntype GoogleModel = GoogleWireModel\n/** What both pi-ai entry points accept here. Tool choice goes through `onPayload`. */\nexport type GoogleStreamOptions = SimpleStreamOptions & Pick<GoogleVertexOptions, 'thinking'>\n/** One pi-ai Gemini stream entry point. */\nexport type GoogleStreamFn = (model: GoogleWireModel, context: TranscriptContext, options: GoogleStreamOptions) => AssistantMessageEventStream\n\n/**\n * pi-ai's `stream` / `streamSimple` pair for one backend, loaded on first\n * use. `streamSimple` takes a `reasoning` level (and `thinkingBudgets`);\n * `stream` takes an explicit `thinking` config (adaptive thinking).\n */\nexport interface GoogleStreams {\n /** Takes an explicit `thinking` config (adaptive thinking). */\n stream: GoogleStreamFn\n /** Takes a `reasoning` level and optional `thinkingBudgets`. */\n streamSimple: GoogleStreamFn\n}\n\n/** Model used when a request names none. Served on free-tier Gemini API keys. */\nexport const GOOGLE_DEFAULT_MODEL = 'gemini-3.8-flash'\n\n/** A Google model pi-ai hasn't bundled yet: a bundled `template` with the same thinking shape, under its own id. */\nexport interface GoogleExtraModel {\n /** Model id sent to the API. */\n id: string\n /** Display name. */\n name: string\n /** A bundled model with the same thinking levels and budgets. */\n template: string\n /** Context window in tokens. */\n contextWindow: number\n /** Largest output in tokens. */\n maxTokens: number\n /** A function, so a dated price change applies to long-running hosts. */\n rates: () => Required<ModelCostRates>\n}\n\n/**\n * Models pi-ai hasn't bundled yet, served on both routes. A pi-ai release\n * that bundles one supersedes its entry (bundled metadata always wins), so\n * delete the entry then.\n */\nexport const GOOGLE_EXTRA_MODELS: readonly GoogleExtraModel[] = []\n\nconst lookupBuiltin = getBuiltinModel as (provider: string, modelId: string) => GoogleModel | undefined\n\nfunction builtinModel(route: GoogleRouteName, modelId: string): GoogleModel | undefined {\n try {\n return lookupBuiltin(route, modelId)\n }\n catch {\n return undefined\n }\n}\n\n/**\n * pi-ai model record for `modelId` on `route`: the bundled entry, else a\n * {@link GOOGLE_EXTRA_MODELS} overlay, else the default model's shape under\n * the requested id. A catalog entry overlays whichever applies.\n *\n * @param route - Backend the request goes to.\n * @param modelId - Requested model id.\n * @param catalog - Per-run catalog override.\n */\nexport function resolveGoogleModel(route: GoogleRouteName, modelId: string, catalog?: ModelCatalog): GoogleModel {\n const entry = catalogLookup(route, modelId, catalog)\n const bundled = builtinModel(route, modelId)\n if (bundled)\n return mergeCatalogEntry(bundled, entry)\n\n const extra = GOOGLE_EXTRA_MODELS.find(m => m.id === modelId)\n const template = builtinModel(route, extra?.template ?? GOOGLE_DEFAULT_MODEL)\n if (!template)\n throw new Error(`Google model registry (${route}) is missing ${extra?.template ?? GOOGLE_DEFAULT_MODEL}`)\n if (extra) {\n return mergeCatalogEntry({\n ...template,\n id: extra.id,\n name: extra.name,\n contextWindow: extra.contextWindow,\n maxTokens: extra.maxTokens,\n cost: extra.rates(),\n }, entry)\n }\n return mergeCatalogEntry({ ...template, id: modelId, name: modelId }, entry)\n}\n\nfunction formatTools(tools: ToolSpec[]): PiTool[] {\n // pi-ai sends `parametersJsonSchema` (full JSON Schema); the OpenAI pass\n // still fixes the root shapes (`$ref`, `anyOf`, nullable roots) MCP servers\n // publish and Gemini rejects as well.\n return sanitizeToolSpecs(tools, { profile: 'openai' }).map(t => ({\n name: t.name,\n description: t.description ?? '',\n parameters: t.inputSchema as PiTool['parameters'],\n }))\n}\n\nfunction documentMarker(doc: ToolResultDocumentContent): string {\n return documentBlockMarker(doc, 'document omitted')\n}\n\nfunction emptyUsage(): PiUsage {\n return {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n }\n}\n\nfunction piUserMessage(content: SessionContentBlock[], provider: string): PiMessage | null {\n for (const b of content) {\n if (b.type === 'audio')\n throw unsupportedMediaError('audio', provider)\n if (b.type === 'video')\n throw unsupportedMediaError('video', provider)\n }\n const parts: Exclude<Extract<PiMessage, { role: 'user' }>['content'], string> = []\n for (const block of content) {\n if (block.type === 'text') {\n parts.push({ type: 'text', text: block.text })\n }\n else if (block.type === 'image') {\n assertResolvedMediaBlock(block, 'Google wire messages')\n parts.push({ type: 'image', data: block.data, mimeType: block.mediaType })\n }\n else if (block.type === 'document') {\n // pi-ai's content union is text | image: no file part to carry a PDF.\n assertResolvedMediaBlock(block, 'Google wire messages')\n parts.push({ type: 'text', text: documentMarker(block) })\n }\n }\n if (parts.length === 0)\n return null\n if (parts.length === 1 && parts[0]!.type === 'text')\n return { role: 'user', content: parts[0]!.text, timestamp: Date.now() }\n return { role: 'user', content: parts, timestamp: Date.now() }\n}\n\nfunction piToolResultMessage(\n result: Extract<SessionContentBlock, { type: 'tool_result' }>,\n toolName: string,\n provider: string,\n): PiMessage {\n const content = typeof result.output === 'string'\n ? [{ type: 'text' as const, text: result.output }]\n : result.output.map((block) => {\n if (block.type === 'image') {\n assertResolvedMediaBlock(block, 'Google wire messages')\n return { type: 'image' as const, data: block.data, mimeType: block.mediaType }\n }\n if (block.type === 'audio')\n throw unsupportedMediaError('audio', provider)\n if (block.type === 'video')\n throw unsupportedMediaError('video', provider)\n if (block.type === 'document') {\n assertResolvedMediaBlock(block, 'Google wire messages')\n return { type: 'text' as const, text: documentMarker(block) }\n }\n return { type: 'text' as const, text: block.text }\n })\n return {\n role: 'toolResult',\n toolCallId: result.callId,\n // Gemini pairs a functionResponse with its call by name.\n toolName,\n content,\n isError: result.isError ?? false,\n timestamp: Date.now(),\n }\n}\n\n/**\n * One assistant turn for pi-ai. A turn holding this route's signatures is\n * stamped with the TARGET model, so pi-ai treats it as its own and replays\n * the signatures (Google accepts them across its models). Any other turn is\n * stamped foreign: pi-ai then sends its reasoning as plain text and its\n * calls unsigned.\n */\nfunction piAssistantMessage(content: SessionContentBlock[], model: GoogleModel, route: GeminiSignatureScope): PiAssistantMessage {\n const native = content.some(block =>\n (block.type === 'text' || block.type === 'tool_call' || block.type === 'thinking')\n && block.signature !== undefined\n && block.signatureProducer === route)\n const own = (block: { signature?: string, signatureProducer?: string }): string | undefined =>\n native && block.signatureProducer === route ? block.signature : undefined\n\n const piContent: PiAssistantMessage['content'] = []\n for (const block of content) {\n if (block.type === 'text') {\n const signature = own(block)\n piContent.push({ type: 'text', text: block.text, ...(signature ? { textSignature: signature } : {}) })\n }\n else if (block.type === 'thinking') {\n const action = reasoningWireAction(block, route)\n if (action === 'drop')\n continue\n const signature = action === 'keep' ? own(block) : undefined\n piContent.push({ type: 'thinking', thinking: block.text, ...(signature ? { thinkingSignature: signature } : {}) })\n }\n else if (block.type === 'tool_call') {\n const signature = own(block)\n piContent.push({\n type: 'toolCall',\n id: block.id,\n name: block.name,\n arguments: block.input as PiJsonObject,\n ...(signature ? { thoughtSignature: signature } : {}),\n })\n }\n // `redacted_thinking`, `provider_reasoning` and server-tool blocks belong\n // to other providers' wires.\n }\n\n return {\n role: 'assistant',\n content: piContent,\n api: model.api,\n provider: native ? model.provider : 'zidane',\n model: native ? model.id : 'history',\n usage: emptyUsage(),\n // pi-ai skips `error` / `aborted` turns outright; a stored turn always replays.\n stopReason: 'stop',\n timestamp: Date.now(),\n }\n}\n\n/**\n * Converts session messages to pi-ai messages for a Google backend.\n *\n * Unlike the Responses wire, an assistant turn stays whole: Gemini signs only\n * the FIRST function call of a parallel step, so splitting the calls into\n * separate model turns would leave the others unsigned. Its tool results\n * follow in call order (pi-ai folds them into one user turn), with the\n * synthetic placeholder for any the history lost.\n *\n * @param messages - Session messages, tool names already on the wire.\n * @param model - Target model.\n * @param route - Signature scope of the target (the backend's route name by default).\n * @param provider - Provider named in unsupported-media errors. Defaults to `route`.\n */\nexport function toGooglePiMessages(messages: SessionMessage[], model: GoogleModel, route: GeminiSignatureScope, provider: string = route): PiMessage[] {\n // System notes have no native slot on this wire: send them as `<system-reminder>` text.\n messages = systemNotesAsText(messages)\n const out: PiMessage[] = []\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i]!\n if (msg.role === 'assistant') {\n out.push(piAssistantMessage(msg.content, model, route))\n const calls = msg.content.filter((b): b is Extract<SessionContentBlock, { type: 'tool_call' }> => b.type === 'tool_call')\n if (calls.length === 0)\n continue\n const next = messages[i + 1]\n const results = new Map(\n (next?.role === 'user' ? next.content : [])\n .filter((b): b is Extract<SessionContentBlock, { type: 'tool_result' }> => b.type === 'tool_result')\n .map(r => [r.callId, r]),\n )\n for (const call of calls) {\n const result = results.get(call.id)\n ?? { type: 'tool_result' as const, callId: call.id, output: SYNTHETIC_TOOL_RESULT_PLACEHOLDER, isError: true }\n out.push(piToolResultMessage(result, call.name, provider))\n }\n if (next?.role === 'user') {\n // Results whose call isn't in the turn above were removed by the\n // canonical pairing repair; never send one unpaired.\n const rest = piUserMessage(next.content.filter(b => b.type !== 'tool_result'), provider)\n if (rest)\n out.push(rest)\n i++\n }\n continue\n }\n const userMsg = piUserMessage(msg.content.filter(b => b.type !== 'tool_result'), provider)\n if (userMsg)\n out.push(userMsg)\n }\n return out\n}\n\n/**\n * Converts pi-ai's final assistant message to a session message, tagging\n * every thought signature with the route that issued it.\n *\n * @param message - pi-ai assistant message.\n * @param route - Signature scope that produced it.\n */\nexport function fromGooglePiAssistantMessage(message: PiAssistantMessage, route: GeminiSignatureScope): SessionMessage {\n const signed = (signature: string | undefined) =>\n signature ? { signature, signatureProducer: route } : {}\n const content: SessionContentBlock[] = []\n for (const block of message.content) {\n if (block.type === 'text')\n content.push({ type: 'text', text: block.text, ...signed(block.textSignature) })\n else if (block.type === 'thinking')\n content.push({ type: 'thinking', text: block.thinking, ...signed(block.thinkingSignature) })\n else if (block.type === 'toolCall')\n content.push({ type: 'tool_call', id: block.id, name: block.name, input: block.arguments, ...signed(block.thoughtSignature) })\n }\n return { role: 'assistant', content }\n}\n\nfunction mapStopReason(stopReason: string | undefined, hasToolCalls: boolean): TurnFinishReason {\n switch (stopReason) {\n case 'toolUse':\n return 'tool-calls'\n case 'length':\n return 'length'\n case 'error':\n return 'error'\n case 'aborted':\n return 'other'\n default:\n return hasToolCalls ? 'tool-calls' : 'stop'\n }\n}\n\n/** Forced tool choice, written into Gemini's `functionCallingConfig`. */\nfunction applyToolChoice(payload: unknown, options: StreamOptions, toWire: (name: string) => string): unknown {\n const choice = options.toolChoice\n if (!choice || choice.type === 'auto')\n return payload\n const params = payload as { config?: { toolConfig?: { functionCallingConfig?: Record<string, unknown> } } }\n if (!params.config?.toolConfig)\n return payload\n params.config.toolConfig.functionCallingConfig = choice.type === 'tool' && choice.name\n ? { mode: 'ANY', allowedFunctionNames: [toWire(choice.name)] }\n : { mode: 'ANY' }\n return params\n}\n\n/**\n * Transient Gemini failures worth a loop-level retry once pi-ai's own retries\n * (408 / 409 / 429 / 5xx before the stream opens) are spent.\n */\nconst TRANSIENT_GOOGLE_MESSAGE_RE = /RESOURCE_EXHAUSTED|UNAVAILABLE|DEADLINE_EXCEEDED|overloaded|high demand|rate.?limit|try again later/i\n\n/** Gemini's `RetryInfo` detail in a 429 body: `\"retryDelay\": \"34s\"`. */\nconst RETRY_DELAY_RE = /\"retryDelay\"\\s*:\\s*\"(\\d+(?:\\.\\d+)?)s\"/\n\n/** pi-ai formats HTTP failures as `<status>: <body>`. */\nfunction leadingStatus(message: string): number | undefined {\n const match = /^(\\d{3})\\b/.exec(message)\n return match ? Number(match[1]) : undefined\n}\n\ninterface GoogleErrorBody { error?: { code?: unknown, message?: unknown, status?: unknown } }\n\nfunction parseGoogleErrorBody(text: string): GoogleErrorBody['error'] | undefined {\n try {\n const parsed = JSON.parse(text) as GoogleErrorBody | null\n return parsed && typeof parsed.error === 'object' && parsed.error ? parsed.error : undefined\n }\n catch {\n return undefined\n }\n}\n\n/**\n * The stream error pi-ai reports, as Google wrote it. `@google/genai` wraps a\n * non-JSON response as `{\"error\":{\"message\":\"<body>\"}}`, so Google's own\n * `{\"error\":{…}}` can arrive JSON-encoded inside it.\n *\n * @param raw - pi-ai's `errorMessage`: `<status>: <body>` or the SDK's message.\n * @returns The innermost message prefixed with its HTTP and RPC status, the\n * status, and the innermost body (it carries details such as `retryDelay`).\n */\nfunction unwrapGoogleError(raw: string): { message: string, status?: number, body?: string } {\n let status = leadingStatus(raw)\n let rpcStatus: string | undefined\n let text = status === undefined ? raw : raw.replace(/^\\d{3}:\\s*/, '')\n let message: string | undefined\n let body = raw\n for (let error = parseGoogleErrorBody(text); error; error = parseGoogleErrorBody(text)) {\n body = text\n if (typeof error.code === 'number')\n status = error.code\n if (typeof error.status === 'string' && /^[A-Z_]+$/.test(error.status))\n rpcStatus = error.status\n if (typeof error.message !== 'string')\n break\n message = text = error.message.trim()\n }\n if (!message)\n return { message: raw, ...(status !== undefined ? { status } : {}) }\n const prefix = [status, rpcStatus].filter(part => part !== undefined).join(' ')\n return { message: prefix ? `${prefix}: ${message}` : message, ...(status !== undefined ? { status } : {}), body }\n}\n\n/**\n * Classify a Gemini API / Vertex AI error.\n *\n * @param err - Error thrown by pi-ai or the SDK.\n * @param label - Product a limit's message names; routes over other services (Antigravity) pass their own.\n */\nexport function classifyGoogleError(err: unknown, label = 'Gemini'): ClassifiedError | null {\n const prelude = classifyErrorPrelude(err)\n if (prelude === 'not-object')\n return null\n if (prelude === 'aborted')\n return { kind: 'aborted' }\n const anyErr = err as { message?: unknown, status?: unknown, body?: unknown }\n const message = typeof anyErr.message === 'string' ? anyErr.message : ''\n if (matchesContextExceeded(message))\n return { kind: 'context_exceeded', providerCode: 'context_length_exceeded', message }\n if (matchesToolPairingError(message))\n return { kind: 'tool_pairing_corruption', message }\n if (!message)\n return null\n const status = typeof anyErr.status === 'number' ? anyErr.status : leadingStatus(message)\n const retryable = (status !== undefined && isRetryableHttpStatus(status)) || TRANSIENT_GOOGLE_MESSAGE_RE.test(message)\n const reason = providerLimitReason({ status, message })\n if (reason) {\n const delay = RETRY_DELAY_RE.exec(typeof anyErr.body === 'string' ? anyErr.body : message)\n return classifyProviderLimit(\n { reason, provider: label, ...(delay ? { retryAfterMs: Number(delay[1]) * 1000 } : {}) },\n { ...(status !== undefined ? { providerCode: String(status) } : {}), retryable },\n )\n }\n return {\n kind: 'provider_error',\n ...(status !== undefined ? { providerCode: String(status) } : {}),\n message,\n ...(retryable ? { retryable: true } : {}),\n }\n}\n\n/** Every budget level at `tokens`: pi-ai picks the level, the caller fixed the budget. */\nfunction budgetsAt(tokens: number): PiThinkingBudgets {\n return { minimal: tokens, low: tokens, medium: tokens, high: tokens }\n}\n\n/** Credentials and settings one request goes out with. */\nexport interface GoogleRequestAuth {\n /** Sent to the stream as `options.apiKey` (an API key, or a bearer token for a custom transport). */\n apiKey?: string\n /**\n * Sent to the stream as `options.env`, which pi-ai reads before\n * `process.env` (project, location, credentials file). A custom transport\n * reads its own per-request settings here, e.g. the account's project.\n */\n env?: Record<string, string>\n /** Removes what the request needed only while it ran. */\n dispose?: () => void\n}\n\n/**\n * A Gemini-wire backend for {@link googleCompatible}: where requests go\n * (`load`), how they authenticate (`auth`) and which models it serves\n * (`resolveModel`). Message conversion, thought-signature bookkeeping, tool\n * names, thinking levels, usage and cost stay in the shared plumbing.\n */\nexport interface GoogleCompatibleRoute {\n /**\n * Provider name (`Provider.name`, error copy) and the default signature\n * scope. Must not be a built-in provider name (`google`,\n * `google-vertex`, `anthropic`, `openai`).\n */\n name: string\n /**\n * pi-ai stream functions for the backend, loaded on first use. pi-ai's\n * `api/google-generative-ai` adapter is the reference: a custom transport\n * emits the same events, applies `options.onPayload` to the SDK-shaped\n * params (`{ model, contents, config }`) before sending, and reports errors\n * as `<status>: <body>` so they classify by HTTP status.\n */\n load: () => Promise<GoogleStreams>\n /** Credentials and settings for one request, resolved per turn. */\n auth: (callbacks: StreamCallbacks) => GoogleRequestAuth | Promise<GoogleRequestAuth>\n /** Whether the provider runs on an OAuth credential. */\n isOAuth: boolean\n /**\n * pi-ai model record for a requested model id, with `api:\n * 'google-generative-ai'`. Its `cost` rates price each turn: zero rates\n * report no cost (quota-backed access).\n *\n * @param modelId - Requested model id.\n * @param catalog - Per-run catalog override.\n */\n resolveModel: (modelId: string, catalog?: ModelCatalog) => GoogleWireModel\n /**\n * Signature scope of a model: the tag its thought signatures carry, and\n * the only scope they replay to. Defaults to `name`, right when every model\n * behind the backend accepts the others' signatures (Gemini does). A\n * backend fronting several model families returns one scope per family,\n * so switching families mid-session sends earlier reasoning unsigned.\n *\n * @param modelId - Model id of the turn.\n */\n signatureScope?: (modelId: string) => string\n /** Error classification. Defaults to {@link classifyGoogleError}. */\n classifyError?: (err: unknown) => ClassifiedError | null\n}\n\n/** Built-in routes, plus the registry lookup only they have. */\ninterface GoogleRoute extends Omit<GoogleCompatibleRoute, 'resolveModel'> {\n resolveModel?: GoogleCompatibleRoute['resolveModel']\n}\n\n/** Names a {@link googleCompatible} route can't take: built-in providers and signature producers. */\nconst RESERVED_ROUTE_NAMES: ReadonlySet<string> = new Set(['google', 'google-vertex', 'anthropic', 'openai', 'zidane'])\n\n/** Settings shared by the Google providers. */\nexport interface GoogleSharedParams {\n /**\n * Model used when a request does not set one.\n * @default 'gemini-3.8-flash'\n */\n defaultModel?: string\n /**\n * Provider capability flags. Gemini takes images in prompts and in tool\n * results; audio, video and PDFs degrade to text markers (pi-ai's content\n * union is text | image).\n */\n capabilities?: ProviderCapabilities\n /** Extra HTTP headers sent on every request. */\n extraHeaders?: Record<string, string>\n}\n\nfunction createGoogleProvider(route: GoogleRoute, params: GoogleSharedParams | undefined): Provider {\n const defaultModel = params?.defaultModel || GOOGLE_DEFAULT_MODEL\n const capabilities: ProviderCapabilities = params?.capabilities ?? {\n vision: true,\n imageInToolResult: true,\n audio: false,\n video: false,\n documents: false,\n }\n\n return {\n name: route.name,\n meta: { defaultModel, isOAuth: route.isOAuth, capabilities },\n formatTools,\n userMessage,\n assistantMessage,\n toolResultsMessage,\n classifyError: route.classifyError ?? classifyGoogleError,\n\n async stream(options: StreamOptions, callbacks: StreamCallbacks): Promise<TurnResult> {\n const auth = await route.auth(callbacks)\n try {\n return await streamTurn(auth, options, callbacks)\n }\n finally {\n auth.dispose?.()\n }\n },\n }\n\n async function streamTurn(auth: GoogleRequestAuth, options: StreamOptions, callbacks: StreamCallbacks): Promise<TurnResult> {\n const modelId = options.model || defaultModel\n const model = route.resolveModel\n ? route.resolveModel(modelId, options.modelCatalog)\n : resolveGoogleModel(route.name as GoogleRouteName, modelId, options.modelCatalog)\n const scope = signatureScopeOf(route, model.id)\n const tools = options.tools as PiTool[]\n const nameBoundary = createToolNameBoundary(options.messages, tools.map(tool => tool.name))\n // pi-ai's stream entry points take a `TranscriptContext`: the prompt and\n // tools folded into a leading system message.\n const context = normalizeContext({\n systemPrompt: renderSystemForWire(options.system),\n messages: toGooglePiMessages(nameBoundary.messages, model, scope, route.name),\n tools: tools.map(tool => ({ ...tool, name: nameBoundary.toWire(tool.name) })),\n })\n const api = await route.load()\n const base: GoogleStreamOptions = {\n ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),\n ...(auth.env ? { env: auth.env } : {}),\n ...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),\n signal: options.signal,\n ...(params?.extraHeaders ? { headers: params.extraHeaders } : {}),\n onPayload: (payload: unknown) => applyToolChoice(payload, options, nameBoundary.toWire),\n }\n\n let s: AssistantMessageEventStream\n if (options.thinking === 'adaptive' && model.reasoning) {\n // pi-ai has no adaptive level: thinking on, no level or budget, so the\n // model thinks as much as it decides, with thought summaries.\n const { buildBaseOptions } = await import('@earendil-works/pi-ai/api/simple-options')\n s = api.stream(model, context, { ...buildBaseOptions(model, context, base), thinking: { enabled: true } })\n }\n else {\n const reasoning = options.thinking && options.thinking !== 'off' && options.thinking !== 'adaptive'\n ? options.thinking\n : undefined\n // `streamSimple` clamps the level to what the model supports and sends\n // `thinkingLevel` (Gemini 3+) or a token budget (2.5), or turns\n // thinking off when none is set.\n s = api.streamSimple(model, context, {\n ...base,\n ...(reasoning ? { reasoning } : {}),\n ...(reasoning && options.thinkingBudget !== undefined ? { thinkingBudgets: budgetsAt(options.thinkingBudget) } : {}),\n })\n }\n\n let finalMessage: PiAssistantMessage | undefined\n let text = ''\n let thinking = ''\n for await (const event of s) {\n if (event.type === 'text_delta') {\n text += event.delta\n callbacks.onText(event.delta)\n }\n else if (event.type === 'thinking_delta') {\n thinking += event.delta\n callbacks.onThinking?.(event.delta)\n }\n else if (event.type === 'thinking_end') {\n const delta = event.content.startsWith(thinking)\n ? event.content.slice(thinking.length)\n : (thinking ? '' : event.content)\n if (delta) {\n thinking += delta\n callbacks.onThinking?.(delta)\n }\n }\n else if (event.type === 'toolcall_start' || event.type === 'toolcall_delta') {\n callbacks.onToolCallDelta?.()\n }\n else if (event.type === 'done') {\n finalMessage = event.message\n }\n else if (event.type === 'error') {\n const { message, ...details } = unwrapGoogleError(event.error.errorMessage || `Google ${route.name} API error`)\n throw Object.assign(new Error(message), details)\n }\n }\n finalMessage ??= await s.result()\n\n const toolCalls = finalMessage.content\n .filter(block => block.type === 'toolCall')\n .map(block => ({ id: block.id, name: nameBoundary.fromWire(block.name), input: block.arguments as Record<string, unknown> }))\n const assistantTurn = fromGooglePiAssistantMessage(finalMessage, scope)\n assistantTurn.content = assistantTurn.content.map(block =>\n block.type === 'tool_call' ? { ...block, name: nameBoundary.fromWire(block.name) } : block,\n )\n const finishReason = mapStopReason(finalMessage.stopReason, toolCalls.length > 0)\n const usage: TurnUsage = await fillEstimatedCost({\n input: finalMessage.usage.input,\n output: finalMessage.usage.output,\n cacheRead: finalMessage.usage.cacheRead || undefined,\n ...(finalMessage.usage.reasoning ? { thinking: finalMessage.usage.reasoning } : {}),\n cost: finalMessage.usage.cost.total || undefined,\n finishReason,\n modelId,\n }, route.name, undefined, options.modelCatalog)\n\n return {\n assistantMessage: assistantTurn,\n text: text || finalMessage.content.flatMap(block => block.type === 'text' ? [block.text] : []).join(''),\n toolCalls,\n done: toolCalls.length === 0,\n usage,\n }\n }\n}\n\n/**\n * The scope a model's thought signatures carry. A custom route's scope can't\n * impersonate a built-in producer, whose signatures it would then replay.\n */\nfunction signatureScopeOf(route: GoogleRoute, modelId: string): GeminiSignatureScope {\n const scope = route.signatureScope?.(modelId) ?? route.name\n if (scope !== route.name && RESERVED_ROUTE_NAMES.has(scope))\n throw new Error(`${route.name}: signature scope \"${scope}\" is reserved for a built-in provider`)\n return scope\n}\n\n/**\n * Creates a provider over another Gemini-wire backend: an extension supplies\n * the transport, auth and model records; message conversion, thought\n * signatures (tagged with the route's scope, never replayed elsewhere), tool\n * names, thinking levels, usage and cost come from the same plumbing as\n * {@link google} and {@link googleVertex}.\n *\n * @param route - The backend: name, transport, auth and models.\n * @param params - Default model, capabilities and extra headers.\n *\n * @example\n * ```ts\n * import { googleCompatible } from 'zidane/providers'\n *\n * const provider = googleCompatible({\n * name: 'my-gateway',\n * isOAuth: false,\n * load: async () => myGeminiTransport,\n * auth: () => ({ apiKey: process.env.MY_GATEWAY_KEY }),\n * resolveModel: id => myModels[id],\n * }, { defaultModel: 'gemini-3.8-flash' })\n * ```\n */\nexport function googleCompatible(route: GoogleCompatibleRoute, params?: GoogleSharedParams): Provider {\n if (!route.name || RESERVED_ROUTE_NAMES.has(route.name))\n throw new Error(`googleCompatible: route name \"${route.name}\" is reserved for a built-in provider`)\n return createGoogleProvider(route, params)\n}\n\n/**\n * pi-ai's Gemini-wire building blocks, for a {@link googleCompatible}\n * transport: the converters, signature helpers and event stream pi-ai's own\n * Gemini adapter (`api/google-generative-ai`) is made of.\n */\nexport interface GoogleWireKit {\n /** Transcript to Gemini `Content[]`. */\n convertMessages: typeof import('@earendil-works/pi-ai/api/google-shared')['convertMessages']\n /** Tools to Gemini function declarations (`parametersJsonSchema`, or legacy `parameters`). */\n convertTools: typeof import('@earendil-works/pi-ai/api/google-shared')['convertTools']\n /** Whether a response part is thought content (`thought: true`), not just signature-bearing. */\n isThinkingPart: typeof import('@earendil-works/pi-ai/api/google-shared')['isThinkingPart']\n /** Keeps a block's last non-empty `thoughtSignature` when later deltas omit it. */\n retainThoughtSignature: typeof import('@earendil-works/pi-ai/api/google-shared')['retainThoughtSignature']\n /** Whether the model needs explicit ids on function calls and responses. */\n requiresToolCallId: typeof import('@earendil-works/pi-ai/api/google-shared')['requiresToolCallId']\n /** Gemini's raw `finishReason` string to a stop reason. */\n mapStopReasonString: typeof import('@earendil-works/pi-ai/api/google-shared')['mapStopReasonString']\n /** Function-calling mode for a tool choice; `VALIDATED` when a tool asks for strict sampling. */\n resolveGoogleFunctionCallingMode: typeof import('@earendil-works/pi-ai/api/google-shared')['resolveGoogleFunctionCallingMode']\n /** Whether the model enforces required parameters in validated tool calling (Gemini 3+). */\n supportsGoogleStrictToolSampling: typeof import('@earendil-works/pi-ai/api/google-shared')['supportsGoogleStrictToolSampling']\n /** A new event stream for the transport to push the assistant message into. */\n createAssistantMessageEventStream: typeof import('@earendil-works/pi-ai')['createAssistantMessageEventStream']\n /** Keeps the leading system message and drops later ones, for an API without mid-conversation system messages. */\n collapseSystemMessages: typeof import('@earendil-works/pi-ai')['collapseSystemMessages']\n /** The transcript's leading system message, if any. */\n getInitialSystemMessage: typeof import('@earendil-works/pi-ai')['getInitialSystemMessage']\n /** Tools in effect after every transcript delta is applied. */\n getCurrentTools: typeof import('@earendil-works/pi-ai')['getCurrentTools']\n /** A system message rendered as a full prompt: content, then sections. */\n getSystemMessageText: typeof import('@earendil-works/pi-ai')['getSystemMessageText']\n /** Cost of a usage record at the model's prices. */\n calculateCost: typeof import('@earendil-works/pi-ai')['calculateCost']\n /** The level if the model supports it, else the next higher supported one, else the next lower. */\n clampThinkingLevel: typeof import('@earendil-works/pi-ai')['clampThinkingLevel']\n}\n\n/**\n * Load the {@link GoogleWireKit} from the HOST's pi-ai. An extension's\n * transport gets it through `zidane/providers` (mapped to the host's module)\n * instead of importing pi-ai itself: one pi-ai copy, the exact wire the\n * host's pi-ai speaks, and it resolves inside compiled binaries too. pi-ai's\n * bare specifiers can't be host-mapped the way `zidane` is: the mapping's\n * loader would re-import the specifier it intercepts. Loaded on first call,\n * since `@google/genai` comes with it.\n */\nexport async function loadGoogleWireKit(): Promise<GoogleWireKit> {\n const [shared, core] = await Promise.all([\n import('@earendil-works/pi-ai/api/google-shared'),\n import('@earendil-works/pi-ai'),\n ])\n return {\n convertMessages: shared.convertMessages,\n convertTools: shared.convertTools,\n isThinkingPart: shared.isThinkingPart,\n retainThoughtSignature: shared.retainThoughtSignature,\n requiresToolCallId: shared.requiresToolCallId,\n mapStopReasonString: shared.mapStopReasonString,\n resolveGoogleFunctionCallingMode: shared.resolveGoogleFunctionCallingMode,\n supportsGoogleStrictToolSampling: shared.supportsGoogleStrictToolSampling,\n createAssistantMessageEventStream: core.createAssistantMessageEventStream,\n collapseSystemMessages: core.collapseSystemMessages,\n getInitialSystemMessage: core.getInitialSystemMessage,\n getCurrentTools: core.getCurrentTools,\n getSystemMessageText: core.getSystemMessageText,\n calculateCost: core.calculateCost,\n clampThinkingLevel: core.clampThinkingLevel,\n }\n}\n\nasync function loadGeminiApi(): Promise<GoogleStreams> {\n return (await import('@earendil-works/pi-ai/api/google-generative-ai')) as unknown as GoogleStreams\n}\nasync function loadVertexApi(): Promise<GoogleStreams> {\n return (await import('@earendil-works/pi-ai/api/google-vertex')) as unknown as GoogleStreams\n}\n\n/** Options for {@link google}. */\nexport interface GoogleParams extends GoogleSharedParams {\n /** Gemini API key. Defaults to `GEMINI_API_KEY`, then `GOOGLE_API_KEY`. */\n apiKey?: string\n}\n\n/**\n * Creates the Google Gemini provider on the Gemini API (Google AI Studio).\n * Authenticates with `apiKey`, else `GEMINI_API_KEY`, else `GOOGLE_API_KEY`.\n *\n * @param params - API key, default model, capabilities and extra headers.\n *\n * @example\n * ```ts\n * import { createAgent } from 'zidane'\n * import { google } from 'zidane/providers/google'\n *\n * const agent = createAgent({\n * provider: google({ apiKey: process.env.GEMINI_API_KEY }),\n * })\n * await agent.run({ prompt: 'Say hello.' })\n * ```\n */\nexport function google(params?: GoogleParams): Provider {\n const resolveKey = (): string | undefined => params?.apiKey || process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY\n const provider = createGoogleProvider({\n name: 'google',\n load: loadGeminiApi,\n isOAuth: false,\n auth: () => {\n const apiKey = resolveKey()\n if (!apiKey)\n throw new Error('No Gemini API key found. Set GEMINI_API_KEY, or add a key in the Google Gemini provider settings.')\n return { apiKey }\n },\n }, params)\n return { ...provider, images: googleImages({ resolveKey }) }\n}\n\n/** Options for {@link googleVertex}. */\nexport interface GoogleVertexParams extends GoogleSharedParams {\n /**\n * Vertex AI API key (express mode). Defaults to `GOOGLE_CLOUD_API_KEY`.\n * Without one, requests authenticate with Google Cloud credentials.\n */\n apiKey?: string\n /** Google Cloud project. Defaults to `GOOGLE_CLOUD_PROJECT`, then `GCLOUD_PROJECT`. */\n project?: string\n /** Vertex AI location. Defaults to `GOOGLE_CLOUD_LOCATION`, then `global`. */\n location?: string\n /**\n * Service-account or authorized-user credentials file. Defaults to\n * `GOOGLE_APPLICATION_CREDENTIALS`, then gcloud's Application Default\n * Credentials (`gcloud auth application-default login`).\n */\n credentialsFile?: string\n /**\n * Run on one stored \"Sign in with Google\" account (its stable id) rather\n * than the active one. See {@link OAuthParams.account}.\n */\n account?: OAuthParams['account']\n}\n\n/** The fields a \"Sign in with Google\" grant carries beyond the token triple. */\ninterface VertexGrant {\n refresh: string\n projectId: string\n clientId: string\n clientSecret: string\n}\n\nconst VERTEX_DIR_PREFIX = 'zidane-vertex-'\nconst VERTEX_DIR_RE = /^zidane-vertex-[A-Za-z0-9]{6}$/\n/** Older than any request: its process crashed or was killed before cleanup. */\nconst STALE_VERTEX_DIR_MS = 60 * 60 * 1000\nlet nextVertexSweepAt = 0\n\n/**\n * Remove this user's credentials dirs that a crashed request left behind;\n * they hold a refresh token. Listing the temp dir can take hundreds of\n * milliseconds, so it runs in the background, at most once an hour.\n */\nfunction sweepStaleVertexDirs(): void {\n const now = Date.now()\n if (now < nextVertexSweepAt)\n return\n nextVertexSweepAt = now + STALE_VERTEX_DIR_MS\n const root = tmpdir()\n const uid = process.getuid?.()\n const sweepOne = async (name: string): Promise<void> => {\n const dir = join(root, name)\n const stat = await lstat(dir)\n if (stat.isDirectory() && (uid === undefined || stat.uid === uid) && now - stat.mtimeMs > STALE_VERTEX_DIR_MS)\n await rm(dir, { recursive: true, force: true })\n }\n // Best effort: a dir removed concurrently, or not ours to remove, is skipped.\n void readdir(root)\n .then(names => Promise.allSettled(names.filter(name => VERTEX_DIR_RE.test(name)).map(sweepOne)))\n .catch(() => {})\n}\n\n/**\n * Request auth from the stored \"Sign in with Google\" grant (the pinned\n * account's, else the active one), or `undefined` when none is stored.\n *\n * The access token rotates through zidane's OAuth path (cross-process locks,\n * persistence, refresh hooks, a clear \"sign in again\" for a revoked grant).\n * Vertex itself authenticates from an `authorized_user` credentials file\n * holding the refresh token: pi-ai's Vertex client takes no bare access\n * token. The file lives in a private temp dir for the length of the request.\n */\nasync function signedInAuth(\n params: GoogleVertexParams | undefined,\n callbacks: StreamCallbacks | undefined,\n): Promise<GoogleRequestAuth | undefined> {\n const account = params?.account\n const read = () => account\n ? readAccountOAuthCredential(GOOGLE_VERTEX_OAUTH_ID, account)\n : readOAuthCredentials()[GOOGLE_VERTEX_OAUTH_ID]\n if (!read()) {\n if (account)\n throw new Error(pinnedAccountMissingError('google-vertex'))\n return undefined\n }\n await resolveOAuthApiKey({\n provider: 'google-vertex',\n providerId: GOOGLE_VERTEX_OAUTH_ID,\n ...(account ? { params: { account } } : {}),\n missingError: 'No Google sign-in found for Vertex AI. Sign in with Google again.',\n refreshError: reason => `Google sign-in refresh failed. Sign in with Google again. ${reason}`,\n }, callbacks)\n const grant = read() as Partial<VertexGrant> | undefined\n if (!grant?.refresh || !grant.clientId || !grant.clientSecret || !grant.projectId)\n throw new Error('This Google sign-in is missing its OAuth client or project. Sign in with Google again.')\n\n const project = params?.project || grant.projectId\n sweepStaleVertexDirs()\n const dir = mkdtempSync(join(tmpdir(), VERTEX_DIR_PREFIX))\n const file = join(dir, 'credentials.json')\n try {\n writeFileSync(file, JSON.stringify({\n type: 'authorized_user',\n client_id: grant.clientId,\n client_secret: grant.clientSecret,\n refresh_token: grant.refresh,\n quota_project_id: project,\n }), { mode: 0o600 })\n }\n catch (err) {\n rmSync(dir, { recursive: true, force: true })\n throw err\n }\n return {\n env: {\n GOOGLE_CLOUD_PROJECT: project,\n GOOGLE_CLOUD_LOCATION: params?.location || process.env.GOOGLE_CLOUD_LOCATION || 'global',\n GOOGLE_APPLICATION_CREDENTIALS: file,\n },\n dispose: () => rmSync(dir, { recursive: true, force: true }),\n }\n}\n\n/**\n * Credentials and settings for a Vertex AI request, read per turn so a\n * credential configured after the provider was built still applies. In\n * order: a pinned account's sign-in, a Vertex API key, the active \"Sign in\n * with Google\" grant, then Google Cloud credentials for the project.\n *\n * @param params - Explicit settings; environment variables fill the rest.\n * @param callbacks - Stream callbacks, for the OAuth refresh hook.\n */\nexport async function resolveVertexAuth(params?: GoogleVertexParams, callbacks?: StreamCallbacks): Promise<GoogleRequestAuth> {\n if (params?.account)\n return (await signedInAuth(params, callbacks))!\n const apiKey = params?.apiKey || process.env.GOOGLE_CLOUD_API_KEY\n if (apiKey)\n return { apiKey }\n const signedIn = await signedInAuth(params, callbacks)\n if (signedIn)\n return signedIn\n const project = params?.project || process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT\n if (!project)\n throw new Error('Vertex AI needs a Google Cloud project. Set GOOGLE_CLOUD_PROJECT, or configure it in the Google Vertex AI provider settings.')\n const location = params?.location || process.env.GOOGLE_CLOUD_LOCATION || 'global'\n const credentialsFile = params?.credentialsFile || process.env.GOOGLE_APPLICATION_CREDENTIALS\n return {\n env: {\n GOOGLE_CLOUD_PROJECT: project,\n GOOGLE_CLOUD_LOCATION: location,\n ...(credentialsFile ? { GOOGLE_APPLICATION_CREDENTIALS: credentialsFile } : {}),\n },\n }\n}\n\n/**\n * Creates the Google Vertex AI provider. Authenticates with a pinned\n * `account`'s Google sign-in, else a Vertex API key (`apiKey` or\n * `GOOGLE_CLOUD_API_KEY`), else the active \"Sign in with Google\" grant, else\n * Google Cloud credentials for `project` in `location`. See\n * {@link resolveVertexAuth}.\n *\n * @param params - Credentials, project, location, default model, capabilities and extra headers.\n *\n * @example\n * ```ts\n * import { createAgent } from 'zidane'\n * import { googleVertex } from 'zidane/providers/google'\n *\n * // After `gcloud auth application-default login`:\n * const agent = createAgent({\n * provider: googleVertex({ project: 'my-project' }),\n * })\n * await agent.run({ prompt: 'Say hello.' })\n * ```\n */\nexport function googleVertex(params?: GoogleVertexParams): Provider {\n return createGoogleProvider({\n name: 'google-vertex',\n load: loadVertexApi,\n isOAuth: !!params?.account || !(params?.apiKey || process.env.GOOGLE_CLOUD_API_KEY),\n auth: callbacks => resolveVertexAuth(params, callbacks),\n }, params)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAWA,MAAM,WAAW;;AAGjB,MAAa,sBAAiD;CAC5D;EAAE,IAAI;EAA0B,MAAM;EAA0B,OAAO,CAAC,QAAQ,OAAO;CAAE;CACzF;EAAE,IAAI;EAAsB,MAAM;EAAsB,OAAO,CAAC,QAAQ,OAAO;CAAE;CACjF;EAAE,IAAI;EAA+B,MAAM;EAA+B,OAAO,CAAC,QAAQ,OAAO;CAAE;CACnG;EAAE,IAAI;EAA0B,MAAM;EAA0B,OAAO,CAAC,QAAQ,OAAO;CAAE;AA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M,WAAW,MAAM,aAAa,QAAQ,SAAS;CACrD,IAAI,UACF,OAAO;CACT,MAAM,UAAU,QAAQ,WAAW,QAAQ,IAAI,wBAAwB,QAAQ,IAAI;CACnF,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,8HAA8H;CAChJ,MAAM,WAAW,QAAQ,YAAY,QAAQ,IAAI,yBAAyB;CAC1E,MAAM,kBAAkB,QAAQ,mBAAmB,QAAQ,IAAI;CAC/D,OAAO,EACL,KAAK;EACH,sBAAsB;EACtB,uBAAuB;EACvB,GAAI,kBAAkB,EAAE,gCAAgC,gBAAgB,IAAI,CAAC;CAC/E,EACF;AACF;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,aAAa,QAAuC;CAClE,OAAO,qBAAqB;EAC1B,MAAM;EACN,MAAM;EACN,SAAS,CAAC,CAAC,QAAQ,WAAW,EAAE,QAAQ,UAAU,QAAQ,IAAI;EAC9D,OAAM,cAAa,kBAAkB,QAAQ,SAAS;CACxD,GAAG,MAAM;AACX"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as installCacheBreakLogger, n as createAgent } from "./agent-
|
|
1
|
+
import { A as installCacheBreakLogger, n as createAgent } from "./agent-CBQglXtH.js";
|
|
2
2
|
import { u as parseFrontmatter } from "./allowed-tools-Vty0kBOj.js";
|
|
3
3
|
import { t as isSpawnTool } from "./is-spawn-tool-BWxYvCYU.js";
|
|
4
4
|
import { d as createMemoryStore, t as createSession } from "./session-7TUHs42_.js";
|
|
@@ -7,7 +7,7 @@ import { t as findGitRoot } from "./project-root-BOgUA6n5.js";
|
|
|
7
7
|
import { c as textOf, o as installHeadlessEventAdapter } from "./headless-format-D9IB_rae.js";
|
|
8
8
|
import { t as projectUserPaths } from "./project-user-paths-DWqZyUgb.js";
|
|
9
9
|
import { n as DEFAULT_MEDIA_BUDGET, t as DEFAULT_MAX_IMAGE_EDGE } from "./defaults-Cx3zvDOV.js";
|
|
10
|
-
import { n as basic_default } from "./presets-
|
|
10
|
+
import { n as basic_default } from "./presets-DXeHsd24.js";
|
|
11
11
|
import { t as createRunSummaryCollector } from "./run-summary-2d26oMyQ.js";
|
|
12
12
|
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
13
13
|
import { join, resolve } from "node:path";
|
|
@@ -712,4 +712,4 @@ function stripThinking(turns) {
|
|
|
712
712
|
//#endregion
|
|
713
713
|
export { listMarkdownDefFiles as a, loadMarkdownCommands as i, applyMarkdownSubagents as n, markdownDefRoots as o, loadMarkdownAgents as r, BUILTIN_SUBAGENTS as s, runHeadless as t };
|
|
714
714
|
|
|
715
|
-
//# sourceMappingURL=headless-
|
|
715
|
+
//# sourceMappingURL=headless-R4pbpTkm.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"headless-Ebd1ZEzC.js","names":["IGNORED_KEYS","basic"],"sources":["../src/markdown-defs/model-aliases.ts","../src/markdown-defs/tool-map.ts","../src/markdown-defs/agents.ts","../src/markdown-defs/builtin-agents.ts","../src/markdown-defs/commands.ts","../src/markdown-defs/roots.ts","../src/markdown-defs/scan.ts","../src/markdown-defs/index.ts","../src/headless.ts"],"sourcesContent":["import type { MarkdownDefDiagnostic } from './types'\n\n/**\n * Claude Code's agent `model:` aliases. Bump alongside `../chat/anthropic-models.ts`\n * when the Anthropic lineup changes.\n */\nexport const CLAUDE_MODEL_ALIASES: Readonly<Record<'haiku' | 'sonnet' | 'opus' | 'fable', string>> = {\n haiku: 'claude-haiku-4-5-20251001',\n sonnet: 'claude-sonnet-5-5',\n opus: 'claude-opus-5-5',\n fable: 'claude-fable-5-1',\n}\n\n/** Context for resolving Claude `model:` aliases in agent files. */\nexport interface ModelAliasContext {\n /** Provider name of the parent session, e.g. `'anthropic'`. */\n parentProvider?: string\n /** Model ids the spawn catalog lists, when one was built. */\n catalogIds?: ReadonlySet<string>\n}\n\n/**\n * Without a catalog, spawn sends a raw id to the PARENT's provider, so a\n * Claude id under an OpenAI parent would fail mid-run. Unresolvable aliases\n * therefore inherit instead of failing the spawn.\n */\nexport function resolveModelAlias(\n value: string | undefined,\n ctx: ModelAliasContext,\n path: string,\n): { model?: string, diagnostic?: MarkdownDefDiagnostic } {\n const raw = value?.trim()\n if (!raw || raw.toLowerCase() === 'inherit')\n return {}\n const key = raw.toLowerCase() as keyof typeof CLAUDE_MODEL_ALIASES\n if (!Object.hasOwn(CLAUDE_MODEL_ALIASES, key))\n return { model: raw }\n const target = CLAUDE_MODEL_ALIASES[key]\n if (ctx.parentProvider === 'anthropic' || ctx.catalogIds?.has(target))\n return { model: target }\n return {\n diagnostic: {\n path,\n kind: 'agent',\n message: `model alias \"${raw}\" needs an Anthropic parent; inheriting the parent model`,\n },\n }\n}\n","import type { MarkdownDefDiagnostic } from './types'\n\n/** Claude Code tool names → zidane `spec.name`. */\nexport const CLAUDE_TOOL_MAP: Readonly<Record<string, string>> = {\n Read: 'read_file',\n Write: 'write_file',\n Edit: 'edit',\n MultiEdit: 'multi_edit',\n Bash: 'shell',\n Grep: 'grep',\n Glob: 'glob',\n LS: 'list_files',\n WebFetch: 'fetch_url',\n WebSearch: 'web_search',\n Task: 'spawn',\n Agent: 'spawn',\n}\n\nconst NATIVE_TOOLS = new Set(Object.values(CLAUDE_TOOL_MAP))\nconst PATTERNED = /^([A-Z]\\w*)\\(.*\\)$/\n\n/**\n * Translate an agent file's `tools:` list. Patterns (`Bash(git:*)`) are not\n * enforced by spawn's allowlist, so they collapse to the bare tool with a\n * diagnostic. Unknown names are dropped loudly instead of narrowing nothing.\n */\nexport function mapClaudeTools(names: readonly string[], path: string): { tools: string[], diagnostics: MarkdownDefDiagnostic[] } {\n const tools = new Set<string>()\n const diagnostics: MarkdownDefDiagnostic[] = []\n for (const raw of names) {\n const name = raw.trim()\n if (!name)\n continue\n if (NATIVE_TOOLS.has(name) || name.startsWith('mcp__')) {\n tools.add(name)\n continue\n }\n const patterned = PATTERNED.exec(name)\n const base = patterned ? patterned[1] : name\n const mapped = Object.hasOwn(CLAUDE_TOOL_MAP, base) ? CLAUDE_TOOL_MAP[base] : undefined\n if (!mapped) {\n diagnostics.push({ path, kind: 'agent', message: `unknown tool \"${name}\" dropped` })\n continue\n }\n if (patterned)\n diagnostics.push({ path, kind: 'agent', message: `tool pattern \"${name}\" is not enforced; granted ${mapped} unrestricted` })\n tools.add(mapped)\n }\n return { tools: [...tools], diagnostics }\n}\n","import type { SubagentDef } from '../tools/spawn'\nimport type { ModelAliasContext } from './model-aliases'\nimport type { MarkdownDefDiagnostic, MarkdownDefFile } from './types'\nimport { parseFrontmatter } from '../skills/discovery'\nimport { resolveModelAlias } from './model-aliases'\nimport { CLAUDE_TOOL_MAP, mapClaudeTools } from './tool-map'\n\nconst IGNORED_KEYS = ['color', 'isolation', 'memory', 'hooks'] as const\n/** Keys that narrow a child's tools; a duplicate of any of them drops the agent. */\nconst RESTRICTION_KEYS = ['tools', 'disallowedTools', 'readonly', 'permissionMode'] as const\n\n/**\n * `tools:` arrives as a YAML list, `[a, b]`, `a, b`, or `a b`. Comma input\n * splits on commas only; otherwise it splits on whitespace outside parens, so\n * `Bash(git log:*)` survives intact either way.\n */\nexport function toStringList(value: unknown): string[] | undefined {\n if (value === undefined || value === null)\n return undefined\n if (Array.isArray(value))\n return value.filter((v): v is string => typeof v === 'string').map(v => v.trim()).filter(Boolean)\n if (typeof value !== 'string')\n return undefined\n const inner = value.trim().replace(/^\\[(.*)\\]$/, '$1')\n const parts = inner.includes(',') ? inner.split(',') : splitOutsideParens(inner)\n return parts.map(p => p.trim()).filter(Boolean)\n}\n\nfunction splitOutsideParens(input: string): string[] {\n const parts: string[] = []\n let depth = 0\n let current = ''\n for (const ch of input) {\n if (ch === '(')\n depth++\n else if (ch === ')')\n depth = Math.max(0, depth - 1)\n if (depth === 0 && /\\s/.test(ch)) {\n parts.push(current)\n current = ''\n }\n else {\n current += ch\n }\n }\n parts.push(current)\n return parts\n}\n\n/** `true`/`false` as a boolean or the strings `'true'`/`'false'`; `undefined` for anything else. */\nfunction toBool(value: unknown): boolean | undefined {\n if (typeof value === 'boolean')\n return value\n if (typeof value === 'string') {\n const v = value.trim().toLowerCase()\n if (v === 'true')\n return true\n if (v === 'false')\n return false\n }\n return undefined\n}\n\nfunction isListShaped(value: unknown): boolean {\n return typeof value === 'string' || Array.isArray(value)\n}\n\n/**\n * `explicitReadonlyFalse` reports a file that wrote `readonly: false`, so the\n * loader can tell \"unset\" from \"opted out\" when a file overrides a builtin.\n */\nexport function parseAgentFile(\n file: MarkdownDefFile,\n content: string,\n modelContext: ModelAliasContext,\n): { entry?: [string, SubagentDef], diagnostics: MarkdownDefDiagnostic[], explicitReadonlyFalse?: boolean } {\n const diagnostics: MarkdownDefDiagnostic[] = []\n const note = (message: string) => diagnostics.push({ path: file.path, kind: 'agent', message })\n const parsed = parseFrontmatter(content)\n for (const d of parsed.diagnostics)\n note(d.message)\n const fm = parsed.frontmatter\n\n const name = typeof fm.name === 'string' && fm.name.trim() ? fm.name.trim() : file.name\n if (!parsed.body) {\n note('empty agent body; skipped')\n return { diagnostics }\n }\n\n // Claude Code requires a description; a file without frontmatter has none.\n if (typeof fm.description !== 'string' || !fm.description.trim()) {\n note('missing description; skipped')\n return { diagnostics }\n }\n const def: SubagentDef = { system: parsed.body, description: fm.description.trim() }\n\n // Last-wins on a repeated restriction key would let a later line silently\n // widen an earlier one; refuse the file instead.\n const duplicated = RESTRICTION_KEYS.filter(key =>\n parsed.diagnostics.some(d => d.code === 'duplicate-key' && d.field === key))\n if (duplicated.length > 0) {\n note(`duplicate restriction keys: ${duplicated.join(', ')}; skipped`)\n return { diagnostics }\n }\n\n // Restriction keys fail closed: an unreadable value drops the agent rather\n // than silently inheriting every parent tool.\n let explicitReadonlyFalse = false\n if (fm.readonly !== undefined && fm.readonly !== null) {\n const ro = toBool(fm.readonly)\n if (ro === undefined) {\n note('unreadable readonly value; skipped')\n return { diagnostics }\n }\n if (ro)\n def.readonly = true\n else\n explicitReadonlyFalse = true\n }\n\n const hasTools = fm.tools !== undefined && fm.tools !== null\n if (hasTools && !isListShaped(fm.tools)) {\n note('unreadable tools value; skipped')\n return { diagnostics }\n }\n const hasDisallowed = fm.disallowedTools !== undefined && fm.disallowedTools !== null\n if (hasDisallowed && !isListShaped(fm.disallowedTools)) {\n note('unreadable disallowedTools value; skipped')\n return { diagnostics }\n }\n\n const rawTools = toStringList(fm.tools)\n if (rawTools !== undefined) {\n if (rawTools.length === 0) {\n note('empty tools list; skipped (an empty list would inherit every tool)')\n return { diagnostics }\n }\n const mapped = mapClaudeTools(rawTools, file.path)\n diagnostics.push(...mapped.diagnostics)\n if (mapped.tools.length === 0) {\n note('no usable tools after mapping; skipped')\n return { diagnostics }\n }\n def.tools = mapped.tools\n }\n\n const rawDisallowed = toStringList(fm.disallowedTools)\n if (rawDisallowed !== undefined) {\n if (rawDisallowed.length === 0) {\n note('empty disallowedTools list; skipped')\n return { diagnostics }\n }\n const mapped = mapClaudeTools(rawDisallowed, file.path)\n diagnostics.push(...mapped.diagnostics)\n const blocked = new Set(mapped.tools)\n if (def.tools) {\n def.tools = def.tools.filter(t => !blocked.has(t))\n }\n else {\n note('disallowedTools without tools restricts to native tools; MCP and extension tools are excluded')\n def.tools = [...new Set(Object.values(CLAUDE_TOOL_MAP))].filter(t => !blocked.has(t))\n }\n if (def.tools.length === 0) {\n note('no tools left after disallowedTools; skipped')\n return { diagnostics }\n }\n }\n\n const model = resolveModelAlias(typeof fm.model === 'string' ? fm.model : undefined, modelContext, file.path)\n if (model.diagnostic)\n diagnostics.push(model.diagnostic)\n if (model.model)\n def.model = model.model\n\n const permissionMode = typeof fm.permissionMode === 'string' ? fm.permissionMode.trim() : undefined\n if (permissionMode === 'plan')\n def.readonly = true\n\n const ignored: string[] = IGNORED_KEYS.filter(key => fm[key] !== undefined)\n if (fm.permissionMode !== undefined && permissionMode !== 'plan')\n ignored.push('permissionMode')\n if (ignored.length > 0)\n note(`ignored frontmatter keys: ${ignored.join(', ')}`)\n\n return { entry: [name, def], diagnostics, explicitReadonlyFalse }\n}\n","import type { SubagentRegistry } from '../tools/spawn'\n\n/**\n * Claude-trained models emit `subagent_type: 'Explore'` / `'Plan'`. Shipping\n * both gives those calls a target. No `model`: the `subagentModels` setting\n * or the parent model applies. A file agent with the same name overrides.\n */\nexport const BUILTIN_SUBAGENTS: Readonly<SubagentRegistry> = {\n Explore: {\n readonly: true,\n description: 'Read-only codebase search. Use for broad fan-out searches; returns conclusions, not file dumps.',\n system: 'You are a read-only search agent. Search with the available read-only tools, read only the excerpts you need, and report findings concisely with file:line references. Do not paste whole files.',\n },\n Plan: {\n readonly: true,\n description: 'Read-only planning. Returns a step-by-step implementation plan with the critical files.',\n system: 'You are a read-only planning agent. Explore the code you need, then return a numbered implementation plan: the files to change, what changes in each, and the risks. Do not edit files.',\n },\n}\n","import type { Command } from '../chat/commands'\nimport type { MarkdownDefDiagnostic, MarkdownDefFile } from './types'\nimport { parseFrontmatter } from '../skills/discovery'\n\n// `\\$` is an escaped literal; `$1`..`$9` followed by another digit is literal text (`$10`).\nconst TOKEN = /\\\\\\$|\\$ARGUMENTS|\\$([1-9])(?!\\d)/g\nconst IGNORED_KEYS = ['model', 'allowed-tools'] as const\nconst DESCRIPTION_MAX = 120\n\n/**\n * Claude Code command templating. Replacers are functions so `$&` / `$1`\n * typed by the user land verbatim instead of being re-expanded by\n * `String.replace`'s replacement-pattern syntax.\n */\nexport function expandCommandTemplate(body: string, args: string, argv: readonly string[]): string {\n let hasPlaceholder = false\n // Single pass: sequential replaces would re-expand `$1` typed inside $ARGUMENTS.\n const out = body.replace(TOKEN, (match, n?: string) => {\n if (match === '\\\\$')\n return '$'\n hasPlaceholder = true\n return n ? (argv[Number(n) - 1] ?? '') : args\n })\n if (!hasPlaceholder)\n return args.trim() ? `${out}\\n\\n${args}` : out\n return out\n}\n\nexport function parseCommandFile(file: MarkdownDefFile, content: string): { command?: Command, diagnostics: MarkdownDefDiagnostic[] } {\n const diagnostics: MarkdownDefDiagnostic[] = []\n const note = (message: string) => diagnostics.push({ path: file.path, kind: 'command', message })\n const parsed = parseFrontmatter(content)\n for (const d of parsed.diagnostics)\n note(d.message)\n\n if (!file.name || /\\s/.test(file.name) || file.name.startsWith('/')) {\n note(`invalid command name \"${file.name}\"; skipped`)\n return { diagnostics }\n }\n const body = parsed.body\n if (!body) {\n note('empty command body; skipped')\n return { diagnostics }\n }\n for (const key of IGNORED_KEYS) {\n if (parsed.frontmatter[key] !== undefined)\n note(`frontmatter \"${key}\" is ignored for commands`)\n }\n\n const fm = parsed.frontmatter\n const firstLine = body.split('\\n').find(line => line.trim())?.trim().replace(/^#+\\s*/, '') || file.name\n let description = typeof fm.description === 'string' && fm.description.trim()\n ? fm.description.trim()\n : firstLine.slice(0, DESCRIPTION_MAX)\n if (typeof fm['argument-hint'] === 'string' && fm['argument-hint'].trim())\n description = `${description} (args: ${fm['argument-hint'].trim()})`\n\n const command: Command = {\n name: file.name,\n description,\n // No `group`: it names the contributing extension (`/<extension>` lists\n // its commands). A namespaced file name (`git:commit`) already matches `/git`.\n run: async (ctx) => {\n await ctx.runAgent(expandCommandTemplate(body, ctx.args, ctx.argv))\n },\n }\n return { command, diagnostics }\n}\n","import type { ProjectUserPath } from '../chat/project-user-paths'\nimport type { MarkdownDefKind } from './types'\nimport { homedir } from 'node:os'\nimport { resolve } from 'node:path'\nimport { findGitRoot } from '../chat/project-root'\nimport { projectUserPaths } from '../chat/project-user-paths'\n\nexport interface MarkdownDefRoot {\n path: string\n source: 'project' | 'user'\n foreign: boolean\n}\n\nexport interface MarkdownDefRootsOptions {\n kind: MarkdownDefKind\n cwd?: string\n home?: string\n /** Storage prefix, default `.zidane`. */\n prefix?: string\n /** `settings.importForeignConfigs`. Adds `.claude/<kind>`. */\n includeForeign: boolean\n /** Default true. False drops `source: 'project'` roots, native and foreign. */\n includeProject?: boolean\n}\n\n/**\n * Claude Code's markdown command / agent dirs, project first. Claude only:\n * Codex and pi have no equivalent format. Project root is the git root, as\n * for the other foreign configs.\n */\nexport function foreignMarkdownScanPaths(kind: MarkdownDefKind, opts: { cwd?: string, home?: string } = {}): ProjectUserPath[] {\n const cwd = opts.cwd ?? process.cwd()\n const projectRoot = findGitRoot(cwd) ?? cwd\n const home = opts.home ?? homedir()\n return [\n { path: resolve(projectRoot, `.claude/${kind}`), source: 'project' },\n { path: resolve(home, `.claude/${kind}`), source: 'user' },\n ]\n}\n\n/** Native project, native user, then (opt-in) foreign project, foreign user. Same order as skills. */\nexport function markdownDefRoots(opts: MarkdownDefRootsOptions): MarkdownDefRoot[] {\n const native = projectUserPaths({ subPath: opts.kind, cwd: opts.cwd, home: opts.home, prefix: opts.prefix })\n .map(p => ({ path: p.path, source: p.source, foreign: false }))\n const foreign = opts.includeForeign\n ? foreignMarkdownScanPaths(opts.kind, { cwd: opts.cwd, home: opts.home })\n .map(p => ({ path: p.path, source: p.source, foreign: true }))\n : []\n const all = [...native, ...foreign]\n return opts.includeProject === false ? all.filter(r => r.source !== 'project') : all\n}\n","import type { MarkdownDefRoot } from './roots'\nimport type { MarkdownDefFile } from './types'\nimport { readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\n\nconst MAX_DEPTH = 3\n/** Dot entries (dirs and dotfiles) are skipped separately. Not the skills skip set: `build/` and `dist/` are legitimate command namespaces. */\nconst SKIP_DIRS: ReadonlySet<string> = new Set(['node_modules'])\n\n/**\n * Every `*.md` under each root, in root order. No dedupe here: agent files\n * can rename themselves via frontmatter, so first-wins runs after parsing.\n */\nexport function listMarkdownDefFiles(roots: readonly MarkdownDefRoot[]): MarkdownDefFile[] {\n const files: MarkdownDefFile[] = []\n for (const root of roots)\n walk(root, root.path, [], files)\n return files\n}\n\nfunction walk(root: MarkdownDefRoot, dir: string, segments: string[], out: MarkdownDefFile[]): void {\n let entries: string[]\n try {\n entries = readdirSync(dir).sort()\n }\n catch {\n return\n }\n for (const entry of entries) {\n if (entry.startsWith('.') || SKIP_DIRS.has(entry))\n continue\n const path = join(dir, entry)\n let isDir: boolean\n try {\n isDir = statSync(path).isDirectory()\n }\n catch {\n continue\n }\n if (isDir) {\n if (segments.length < MAX_DEPTH)\n walk(root, path, [...segments, entry], out)\n continue\n }\n if (!entry.endsWith('.md'))\n continue\n const name = [...segments, entry.slice(0, -3)].join(':').toLowerCase()\n out.push({ path, name, source: root.source, foreign: root.foreign })\n }\n}\n","import type { Command } from '../chat/commands'\nimport type { Preset } from '../presets'\nimport type { SubagentDef, SubagentOverride, SubagentRegistry } from '../tools/spawn'\nimport type { ModelAliasContext } from './model-aliases'\nimport type { MarkdownDefDiagnostic, MarkdownDefFile, MarkdownDefKind } from './types'\nimport { readFileSync } from 'node:fs'\nimport { isSpawnTool } from '../tools/spawn'\nimport { parseAgentFile } from './agents'\nimport { BUILTIN_SUBAGENTS } from './builtin-agents'\nimport { parseCommandFile } from './commands'\nimport { markdownDefRoots } from './roots'\nimport { listMarkdownDefFiles } from './scan'\n\nexport { BUILTIN_SUBAGENTS } from './builtin-agents'\nexport type { ModelAliasContext } from './model-aliases'\nexport type { MarkdownDefDiagnostic } from './types'\n\nexport interface LoadMarkdownOptions {\n cwd?: string\n home?: string\n /** Storage prefix, default `.zidane`. */\n prefix?: string\n /** `settings.importForeignConfigs`. */\n includeForeign: boolean\n /**\n * Default true. False drops every `source: 'project'` root (native and\n * foreign). The seam for SDK hosts that open untrusted repos: a project file\n * writes a prompt (command body, subagent system prompt) the user did not,\n * so such hosts load user-level files only. Headless sets it false unless\n * `--project-agents` is passed.\n */\n includeProject?: boolean\n}\n\nexport interface LoadMarkdownCommandsOptions extends LoadMarkdownOptions {\n /**\n * True when an enabled skill answers `/<name>`. Skills win that name, as in\n * Claude Code, so the file command is dropped with a diagnostic instead of\n * silently hiding the skill.\n */\n isSkillName?: (name: string) => boolean\n}\n\n/** Names that would collide with `Object.prototype` keys in a plain registry. */\nconst RESERVED_NAMES: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])\n\nfunction filesFor(kind: MarkdownDefKind, opts: LoadMarkdownOptions): MarkdownDefFile[] {\n return listMarkdownDefFiles(markdownDefRoots({ kind, ...opts }))\n}\n\nfunction read(path: string): string | undefined {\n try {\n return readFileSync(path, 'utf8')\n }\n catch {\n return undefined\n }\n}\n\n/**\n * Markdown slash commands, first-wins by name in root order. Never throws.\n * @param opts - Search roots, project and foreign-config switches, and an optional skill-name check.\n */\nexport function loadMarkdownCommands(opts: LoadMarkdownCommandsOptions): { commands: Command[], diagnostics: MarkdownDefDiagnostic[] } {\n const commands: Command[] = []\n const diagnostics: MarkdownDefDiagnostic[] = []\n const winners = new Map<string, string>()\n for (const file of filesFor('commands', opts)) {\n const content = read(file.path)\n if (content === undefined)\n continue\n const parsed = parseCommandFile(file, content)\n diagnostics.push(...parsed.diagnostics)\n if (!parsed.command)\n continue\n const key = parsed.command.name.toLowerCase()\n if (RESERVED_NAMES.has(key)) {\n diagnostics.push({ path: file.path, kind: 'command', message: 'reserved command name' })\n continue\n }\n if (opts.isSkillName?.(key)) {\n diagnostics.push({ path: file.path, kind: 'command', message: `skill \"${key}\" has the same name and wins; rename the command or the skill` })\n continue\n }\n const winner = winners.get(key)\n if (winner) {\n diagnostics.push({ path: file.path, kind: 'command', message: `shadowed by ${winner}` })\n continue\n }\n winners.set(key, file.path)\n commands.push(parsed.command)\n }\n return { commands, diagnostics }\n}\n\n/**\n * Builtin Explore/Plan plus markdown agents. User-scope files override\n * builtins (project files are refused with a diagnostic); among files, first-wins by name in root order. Never throws.\n * @param opts - Search roots and switches, plus the model context used to resolve `model:` aliases.\n */\nexport function loadMarkdownAgents(\n opts: LoadMarkdownOptions & { modelContext: ModelAliasContext },\n): { subagents: SubagentRegistry, diagnostics: MarkdownDefDiagnostic[] } {\n const fromFiles: SubagentRegistry = Object.create(null)\n const winners = new Map<string, string>()\n const diagnostics: MarkdownDefDiagnostic[] = []\n for (const file of filesFor('agents', opts)) {\n const content = read(file.path)\n if (content === undefined)\n continue\n const parsed = parseAgentFile(file, content, opts.modelContext)\n diagnostics.push(...parsed.diagnostics)\n if (!parsed.entry)\n continue\n const [name, def] = parsed.entry\n if (RESERVED_NAMES.has(name)) {\n diagnostics.push({ path: file.path, kind: 'agent', message: 'reserved agent name' })\n continue\n }\n if (Object.hasOwn(BUILTIN_SUBAGENTS, name)) {\n // A cloned repo must not turn read-only Explore/Plan, which models call\n // unprompted, into writers: only user-scope files may replace them.\n if (file.source === 'project') {\n diagnostics.push({ path: file.path, kind: 'agent', message: `project files cannot replace builtin ${name}; rename the agent or move it to the user folder` })\n continue\n }\n // Without its own tool restriction the replacement would inherit every\n // parent tool, so it stays read-only unless the file wrote `readonly: false`.\n if (!def.tools && !parsed.explicitReadonlyFalse)\n def.readonly = true\n }\n const winner = winners.get(name)\n if (winner) {\n diagnostics.push({ path: file.path, kind: 'agent', message: `shadowed by ${winner}` })\n continue\n }\n winners.set(name, file.path)\n fromFiles[name] = def\n }\n const subagents: SubagentRegistry = {}\n for (const [name, def] of Object.entries(BUILTIN_SUBAGENTS))\n subagents[name] = { ...def }\n for (const [name, def] of Object.entries(fromFiles))\n subagents[name] = def\n return { subagents, diagnostics }\n}\n\n/**\n * Fold markdown/builtin agents into the preset's spawn tool, filling gaps\n * only: an agent the profile or an extension already registered keeps its\n * definition. Runs after `composeExtensionPreset`, so precedence is\n * builtin < file < extension without threading files through composition.\n * @param preset - Preset whose `spawn` tool receives the agents. Returned unchanged when it has no spawn tool or `subagents` is empty.\n * @param subagents - Agent registry to merge, typically from {@link loadMarkdownAgents}.\n */\nexport function applyMarkdownSubagents(preset: Preset, subagents: SubagentRegistry): Preset {\n const spawn = preset.tools?.spawn\n const entries = Object.entries(subagents)\n if (!spawn || !isSpawnTool(spawn) || entries.length === 0)\n return preset\n const overrides: Record<string, SubagentOverride> = Object.create(null)\n for (const [name, def] of entries)\n overrides[name] = (current: SubagentDef | undefined) => current ?? def\n return { ...preset, tools: { ...preset.tools, spawn: spawn.withSubagents({}, overrides) } }\n}\n","/**\n * Headless mode — a non-interactive, fully-structured way to drive the agent\n * for automation and RL rollouts.\n *\n * `agent.run()` already returns rich {@link AgentStats}, the session captures a\n * lossless transcript (`session.turns`), and the hook bus exposes every\n * streaming/tool/turn event. What this module adds is the *contract* an RL loop\n * needs: one call (`runHeadless`) that runs a prompt to completion in a chosen\n * workdir, bounded by turns + wall-clock, and hands back a single serializable\n * {@link HeadlessResult} — final answer, verifiable structured output, usage,\n * and the complete trajectory — plus an optional live {@link HeadlessEvent}\n * stream (the in-process equivalent of `--output-format stream-json`).\n *\n * It is provider-agnostic: the caller passes a built {@link Provider} (e.g.\n * `local()` pointed at a vLLM server, or any of the named providers). The thin\n * CLI in `src/headless-cli.ts` wraps this with arg parsing, file/stdin I/O, and\n * JSONL transcript writing.\n */\n\nimport type { AgentOptions } from './agent'\nimport type { ExecutionContext } from './contexts'\nimport type { ExtensionRegistry } from './extensions'\nimport type { HeadlessErrorInfo, HeadlessEvent, HeadlessResult, HeadlessStatus } from './headless-format'\nimport type { Preset } from './presets'\nimport type { Provider } from './providers'\nimport type { Session, SessionStore } from './session'\nimport type { ToolDef } from './tools'\nimport type { SubagentRegistry } from './tools/spawn'\nimport type {\n AgentStats,\n McpServerConfig,\n PromptPart,\n SessionTurn,\n ThinkingLevel,\n TurnFinishReason,\n} from './types'\nimport { createAgent } from './agent'\nimport { installCacheBreakLogger } from './cache-telemetry'\nimport { createProcessContext } from './contexts'\nimport { installHeadlessEventAdapter, textOf } from './headless-format'\nimport { applyMarkdownSubagents } from './markdown-defs'\nimport { DEFAULT_MAX_IMAGE_EDGE, DEFAULT_MEDIA_BUDGET } from './media/defaults'\nimport { basic } from './presets'\nimport { createRunSummaryCollector } from './run-summary'\nimport { createMemoryStore, createSession } from './session'\n\n// The contract (shapes, formatting, events) lives in `headless-format.ts` so\n// serializers can import it without the runner.\nexport type { FormattedHeadlessResult, FormattedHeadlessTurnEvent, HeadlessErrorInfo, HeadlessEvent, HeadlessOutputFormat, HeadlessResult, HeadlessStatus, HeadlessUsage, OpenAIChatContentPart, OpenAIChatMessage, ProviderTranscriptFormat } from './headless-format'\nexport { exitCodeForHeadlessResult, formatHeadlessResult, formatHeadlessTurnEvent, formattedHeadlessTurnEventToJsonl, headlessEventToJsonl, installHeadlessEventAdapter, providerTranscriptFormatForProvider, transcriptToOpenAIMessages, transcriptToProviderMessages } from './headless-format'\n\n/** Options for {@link runHeadless}. */\nexport interface HeadlessOptions {\n /** User prompt — plain string or multimodal `PromptPart[]`. */\n prompt: string | PromptPart[]\n /** Built provider (e.g. `local()`, `openaiCompat(...)`, `anthropic(...)`). */\n provider: Provider\n /** Model id. Defaults to the provider's default model. */\n model?: string\n /** Override the preset system prompt for this run. */\n system?: string\n /** Thinking effort for the run. Defaults to `'off'`. */\n thinking?: ThinkingLevel\n /** Maximum number of loop turns. Sets `behavior.maxTurns`. */\n maxTurns?: number\n /** Maximum output tokens per turn. Sets `behavior.maxTokens`. */\n maxTokens?: number\n /** Wall-clock cap; on expiry the run is aborted and `status` becomes `'timeout'`. */\n timeoutMs?: number\n /** External abort signal — chained with the internal timeout controller. */\n signal?: AbortSignal\n /** JSON Schema for structured-output enforcement → populates `result.output`. */\n schema?: Record<string, unknown>\n /** Agent behavior defaults for this headless run. Top-level shortcuts below override matching fields. */\n behavior?: AgentOptions['behavior']\n /** Tool overrides. Omit to use the basic preset's tools. */\n tools?: Record<string, ToolDef>\n /** MCP servers to connect and expose as tools. */\n mcpServers?: McpServerConfig[]\n /** Skills configuration. */\n skills?: AgentOptions['skills']\n /**\n * Base {@link Preset} for the agent — spread in place of the default `basic`\n * preset (use it to swap the system prompt / tool set wholesale). The\n * top-level shortcuts above (`system`, `behavior`, `tools`, `mcpServers`,\n * `skills`) still override matching preset fields.\n */\n preset?: Preset\n /**\n * Subagents folded into the preset's spawn tool, filling gaps only (an\n * agent the preset or an extension already defines wins). The CLI passes\n * builtin + markdown agents from `loadMarkdownAgents`.\n */\n subagents?: SubagentRegistry\n /**\n * Pre-built extension registry folded into the agent via `createAgent`\n * (build it with `buildExtensionRegistry(defs.map(inlineLoadedExtension))`).\n * Contributes the registry's tools / hooks / mcpServers / skills /\n * system-fragments / subagents, with the explicit options above winning on\n * collision. Because hooks fold through `createAgent`, a headless run with\n * `extensions` also gets extension hooks (e.g. a `tool:transform` that\n * rewrites results), not just tools.\n */\n extensions?: ExtensionRegistry\n /** Execution context. Defaults to a process context rooted at `cwd`. */\n execution?: ExecutionContext\n /** Working directory for the default process context (ignored if `execution` is set). */\n cwd?: string\n /** Reuse / resume an existing session. */\n session?: Session\n /** Session store for a fresh session (defaults to an in-memory store). */\n store?: SessionStore\n /** Keep `thinking` blocks in `result.transcript` (default true). */\n includeThinking?: boolean\n /** Live event callback — the in-process stream-json equivalent. */\n onEvent?: (event: HeadlessEvent) => void\n}\n\n// ---------------------------------------------------------------------------\n// runHeadless\n// ---------------------------------------------------------------------------\n\n/**\n * Run a prompt to completion, headless, and return a single serializable\n * {@link HeadlessResult}. Safe to call concurrently for parallel rollouts —\n * each call builds its own agent + session and tears them down in `finally`.\n *\n * @param opts - Prompt, provider and run limits. `prompt` and `provider` are required.\n * @returns The run result. Errors from the agent loop, aborts and timeouts are reported in `status` and `error` instead of being thrown.\n *\n * @example\n * ~~~ts\n * import { exitCodeForHeadlessResult, runHeadless } from 'zidane/headless'\n * import { anthropic } from 'zidane/providers/anthropic'\n *\n * const result = await runHeadless({\n * prompt: 'List the TypeScript files in this directory.',\n * provider: anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }),\n * cwd: process.cwd(),\n * maxTurns: 10,\n * timeoutMs: 120_000,\n * })\n *\n * console.log(result.status, result.finalText)\n * process.exitCode = exitCodeForHeadlessResult(result)\n * ~~~\n */\nexport async function runHeadless(opts: HeadlessOptions): Promise<HeadlessResult> {\n const startedAt = Date.now()\n const execution = opts.execution ?? createProcessContext({ cwd: opts.cwd })\n const session = opts.session ?? await createSession({ store: opts.store ?? createMemoryStore() })\n\n // Layer behavior on top of the base preset's: the `behavior` key is spread\n // last into `createAgent`, so without seeding from `basePreset.behavior` a\n // custom `preset` carrying behavior defaults would be silently wiped (the\n // top-level shortcuts are meant to OVERRIDE preset fields, not replace them).\n const basePreset = opts.subagents\n ? applyMarkdownSubagents(opts.preset ?? basic, opts.subagents)\n : (opts.preset ?? basic)\n // Media defaults match the built-in chat profiles: keep media inline until\n // the request nears the provider's hard limits (`mediaBudget`), and shrink\n // Retina screenshots once at entry (`maxImageEdge`). Aged media stays\n // re-resolvable via `read_file path=\"attachment://…\"`. A preset or explicit\n // `behavior` still overrides: a `mediaKeepTurns` window takes precedence\n // over the budget, and `mediaBudget: undefined` disables it.\n const behavior: NonNullable<AgentOptions['behavior']> = { mediaBudget: DEFAULT_MEDIA_BUDGET, maxImageEdge: DEFAULT_MAX_IMAGE_EDGE, ...basePreset.behavior, ...(opts.behavior ?? {}) }\n if (opts.maxTurns !== undefined)\n behavior.maxTurns = opts.maxTurns\n if (opts.maxTokens !== undefined)\n behavior.maxTokens = opts.maxTokens\n if (opts.schema !== undefined)\n behavior.schema = opts.schema\n\n const agent = createAgent({\n ...basePreset,\n provider: opts.provider,\n execution,\n session,\n behavior,\n ...(opts.tools !== undefined ? { tools: opts.tools } : {}),\n ...(opts.mcpServers !== undefined ? { mcpServers: opts.mcpServers } : {}),\n ...(opts.skills !== undefined ? { skills: opts.skills } : {}),\n ...(opts.extensions !== undefined ? { extensions: opts.extensions } : {}),\n })\n\n const collector = createRunSummaryCollector()\n const uninstallSummary = collector.install(agent.hooks)\n const uninstallEvents = opts.onEvent ? installHeadlessEventAdapter(agent.hooks, opts.onEvent) : noop\n // Debug output goes to stderr so stdout stays the result (text, JSON or JSONL).\n const debug = process.env.ZIDANE_DEBUG\n const uninstallCacheLog = debug\n ? installCacheBreakLogger(agent.hooks, { log: line => process.stderr.write(`${line}\\n`), verbose: debug.includes('cache') })\n : noop\n\n // Resumed sessions carry turns from prior runs — remember where this run\n // starts so transcript/finalText/numToolCalls stay per-run, matching the\n // per-run usage/turns/durationMs stats.\n const runStartIndex = session.turns.length\n\n // Internal controller drives the wall-clock timeout and chains any external\n // signal so a host cancel and a timeout both abort the same run. The\n // listener is removed in `finally` — a long-lived host signal must not\n // accumulate one listener per rollout.\n const controller = new AbortController()\n const onExternalAbort = (): void => controller.abort(opts.signal!.reason)\n if (opts.signal) {\n if (opts.signal.aborted)\n controller.abort(opts.signal.reason)\n else\n opts.signal.addEventListener('abort', onExternalAbort, { once: true })\n }\n let timedOut = false\n const timer = opts.timeoutMs && opts.timeoutMs > 0\n ? setTimeout(() => {\n timedOut = true\n controller.abort(new Error(`Headless run timed out after ${opts.timeoutMs}ms`))\n }, opts.timeoutMs)\n : undefined\n\n let stats: AgentStats | undefined\n let error: HeadlessErrorInfo | undefined\n\n try {\n stats = await agent.run({\n prompt: opts.prompt,\n signal: controller.signal,\n ...(opts.model !== undefined ? { model: opts.model } : {}),\n ...(opts.system !== undefined ? { system: opts.system } : {}),\n ...(opts.thinking !== undefined ? { thinking: opts.thinking } : {}),\n })\n }\n catch (err) {\n // The agent loop throws typed errors (AgentAbortedError,\n // AgentContextExceededError, AgentProviderError, …) — their `name` already\n // classifies the failure, so surface it directly.\n const e = err instanceof Error ? err : new Error(String(err))\n error = { message: e.message, type: e.name }\n }\n finally {\n if (timer)\n clearTimeout(timer)\n opts.signal?.removeEventListener('abort', onExternalAbort)\n uninstallEvents()\n uninstallSummary()\n uninstallCacheLog()\n await agent.destroy()\n }\n\n // Status: a thrown error wins, but an abort/timeout can also surface as a\n // clean resolve (the loop returns partial stats), so check the signal too.\n let status: HeadlessStatus\n if (error)\n status = timedOut ? 'timeout' : controller.signal.aborted ? 'aborted' : 'error'\n else if (controller.signal.aborted)\n status = timedOut ? 'timeout' : 'aborted'\n else\n status = 'completed'\n\n const rawTranscript = session.turns.slice(runStartIndex)\n const transcript = opts.includeThinking === false ? stripThinking(rawTranscript) : rawTranscript\n const summary = collector.latest()\n\n const result: HeadlessResult = {\n status,\n finalText: extractFinalText(rawTranscript),\n ...(stats?.output ? { output: stats.output } : {}),\n usage: {\n input: stats?.totalIn ?? 0,\n output: stats?.totalOut ?? 0,\n cacheRead: stats?.totalCacheRead ?? 0,\n cacheCreation: stats?.totalCacheCreation ?? 0,\n ...(typeof stats?.cost === 'number' ? { cost: stats.cost } : {}),\n },\n turns: stats?.turns ?? 0,\n durationMs: stats?.elapsed ?? (Date.now() - startedAt),\n numToolCalls: countToolCalls(rawTranscript),\n // Suppress `finishReason` on abort/timeout: the last persisted turn can\n // carry `finishReason: 'stop'` (e.g. the model finished a turn, a follow-up\n // continued, then the run was cancelled), which would make a consumer\n // keyed on `finishReason === 'stop'` misread a cancel as \"model finished\".\n // `status` is authoritative for those exits; let it speak alone. The\n // `'pause'` exhaustion exit keeps `status: 'completed'` so it still\n // surfaces its `finishReason: 'pause'` here.\n ...(status !== 'aborted' && status !== 'timeout' && lastFinishReason(stats)\n ? { finishReason: lastFinishReason(stats) }\n : {}),\n ...(error ? { error } : {}),\n sessionId: session.id,\n ...(summary ? { summary } : {}),\n transcript,\n }\n\n opts.onEvent?.({ type: 'result', result })\n return result\n}\n\nfunction noop(): void {}\n\nfunction extractFinalText(turns: SessionTurn[]): string {\n for (let i = turns.length - 1; i >= 0; i--) {\n const turn = turns[i]\n if (turn.role !== 'assistant')\n continue\n const text = textOf(turn.content)\n if (text)\n return text\n }\n return ''\n}\n\nfunction countToolCalls(turns: SessionTurn[]): number {\n let n = 0\n for (const turn of turns) {\n for (const block of turn.content) {\n if (block.type === 'tool_call')\n n++\n }\n }\n return n\n}\n\nfunction lastFinishReason(stats?: AgentStats): TurnFinishReason | undefined {\n const usages = stats?.turnUsage\n if (!usages)\n return undefined\n for (let i = usages.length - 1; i >= 0; i--) {\n if (usages[i].finishReason)\n return usages[i].finishReason\n }\n return undefined\n}\n\nfunction stripThinking(turns: SessionTurn[]): SessionTurn[] {\n return turns.map(turn => ({\n ...turn,\n content: turn.content.filter(b => b.type !== 'thinking' && b.type !== 'redacted_thinking'),\n }))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAMA,MAAa,uBAAwF;C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Tkm.js","names":["IGNORED_KEYS","basic"],"sources":["../src/markdown-defs/model-aliases.ts","../src/markdown-defs/tool-map.ts","../src/markdown-defs/agents.ts","../src/markdown-defs/builtin-agents.ts","../src/markdown-defs/commands.ts","../src/markdown-defs/roots.ts","../src/markdown-defs/scan.ts","../src/markdown-defs/index.ts","../src/headless.ts"],"sourcesContent":["import type { MarkdownDefDiagnostic } from './types'\n\n/**\n * Claude Code's agent `model:` aliases. Bump alongside `../chat/anthropic-models.ts`\n * when the Anthropic lineup changes.\n */\nexport const CLAUDE_MODEL_ALIASES: Readonly<Record<'haiku' | 'sonnet' | 'opus' | 'fable', string>> = {\n haiku: 'claude-haiku-4-5-20251001',\n sonnet: 'claude-sonnet-5-5',\n opus: 'claude-opus-5-5',\n fable: 'claude-fable-5-1',\n}\n\n/** Context for resolving Claude `model:` aliases in agent files. */\nexport interface ModelAliasContext {\n /** Provider name of the parent session, e.g. `'anthropic'`. */\n parentProvider?: string\n /** Model ids the spawn catalog lists, when one was built. */\n catalogIds?: ReadonlySet<string>\n}\n\n/**\n * Without a catalog, spawn sends a raw id to the PARENT's provider, so a\n * Claude id under an OpenAI parent would fail mid-run. Unresolvable aliases\n * therefore inherit instead of failing the spawn.\n */\nexport function resolveModelAlias(\n value: string | undefined,\n ctx: ModelAliasContext,\n path: string,\n): { model?: string, diagnostic?: MarkdownDefDiagnostic } {\n const raw = value?.trim()\n if (!raw || raw.toLowerCase() === 'inherit')\n return {}\n const key = raw.toLowerCase() as keyof typeof CLAUDE_MODEL_ALIASES\n if (!Object.hasOwn(CLAUDE_MODEL_ALIASES, key))\n return { model: raw }\n const target = CLAUDE_MODEL_ALIASES[key]\n if (ctx.parentProvider === 'anthropic' || ctx.catalogIds?.has(target))\n return { model: target }\n return {\n diagnostic: {\n path,\n kind: 'agent',\n message: `model alias \"${raw}\" needs an Anthropic parent; inheriting the parent model`,\n },\n }\n}\n","import type { MarkdownDefDiagnostic } from './types'\n\n/** Claude Code tool names → zidane `spec.name`. */\nexport const CLAUDE_TOOL_MAP: Readonly<Record<string, string>> = {\n Read: 'read_file',\n Write: 'write_file',\n Edit: 'edit',\n MultiEdit: 'multi_edit',\n Bash: 'shell',\n Grep: 'grep',\n Glob: 'glob',\n LS: 'list_files',\n WebFetch: 'fetch_url',\n WebSearch: 'web_search',\n Task: 'spawn',\n Agent: 'spawn',\n}\n\nconst NATIVE_TOOLS = new Set(Object.values(CLAUDE_TOOL_MAP))\nconst PATTERNED = /^([A-Z]\\w*)\\(.*\\)$/\n\n/**\n * Translate an agent file's `tools:` list. Patterns (`Bash(git:*)`) are not\n * enforced by spawn's allowlist, so they collapse to the bare tool with a\n * diagnostic. Unknown names are dropped loudly instead of narrowing nothing.\n */\nexport function mapClaudeTools(names: readonly string[], path: string): { tools: string[], diagnostics: MarkdownDefDiagnostic[] } {\n const tools = new Set<string>()\n const diagnostics: MarkdownDefDiagnostic[] = []\n for (const raw of names) {\n const name = raw.trim()\n if (!name)\n continue\n if (NATIVE_TOOLS.has(name) || name.startsWith('mcp__')) {\n tools.add(name)\n continue\n }\n const patterned = PATTERNED.exec(name)\n const base = patterned ? patterned[1] : name\n const mapped = Object.hasOwn(CLAUDE_TOOL_MAP, base) ? CLAUDE_TOOL_MAP[base] : undefined\n if (!mapped) {\n diagnostics.push({ path, kind: 'agent', message: `unknown tool \"${name}\" dropped` })\n continue\n }\n if (patterned)\n diagnostics.push({ path, kind: 'agent', message: `tool pattern \"${name}\" is not enforced; granted ${mapped} unrestricted` })\n tools.add(mapped)\n }\n return { tools: [...tools], diagnostics }\n}\n","import type { SubagentDef } from '../tools/spawn'\nimport type { ModelAliasContext } from './model-aliases'\nimport type { MarkdownDefDiagnostic, MarkdownDefFile } from './types'\nimport { parseFrontmatter } from '../skills/discovery'\nimport { resolveModelAlias } from './model-aliases'\nimport { CLAUDE_TOOL_MAP, mapClaudeTools } from './tool-map'\n\nconst IGNORED_KEYS = ['color', 'isolation', 'memory', 'hooks'] as const\n/** Keys that narrow a child's tools; a duplicate of any of them drops the agent. */\nconst RESTRICTION_KEYS = ['tools', 'disallowedTools', 'readonly', 'permissionMode'] as const\n\n/**\n * `tools:` arrives as a YAML list, `[a, b]`, `a, b`, or `a b`. Comma input\n * splits on commas only; otherwise it splits on whitespace outside parens, so\n * `Bash(git log:*)` survives intact either way.\n */\nexport function toStringList(value: unknown): string[] | undefined {\n if (value === undefined || value === null)\n return undefined\n if (Array.isArray(value))\n return value.filter((v): v is string => typeof v === 'string').map(v => v.trim()).filter(Boolean)\n if (typeof value !== 'string')\n return undefined\n const inner = value.trim().replace(/^\\[(.*)\\]$/, '$1')\n const parts = inner.includes(',') ? inner.split(',') : splitOutsideParens(inner)\n return parts.map(p => p.trim()).filter(Boolean)\n}\n\nfunction splitOutsideParens(input: string): string[] {\n const parts: string[] = []\n let depth = 0\n let current = ''\n for (const ch of input) {\n if (ch === '(')\n depth++\n else if (ch === ')')\n depth = Math.max(0, depth - 1)\n if (depth === 0 && /\\s/.test(ch)) {\n parts.push(current)\n current = ''\n }\n else {\n current += ch\n }\n }\n parts.push(current)\n return parts\n}\n\n/** `true`/`false` as a boolean or the strings `'true'`/`'false'`; `undefined` for anything else. */\nfunction toBool(value: unknown): boolean | undefined {\n if (typeof value === 'boolean')\n return value\n if (typeof value === 'string') {\n const v = value.trim().toLowerCase()\n if (v === 'true')\n return true\n if (v === 'false')\n return false\n }\n return undefined\n}\n\nfunction isListShaped(value: unknown): boolean {\n return typeof value === 'string' || Array.isArray(value)\n}\n\n/**\n * `explicitReadonlyFalse` reports a file that wrote `readonly: false`, so the\n * loader can tell \"unset\" from \"opted out\" when a file overrides a builtin.\n */\nexport function parseAgentFile(\n file: MarkdownDefFile,\n content: string,\n modelContext: ModelAliasContext,\n): { entry?: [string, SubagentDef], diagnostics: MarkdownDefDiagnostic[], explicitReadonlyFalse?: boolean } {\n const diagnostics: MarkdownDefDiagnostic[] = []\n const note = (message: string) => diagnostics.push({ path: file.path, kind: 'agent', message })\n const parsed = parseFrontmatter(content)\n for (const d of parsed.diagnostics)\n note(d.message)\n const fm = parsed.frontmatter\n\n const name = typeof fm.name === 'string' && fm.name.trim() ? fm.name.trim() : file.name\n if (!parsed.body) {\n note('empty agent body; skipped')\n return { diagnostics }\n }\n\n // Claude Code requires a description; a file without frontmatter has none.\n if (typeof fm.description !== 'string' || !fm.description.trim()) {\n note('missing description; skipped')\n return { diagnostics }\n }\n const def: SubagentDef = { system: parsed.body, description: fm.description.trim() }\n\n // Last-wins on a repeated restriction key would let a later line silently\n // widen an earlier one; refuse the file instead.\n const duplicated = RESTRICTION_KEYS.filter(key =>\n parsed.diagnostics.some(d => d.code === 'duplicate-key' && d.field === key))\n if (duplicated.length > 0) {\n note(`duplicate restriction keys: ${duplicated.join(', ')}; skipped`)\n return { diagnostics }\n }\n\n // Restriction keys fail closed: an unreadable value drops the agent rather\n // than silently inheriting every parent tool.\n let explicitReadonlyFalse = false\n if (fm.readonly !== undefined && fm.readonly !== null) {\n const ro = toBool(fm.readonly)\n if (ro === undefined) {\n note('unreadable readonly value; skipped')\n return { diagnostics }\n }\n if (ro)\n def.readonly = true\n else\n explicitReadonlyFalse = true\n }\n\n const hasTools = fm.tools !== undefined && fm.tools !== null\n if (hasTools && !isListShaped(fm.tools)) {\n note('unreadable tools value; skipped')\n return { diagnostics }\n }\n const hasDisallowed = fm.disallowedTools !== undefined && fm.disallowedTools !== null\n if (hasDisallowed && !isListShaped(fm.disallowedTools)) {\n note('unreadable disallowedTools value; skipped')\n return { diagnostics }\n }\n\n const rawTools = toStringList(fm.tools)\n if (rawTools !== undefined) {\n if (rawTools.length === 0) {\n note('empty tools list; skipped (an empty list would inherit every tool)')\n return { diagnostics }\n }\n const mapped = mapClaudeTools(rawTools, file.path)\n diagnostics.push(...mapped.diagnostics)\n if (mapped.tools.length === 0) {\n note('no usable tools after mapping; skipped')\n return { diagnostics }\n }\n def.tools = mapped.tools\n }\n\n const rawDisallowed = toStringList(fm.disallowedTools)\n if (rawDisallowed !== undefined) {\n if (rawDisallowed.length === 0) {\n note('empty disallowedTools list; skipped')\n return { diagnostics }\n }\n const mapped = mapClaudeTools(rawDisallowed, file.path)\n diagnostics.push(...mapped.diagnostics)\n const blocked = new Set(mapped.tools)\n if (def.tools) {\n def.tools = def.tools.filter(t => !blocked.has(t))\n }\n else {\n note('disallowedTools without tools restricts to native tools; MCP and extension tools are excluded')\n def.tools = [...new Set(Object.values(CLAUDE_TOOL_MAP))].filter(t => !blocked.has(t))\n }\n if (def.tools.length === 0) {\n note('no tools left after disallowedTools; skipped')\n return { diagnostics }\n }\n }\n\n const model = resolveModelAlias(typeof fm.model === 'string' ? fm.model : undefined, modelContext, file.path)\n if (model.diagnostic)\n diagnostics.push(model.diagnostic)\n if (model.model)\n def.model = model.model\n\n const permissionMode = typeof fm.permissionMode === 'string' ? fm.permissionMode.trim() : undefined\n if (permissionMode === 'plan')\n def.readonly = true\n\n const ignored: string[] = IGNORED_KEYS.filter(key => fm[key] !== undefined)\n if (fm.permissionMode !== undefined && permissionMode !== 'plan')\n ignored.push('permissionMode')\n if (ignored.length > 0)\n note(`ignored frontmatter keys: ${ignored.join(', ')}`)\n\n return { entry: [name, def], diagnostics, explicitReadonlyFalse }\n}\n","import type { SubagentRegistry } from '../tools/spawn'\n\n/**\n * Claude-trained models emit `subagent_type: 'Explore'` / `'Plan'`. Shipping\n * both gives those calls a target. No `model`: the `subagentModels` setting\n * or the parent model applies. A file agent with the same name overrides.\n */\nexport const BUILTIN_SUBAGENTS: Readonly<SubagentRegistry> = {\n Explore: {\n readonly: true,\n description: 'Read-only codebase search. Use for broad fan-out searches; returns conclusions, not file dumps.',\n system: 'You are a read-only search agent. Search with the available read-only tools, read only the excerpts you need, and report findings concisely with file:line references. Do not paste whole files.',\n },\n Plan: {\n readonly: true,\n description: 'Read-only planning. Returns a step-by-step implementation plan with the critical files.',\n system: 'You are a read-only planning agent. Explore the code you need, then return a numbered implementation plan: the files to change, what changes in each, and the risks. Do not edit files.',\n },\n}\n","import type { Command } from '../chat/commands'\nimport type { MarkdownDefDiagnostic, MarkdownDefFile } from './types'\nimport { parseFrontmatter } from '../skills/discovery'\n\n// `\\$` is an escaped literal; `$1`..`$9` followed by another digit is literal text (`$10`).\nconst TOKEN = /\\\\\\$|\\$ARGUMENTS|\\$([1-9])(?!\\d)/g\nconst IGNORED_KEYS = ['model', 'allowed-tools'] as const\nconst DESCRIPTION_MAX = 120\n\n/**\n * Claude Code command templating. Replacers are functions so `$&` / `$1`\n * typed by the user land verbatim instead of being re-expanded by\n * `String.replace`'s replacement-pattern syntax.\n */\nexport function expandCommandTemplate(body: string, args: string, argv: readonly string[]): string {\n let hasPlaceholder = false\n // Single pass: sequential replaces would re-expand `$1` typed inside $ARGUMENTS.\n const out = body.replace(TOKEN, (match, n?: string) => {\n if (match === '\\\\$')\n return '$'\n hasPlaceholder = true\n return n ? (argv[Number(n) - 1] ?? '') : args\n })\n if (!hasPlaceholder)\n return args.trim() ? `${out}\\n\\n${args}` : out\n return out\n}\n\nexport function parseCommandFile(file: MarkdownDefFile, content: string): { command?: Command, diagnostics: MarkdownDefDiagnostic[] } {\n const diagnostics: MarkdownDefDiagnostic[] = []\n const note = (message: string) => diagnostics.push({ path: file.path, kind: 'command', message })\n const parsed = parseFrontmatter(content)\n for (const d of parsed.diagnostics)\n note(d.message)\n\n if (!file.name || /\\s/.test(file.name) || file.name.startsWith('/')) {\n note(`invalid command name \"${file.name}\"; skipped`)\n return { diagnostics }\n }\n const body = parsed.body\n if (!body) {\n note('empty command body; skipped')\n return { diagnostics }\n }\n for (const key of IGNORED_KEYS) {\n if (parsed.frontmatter[key] !== undefined)\n note(`frontmatter \"${key}\" is ignored for commands`)\n }\n\n const fm = parsed.frontmatter\n const firstLine = body.split('\\n').find(line => line.trim())?.trim().replace(/^#+\\s*/, '') || file.name\n let description = typeof fm.description === 'string' && fm.description.trim()\n ? fm.description.trim()\n : firstLine.slice(0, DESCRIPTION_MAX)\n if (typeof fm['argument-hint'] === 'string' && fm['argument-hint'].trim())\n description = `${description} (args: ${fm['argument-hint'].trim()})`\n\n const command: Command = {\n name: file.name,\n description,\n // No `group`: it names the contributing extension (`/<extension>` lists\n // its commands). A namespaced file name (`git:commit`) already matches `/git`.\n run: async (ctx) => {\n await ctx.runAgent(expandCommandTemplate(body, ctx.args, ctx.argv))\n },\n }\n return { command, diagnostics }\n}\n","import type { ProjectUserPath } from '../chat/project-user-paths'\nimport type { MarkdownDefKind } from './types'\nimport { homedir } from 'node:os'\nimport { resolve } from 'node:path'\nimport { findGitRoot } from '../chat/project-root'\nimport { projectUserPaths } from '../chat/project-user-paths'\n\nexport interface MarkdownDefRoot {\n path: string\n source: 'project' | 'user'\n foreign: boolean\n}\n\nexport interface MarkdownDefRootsOptions {\n kind: MarkdownDefKind\n cwd?: string\n home?: string\n /** Storage prefix, default `.zidane`. */\n prefix?: string\n /** `settings.importForeignConfigs`. Adds `.claude/<kind>`. */\n includeForeign: boolean\n /** Default true. False drops `source: 'project'` roots, native and foreign. */\n includeProject?: boolean\n}\n\n/**\n * Claude Code's markdown command / agent dirs, project first. Claude only:\n * Codex and pi have no equivalent format. Project root is the git root, as\n * for the other foreign configs.\n */\nexport function foreignMarkdownScanPaths(kind: MarkdownDefKind, opts: { cwd?: string, home?: string } = {}): ProjectUserPath[] {\n const cwd = opts.cwd ?? process.cwd()\n const projectRoot = findGitRoot(cwd) ?? cwd\n const home = opts.home ?? homedir()\n return [\n { path: resolve(projectRoot, `.claude/${kind}`), source: 'project' },\n { path: resolve(home, `.claude/${kind}`), source: 'user' },\n ]\n}\n\n/** Native project, native user, then (opt-in) foreign project, foreign user. Same order as skills. */\nexport function markdownDefRoots(opts: MarkdownDefRootsOptions): MarkdownDefRoot[] {\n const native = projectUserPaths({ subPath: opts.kind, cwd: opts.cwd, home: opts.home, prefix: opts.prefix })\n .map(p => ({ path: p.path, source: p.source, foreign: false }))\n const foreign = opts.includeForeign\n ? foreignMarkdownScanPaths(opts.kind, { cwd: opts.cwd, home: opts.home })\n .map(p => ({ path: p.path, source: p.source, foreign: true }))\n : []\n const all = [...native, ...foreign]\n return opts.includeProject === false ? all.filter(r => r.source !== 'project') : all\n}\n","import type { MarkdownDefRoot } from './roots'\nimport type { MarkdownDefFile } from './types'\nimport { readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\n\nconst MAX_DEPTH = 3\n/** Dot entries (dirs and dotfiles) are skipped separately. Not the skills skip set: `build/` and `dist/` are legitimate command namespaces. */\nconst SKIP_DIRS: ReadonlySet<string> = new Set(['node_modules'])\n\n/**\n * Every `*.md` under each root, in root order. No dedupe here: agent files\n * can rename themselves via frontmatter, so first-wins runs after parsing.\n */\nexport function listMarkdownDefFiles(roots: readonly MarkdownDefRoot[]): MarkdownDefFile[] {\n const files: MarkdownDefFile[] = []\n for (const root of roots)\n walk(root, root.path, [], files)\n return files\n}\n\nfunction walk(root: MarkdownDefRoot, dir: string, segments: string[], out: MarkdownDefFile[]): void {\n let entries: string[]\n try {\n entries = readdirSync(dir).sort()\n }\n catch {\n return\n }\n for (const entry of entries) {\n if (entry.startsWith('.') || SKIP_DIRS.has(entry))\n continue\n const path = join(dir, entry)\n let isDir: boolean\n try {\n isDir = statSync(path).isDirectory()\n }\n catch {\n continue\n }\n if (isDir) {\n if (segments.length < MAX_DEPTH)\n walk(root, path, [...segments, entry], out)\n continue\n }\n if (!entry.endsWith('.md'))\n continue\n const name = [...segments, entry.slice(0, -3)].join(':').toLowerCase()\n out.push({ path, name, source: root.source, foreign: root.foreign })\n }\n}\n","import type { Command } from '../chat/commands'\nimport type { Preset } from '../presets'\nimport type { SubagentDef, SubagentOverride, SubagentRegistry } from '../tools/spawn'\nimport type { ModelAliasContext } from './model-aliases'\nimport type { MarkdownDefDiagnostic, MarkdownDefFile, MarkdownDefKind } from './types'\nimport { readFileSync } from 'node:fs'\nimport { isSpawnTool } from '../tools/spawn'\nimport { parseAgentFile } from './agents'\nimport { BUILTIN_SUBAGENTS } from './builtin-agents'\nimport { parseCommandFile } from './commands'\nimport { markdownDefRoots } from './roots'\nimport { listMarkdownDefFiles } from './scan'\n\nexport { BUILTIN_SUBAGENTS } from './builtin-agents'\nexport type { ModelAliasContext } from './model-aliases'\nexport type { MarkdownDefDiagnostic } from './types'\n\nexport interface LoadMarkdownOptions {\n cwd?: string\n home?: string\n /** Storage prefix, default `.zidane`. */\n prefix?: string\n /** `settings.importForeignConfigs`. */\n includeForeign: boolean\n /**\n * Default true. False drops every `source: 'project'` root (native and\n * foreign). The seam for SDK hosts that open untrusted repos: a project file\n * writes a prompt (command body, subagent system prompt) the user did not,\n * so such hosts load user-level files only. Headless sets it false unless\n * `--project-agents` is passed.\n */\n includeProject?: boolean\n}\n\nexport interface LoadMarkdownCommandsOptions extends LoadMarkdownOptions {\n /**\n * True when an enabled skill answers `/<name>`. Skills win that name, as in\n * Claude Code, so the file command is dropped with a diagnostic instead of\n * silently hiding the skill.\n */\n isSkillName?: (name: string) => boolean\n}\n\n/** Names that would collide with `Object.prototype` keys in a plain registry. */\nconst RESERVED_NAMES: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])\n\nfunction filesFor(kind: MarkdownDefKind, opts: LoadMarkdownOptions): MarkdownDefFile[] {\n return listMarkdownDefFiles(markdownDefRoots({ kind, ...opts }))\n}\n\nfunction read(path: string): string | undefined {\n try {\n return readFileSync(path, 'utf8')\n }\n catch {\n return undefined\n }\n}\n\n/**\n * Markdown slash commands, first-wins by name in root order. Never throws.\n * @param opts - Search roots, project and foreign-config switches, and an optional skill-name check.\n */\nexport function loadMarkdownCommands(opts: LoadMarkdownCommandsOptions): { commands: Command[], diagnostics: MarkdownDefDiagnostic[] } {\n const commands: Command[] = []\n const diagnostics: MarkdownDefDiagnostic[] = []\n const winners = new Map<string, string>()\n for (const file of filesFor('commands', opts)) {\n const content = read(file.path)\n if (content === undefined)\n continue\n const parsed = parseCommandFile(file, content)\n diagnostics.push(...parsed.diagnostics)\n if (!parsed.command)\n continue\n const key = parsed.command.name.toLowerCase()\n if (RESERVED_NAMES.has(key)) {\n diagnostics.push({ path: file.path, kind: 'command', message: 'reserved command name' })\n continue\n }\n if (opts.isSkillName?.(key)) {\n diagnostics.push({ path: file.path, kind: 'command', message: `skill \"${key}\" has the same name and wins; rename the command or the skill` })\n continue\n }\n const winner = winners.get(key)\n if (winner) {\n diagnostics.push({ path: file.path, kind: 'command', message: `shadowed by ${winner}` })\n continue\n }\n winners.set(key, file.path)\n commands.push(parsed.command)\n }\n return { commands, diagnostics }\n}\n\n/**\n * Builtin Explore/Plan plus markdown agents. User-scope files override\n * builtins (project files are refused with a diagnostic); among files, first-wins by name in root order. Never throws.\n * @param opts - Search roots and switches, plus the model context used to resolve `model:` aliases.\n */\nexport function loadMarkdownAgents(\n opts: LoadMarkdownOptions & { modelContext: ModelAliasContext },\n): { subagents: SubagentRegistry, diagnostics: MarkdownDefDiagnostic[] } {\n const fromFiles: SubagentRegistry = Object.create(null)\n const winners = new Map<string, string>()\n const diagnostics: MarkdownDefDiagnostic[] = []\n for (const file of filesFor('agents', opts)) {\n const content = read(file.path)\n if (content === undefined)\n continue\n const parsed = parseAgentFile(file, content, opts.modelContext)\n diagnostics.push(...parsed.diagnostics)\n if (!parsed.entry)\n continue\n const [name, def] = parsed.entry\n if (RESERVED_NAMES.has(name)) {\n diagnostics.push({ path: file.path, kind: 'agent', message: 'reserved agent name' })\n continue\n }\n if (Object.hasOwn(BUILTIN_SUBAGENTS, name)) {\n // A cloned repo must not turn read-only Explore/Plan, which models call\n // unprompted, into writers: only user-scope files may replace them.\n if (file.source === 'project') {\n diagnostics.push({ path: file.path, kind: 'agent', message: `project files cannot replace builtin ${name}; rename the agent or move it to the user folder` })\n continue\n }\n // Without its own tool restriction the replacement would inherit every\n // parent tool, so it stays read-only unless the file wrote `readonly: false`.\n if (!def.tools && !parsed.explicitReadonlyFalse)\n def.readonly = true\n }\n const winner = winners.get(name)\n if (winner) {\n diagnostics.push({ path: file.path, kind: 'agent', message: `shadowed by ${winner}` })\n continue\n }\n winners.set(name, file.path)\n fromFiles[name] = def\n }\n const subagents: SubagentRegistry = {}\n for (const [name, def] of Object.entries(BUILTIN_SUBAGENTS))\n subagents[name] = { ...def }\n for (const [name, def] of Object.entries(fromFiles))\n subagents[name] = def\n return { subagents, diagnostics }\n}\n\n/**\n * Fold markdown/builtin agents into the preset's spawn tool, filling gaps\n * only: an agent the profile or an extension already registered keeps its\n * definition. Runs after `composeExtensionPreset`, so precedence is\n * builtin < file < extension without threading files through composition.\n * @param preset - Preset whose `spawn` tool receives the agents. Returned unchanged when it has no spawn tool or `subagents` is empty.\n * @param subagents - Agent registry to merge, typically from {@link loadMarkdownAgents}.\n */\nexport function applyMarkdownSubagents(preset: Preset, subagents: SubagentRegistry): Preset {\n const spawn = preset.tools?.spawn\n const entries = Object.entries(subagents)\n if (!spawn || !isSpawnTool(spawn) || entries.length === 0)\n return preset\n const overrides: Record<string, SubagentOverride> = Object.create(null)\n for (const [name, def] of entries)\n overrides[name] = (current: SubagentDef | undefined) => current ?? def\n return { ...preset, tools: { ...preset.tools, spawn: spawn.withSubagents({}, overrides) } }\n}\n","/**\n * Headless mode — a non-interactive, fully-structured way to drive the agent\n * for automation and RL rollouts.\n *\n * `agent.run()` already returns rich {@link AgentStats}, the session captures a\n * lossless transcript (`session.turns`), and the hook bus exposes every\n * streaming/tool/turn event. What this module adds is the *contract* an RL loop\n * needs: one call (`runHeadless`) that runs a prompt to completion in a chosen\n * workdir, bounded by turns + wall-clock, and hands back a single serializable\n * {@link HeadlessResult} — final answer, verifiable structured output, usage,\n * and the complete trajectory — plus an optional live {@link HeadlessEvent}\n * stream (the in-process equivalent of `--output-format stream-json`).\n *\n * It is provider-agnostic: the caller passes a built {@link Provider} (e.g.\n * `local()` pointed at a vLLM server, or any of the named providers). The thin\n * CLI in `src/headless-cli.ts` wraps this with arg parsing, file/stdin I/O, and\n * JSONL transcript writing.\n */\n\nimport type { AgentOptions } from './agent'\nimport type { ExecutionContext } from './contexts'\nimport type { ExtensionRegistry } from './extensions'\nimport type { HeadlessErrorInfo, HeadlessEvent, HeadlessResult, HeadlessStatus } from './headless-format'\nimport type { Preset } from './presets'\nimport type { Provider } from './providers'\nimport type { Session, SessionStore } from './session'\nimport type { ToolDef } from './tools'\nimport type { SubagentRegistry } from './tools/spawn'\nimport type {\n AgentStats,\n McpServerConfig,\n PromptPart,\n SessionTurn,\n ThinkingLevel,\n TurnFinishReason,\n} from './types'\nimport { createAgent } from './agent'\nimport { installCacheBreakLogger } from './cache-telemetry'\nimport { createProcessContext } from './contexts'\nimport { installHeadlessEventAdapter, textOf } from './headless-format'\nimport { applyMarkdownSubagents } from './markdown-defs'\nimport { DEFAULT_MAX_IMAGE_EDGE, DEFAULT_MEDIA_BUDGET } from './media/defaults'\nimport { basic } from './presets'\nimport { createRunSummaryCollector } from './run-summary'\nimport { createMemoryStore, createSession } from './session'\n\n// The contract (shapes, formatting, events) lives in `headless-format.ts` so\n// serializers can import it without the runner.\nexport type { FormattedHeadlessResult, FormattedHeadlessTurnEvent, HeadlessErrorInfo, HeadlessEvent, HeadlessOutputFormat, HeadlessResult, HeadlessStatus, HeadlessUsage, OpenAIChatContentPart, OpenAIChatMessage, ProviderTranscriptFormat } from './headless-format'\nexport { exitCodeForHeadlessResult, formatHeadlessResult, formatHeadlessTurnEvent, formattedHeadlessTurnEventToJsonl, headlessEventToJsonl, installHeadlessEventAdapter, providerTranscriptFormatForProvider, transcriptToOpenAIMessages, transcriptToProviderMessages } from './headless-format'\n\n/** Options for {@link runHeadless}. */\nexport interface HeadlessOptions {\n /** User prompt — plain string or multimodal `PromptPart[]`. */\n prompt: string | PromptPart[]\n /** Built provider (e.g. `local()`, `openaiCompat(...)`, `anthropic(...)`). */\n provider: Provider\n /** Model id. Defaults to the provider's default model. */\n model?: string\n /** Override the preset system prompt for this run. */\n system?: string\n /** Thinking effort for the run. Defaults to `'off'`. */\n thinking?: ThinkingLevel\n /** Maximum number of loop turns. Sets `behavior.maxTurns`. */\n maxTurns?: number\n /** Maximum output tokens per turn. Sets `behavior.maxTokens`. */\n maxTokens?: number\n /** Wall-clock cap; on expiry the run is aborted and `status` becomes `'timeout'`. */\n timeoutMs?: number\n /** External abort signal — chained with the internal timeout controller. */\n signal?: AbortSignal\n /** JSON Schema for structured-output enforcement → populates `result.output`. */\n schema?: Record<string, unknown>\n /** Agent behavior defaults for this headless run. Top-level shortcuts below override matching fields. */\n behavior?: AgentOptions['behavior']\n /** Tool overrides. Omit to use the basic preset's tools. */\n tools?: Record<string, ToolDef>\n /** MCP servers to connect and expose as tools. */\n mcpServers?: McpServerConfig[]\n /** Skills configuration. */\n skills?: AgentOptions['skills']\n /**\n * Base {@link Preset} for the agent — spread in place of the default `basic`\n * preset (use it to swap the system prompt / tool set wholesale). The\n * top-level shortcuts above (`system`, `behavior`, `tools`, `mcpServers`,\n * `skills`) still override matching preset fields.\n */\n preset?: Preset\n /**\n * Subagents folded into the preset's spawn tool, filling gaps only (an\n * agent the preset or an extension already defines wins). The CLI passes\n * builtin + markdown agents from `loadMarkdownAgents`.\n */\n subagents?: SubagentRegistry\n /**\n * Pre-built extension registry folded into the agent via `createAgent`\n * (build it with `buildExtensionRegistry(defs.map(inlineLoadedExtension))`).\n * Contributes the registry's tools / hooks / mcpServers / skills /\n * system-fragments / subagents, with the explicit options above winning on\n * collision. Because hooks fold through `createAgent`, a headless run with\n * `extensions` also gets extension hooks (e.g. a `tool:transform` that\n * rewrites results), not just tools.\n */\n extensions?: ExtensionRegistry\n /** Execution context. Defaults to a process context rooted at `cwd`. */\n execution?: ExecutionContext\n /** Working directory for the default process context (ignored if `execution` is set). */\n cwd?: string\n /** Reuse / resume an existing session. */\n session?: Session\n /** Session store for a fresh session (defaults to an in-memory store). */\n store?: SessionStore\n /** Keep `thinking` blocks in `result.transcript` (default true). */\n includeThinking?: boolean\n /** Live event callback — the in-process stream-json equivalent. */\n onEvent?: (event: HeadlessEvent) => void\n}\n\n// ---------------------------------------------------------------------------\n// runHeadless\n// ---------------------------------------------------------------------------\n\n/**\n * Run a prompt to completion, headless, and return a single serializable\n * {@link HeadlessResult}. Safe to call concurrently for parallel rollouts —\n * each call builds its own agent + session and tears them down in `finally`.\n *\n * @param opts - Prompt, provider and run limits. `prompt` and `provider` are required.\n * @returns The run result. Errors from the agent loop, aborts and timeouts are reported in `status` and `error` instead of being thrown.\n *\n * @example\n * ~~~ts\n * import { exitCodeForHeadlessResult, runHeadless } from 'zidane/headless'\n * import { anthropic } from 'zidane/providers/anthropic'\n *\n * const result = await runHeadless({\n * prompt: 'List the TypeScript files in this directory.',\n * provider: anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }),\n * cwd: process.cwd(),\n * maxTurns: 10,\n * timeoutMs: 120_000,\n * })\n *\n * console.log(result.status, result.finalText)\n * process.exitCode = exitCodeForHeadlessResult(result)\n * ~~~\n */\nexport async function runHeadless(opts: HeadlessOptions): Promise<HeadlessResult> {\n const startedAt = Date.now()\n const execution = opts.execution ?? createProcessContext({ cwd: opts.cwd })\n const session = opts.session ?? await createSession({ store: opts.store ?? createMemoryStore() })\n\n // Layer behavior on top of the base preset's: the `behavior` key is spread\n // last into `createAgent`, so without seeding from `basePreset.behavior` a\n // custom `preset` carrying behavior defaults would be silently wiped (the\n // top-level shortcuts are meant to OVERRIDE preset fields, not replace them).\n const basePreset = opts.subagents\n ? applyMarkdownSubagents(opts.preset ?? basic, opts.subagents)\n : (opts.preset ?? basic)\n // Media defaults match the built-in chat profiles: keep media inline until\n // the request nears the provider's hard limits (`mediaBudget`), and shrink\n // Retina screenshots once at entry (`maxImageEdge`). Aged media stays\n // re-resolvable via `read_file path=\"attachment://…\"`. A preset or explicit\n // `behavior` still overrides: a `mediaKeepTurns` window takes precedence\n // over the budget, and `mediaBudget: undefined` disables it.\n const behavior: NonNullable<AgentOptions['behavior']> = { mediaBudget: DEFAULT_MEDIA_BUDGET, maxImageEdge: DEFAULT_MAX_IMAGE_EDGE, ...basePreset.behavior, ...(opts.behavior ?? {}) }\n if (opts.maxTurns !== undefined)\n behavior.maxTurns = opts.maxTurns\n if (opts.maxTokens !== undefined)\n behavior.maxTokens = opts.maxTokens\n if (opts.schema !== undefined)\n behavior.schema = opts.schema\n\n const agent = createAgent({\n ...basePreset,\n provider: opts.provider,\n execution,\n session,\n behavior,\n ...(opts.tools !== undefined ? { tools: opts.tools } : {}),\n ...(opts.mcpServers !== undefined ? { mcpServers: opts.mcpServers } : {}),\n ...(opts.skills !== undefined ? { skills: opts.skills } : {}),\n ...(opts.extensions !== undefined ? { extensions: opts.extensions } : {}),\n })\n\n const collector = createRunSummaryCollector()\n const uninstallSummary = collector.install(agent.hooks)\n const uninstallEvents = opts.onEvent ? installHeadlessEventAdapter(agent.hooks, opts.onEvent) : noop\n // Debug output goes to stderr so stdout stays the result (text, JSON or JSONL).\n const debug = process.env.ZIDANE_DEBUG\n const uninstallCacheLog = debug\n ? installCacheBreakLogger(agent.hooks, { log: line => process.stderr.write(`${line}\\n`), verbose: debug.includes('cache') })\n : noop\n\n // Resumed sessions carry turns from prior runs — remember where this run\n // starts so transcript/finalText/numToolCalls stay per-run, matching the\n // per-run usage/turns/durationMs stats.\n const runStartIndex = session.turns.length\n\n // Internal controller drives the wall-clock timeout and chains any external\n // signal so a host cancel and a timeout both abort the same run. The\n // listener is removed in `finally` — a long-lived host signal must not\n // accumulate one listener per rollout.\n const controller = new AbortController()\n const onExternalAbort = (): void => controller.abort(opts.signal!.reason)\n if (opts.signal) {\n if (opts.signal.aborted)\n controller.abort(opts.signal.reason)\n else\n opts.signal.addEventListener('abort', onExternalAbort, { once: true })\n }\n let timedOut = false\n const timer = opts.timeoutMs && opts.timeoutMs > 0\n ? setTimeout(() => {\n timedOut = true\n controller.abort(new Error(`Headless run timed out after ${opts.timeoutMs}ms`))\n }, opts.timeoutMs)\n : undefined\n\n let stats: AgentStats | undefined\n let error: HeadlessErrorInfo | undefined\n\n try {\n stats = await agent.run({\n prompt: opts.prompt,\n signal: controller.signal,\n ...(opts.model !== undefined ? { model: opts.model } : {}),\n ...(opts.system !== undefined ? { system: opts.system } : {}),\n ...(opts.thinking !== undefined ? { thinking: opts.thinking } : {}),\n })\n }\n catch (err) {\n // The agent loop throws typed errors (AgentAbortedError,\n // AgentContextExceededError, AgentProviderError, …) — their `name` already\n // classifies the failure, so surface it directly.\n const e = err instanceof Error ? err : new Error(String(err))\n error = { message: e.message, type: e.name }\n }\n finally {\n if (timer)\n clearTimeout(timer)\n opts.signal?.removeEventListener('abort', onExternalAbort)\n uninstallEvents()\n uninstallSummary()\n uninstallCacheLog()\n await agent.destroy()\n }\n\n // Status: a thrown error wins, but an abort/timeout can also surface as a\n // clean resolve (the loop returns partial stats), so check the signal too.\n let status: HeadlessStatus\n if (error)\n status = timedOut ? 'timeout' : controller.signal.aborted ? 'aborted' : 'error'\n else if (controller.signal.aborted)\n status = timedOut ? 'timeout' : 'aborted'\n else\n status = 'completed'\n\n const rawTranscript = session.turns.slice(runStartIndex)\n const transcript = opts.includeThinking === false ? stripThinking(rawTranscript) : rawTranscript\n const summary = collector.latest()\n\n const result: HeadlessResult = {\n status,\n finalText: extractFinalText(rawTranscript),\n ...(stats?.output ? { output: stats.output } : {}),\n usage: {\n input: stats?.totalIn ?? 0,\n output: stats?.totalOut ?? 0,\n cacheRead: stats?.totalCacheRead ?? 0,\n cacheCreation: stats?.totalCacheCreation ?? 0,\n ...(typeof stats?.cost === 'number' ? { cost: stats.cost } : {}),\n },\n turns: stats?.turns ?? 0,\n durationMs: stats?.elapsed ?? (Date.now() - startedAt),\n numToolCalls: countToolCalls(rawTranscript),\n // Suppress `finishReason` on abort/timeout: the last persisted turn can\n // carry `finishReason: 'stop'` (e.g. the model finished a turn, a follow-up\n // continued, then the run was cancelled), which would make a consumer\n // keyed on `finishReason === 'stop'` misread a cancel as \"model finished\".\n // `status` is authoritative for those exits; let it speak alone. The\n // `'pause'` exhaustion exit keeps `status: 'completed'` so it still\n // surfaces its `finishReason: 'pause'` here.\n ...(status !== 'aborted' && status !== 'timeout' && lastFinishReason(stats)\n ? { finishReason: lastFinishReason(stats) }\n : {}),\n ...(error ? { error } : {}),\n sessionId: session.id,\n ...(summary ? { summary } : {}),\n transcript,\n }\n\n opts.onEvent?.({ type: 'result', result })\n return result\n}\n\nfunction noop(): void {}\n\nfunction extractFinalText(turns: SessionTurn[]): string {\n for (let i = turns.length - 1; i >= 0; i--) {\n const turn = turns[i]\n if (turn.role !== 'assistant')\n continue\n const text = textOf(turn.content)\n if (text)\n return text\n }\n return ''\n}\n\nfunction countToolCalls(turns: SessionTurn[]): number {\n let n = 0\n for (const turn of turns) {\n for (const block of turn.content) {\n if (block.type === 'tool_call')\n n++\n }\n }\n return n\n}\n\nfunction lastFinishReason(stats?: AgentStats): TurnFinishReason | undefined {\n const usages = stats?.turnUsage\n if (!usages)\n return undefined\n for (let i = usages.length - 1; i >= 0; i--) {\n if (usages[i].finishReason)\n return usages[i].finishReason\n }\n return undefined\n}\n\nfunction stripThinking(turns: SessionTurn[]): SessionTurn[] {\n return turns.map(turn => ({\n ...turn,\n content: turn.content.filter(b => b.type !== 'thinking' && b.type !== 'redacted_thinking'),\n }))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAMA,MAAa,uBAAwF;CACnG,OAAO;CACP,QAAQ;CACR,MAAM;CACN,OAAO;AACT;;;;;;AAeA,SAAgB,kBACd,OACA,KACA,MACwD;CACxD,MAAM,MAAM,OAAO,KAAK;CACxB,IAAI,CAAC,OAAO,IAAI,YAAY,MAAM,WAChC,OAAO,CAAC;CACV,MAAM,MAAM,IAAI,YAAY;CAC5B,IAAI,CAAC,OAAO,OAAO,sBAAsB,GAAG,GAC1C,OAAO,EAAE,OAAO,IAAI;CACtB,MAAM,SAAS,qBAAqB;CACpC,IAAI,IAAI,mBAAmB,eAAe,IAAI,YAAY,IAAI,MAAM,GAClE,OAAO,EAAE,OAAO,OAAO;CACzB,OAAO,EACL,YAAY;EACV;EACA,MAAM;EACN,SAAS,gBAAgB,IAAI;CAC/B,EACF;AACF;;;;AC5CA,MAAa,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K,IAAI,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK;EAC1C,MAAM,OAAO,MAAM;EACnB,IAAI,KAAK,SAAS,aAChB;EACF,MAAM,OAAO,OAAO,KAAK,OAAO;EAChC,IAAI,MACF,OAAO;CACX;CACA,OAAO;AACT;AAEA,SAAS,eAAe,OAA8B;CACpD,IAAI,IAAI;CACR,KAAK,MAAM,QAAQ,OACjB,KAAK,MAAM,SAAS,KAAK,SACvB,IAAI,MAAM,SAAS,aACjB;CAGN,OAAO;AACT;AAEA,SAAS,iBAAiB,OAAkD;CAC1E,MAAM,SAAS,OAAO;CACtB,IAAI,CAAC,QACH,OAAO,KAAA;CACT,KAAK,IAAI,IAAI,OAAO,SAAS,GAAG,KAAK,GAAG,KACtC,IAAI,OAAO,EAAE,CAAC,cACZ,OAAO,OAAO,EAAE,CAAC;AAGvB;AAEA,SAAS,cAAc,OAAqC;CAC1D,OAAO,MAAM,KAAI,UAAS;EACxB,GAAG;EACH,SAAS,KAAK,QAAQ,QAAO,MAAK,EAAE,SAAS,cAAc,EAAE,SAAS,mBAAmB;CAC3F,EAAE;AACJ"}
|
package/dist/headless.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Sr as runHeadless, _i as providerTranscriptFormatForProvider, ai as HeadlessResult, ci as OpenAIChatContentPart, di as exitCodeForHeadlessResult, ei as FormattedHeadlessResult, fi as formatHeadlessResult, gi as installHeadlessEventAdapter, hi as headlessEventToJsonl, ii as HeadlessOutputFormat, li as OpenAIChatMessage, mi as formattedHeadlessTurnEventToJsonl, ni as HeadlessErrorInfo, oi as HeadlessStatus, pi as formatHeadlessTurnEvent, ri as HeadlessEvent, si as HeadlessUsage, ti as FormattedHeadlessTurnEvent, ui as ProviderTranscriptFormat, vi as transcriptToOpenAIMessages, xr as HeadlessOptions, yi as transcriptToProviderMessages } from "./index-DyQyDLX1.js";
|
|
2
2
|
export { type FormattedHeadlessResult, type FormattedHeadlessTurnEvent, type HeadlessErrorInfo, type HeadlessEvent, HeadlessOptions, type HeadlessOutputFormat, type HeadlessResult, type HeadlessStatus, type HeadlessUsage, type OpenAIChatContentPart, type OpenAIChatMessage, type ProviderTranscriptFormat, exitCodeForHeadlessResult, formatHeadlessResult, formatHeadlessTurnEvent, formattedHeadlessTurnEventToJsonl, headlessEventToJsonl, installHeadlessEventAdapter, providerTranscriptFormatForProvider, runHeadless, transcriptToOpenAIMessages, transcriptToProviderMessages };
|
package/dist/headless.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { a as headlessEventToJsonl, i as formattedHeadlessTurnEventToJsonl, l as transcriptToOpenAIMessages, n as formatHeadlessResult, o as installHeadlessEventAdapter, r as formatHeadlessTurnEvent, s as providerTranscriptFormatForProvider, t as exitCodeForHeadlessResult, u as transcriptToProviderMessages } from "./headless-format-D9IB_rae.js";
|
|
2
|
-
import { t as runHeadless } from "./headless-
|
|
2
|
+
import { t as runHeadless } from "./headless-R4pbpTkm.js";
|
|
3
3
|
export { exitCodeForHeadlessResult, formatHeadlessResult, formatHeadlessTurnEvent, formattedHeadlessTurnEventToJsonl, headlessEventToJsonl, installHeadlessEventAdapter, providerTranscriptFormatForProvider, runHeadless, transcriptToOpenAIMessages, transcriptToProviderMessages };
|
|
@@ -3,7 +3,7 @@ import { v as normalizeMcpServers } from "./mcp-BnXLqb2R.js";
|
|
|
3
3
|
import { n as writeFileAtomic } from "./atomic-write-Ijgf2Mhc.js";
|
|
4
4
|
import { a as projectRootOf, t as findGitRoot } from "./project-root-BOgUA6n5.js";
|
|
5
5
|
import { t as projectUserPaths } from "./project-user-paths-DWqZyUgb.js";
|
|
6
|
-
import { L as isLocalBrowserUrl, R as normalizeBrowserUrl, c as SETTINGS_INPUTS, j as approvalModeFromSafeMode, s as SETTINGS_CHOICES, u as SETTINGS_TOGGLES } from "./secret-shapes-
|
|
6
|
+
import { L as isLocalBrowserUrl, R as normalizeBrowserUrl, c as SETTINGS_INPUTS, j as approvalModeFromSafeMode, s as SETTINGS_CHOICES, u as SETTINGS_TOGGLES } from "./secret-shapes-BjW4l6U0.js";
|
|
7
7
|
import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
8
8
|
import { join, resolve, sep } from "node:path";
|
|
9
9
|
import { homedir } from "node:os";
|
|
@@ -1706,4 +1706,4 @@ function splitHostSettingsPatch(patch) {
|
|
|
1706
1706
|
//#endregion
|
|
1707
1707
|
export { isOnSafelist as A, foreignSkillScanPaths as C, addToSafelistForCwd as D, addToSafelist as E, suggestSafelistEntries as F, writeProjects as I, projectsFilePath as M, readProjects as N, getSafelist as O, safelistProjectKey as P, foreignMcpConfigFiles as S, IMPLICITLY_SAFE_TOOLS as T, parseMcpsFile as _, settingsFromWire as a, rulerInstructionFiles as b, discoverSystemMd as c, userSystemMdPath as d, buildMcpServers as f, parseJsonTolerant as g, discoverProjectMcps as h, overlayHostSettings as i, matchesSafelistEntry as j, getSafelistForCwd as k, renderSystemMdSeed as l, defaultMcpsConfigPaths as m, WINDOW_LOCAL_SETTINGS as n, settingsToWire as o, dedupMcpServersByName as p, isWindowOnlySetting as r, splitHostSettingsPatch as s, HOST_ENABLED_LISTS as t, userScopeOverridesLoad as u, withSessionStdioCwd as v, parseClaudeState as w, rulerSkillScanPaths as x, isRulerGenerated as y };
|
|
1708
1708
|
|
|
1709
|
-
//# sourceMappingURL=host-scoped-settings-
|
|
1709
|
+
//# sourceMappingURL=host-scoped-settings-C-Nmb6vr.js.map
|