zidane 5.13.1 → 5.13.2
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/README.md +5 -1
- package/dist/{acp-CEE6C0m_.js → acp-BqIU2mo-.js} +109 -12
- package/dist/acp-BqIU2mo-.js.map +1 -0
- package/dist/acp-cli.js +163 -25
- package/dist/acp-cli.js.map +1 -1
- package/dist/acp.d.ts +41 -2
- package/dist/acp.d.ts.map +1 -1
- package/dist/acp.js +1 -1
- package/dist/chat.js +3 -2
- package/dist/chat.js.map +1 -1
- package/dist/eval.js +2 -2
- package/dist/{headless-Bz1SpTB-.js → headless-0O6HMNBQ.js} +5 -5
- package/dist/{headless-Bz1SpTB-.js.map → headless-0O6HMNBQ.js.map} +1 -1
- package/dist/headless.js +1 -1
- package/dist/index.js +6 -6
- package/dist/{messages-CGazSyTL.js → messages-DEsLGBB9.js} +2 -2
- package/dist/{messages-CGazSyTL.js.map → messages-DEsLGBB9.js.map} +1 -1
- package/dist/output/stream-json.js +1 -1
- package/dist/{presets-5IGiSsxm.js → presets-HDIxliiq.js} +2 -2
- package/dist/{presets-5IGiSsxm.js.map → presets-HDIxliiq.js.map} +1 -1
- package/dist/presets.js +1 -1
- package/dist/{providers-DMPAmUuY.js → providers-Cz-RNYZO.js} +2 -2
- package/dist/{providers-DMPAmUuY.js.map → providers-Cz-RNYZO.js.map} +1 -1
- package/dist/providers.js +2 -2
- package/dist/{session-B69BQSn1.js → session-BDWZZaYa.js} +2 -2
- package/dist/{session-B69BQSn1.js.map → session-BDWZZaYa.js.map} +1 -1
- package/dist/session.js +2 -2
- package/dist/{tools-CfS7rjuh.js → tools-DhzKzB1y.js} +2 -2
- package/dist/{tools-CfS7rjuh.js.map → tools-DhzKzB1y.js.map} +1 -1
- package/dist/tools.js +1 -1
- package/dist/{transcript-anchors-B_a1edre.js → transcript-anchors-Cq-8gx8u.js} +7 -1415
- package/dist/transcript-anchors-Cq-8gx8u.js.map +1 -0
- package/dist/tui.js +6 -5
- package/dist/tui.js.map +1 -1
- package/dist/xdg-zlSeVBhQ.js +1417 -0
- package/dist/xdg-zlSeVBhQ.js.map +1 -0
- package/docs/ACP.md +68 -0
- package/package.json +1 -1
- package/dist/acp-CEE6C0m_.js.map +0 -1
- package/dist/transcript-anchors-B_a1edre.js.map +0 -1
package/dist/chat.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { $ as useMcpAuthDispatch, $n as
|
|
2
|
-
import { ct as effectiveContextWindow, lt as shouldAutoCompact, ot as AUTO_COMPACT_MIN_GROWTH_FRACTION, st as OUTPUT_RESERVE_TOKENS } from "./tools-
|
|
1
|
+
import { $ as useMcpAuthDispatch, $n as resolveAgentId, $t as createStateStore, A as runOAuthLogin, An as bootTick, At as SettingsProvider, B as refreshMcpToolsCatalog, Bn as resolvePlatformPackage, Bt as CATPPUCCIN_FRAPPE, C as projectsFilePath, Cn as mergeKeybindings, Cr as SUBAGENT_GUIDANCE, Ct as shortChord, D as formatPathForCwd, Dn as useCompletion, Dr as envSection, Dt as SETTINGS_CATEGORIES, E as writeProjects, En as stripJsonComments, Er as buildPlanSystem, Et as DEFAULT_SETTINGS, F as parseMcpsFile, Fn as detectLibc, Ft as resolveChipColor, G as useMcpToolToggleSet, Gn as findGitRoot, Gt as DiscoveryProvider, H as subscribeMcpToolsCache, Hn as detectAuth, Ht as CATPPUCCIN_MACCHIATO, I as projectUserPaths, In as detectPackageManager, It as resolveTheme, J as parentServerName, Jn as DEFAULT_AGENT_ID, Jt as ConfigProvider, K as buildVisibleMcpRows, Kn as BUILD_AGENT, Kt as useDiscovery, L as clearMcpToolsCache, Ln as parseSemver, Lt as VAPORWAVE_THEME, M as buildMcpServers, Mn as useUpdateCheck, Mt as useSettings, N as defaultMcpsConfigPaths, Nn as checkForUpdate, Nt as BUILTIN_THEMES, O as fetchOAuthRedirect, On as tryOpenBrowser, Ot as SETTINGS_CHOICES, P as discoverProjectMcps, Pn as compareSemver, Pt as DEFAULT_THEME, Q as McpAuthProvider, Qn as accentColor, Qt as compactSummaryEvent, R as loadMcpToolsCache, Rn as performInPlaceSelfUpdate, Rt as GRUVBOX_DARK, S as matchesSafelistEntry, Sn as matchesBinding, Sr as PLAN_MODE_DOCTRINE_NO_PROMPTS, St as buildHints, T as suggestSafelistEntry, Tn as readKeybindings, Tr as buildBuildSystem, Tt as useEnabledToggleSet, U as buildToolToggle, Un as discoverAgentsMd, Ut as CATPPUCCIN_MOCHA, V as saveMcpToolsCache, Vn as chatAutoCompactBehavior, Vt as CATPPUCCIN_LATTE, W as useMcpToolToggleMap, Wn as renderAgentsMdBlock, Wt as createDiscoverySlot, X as mcpCredentialsPath, Xn as DEFAULT_PERSIST_EXCLUDE_TOOLS, Xt as resolveConfig, Y as createFileMcpCredentialStore, Yn as DEFAULT_BUDGET_EXCLUDE_TOOLS, Yt as useConfig, Z as patchMcpCredential, Zn as PLAN_AGENT, Zt as resolveStoragePaths, _ as useSafeModeQueue, _n as KEYBINDING_KEY_COL_WIDTH, _r as DOING_TASKS_DOCTRINE, _t as clipHintsToWidth, a as useSurfaces, an as marginTopFor, ar as TODO_WRITE_COUNTS_METADATA_KEY, at as ASK_USER_TOOL, b as getSafelist, bn as groupBindings, br as INTERACTION_GUIDANCE_NO_PROMPTS, bt as cleanTitle, c as useStreamBuffer, cn as stripSpawnTokensLine, cr as getTodosForRun, ct as buildResumedToolResultsTurn, d as discoverProjectSkills, dn as toolCallPreview, dr as pruneTodosByRun, dt as makeRequestInteraction, en as deriveSessionTitle, er as singleAgentRegistry, et as useMcpAuthState, f as renderSession, fn as toolResultText, fr as selectActiveTodos, ft as pendingInteractionsFromTurns, g as useSafeModeActions, gn as KEYBINDING_DEF_BY_ACTION, gr as COMMUNICATION_DOCTRINE, gt as EMPTY_HINTS, h as SafeModeProvider, hn as KEYBINDING_DEFS, hr as ACTIONS_WITH_CARE_DOCTRINE, ht as useInteractionsQueue, i as useSelectStyle, in as loadState, ir as TODO_STATUS_GLYPHS, it as splitMarkdownCodeBlocks, j as supportsOAuth, jn as buildUpdateHint, k as oauthUsesManualCodePaste, kn as bootProfileEnabled, kt as SETTINGS_TOGGLES, l as buildSkillsConfig, ln as sumRunCosts, lr as isTodoTool, lt as createInteractionTools, m as writeSessionExport, mn as DEFAULT_KEYBINDINGS, mr as useActiveTodos, mt as useInteractionsActions, n as ThemeProvider, nn as lastContextSizeFromTurns, nr as TODOS_METADATA_KEY, nt as reduceMcpAuth, o as useSyntaxStyles, on as saveState, or as createTodoTools, ot as InteractionsProvider, p as resolveSessionExportTarget, pn as updateToolEventOutcomes, pr as setTodosForRun, pt as serializeInteractionResponse, q as indexOfServerRow, qn as BUILTIN_AGENTS, qt as useDiscoveryOptional, r as useColors, rn as listSessionMeta, rr as TODOWRITE_TOOL, s as useTheme, sr as getArchivedTodosForRun, st as PRESENT_PLAN_TOOL, t as computeTurnAnchors, tn as eventsFromTurns, tr as TODOREAD_TOOL, tt as getMcpAuthStatus, u as defaultSkillScanPaths, un as titleFromTurns, ur as pickActiveRunId, ut as isInteractionTool, v as IMPLICITLY_SAFE_TOOLS, vn as ensureKeybindingsFile, vr as IDENTITY_PREFIX, vt as hintsLength, w as readProjects, wn as parseBindingSpec, wr as TOKEN_DISCIPLINE_DOCTRINE, wt as listProjectFiles, x as isOnSafelist, xn as keybindingsPath, xr as PLAN_MODE_DOCTRINE, xt as generateSessionTitle, y as addToSafelist, yn as formatBindingForDisplay, yr as INTERACTION_GUIDANCE, yt as truncateTrailing, z as mcpToolsCachePath, zn as performSelfUpdate, zt as GRUVBOX_LIGHT } from "./transcript-anchors-Cq-8gx8u.js";
|
|
2
|
+
import { ct as effectiveContextWindow, lt as shouldAutoCompact, ot as AUTO_COMPACT_MIN_GROWTH_FRACTION, st as OUTPUT_RESERVE_TOKENS } from "./tools-DhzKzB1y.js";
|
|
3
3
|
import { t as buildContextBreakdown } from "./context-breakdown-kO-pDsay.js";
|
|
4
4
|
import { a as formatTaskStatus, c as shortId, i as formatDuration, n as compactPath, o as formatTaskSummary, r as fmtTokens, s as previewLine, t as ageString } from "./format-BNOXpl-1.js";
|
|
5
|
+
import { C as restoreModelOptions, S as piIdOf, _ as modelOptionsFor, a as readProviderCredential, b as openaiDescriptor, c as writeCredentials, d as cerebrasDescriptor, f as credKeyOf, g as localDescriptor, h as getModelInfo, i as readCredentials, l as BUILTIN_PROVIDERS, m as getContextWindow, n as applyApiKeyEnv, o as removeProviderCredential, p as enabledModelOptions, r as credentialsPath, s as setProviderCredential, t as resolveStorageDirs, u as anthropicDescriptor, v as modelSupportsReasoning, x as openrouterDescriptor, y as modelsForDescriptor } from "./xdg-zlSeVBhQ.js";
|
|
5
6
|
import { A as splitLines, B as summarizeOutcomes, C as buildContextualDiff, D as extractEditPayload, E as computeLineDiff, F as mergeApprovalAndBodyOutcomes, G as createFilesCompletionProvider, H as createSkillsCompletionProvider, I as parseEditOutcomesFromResult, J as collectReferences, K as uniqueFilesFromReferences, L as resolveApprovalForPayload, M as tokenize, N as buildEditOutcomesAnnotation, O as filetypeFromPath, P as maskToOutcomeKinds, Q as buildLinearRamp, R as rewriteMultiEditHeader, S as applyEditPayload, T as computeInlineDiff, U as uniqueSkillNamesFromReferences, V as SKILLS_TRIGGER, W as FILES_TRIGGER, X as mergeReferences, Y as findActiveTrigger, Z as blendHsl, _ as isEditErrorResult, a as TOOL_DISPLAY, b as selectableTurnIds, c as finalizeStreamingMarkdown, d as turnContextSize, f as splitPromptSegments, h as indexOfEntry, i as turnAsText, j as summarizeEditPayload, k as previewEditPayload, l as finalizeStreamingMarkdownForOwner, m as filterModelCatalog, n as deleteTurnSafely, o as displayNameFor, p as buildModelCatalog, q as applyInsert, r as truncateTurnsAt, s as formatToolCall, t as countNeighbors, v as isTurnHighlighted, w as buildUnifiedDiff, x as turnSelectionOwnership, y as isVisible, z as stripEditOutcomesAnnotation } from "./turn-operations-DLWN2J7f.js";
|
|
6
7
|
//#region src/chat/auto-update-cli.ts
|
|
7
8
|
const UPGRADE_HELP = `Usage: zidane upgrade [options]
|
package/dist/chat.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat.js","names":[],"sources":["../src/chat/auto-update-cli.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// `zidane upgrade` subcommand — drop-in handler for consumer CLIs.\n//\n// Wraps `checkForUpdate` + `performSelfUpdate` + `performInPlaceSelfUpdate`\n// into a single function the host's `cli.ts` can call. The behavior layers:\n//\n// - no flags → check + run the package manager\n// - `--check` → check only, print the latest version + bail\n// - `--in-place` → skip the PM, download + atomic-rename the binary\n// - `--dry-run` → resolve everything but don't actually swap\n// - `--channel <tag>` → override dist-tag (defaults to `'latest'`)\n// - `--registry <url>`→ override the npm registry URL\n//\n// Pure I/O — writes to stdout/stderr, returns the exit code the caller\n// should pass to `process.exit`. No React, no OpenTUI; safe to call\n// before / instead of `runTui`.\n// ---------------------------------------------------------------------------\n\nimport {\n checkForUpdate,\n compareSemver,\n detectPackageManager,\n performInPlaceSelfUpdate,\n performSelfUpdate,\n resolvePlatformPackage,\n} from './auto-update'\n\nexport interface RunUpdateCommandOptions {\n /** Top-level package the user installs (e.g. `'zidane-tui'`). */\n packageName: string\n /** Inlined at build time. */\n currentVersion: string\n /** Args passed after `upgrade` (typically `process.argv.slice(3)`). */\n argv: readonly string[]\n /** Where to persist the TTL cache. Usually `paths.userDir`. */\n cacheDir?: string\n /** Default channel when `--channel` isn't passed. Defaults to `'latest'`. */\n defaultChannel?: string\n /**\n * Override the platform-package-name prefix used by `--in-place`.\n * Defaults to `'<packageName>-'`, matching the `zidane-tui-<key>` layout.\n */\n platformPackagePrefix?: string\n /** Override registry. Defaults to npmjs. */\n registry?: string\n /** stdout. Defaults to `process.stdout`. */\n stdout?: NodeJS.WritableStream\n /** stderr. Defaults to `process.stderr`. */\n stderr?: NodeJS.WritableStream\n}\n\nexport interface RunUpdateCommandResult {\n exitCode: number\n}\n\nconst UPGRADE_HELP = `Usage: zidane upgrade [options]\n\nUpdate the zidane CLI to the latest release.\n\nOptions:\n --check Print the latest version and exit (no install).\n --in-place Download the platform binary directly from npm\n and atomic-rename over the running binary.\n Skips the package manager. Refused on Volta.\n --dry-run Resolve everything but don't actually install.\n --channel <tag> dist-tag to query (default: latest).\n --registry <url> Override the npm registry.\n --package-manager <pm> Force npm | pnpm | yarn | bun | volta.\n --force Run the install even if we're already on latest,\n or the registry check failed.\n -h, --help Print this help.\n\nEnvironment:\n NO_UPDATE_NOTIFIER Silence the background check (set to \"1\").\n ZIDANE_NO_UPDATE Same, project-specific.\n`\n\n/**\n * Run the `upgrade` subcommand. Exit code contract:\n * - `0` — update succeeded, `--check` reported no update, or `--check`\n * reported an update (informational only).\n * - `1` — update failed (PM exit non-zero, in-place download failed,\n * registry returned non-2xx).\n * - `2` — argv parse error (unknown flag).\n */\nexport async function runUpdateCommand(options: RunUpdateCommandOptions): Promise<RunUpdateCommandResult> {\n const out = options.stdout ?? process.stdout\n const err = options.stderr ?? process.stderr\n const parsed = parseArgs(options.argv)\n if (parsed.kind === 'error') {\n err.write(`zidane upgrade: ${parsed.message}\\n`)\n err.write(UPGRADE_HELP)\n return { exitCode: 2 }\n }\n if (parsed.help) {\n out.write(UPGRADE_HELP)\n return { exitCode: 0 }\n }\n\n const channel = parsed.channel ?? options.defaultChannel ?? 'latest'\n const registry = parsed.registry ?? options.registry\n\n // Always force the check — user typed `upgrade`, env opt-outs shouldn't\n // get in the way.\n const status = await checkForUpdate({\n packageName: options.packageName,\n currentVersion: options.currentVersion,\n channel,\n registry,\n cacheDir: options.cacheDir,\n force: true,\n timeoutMs: 8000,\n })\n\n // `--check` is informational — degrade gracefully on registry errors\n // (offline laptop, restricted proxy) and exit 0 so the user can script\n // around it without quoting tricks.\n if (parsed.check) {\n if (status.source === 'error') {\n err.write(`Could not check \\`${channel}\\` (${status.error ?? 'unknown error'}). Current: v${options.currentVersion}.\\n`)\n return { exitCode: 0 }\n }\n if (!status.latest) {\n err.write(`Could not determine latest version on \\`${channel}\\`. Current: v${options.currentVersion}.\\n`)\n return { exitCode: 0 }\n }\n const cmp = compareSemver(status.latest, options.currentVersion)\n if (cmp > 0)\n out.write(`v${status.latest} is available on \\`${channel}\\` (current: v${options.currentVersion}).\\n`)\n else\n out.write(`Already on v${options.currentVersion} (latest on \\`${channel}\\` is v${status.latest}).\\n`)\n return { exitCode: 0 }\n }\n\n // Install path — a registry error means we don't KNOW if we need an\n // update. Refuse to spawn the PM blindly unless the user explicitly\n // asks via `--force`.\n if (status.source === 'error') {\n err.write(`zidane upgrade: registry check failed (${status.error ?? 'unknown error'})\\n`)\n if (!parsed.force) {\n err.write('Pass --force to attempt the install anyway.\\n')\n return { exitCode: 1 }\n }\n }\n\n if (status.latest && !parsed.force) {\n const cmp = compareSemver(status.latest, options.currentVersion)\n if (cmp <= 0) {\n out.write(`Already on v${options.currentVersion} (latest on \\`${channel}\\` is v${status.latest}).\\n`)\n return { exitCode: 0 }\n }\n }\n\n // ---------------------------------------------------------------------\n // In-place path\n // ---------------------------------------------------------------------\n\n if (parsed.inPlace) {\n const platformPkg = resolvePlatformPackage({\n prefix: options.platformPackagePrefix ?? `${options.packageName}-`,\n })\n if (!platformPkg) {\n err.write(`No prebuilt binary for ${process.platform}/${process.arch}. Run \\`${options.packageName}-upgrade\\` via your package manager instead.\\n`)\n return { exitCode: 1 }\n }\n out.write(`Downloading ${platformPkg}@${channel}…\\n`)\n const result = await performInPlaceSelfUpdate({\n packageName: platformPkg,\n channel,\n registry,\n dryRun: parsed.dryRun,\n })\n if (result.status === 'success') {\n const verb = parsed.dryRun ? 'Would install' : 'Installed'\n out.write(`${verb} v${result.installedVersion} at ${result.binaryPath}.\\n`)\n return { exitCode: 0 }\n }\n err.write(`In-place update failed: ${result.reason ?? 'unknown error'}\\n`)\n if (result.status === 'refused')\n err.write('Falling back to package-manager path (drop --in-place to retry).\\n')\n return { exitCode: 1 }\n }\n\n // ---------------------------------------------------------------------\n // Package-manager path\n // ---------------------------------------------------------------------\n\n const detected = detectPackageManager({ packageName: options.packageName, channel })\n if (detected.note)\n out.write(`${detected.note}\\n`)\n out.write(`Running: ${detected.argv.join(' ')}\\n`)\n if (parsed.dryRun)\n return { exitCode: 0 }\n\n const result = await performSelfUpdate({\n packageName: options.packageName,\n channel,\n packageManager: parsed.packageManager ?? 'auto',\n })\n if (result.spawnError) {\n err.write(`Failed to launch \\`${result.command.argv[0]}\\`: ${result.spawnError}\\n`)\n err.write('Is the package manager installed and on $PATH?\\n')\n return { exitCode: 1 }\n }\n return { exitCode: result.exitCode ?? 1 }\n}\n\n// ---------------------------------------------------------------------------\n// Argv parser — minimal, just enough to drop into the consumer's `cli.ts`.\n// We deliberately don't pull in commander/yargs for a 5-flag surface.\n// ---------------------------------------------------------------------------\n\ntype ParseResult\n = | {\n kind: 'ok'\n check: boolean\n inPlace: boolean\n dryRun: boolean\n force: boolean\n help: boolean\n channel?: string\n registry?: string\n packageManager?: 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta'\n }\n | { kind: 'error', message: string }\n\nfunction parseArgs(argv: readonly string[]): ParseResult {\n let check = false\n let inPlace = false\n let dryRun = false\n let force = false\n let help = false\n let channel: string | undefined\n let registry: string | undefined\n let packageManager: 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta' | undefined\n\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i]!\n switch (a) {\n case '--check': check = true; break\n case '--in-place':\n case '--inplace': inPlace = true; break\n case '--dry-run':\n case '--dryrun': dryRun = true; break\n case '--force': force = true; break\n case '-h':\n case '--help': help = true; break\n case '--channel':\n channel = argv[++i]\n if (!channel)\n return { kind: 'error', message: '--channel requires a value' }\n break\n case '--registry':\n registry = argv[++i]\n if (!registry)\n return { kind: 'error', message: '--registry requires a value' }\n break\n case '--package-manager':\n case '--pm': {\n const v = argv[++i]\n if (!v)\n return { kind: 'error', message: '--package-manager requires a value' }\n if (v !== 'npm' && v !== 'pnpm' && v !== 'yarn' && v !== 'bun' && v !== 'volta')\n return { kind: 'error', message: `unknown package manager: ${v}` }\n packageManager = v\n break\n }\n default:\n return { kind: 'error', message: `unknown argument: ${a}` }\n }\n }\n\n return { kind: 'ok', check, inPlace, dryRun, force, help, channel, registry, packageManager }\n}\n"],"mappings":";;;;;;AAuDA,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BrB,eAAsB,iBAAiB,SAAmE;CACxG,MAAM,MAAM,QAAQ,UAAU,QAAQ;CACtC,MAAM,MAAM,QAAQ,UAAU,QAAQ;CACtC,MAAM,SAAS,UAAU,QAAQ,IAAI;CACrC,IAAI,OAAO,SAAS,SAAS;EAC3B,IAAI,MAAM,mBAAmB,OAAO,QAAQ,GAAG;EAC/C,IAAI,MAAM,YAAY;EACtB,OAAO,EAAE,UAAU,EAAE;CACvB;CACA,IAAI,OAAO,MAAM;EACf,IAAI,MAAM,YAAY;EACtB,OAAO,EAAE,UAAU,EAAE;CACvB;CAEA,MAAM,UAAU,OAAO,WAAW,QAAQ,kBAAkB;CAC5D,MAAM,WAAW,OAAO,YAAY,QAAQ;CAI5C,MAAM,SAAS,MAAM,eAAe;EAClC,aAAa,QAAQ;EACrB,gBAAgB,QAAQ;EACxB;EACA;EACA,UAAU,QAAQ;EAClB,OAAO;EACP,WAAW;CACb,CAAC;CAKD,IAAI,OAAO,OAAO;EAChB,IAAI,OAAO,WAAW,SAAS;GAC7B,IAAI,MAAM,qBAAqB,QAAQ,MAAM,OAAO,SAAS,gBAAgB,eAAe,QAAQ,eAAe,IAAI;GACvH,OAAO,EAAE,UAAU,EAAE;EACvB;EACA,IAAI,CAAC,OAAO,QAAQ;GAClB,IAAI,MAAM,2CAA2C,QAAQ,gBAAgB,QAAQ,eAAe,IAAI;GACxG,OAAO,EAAE,UAAU,EAAE;EACvB;EAEA,IADY,cAAc,OAAO,QAAQ,QAAQ,cAC3C,IAAI,GACR,IAAI,MAAM,IAAI,OAAO,OAAO,qBAAqB,QAAQ,gBAAgB,QAAQ,eAAe,KAAK;OAErG,IA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;KAAE,MAAM;KAAS,SAAS;IAAqC;IACxE,IAAI,MAAM,SAAS,MAAM,UAAU,MAAM,UAAU,MAAM,SAAS,MAAM,SACtE,OAAO;KAAE,MAAM;KAAS,SAAS,4BAA4B;IAAI;IACnE,iBAAiB;IACjB;GACF;GACA,SACE,OAAO;IAAE,MAAM;IAAS,SAAS,qBAAqB;GAAI;EAC9D;CACF;CAEA,OAAO;EAAE,MAAM;EAAM;EAAO;EAAS;EAAQ;EAAO;EAAM;EAAS;EAAU;CAAe;AAC9F"}
|
|
1
|
+
{"version":3,"file":"chat.js","names":[],"sources":["../src/chat/auto-update-cli.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// `zidane upgrade` subcommand — drop-in handler for consumer CLIs.\n//\n// Wraps `checkForUpdate` + `performSelfUpdate` + `performInPlaceSelfUpdate`\n// into a single function the host's `cli.ts` can call. The behavior layers:\n//\n// - no flags → check + run the package manager\n// - `--check` → check only, print the latest version + bail\n// - `--in-place` → skip the PM, download + atomic-rename the binary\n// - `--dry-run` → resolve everything but don't actually swap\n// - `--channel <tag>` → override dist-tag (defaults to `'latest'`)\n// - `--registry <url>`→ override the npm registry URL\n//\n// Pure I/O — writes to stdout/stderr, returns the exit code the caller\n// should pass to `process.exit`. No React, no OpenTUI; safe to call\n// before / instead of `runTui`.\n// ---------------------------------------------------------------------------\n\nimport {\n checkForUpdate,\n compareSemver,\n detectPackageManager,\n performInPlaceSelfUpdate,\n performSelfUpdate,\n resolvePlatformPackage,\n} from './auto-update'\n\nexport interface RunUpdateCommandOptions {\n /** Top-level package the user installs (e.g. `'zidane-tui'`). */\n packageName: string\n /** Inlined at build time. */\n currentVersion: string\n /** Args passed after `upgrade` (typically `process.argv.slice(3)`). */\n argv: readonly string[]\n /** Where to persist the TTL cache. Usually `paths.userDir`. */\n cacheDir?: string\n /** Default channel when `--channel` isn't passed. Defaults to `'latest'`. */\n defaultChannel?: string\n /**\n * Override the platform-package-name prefix used by `--in-place`.\n * Defaults to `'<packageName>-'`, matching the `zidane-tui-<key>` layout.\n */\n platformPackagePrefix?: string\n /** Override registry. Defaults to npmjs. */\n registry?: string\n /** stdout. Defaults to `process.stdout`. */\n stdout?: NodeJS.WritableStream\n /** stderr. Defaults to `process.stderr`. */\n stderr?: NodeJS.WritableStream\n}\n\nexport interface RunUpdateCommandResult {\n exitCode: number\n}\n\nconst UPGRADE_HELP = `Usage: zidane upgrade [options]\n\nUpdate the zidane CLI to the latest release.\n\nOptions:\n --check Print the latest version and exit (no install).\n --in-place Download the platform binary directly from npm\n and atomic-rename over the running binary.\n Skips the package manager. Refused on Volta.\n --dry-run Resolve everything but don't actually install.\n --channel <tag> dist-tag to query (default: latest).\n --registry <url> Override the npm registry.\n --package-manager <pm> Force npm | pnpm | yarn | bun | volta.\n --force Run the install even if we're already on latest,\n or the registry check failed.\n -h, --help Print this help.\n\nEnvironment:\n NO_UPDATE_NOTIFIER Silence the background check (set to \"1\").\n ZIDANE_NO_UPDATE Same, project-specific.\n`\n\n/**\n * Run the `upgrade` subcommand. Exit code contract:\n * - `0` — update succeeded, `--check` reported no update, or `--check`\n * reported an update (informational only).\n * - `1` — update failed (PM exit non-zero, in-place download failed,\n * registry returned non-2xx).\n * - `2` — argv parse error (unknown flag).\n */\nexport async function runUpdateCommand(options: RunUpdateCommandOptions): Promise<RunUpdateCommandResult> {\n const out = options.stdout ?? process.stdout\n const err = options.stderr ?? process.stderr\n const parsed = parseArgs(options.argv)\n if (parsed.kind === 'error') {\n err.write(`zidane upgrade: ${parsed.message}\\n`)\n err.write(UPGRADE_HELP)\n return { exitCode: 2 }\n }\n if (parsed.help) {\n out.write(UPGRADE_HELP)\n return { exitCode: 0 }\n }\n\n const channel = parsed.channel ?? options.defaultChannel ?? 'latest'\n const registry = parsed.registry ?? options.registry\n\n // Always force the check — user typed `upgrade`, env opt-outs shouldn't\n // get in the way.\n const status = await checkForUpdate({\n packageName: options.packageName,\n currentVersion: options.currentVersion,\n channel,\n registry,\n cacheDir: options.cacheDir,\n force: true,\n timeoutMs: 8000,\n })\n\n // `--check` is informational — degrade gracefully on registry errors\n // (offline laptop, restricted proxy) and exit 0 so the user can script\n // around it without quoting tricks.\n if (parsed.check) {\n if (status.source === 'error') {\n err.write(`Could not check \\`${channel}\\` (${status.error ?? 'unknown error'}). Current: v${options.currentVersion}.\\n`)\n return { exitCode: 0 }\n }\n if (!status.latest) {\n err.write(`Could not determine latest version on \\`${channel}\\`. Current: v${options.currentVersion}.\\n`)\n return { exitCode: 0 }\n }\n const cmp = compareSemver(status.latest, options.currentVersion)\n if (cmp > 0)\n out.write(`v${status.latest} is available on \\`${channel}\\` (current: v${options.currentVersion}).\\n`)\n else\n out.write(`Already on v${options.currentVersion} (latest on \\`${channel}\\` is v${status.latest}).\\n`)\n return { exitCode: 0 }\n }\n\n // Install path — a registry error means we don't KNOW if we need an\n // update. Refuse to spawn the PM blindly unless the user explicitly\n // asks via `--force`.\n if (status.source === 'error') {\n err.write(`zidane upgrade: registry check failed (${status.error ?? 'unknown error'})\\n`)\n if (!parsed.force) {\n err.write('Pass --force to attempt the install anyway.\\n')\n return { exitCode: 1 }\n }\n }\n\n if (status.latest && !parsed.force) {\n const cmp = compareSemver(status.latest, options.currentVersion)\n if (cmp <= 0) {\n out.write(`Already on v${options.currentVersion} (latest on \\`${channel}\\` is v${status.latest}).\\n`)\n return { exitCode: 0 }\n }\n }\n\n // ---------------------------------------------------------------------\n // In-place path\n // ---------------------------------------------------------------------\n\n if (parsed.inPlace) {\n const platformPkg = resolvePlatformPackage({\n prefix: options.platformPackagePrefix ?? `${options.packageName}-`,\n })\n if (!platformPkg) {\n err.write(`No prebuilt binary for ${process.platform}/${process.arch}. Run \\`${options.packageName}-upgrade\\` via your package manager instead.\\n`)\n return { exitCode: 1 }\n }\n out.write(`Downloading ${platformPkg}@${channel}…\\n`)\n const result = await performInPlaceSelfUpdate({\n packageName: platformPkg,\n channel,\n registry,\n dryRun: parsed.dryRun,\n })\n if (result.status === 'success') {\n const verb = parsed.dryRun ? 'Would install' : 'Installed'\n out.write(`${verb} v${result.installedVersion} at ${result.binaryPath}.\\n`)\n return { exitCode: 0 }\n }\n err.write(`In-place update failed: ${result.reason ?? 'unknown error'}\\n`)\n if (result.status === 'refused')\n err.write('Falling back to package-manager path (drop --in-place to retry).\\n')\n return { exitCode: 1 }\n }\n\n // ---------------------------------------------------------------------\n // Package-manager path\n // ---------------------------------------------------------------------\n\n const detected = detectPackageManager({ packageName: options.packageName, channel })\n if (detected.note)\n out.write(`${detected.note}\\n`)\n out.write(`Running: ${detected.argv.join(' ')}\\n`)\n if (parsed.dryRun)\n return { exitCode: 0 }\n\n const result = await performSelfUpdate({\n packageName: options.packageName,\n channel,\n packageManager: parsed.packageManager ?? 'auto',\n })\n if (result.spawnError) {\n err.write(`Failed to launch \\`${result.command.argv[0]}\\`: ${result.spawnError}\\n`)\n err.write('Is the package manager installed and on $PATH?\\n')\n return { exitCode: 1 }\n }\n return { exitCode: result.exitCode ?? 1 }\n}\n\n// ---------------------------------------------------------------------------\n// Argv parser — minimal, just enough to drop into the consumer's `cli.ts`.\n// We deliberately don't pull in commander/yargs for a 5-flag surface.\n// ---------------------------------------------------------------------------\n\ntype ParseResult\n = | {\n kind: 'ok'\n check: boolean\n inPlace: boolean\n dryRun: boolean\n force: boolean\n help: boolean\n channel?: string\n registry?: string\n packageManager?: 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta'\n }\n | { kind: 'error', message: string }\n\nfunction parseArgs(argv: readonly string[]): ParseResult {\n let check = false\n let inPlace = false\n let dryRun = false\n let force = false\n let help = false\n let channel: string | undefined\n let registry: string | undefined\n let packageManager: 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta' | undefined\n\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i]!\n switch (a) {\n case '--check': check = true; break\n case '--in-place':\n case '--inplace': inPlace = true; break\n case '--dry-run':\n case '--dryrun': dryRun = true; break\n case '--force': force = true; break\n case '-h':\n case '--help': help = true; break\n case '--channel':\n channel = argv[++i]\n if (!channel)\n return { kind: 'error', message: '--channel requires a value' }\n break\n case '--registry':\n registry = argv[++i]\n if (!registry)\n return { kind: 'error', message: '--registry requires a value' }\n break\n case '--package-manager':\n case '--pm': {\n const v = argv[++i]\n if (!v)\n return { kind: 'error', message: '--package-manager requires a value' }\n if (v !== 'npm' && v !== 'pnpm' && v !== 'yarn' && v !== 'bun' && v !== 'volta')\n return { kind: 'error', message: `unknown package manager: ${v}` }\n packageManager = v\n break\n }\n default:\n return { kind: 'error', message: `unknown argument: ${a}` }\n }\n }\n\n return { kind: 'ok', check, inPlace, dryRun, force, help, channel, registry, packageManager }\n}\n"],"mappings":";;;;;;;AAuDA,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BrB,eAAsB,iBAAiB,SAAmE;CACxG,MAAM,MAAM,QAAQ,UAAU,QAAQ;CACtC,MAAM,MAAM,QAAQ,UAAU,QAAQ;CACtC,MAAM,SAAS,UAAU,QAAQ,IAAI;CACrC,IAAI,OAAO,SAAS,SAAS;EAC3B,IAAI,MAAM,mBAAmB,OAAO,QAAQ,GAAG;EAC/C,IAAI,MAAM,YAAY;EACtB,OAAO,EAAE,UAAU,EAAE;CACvB;CACA,IAAI,OAAO,MAAM;EACf,IAAI,MAAM,YAAY;EACtB,OAAO,EAAE,UAAU,EAAE;CACvB;CAEA,MAAM,UAAU,OAAO,WAAW,QAAQ,kBAAkB;CAC5D,MAAM,WAAW,OAAO,YAAY,QAAQ;CAI5C,MAAM,SAAS,MAAM,eAAe;EAClC,aAAa,QAAQ;EACrB,gBAAgB,QAAQ;EACxB;EACA;EACA,UAAU,QAAQ;EAClB,OAAO;EACP,WAAW;CACb,CAAC;CAKD,IAAI,OAAO,OAAO;EAChB,IAAI,OAAO,WAAW,SAAS;GAC7B,IAAI,MAAM,qBAAqB,QAAQ,MAAM,OAAO,SAAS,gBAAgB,eAAe,QAAQ,eAAe,IAAI;GACvH,OAAO,EAAE,UAAU,EAAE;EACvB;E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KAAK,EAAE;IACjB,IAAI,CAAC,SACH,OAAO;KAAE,MAAM;KAAS,SAAS;IAA6B;IAChE;GACF,KAAK;IACH,WAAW,KAAK,EAAE;IAClB,IAAI,CAAC,UACH,OAAO;KAAE,MAAM;KAAS,SAAS;IAA8B;IACjE;GACF,KAAK;GACL,KAAK,QAAQ;IACX,MAAM,IAAI,KAAK,EAAE;IACjB,IAAI,CAAC,GACH,OAAO;KAAE,MAAM;KAAS,SAAS;IAAqC;IACxE,IAAI,MAAM,SAAS,MAAM,UAAU,MAAM,UAAU,MAAM,SAAS,MAAM,SACtE,OAAO;KAAE,MAAM;KAAS,SAAS,4BAA4B;IAAI;IACnE,iBAAiB;IACjB;GACF;GACA,SACE,OAAO;IAAE,MAAM;IAAS,SAAS,qBAAqB;GAAI;EAC9D;CACF;CAEA,OAAO;EAAE,MAAM;EAAM;EAAO;EAAS;EAAQ;EAAO;EAAM;EAAS;EAAU;CAAe;AAC9F"}
|
package/dist/eval.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { r as createProcessContext } from "./contexts-DHi8LPCp.js";
|
|
2
2
|
import { t as alwaysQuote } from "./shell-quote-BmnhZmdM.js";
|
|
3
|
-
import { a as headlessEventToJsonl, c as runHeadless } from "./headless-
|
|
4
|
-
import { a as createMemoryStore, t as createSession } from "./session-
|
|
3
|
+
import { a as headlessEventToJsonl, c as runHeadless } from "./headless-0O6HMNBQ.js";
|
|
4
|
+
import { a as createMemoryStore, t as createSession } from "./session-BDWZZaYa.js";
|
|
5
5
|
import { join, relative, resolve } from "node:path";
|
|
6
6
|
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
7
7
|
import { tmpdir } from "node:os";
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { p as toAnthropic, s as ensureToolResultPairing } from "./messages-
|
|
2
|
-
import { d as createAgent } from "./tools-
|
|
1
|
+
import { p as toAnthropic, s as ensureToolResultPairing } from "./messages-DEsLGBB9.js";
|
|
2
|
+
import { d as createAgent } from "./tools-DhzKzB1y.js";
|
|
3
3
|
import { r as createProcessContext } from "./contexts-DHi8LPCp.js";
|
|
4
4
|
import { n as assertResolvedMediaBlock, o as toolResultToText, r as documentBlockMarker } from "./types-DxHDaqN7.js";
|
|
5
5
|
import { t as audioFormatFromMediaType } from "./media-sniff-Bn76JxAu.js";
|
|
6
6
|
import { i as statsByModel } from "./stats-DAKBEKjc.js";
|
|
7
|
-
import { i as basic_default } from "./presets-
|
|
8
|
-
import { a as createMemoryStore, t as createSession } from "./session-
|
|
7
|
+
import { i as basic_default } from "./presets-HDIxliiq.js";
|
|
8
|
+
import { a as createMemoryStore, t as createSession } from "./session-BDWZZaYa.js";
|
|
9
9
|
//#region src/run-summary.ts
|
|
10
10
|
/**
|
|
11
11
|
* Build a run-summary collector. State is created fresh inside each
|
|
@@ -653,4 +653,4 @@ function installHeadlessEventAdapter(hooks, onEvent) {
|
|
|
653
653
|
//#endregion
|
|
654
654
|
export { headlessEventToJsonl as a, runHeadless as c, createRunSummaryCollector as d, formattedHeadlessTurnEventToJsonl as i, transcriptToOpenAIMessages as l, formatHeadlessResult as n, installHeadlessEventAdapter as o, formatHeadlessTurnEvent as r, providerTranscriptFormatForProvider as s, exitCodeForHeadlessResult as t, transcriptToProviderMessages as u };
|
|
655
655
|
|
|
656
|
-
//# sourceMappingURL=headless-
|
|
656
|
+
//# sourceMappingURL=headless-0O6HMNBQ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"headless-Bz1SpTB-.js","names":["basic"],"sources":["../src/run-summary.ts","../src/headless.ts"],"sourcesContent":["/**\n * Run summary collector — one JSON postmortem per `agent.run()`.\n *\n * `AgentStats` is great for billing and per-turn accounting but doesn't\n * carry a record of the *interesting* events that happened during a run\n * (errors, gate blocks, validation rejects, budget hits, MCP failures).\n * Reconstructing that from a hook stream after the fact is exactly the\n * kind of plumbing every consumer ends up re-implementing.\n *\n * This module ships:\n *\n * - {@link RunSummary} — a serializable shape that bundles totals,\n * per-model breakdown, and all the per-run incident lists.\n * - {@link createRunSummaryCollector} — installs hook listeners that\n * build up a {@link RunSummary} during the run and surfaces it on\n * `agent:done`. Calls an optional `onSummary` callback so the host can\n * forward to a log aggregator / DB / postmortem dashboard without\n * touching `agent.run()`'s return value.\n *\n * The collector is purely additive — it doesn't touch the agent loop,\n * doesn't change return shapes, and doesn't suppress any other hook\n * handlers. Drop it in alongside tracing / metrics / logging or use it\n * standalone when you only need the summary.\n */\n\nimport type { Hookable } from 'hookable'\nimport type { AgentHooks } from './agent'\nimport type { AgentStats } from './types'\nimport { statsByModel } from './stats'\n\n// ---------------------------------------------------------------------------\n// Public shape\n// ---------------------------------------------------------------------------\n\nexport interface RunSummaryTokens {\n input: number\n output: number\n cacheRead: number\n cacheCreation: number\n cost?: number\n /** First observable byte from the provider, ms from run start. */\n ttftMs?: number\n}\n\nexport interface RunSummaryByModel {\n modelId: string\n input: number\n output: number\n cacheRead: number\n cacheCreation: number\n cost: number\n turns: number\n}\n\nexport interface RunSummaryError {\n kind: 'stream' | 'tool' | 'mcp-tool' | 'mcp' | 'spawn'\n message: string\n errorType?: string\n turnId?: string\n callId?: string\n server?: string\n toolName?: string\n childId?: string\n statusCode?: number\n requestId?: string\n}\n\nexport interface RunSummaryBlock {\n callId: string\n toolName: string\n outcome: 'gate-block' | 'unknown' | 'invalid-input'\n reason?: string\n}\n\nexport interface RunSummaryValidation {\n callId: string\n toolName: string\n reason: string\n}\n\nexport interface RunSummaryBudget {\n kind: 'bytes' | 'tool-count'\n /** Tool name (for `'tool-count'`); absent for byte budgets. */\n toolName?: string\n /** `mode` for `'tool-count'`; absent for byte budgets. */\n mode?: 'steer' | 'block'\n observed: number\n limit: number\n turnId?: string\n}\n\nexport interface RunSummaryRepeatGuard {\n toolName: string\n /** Observed repeat count that tripped the guard. */\n count: number\n threshold: number\n action: 'block' | 'steer' | 'abort'\n turnId?: string\n}\n\n/**\n * Postmortem snapshot of one `agent.run()`. Strictly serializable — every\n * field round-trips through `JSON.stringify` / `JSON.parse` without loss\n * so a log aggregator can ingest it as-is.\n */\nexport interface RunSummary {\n runId?: string\n parentRunId?: string\n depth: number\n agentName?: string\n startedAt: number\n endedAt: number\n durationMs: number\n status: 'completed' | 'aborted'\n turns: number\n totals: RunSummaryTokens\n byModel: RunSummaryByModel[]\n errors: RunSummaryError[]\n blocks: RunSummaryBlock[]\n validationRejects: RunSummaryValidation[]\n budgetEvents: RunSummaryBudget[]\n /**\n * Repeat-guard escalations. An `action: 'steer'` entry means the tool still\n * executed and got a steering message appended to its result. An\n * `action: 'abort'` entry means the guard terminated the run via the agent's\n * AbortController (the run finalizes as `'aborted'`).\n */\n repeatGuardEvents: RunSummaryRepeatGuard[]\n /** Counts of pairing repairs, keyed by repair mode. */\n pairingRepairs: Record<string, number>\n /**\n * Postmortem snapshots of child runs that bubbled their stats up via\n * `spawn:complete`. Only present when the run actually spawned.\n */\n children?: RunSummary[]\n}\n\n// ---------------------------------------------------------------------------\n// Collector\n// ---------------------------------------------------------------------------\n\nexport interface RunSummaryCollectorOptions {\n /**\n * Called with the assembled {@link RunSummary} on every `agent:done`.\n * Synchronous — heavy I/O should be deferred (e.g. via `setImmediate`).\n */\n onSummary?: (summary: RunSummary) => void\n}\n\nexport interface RunSummaryCollector {\n /** Install the collector's hook handlers. Returns an uninstall fn. */\n install: (hooks: Hookable<AgentHooks>) => () => void\n /** Most-recent summary; `undefined` until the first `agent:done` fires. */\n latest: () => RunSummary | undefined\n}\n\n/**\n * Build a run-summary collector. State is created fresh inside each\n * `install()` call, so a single collector instance can be installed\n * across multiple agents without attribution cross-talk. `latest()`\n * returns the most-recent summary across **any** install — install\n * per-agent collectors if you need separate post-run snapshots.\n *\n * @example\n * ```ts\n * const collector = createRunSummaryCollector({\n * onSummary: s => console.log(JSON.stringify(s)),\n * })\n * const uninstall = collector.install(agent.hooks)\n * try { await agent.run({ prompt }) }\n * finally { uninstall() }\n * ```\n */\nexport function createRunSummaryCollector(\n options: RunSummaryCollectorOptions = {},\n): RunSummaryCollector {\n let last: RunSummary | undefined\n\n return {\n latest: () => last,\n install(hooks: Hookable<AgentHooks>): () => void {\n // Per-run in-progress accumulators. The hookable bus serializes\n // agent.run lifecycles per agent — we reset between runs on\n // `agent:start` and consume on `agent:done`.\n let runId: string | undefined\n let parentRunId: string | undefined\n let depth = 0\n let agentName: string | undefined\n let startedAt = Date.now()\n let aborted = false\n const errors: RunSummaryError[] = []\n const blocks: RunSummaryBlock[] = []\n const validationRejects: RunSummaryValidation[] = []\n const budgetEvents: RunSummaryBudget[] = []\n const repeatGuardEvents: RunSummaryRepeatGuard[] = []\n const pairingRepairs: Record<string, number> = {}\n const children: RunSummary[] = []\n\n function resetForNewRun(): void {\n aborted = false\n errors.length = 0\n blocks.length = 0\n validationRejects.length = 0\n budgetEvents.length = 0\n repeatGuardEvents.length = 0\n for (const k of Object.keys(pairingRepairs))\n delete pairingRepairs[k]\n children.length = 0\n }\n\n const unregisters: Array<() => void> = []\n\n unregisters.push(hooks.hook('agent:start', (ctx) => {\n resetForNewRun()\n runId = ctx.runId\n parentRunId = ctx.parentRunId\n depth = ctx.depth\n agentName = ctx.agentName\n startedAt = ctx.startedAt\n }))\n\n unregisters.push(hooks.hook('agent:abort', () => {\n aborted = true\n }))\n\n unregisters.push(hooks.hook('stream:error', (ctx) => {\n const msg = ctx.err instanceof Error ? ctx.err.message : String(ctx.err)\n const errorType = ctx.err instanceof Error ? ctx.err.name : 'unknown'\n errors.push({\n kind: 'stream',\n message: msg,\n errorType,\n turnId: ctx.turnId,\n ...(ctx.statusCode !== undefined ? { statusCode: ctx.statusCode } : {}),\n ...(ctx.requestId !== undefined ? { requestId: ctx.requestId } : {}),\n })\n }))\n\n unregisters.push(hooks.hook('tool:error', (ctx) => {\n errors.push({\n kind: 'tool',\n message: ctx.error.message,\n errorType: ctx.error.name,\n turnId: ctx.turnId,\n callId: ctx.callId,\n toolName: ctx.name,\n })\n }))\n\n unregisters.push(hooks.hook('mcp:tool:error', (ctx) => {\n errors.push({\n kind: 'mcp-tool',\n message: ctx.error.message,\n errorType: ctx.error.name,\n turnId: ctx.turnId,\n callId: ctx.callId,\n server: ctx.server,\n toolName: ctx.displayName,\n })\n }))\n\n unregisters.push(hooks.hook('mcp:error', (ctx) => {\n errors.push({\n kind: 'mcp',\n message: ctx.error.message,\n errorType: ctx.error.name,\n server: ctx.name,\n })\n }))\n\n unregisters.push(hooks.hook('spawn:error', (ctx) => {\n errors.push({\n kind: 'spawn',\n message: ctx.error.message,\n errorType: ctx.error.name,\n childId: ctx.id,\n })\n }))\n\n unregisters.push(hooks.hook('tool:dispatched', (ctx) => {\n if (ctx.outcome === 'gate-block' || ctx.outcome === 'unknown' || ctx.outcome === 'invalid-input') {\n blocks.push({\n callId: ctx.callId,\n toolName: ctx.name,\n outcome: ctx.outcome,\n ...(ctx.reason ? { reason: ctx.reason } : {}),\n })\n }\n }))\n\n unregisters.push(hooks.hook('validation:reject', (ctx) => {\n validationRejects.push({\n callId: ctx.callId,\n toolName: ctx.name,\n reason: ctx.reason,\n })\n }))\n\n unregisters.push(hooks.hook('budget:exceeded', (ctx) => {\n budgetEvents.push({\n kind: 'bytes',\n observed: ctx.bytes,\n limit: ctx.budget,\n turnId: ctx.turnId,\n })\n }))\n\n unregisters.push(hooks.hook('tool-budget:exceeded', (ctx) => {\n budgetEvents.push({\n kind: 'tool-count',\n toolName: ctx.tool,\n mode: ctx.mode,\n observed: ctx.count,\n limit: ctx.max,\n turnId: ctx.turnId,\n })\n }))\n\n unregisters.push(hooks.hook('repeat-guard:exceeded', (ctx) => {\n repeatGuardEvents.push({\n toolName: ctx.tool,\n count: ctx.count,\n threshold: ctx.threshold,\n action: ctx.action,\n turnId: ctx.turnId,\n })\n }))\n\n unregisters.push(hooks.hook('pairing:repair', (ctx) => {\n pairingRepairs[ctx.mode] = (pairingRepairs[ctx.mode] ?? 0) + 1\n }))\n\n unregisters.push(hooks.hook('agent:done', (stats) => {\n const endedAt = Date.now()\n\n // Build per-model rollup via the existing `statsByModel` helper\n // so we stay in lockstep with how the rest of the harness\n // attributes cost and tokens by model id.\n const byModel: RunSummaryByModel[] = []\n for (const [modelId, usage] of statsByModel(stats)) {\n byModel.push({\n modelId,\n input: usage.input,\n output: usage.output,\n cacheRead: usage.cacheRead,\n cacheCreation: usage.cacheCreation,\n cost: usage.cost,\n turns: usage.turns,\n })\n }\n\n // Flatten child stats into nested summaries. We don't have the\n // child's full event lists here (those landed on the child's\n // own hooks), so the nested entry is a minimal totals-only\n // record — enough for a flat per-run audit trail; consumers\n // wanting full per-child event lists install a collector on\n // each subagent.\n for (const c of stats.children ?? []) {\n children.push(minimalSummaryFromStats(c.stats, {\n depth: c.depth ?? depth + 1,\n status: c.status === 'aborted' ? 'aborted' : 'completed',\n }))\n }\n\n const summary: RunSummary = {\n ...(runId ? { runId } : {}),\n ...(parentRunId ? { parentRunId } : {}),\n depth,\n ...(agentName ? { agentName } : {}),\n startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n status: aborted ? 'aborted' : 'completed',\n turns: stats.turns,\n totals: buildTotals(stats),\n byModel,\n errors: errors.slice(),\n blocks: blocks.slice(),\n validationRejects: validationRejects.slice(),\n budgetEvents: budgetEvents.slice(),\n repeatGuardEvents: repeatGuardEvents.slice(),\n pairingRepairs: { ...pairingRepairs },\n ...(children.length > 0 ? { children: children.slice() } : {}),\n }\n\n last = summary\n try {\n options.onSummary?.(summary)\n }\n catch {\n // Sink errors are not the collector's concern.\n }\n }))\n\n let disposed = false\n return function uninstall() {\n if (disposed)\n return\n disposed = true\n for (const un of unregisters) {\n try {\n un()\n }\n catch { /* ignore */ }\n }\n }\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction buildTotals(stats: AgentStats): RunSummaryTokens {\n return {\n input: stats.totalIn,\n output: stats.totalOut,\n cacheRead: stats.totalCacheRead,\n cacheCreation: stats.totalCacheCreation,\n ...(typeof stats.cost === 'number' ? { cost: stats.cost } : {}),\n ...(typeof stats.timeTillFirstTokenMs === 'number' ? { ttftMs: stats.timeTillFirstTokenMs } : {}),\n }\n}\n\nfunction minimalSummaryFromStats(\n stats: AgentStats,\n meta: { depth: number, status: 'completed' | 'aborted' },\n): RunSummary {\n const byModel: RunSummaryByModel[] = []\n for (const [modelId, usage] of statsByModel(stats)) {\n byModel.push({\n modelId,\n input: usage.input,\n output: usage.output,\n cacheRead: usage.cacheRead,\n cacheCreation: usage.cacheCreation,\n cost: usage.cost,\n turns: usage.turns,\n })\n }\n const children: RunSummary[] = []\n for (const c of stats.children ?? []) {\n children.push(minimalSummaryFromStats(c.stats, {\n depth: c.depth ?? meta.depth + 1,\n status: c.status === 'aborted' ? 'aborted' : 'completed',\n }))\n }\n return {\n depth: meta.depth,\n startedAt: 0,\n endedAt: 0,\n durationMs: stats.elapsed,\n status: meta.status,\n turns: stats.turns,\n totals: buildTotals(stats),\n byModel,\n errors: [],\n blocks: [],\n validationRejects: [],\n budgetEvents: [],\n repeatGuardEvents: [],\n pairingRepairs: {},\n ...(children.length > 0 ? { children } : {}),\n }\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 { Hookable } from 'hookable'\nimport type { AgentHooks, AgentOptions } from './agent'\nimport type { ExecutionContext } from './contexts'\nimport type { Provider } from './providers'\nimport type { RunSummary } from './run-summary'\nimport type { Session, SessionStore } from './session'\nimport type { PairingRepair } from './session/messages'\nimport type { ToolDef } from './tools'\nimport type {\n AgentStats,\n McpServerConfig,\n PromptPart,\n SessionContentBlock,\n SessionTurn,\n ThinkingLevel,\n ToolResultContent,\n ToolResultDocumentContent,\n TurnFinishReason,\n} from './types'\nimport { createAgent } from './agent'\nimport { createProcessContext } from './contexts'\nimport { basic } from './presets'\nimport { createRunSummaryCollector } from './run-summary'\nimport { createMemoryStore, createSession, toAnthropic } from './session'\nimport { ensureToolResultPairing } from './session/messages'\nimport { audioFormatFromMediaType } from './tools/media-sniff'\nimport { assertResolvedMediaBlock, documentBlockMarker, toolResultToText } from './types'\n\n// ---------------------------------------------------------------------------\n// Public shapes\n// ---------------------------------------------------------------------------\n\nexport type HeadlessStatus = 'completed' | 'aborted' | 'error' | 'timeout'\n\nexport interface HeadlessUsage {\n input: number\n output: number\n cacheRead: number\n cacheCreation: number\n /** Cumulative USD cost when the provider/registry could price the run. */\n cost?: number\n}\n\nexport interface HeadlessErrorInfo {\n message: string\n /** Typed-error class name (`AgentAbortedError`, `AgentContextExceededError`, …). */\n type: string\n}\n\n/**\n * Strictly JSON-serializable postmortem of one headless run. Everything an RL\n * reward function needs: the final answer (`finalText`), the verifiable\n * structured output (`output`, present iff a `schema` was set), usage/turns,\n * and the lossless `transcript` (the SFT training data).\n */\nexport interface HeadlessResult {\n status: HeadlessStatus\n /** Concatenated text of the last assistant turn that produced any text. */\n finalText: string\n /** Schema-enforced structured output (only when `opts.schema` is set). */\n output?: Record<string, unknown>\n usage: HeadlessUsage\n turns: number\n durationMs: number\n /** Total `tool_call` blocks across the whole transcript. */\n numToolCalls: number\n /** Finish reason of the final turn that reported one. */\n finishReason?: TurnFinishReason\n error?: HeadlessErrorInfo\n sessionId: string\n /** Incident postmortem (errors, gate blocks, budget events) via run-summary. */\n summary?: RunSummary\n /** Lossless transcript — raw `session.turns`. Thinking stripped when `includeThinking: false`. */\n transcript: SessionTurn[]\n}\n\nexport type HeadlessOutputFormat = 'zidane' | 'provider'\n\nexport type ProviderTranscriptFormat = 'anthropic' | 'openai'\n\nexport type FormattedHeadlessResult\n = | HeadlessResult\n | unknown[]\n\nexport type FormattedHeadlessTurnEvent\n = | Extract<HeadlessEvent, { type: 'turn' }>\n | unknown[]\n\nexport function exitCodeForHeadlessResult(result: HeadlessResult): number {\n switch (result.status) {\n case 'completed': return 0\n case 'timeout': return 124\n case 'aborted': return 130\n case 'error':\n default: return 1\n }\n}\n\n/**\n * Live event union — the in-process equivalent of a `stream-json` line. Every\n * member is JSON-serializable; render to JSONL with {@link headlessEventToJsonl}.\n */\nexport type HeadlessEvent\n = | { type: 'start', runId: string, provider?: string }\n | { type: 'text', delta: string }\n | { type: 'thinking', delta: string }\n | { type: 'tool_call', callId: string, name: string, input: Record<string, unknown> }\n | { type: 'tool_result', callId: string, name: string, output: string, isError: boolean }\n | { type: 'turn', index: number, turn: SessionTurn }\n | { type: 'spawn', event: 'before' | 'complete' | 'error', id: string, info?: Record<string, unknown> }\n | { type: 'error', message: string, errorType?: string }\n | { type: 'result', result: HeadlessResult }\n\n/** Serialize one event as a newline-terminated JSON line (stream-json). */\nexport function headlessEventToJsonl(event: HeadlessEvent): string {\n return `${JSON.stringify(event)}\\n`\n}\n\nexport function formattedHeadlessTurnEventToJsonl(event: FormattedHeadlessTurnEvent): string {\n return `${JSON.stringify(event)}\\n`\n}\n\nexport function providerTranscriptFormatForProvider(providerName: string): ProviderTranscriptFormat {\n return providerName === 'anthropic' ? 'anthropic' : 'openai'\n}\n\nexport function transcriptToProviderMessages(\n turns: SessionTurn[],\n providerName: string,\n): unknown[] {\n const format = providerTranscriptFormatForProvider(providerName)\n if (format === 'anthropic') {\n return turns\n .filter((turn): turn is SessionTurn & { role: 'user' | 'assistant' } => turn.role === 'user' || turn.role === 'assistant')\n .map(turn => toAnthropic({ role: turn.role, content: turn.content }))\n }\n return transcriptToOpenAIMessages(turns, { strictToolPairing: false })\n}\n\nexport function formatHeadlessResult(\n result: HeadlessResult,\n options: { format: HeadlessOutputFormat, providerName: string },\n): FormattedHeadlessResult {\n if (options.format === 'zidane')\n return result\n return transcriptToProviderMessages(result.transcript, options.providerName)\n}\n\nexport function formatHeadlessTurnEvent(\n event: Extract<HeadlessEvent, { type: 'turn' }>,\n options: { format: HeadlessOutputFormat, providerName: string },\n): FormattedHeadlessTurnEvent {\n if (options.format === 'zidane')\n return event\n return transcriptToProviderMessages([event.turn], options.providerName)\n}\n\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?: string\n /** Override the preset system prompt for this run. */\n system?: string\n thinking?: ThinkingLevel\n maxTurns?: number\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 mcpServers?: McpServerConfig[]\n skills?: AgentOptions['skills']\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 */\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 const behavior: NonNullable<AgentOptions['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 ...basic,\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 })\n\n const collector = createRunSummaryCollector()\n const uninstallSummary = collector.install(agent.hooks)\n const uninstallEvents = opts.onEvent ? installHeadlessEventAdapter(agent.hooks, opts.onEvent) : 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 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\n// ---------------------------------------------------------------------------\n// Transcript → OpenAI chat messages (SFT-ready)\n// ---------------------------------------------------------------------------\n\nexport interface OpenAIChatMessage {\n role: 'system' | 'user' | 'assistant' | 'tool'\n content: string | null | OpenAIChatContentPart[]\n tool_calls?: Array<{ id: string, type: 'function', function: { name: string, arguments: string } }>\n tool_call_id?: string\n}\n\nexport type OpenAIChatContentPart\n = | { type: 'text', text: string }\n | { type: 'image_url', image_url: { url: string } }\n | { type: 'input_audio', input_audio: { data: string, format: string } }\n | { type: 'video_url', video_url: { url: string } }\n\n/**\n * Convert raw `session.turns` into standard OpenAI chat-completion messages:\n * assistant turns carry `tool_calls`, and each `tool_result` becomes its own\n * `role: 'tool'` message. This is the drop-in shape for an SFT renderer —\n * unlike `toOpenAI` (session/messages.ts), which emits an internal `_tag`\n * envelope meant for re-sending to a provider, not for training data.\n *\n * Fails closed on corrupt raw turns instead of fabricating tool results; silent\n * placeholders would create structurally-valid but semantically-poisoned SFT\n * examples.\n */\nexport function transcriptToOpenAIMessages(\n turns: SessionTurn[],\n options: { strictToolPairing?: boolean } = {},\n): OpenAIChatMessage[] {\n const { strictToolPairing = true } = options\n const messages: OpenAIChatMessage[] = []\n let chunk: Array<{ role: 'user' | 'assistant', content: SessionContentBlock[] }> = []\n const flushChunk = () => {\n if (chunk.length === 0)\n return\n let paired = chunk\n if (strictToolPairing) {\n const repairs: PairingRepair[] = []\n paired = ensureToolResultPairing(chunk, { onRepair: repair => repairs.push(repair) })\n if (repairs.length > 0) {\n throw new Error(\n `Cannot convert transcript to OpenAI messages: tool pairing repair required (${repairs.map(r => r.mode).join(', ')})`,\n )\n }\n }\n for (const msg of paired)\n pushOpenAIChatMessage(messages, msg)\n chunk = []\n }\n\n for (const turn of turns) {\n if (turn.role === 'system') {\n flushChunk()\n messages.push({ role: 'system', content: textOf(turn.content) })\n continue\n }\n chunk.push({ role: turn.role, content: turn.content })\n }\n flushChunk()\n\n return messages\n}\n\nfunction pushOpenAIChatMessage(messages: OpenAIChatMessage[], msg: { role: 'user' | 'assistant', content: SessionContentBlock[] }): void {\n const text = textOf(msg.content)\n\n if (msg.role === 'assistant') {\n const toolCalls = msg.content.filter((b): b is ToolCallBlock => b.type === 'tool_call')\n const out: OpenAIChatMessage = { role: 'assistant', content: text || null }\n if (toolCalls.length > 0) {\n out.tool_calls = toolCalls.map(b => ({\n id: b.id,\n type: 'function' as const,\n function: { name: b.name, arguments: JSON.stringify(b.input) },\n }))\n }\n messages.push(out)\n return\n }\n\n // user turn — may carry prompt text/images and/or tool_result blocks\n const userParts = contentPartsFromBlocks(msg.content)\n if (userParts.length > 0)\n messages.push({ role: 'user', content: simplifyOpenAIContent(userParts) })\n\n for (const tr of msg.content.filter((b): b is ToolResultBlock => b.type === 'tool_result')) {\n const { text, images } = summarizeToolResultForOpenAI(tr.output)\n if (images.length === 0) {\n messages.push({ role: 'tool', tool_call_id: tr.callId, content: text })\n continue\n }\n\n const noun = images.length === 1 ? 'image' : 'images'\n const marker = `[${images.length} ${noun} attached — see next user message]`\n messages.push({\n role: 'tool',\n tool_call_id: tr.callId,\n content: text.length > 0 ? `${text}\\n\\n${marker}` : marker,\n })\n messages.push({\n role: 'user',\n content: [\n ...images.map(toOpenAIImagePart),\n { type: 'text', text: `(${noun} returned by tool call ${tr.callId})` },\n ],\n })\n }\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\ntype TextBlock = Extract<SessionContentBlock, { type: 'text' }>\ntype ToolCallBlock = Extract<SessionContentBlock, { type: 'tool_call' }>\ntype ToolResultBlock = Extract<SessionContentBlock, { type: 'tool_result' }>\n\nfunction noop(): void {}\n\nfunction textOf(content: SessionContentBlock[]): string {\n return content.filter((b): b is TextBlock => b.type === 'text').map(b => b.text).join('')\n}\n\nfunction contentPartsFromBlocks(content: SessionContentBlock[]): OpenAIChatContentPart[] {\n const parts: OpenAIChatContentPart[] = []\n for (const block of content) {\n if (block.type === 'image') {\n assertResolvedMediaBlock(block, 'OpenAI transcript messages')\n parts.push(toOpenAIImagePart(block))\n }\n else if (block.type === 'audio') {\n parts.push({ type: 'input_audio', input_audio: { data: block.data, format: audioFormatFromMediaType(block.mediaType) } })\n }\n else if (block.type === 'video') {\n parts.push({ type: 'video_url', video_url: { url: `data:${block.mediaType};base64,${block.data}` } })\n }\n else if (block.type === 'document') {\n assertResolvedMediaBlock(block, 'OpenAI transcript messages')\n parts.push({ type: 'text', text: documentMarker(block) })\n }\n else if (block.type === 'text' && block.text.length > 0) {\n parts.push({ type: 'text', text: block.text })\n }\n }\n return parts\n}\n\nfunction simplifyOpenAIContent(parts: OpenAIChatContentPart[]): string | OpenAIChatContentPart[] {\n if (parts.length === 1 && parts[0].type === 'text')\n return parts[0].text\n return parts\n}\n\nfunction toOpenAIImagePart(image: { mediaType: string, data: string }): OpenAIChatContentPart {\n return {\n type: 'image_url',\n image_url: { url: `data:${image.mediaType};base64,${image.data}` },\n }\n}\n\nfunction summarizeToolResultForOpenAI(output: string | ToolResultContent[]): {\n text: string\n images: Array<{ mediaType: string, data: string }>\n} {\n if (typeof output === 'string')\n return { text: output, images: [] }\n\n const texts: string[] = []\n const images: Array<{ mediaType: string, data: string }> = []\n for (const block of output) {\n if (block.type === 'text') {\n texts.push(block.text)\n }\n else if (block.type === 'image') {\n assertResolvedMediaBlock(block, 'OpenAI transcript messages')\n images.push({ mediaType: block.mediaType, data: block.data })\n }\n else if (block.type === 'audio') {\n texts.push(`[audio: ${block.mediaType}]`)\n }\n else if (block.type === 'video') {\n texts.push(`[video: ${block.mediaType}]`)\n }\n else {\n assertResolvedMediaBlock(block, 'OpenAI transcript messages')\n texts.push(documentMarker(block))\n }\n }\n return { text: texts.join('\\n'), images }\n}\n\nfunction documentMarker(doc: ToolResultDocumentContent): string {\n return documentBlockMarker(doc, 'document omitted')\n}\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\nexport function installHeadlessEventAdapter(\n hooks: Hookable<AgentHooks>,\n onEvent: (event: HeadlessEvent) => void,\n): () => void {\n const unregs: Array<() => void> = []\n const emittedTurnIds = new Set<string>()\n const emit = (event: HeadlessEvent): void => {\n try {\n onEvent(event)\n }\n catch {\n // A consumer's sink throwing is not the adapter's concern.\n }\n }\n\n unregs.push(hooks.hook('agent:start', ctx => emit({\n type: 'start',\n runId: ctx.runId,\n ...(ctx.providerName ? { provider: ctx.providerName } : {}),\n })))\n unregs.push(hooks.hook('stream:text', ctx => emit({ type: 'text', delta: ctx.delta })))\n unregs.push(hooks.hook('stream:thinking', ctx => emit({ type: 'thinking', delta: ctx.delta })))\n unregs.push(hooks.hook('tool:before', ctx => emit({\n type: 'tool_call',\n callId: ctx.callId,\n name: ctx.name,\n input: ctx.input,\n })))\n unregs.push(hooks.hook('tool:after', ctx => emit({\n type: 'tool_result',\n callId: ctx.callId,\n name: ctx.name,\n output: toolResultToText(ctx.result),\n isError: false,\n })))\n unregs.push(hooks.hook('tool:error', ctx => emit({\n type: 'tool_result',\n callId: ctx.callId,\n name: ctx.name,\n output: ctx.error.message,\n isError: true,\n })))\n unregs.push(hooks.hook('session:turns', (ctx) => {\n const startIndex = ctx.count - ctx.turns.length\n ctx.turns.forEach((turn, i) => {\n if (emittedTurnIds.has(turn.id))\n return\n emittedTurnIds.add(turn.id)\n emit({ type: 'turn', index: startIndex + i, turn })\n })\n }))\n unregs.push(hooks.hook('spawn:before', ctx => emit({ type: 'spawn', event: 'before', id: ctx.id })))\n unregs.push(hooks.hook('spawn:complete', ctx => emit({\n type: 'spawn',\n event: 'complete',\n id: ctx.id,\n info: { status: ctx.status ?? 'completed' },\n })))\n unregs.push(hooks.hook('spawn:error', ctx => emit({\n type: 'spawn',\n event: 'error',\n id: ctx.id,\n info: { message: ctx.error.message },\n })))\n unregs.push(hooks.hook('stream:error', ctx => emit({\n type: 'error',\n message: ctx.err instanceof Error ? ctx.err.message : String(ctx.err),\n ...(ctx.err instanceof Error ? { errorType: ctx.err.name } : {}),\n })))\n\n return () => {\n for (const un of unregs) {\n try {\n un()\n }\n catch {\n // ignore\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6KA,SAAgB,0BACd,UAAsC,CAAC,GAClB;CACrB,IAAI;CAEJ,OAAO;EACL,cAAc;EACd,QAAQ,OAAyC;GAI/C,IAAI;GACJ,IAAI;GACJ,IAAI,QAAQ;GACZ,IAAI;GACJ,IAAI,YAAY,KAAK,IAAI;GACzB,IAAI,UAAU;GACd,MAAM,SAA4B,CAAC;GACnC,MAAM,SAA4B,CAAC;GACnC,MAAM,oBAA4C,CAAC;GACnD,MAAM,eAAmC,CAAC;GAC1C,MAAM,oBAA6C,CAAC;GACpD,MAAM,iBAAyC,CAAC;GAChD,MAAM,WAAyB,CAAC;GAEhC,SAAS,iBAAuB;IAC9B,UAAU;IACV,OAAO,SAAS;IAChB,OAAO,SAAS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K;EAChD,MAAM;EACN,OAAO;EACP,IAAI,IAAI;EACR,MAAM,EAAE,SAAS,IAAI,MAAM,QAAQ;CACrC,CAAC,CAAC,CAAC;CACH,OAAO,KAAK,MAAM,KAAK,iBAAgB,QAAO,KAAK;EACjD,MAAM;EACN,SAAS,IAAI,eAAe,QAAQ,IAAI,IAAI,UAAU,OAAO,IAAI,GAAG;EACpE,GAAI,IAAI,eAAe,QAAQ,EAAE,WAAW,IAAI,IAAI,KAAK,IAAI,CAAC;CAChE,CAAC,CAAC,CAAC;CAEH,aAAa;EACX,KAAK,MAAM,MAAM,QACf,IAAI;GACF,GAAG;EACL,QACM,CAEN;CAEJ;AACF"}
|
|
1
|
+
{"version":3,"file":"headless-0O6HMNBQ.js","names":["basic"],"sources":["../src/run-summary.ts","../src/headless.ts"],"sourcesContent":["/**\n * Run summary collector — one JSON postmortem per `agent.run()`.\n *\n * `AgentStats` is great for billing and per-turn accounting but doesn't\n * carry a record of the *interesting* events that happened during a run\n * (errors, gate blocks, validation rejects, budget hits, MCP failures).\n * Reconstructing that from a hook stream after the fact is exactly the\n * kind of plumbing every consumer ends up re-implementing.\n *\n * This module ships:\n *\n * - {@link RunSummary} — a serializable shape that bundles totals,\n * per-model breakdown, and all the per-run incident lists.\n * - {@link createRunSummaryCollector} — installs hook listeners that\n * build up a {@link RunSummary} during the run and surfaces it on\n * `agent:done`. Calls an optional `onSummary` callback so the host can\n * forward to a log aggregator / DB / postmortem dashboard without\n * touching `agent.run()`'s return value.\n *\n * The collector is purely additive — it doesn't touch the agent loop,\n * doesn't change return shapes, and doesn't suppress any other hook\n * handlers. Drop it in alongside tracing / metrics / logging or use it\n * standalone when you only need the summary.\n */\n\nimport type { Hookable } from 'hookable'\nimport type { AgentHooks } from './agent'\nimport type { AgentStats } from './types'\nimport { statsByModel } from './stats'\n\n// ---------------------------------------------------------------------------\n// Public shape\n// ---------------------------------------------------------------------------\n\nexport interface RunSummaryTokens {\n input: number\n output: number\n cacheRead: number\n cacheCreation: number\n cost?: number\n /** First observable byte from the provider, ms from run start. */\n ttftMs?: number\n}\n\nexport interface RunSummaryByModel {\n modelId: string\n input: number\n output: number\n cacheRead: number\n cacheCreation: number\n cost: number\n turns: number\n}\n\nexport interface RunSummaryError {\n kind: 'stream' | 'tool' | 'mcp-tool' | 'mcp' | 'spawn'\n message: string\n errorType?: string\n turnId?: string\n callId?: string\n server?: string\n toolName?: string\n childId?: string\n statusCode?: number\n requestId?: string\n}\n\nexport interface RunSummaryBlock {\n callId: string\n toolName: string\n outcome: 'gate-block' | 'unknown' | 'invalid-input'\n reason?: string\n}\n\nexport interface RunSummaryValidation {\n callId: string\n toolName: string\n reason: string\n}\n\nexport interface RunSummaryBudget {\n kind: 'bytes' | 'tool-count'\n /** Tool name (for `'tool-count'`); absent for byte budgets. */\n toolName?: string\n /** `mode` for `'tool-count'`; absent for byte budgets. */\n mode?: 'steer' | 'block'\n observed: number\n limit: number\n turnId?: string\n}\n\nexport interface RunSummaryRepeatGuard {\n toolName: string\n /** Observed repeat count that tripped the guard. */\n count: number\n threshold: number\n action: 'block' | 'steer' | 'abort'\n turnId?: string\n}\n\n/**\n * Postmortem snapshot of one `agent.run()`. Strictly serializable — every\n * field round-trips through `JSON.stringify` / `JSON.parse` without loss\n * so a log aggregator can ingest it as-is.\n */\nexport interface RunSummary {\n runId?: string\n parentRunId?: string\n depth: number\n agentName?: string\n startedAt: number\n endedAt: number\n durationMs: number\n status: 'completed' | 'aborted'\n turns: number\n totals: RunSummaryTokens\n byModel: RunSummaryByModel[]\n errors: RunSummaryError[]\n blocks: RunSummaryBlock[]\n validationRejects: RunSummaryValidation[]\n budgetEvents: RunSummaryBudget[]\n /**\n * Repeat-guard escalations. An `action: 'steer'` entry means the tool still\n * executed and got a steering message appended to its result. An\n * `action: 'abort'` entry means the guard terminated the run via the agent's\n * AbortController (the run finalizes as `'aborted'`).\n */\n repeatGuardEvents: RunSummaryRepeatGuard[]\n /** Counts of pairing repairs, keyed by repair mode. */\n pairingRepairs: Record<string, number>\n /**\n * Postmortem snapshots of child runs that bubbled their stats up via\n * `spawn:complete`. Only present when the run actually spawned.\n */\n children?: RunSummary[]\n}\n\n// ---------------------------------------------------------------------------\n// Collector\n// ---------------------------------------------------------------------------\n\nexport interface RunSummaryCollectorOptions {\n /**\n * Called with the assembled {@link RunSummary} on every `agent:done`.\n * Synchronous — heavy I/O should be deferred (e.g. via `setImmediate`).\n */\n onSummary?: (summary: RunSummary) => void\n}\n\nexport interface RunSummaryCollector {\n /** Install the collector's hook handlers. Returns an uninstall fn. */\n install: (hooks: Hookable<AgentHooks>) => () => void\n /** Most-recent summary; `undefined` until the first `agent:done` fires. */\n latest: () => RunSummary | undefined\n}\n\n/**\n * Build a run-summary collector. State is created fresh inside each\n * `install()` call, so a single collector instance can be installed\n * across multiple agents without attribution cross-talk. `latest()`\n * returns the most-recent summary across **any** install — install\n * per-agent collectors if you need separate post-run snapshots.\n *\n * @example\n * ```ts\n * const collector = createRunSummaryCollector({\n * onSummary: s => console.log(JSON.stringify(s)),\n * })\n * const uninstall = collector.install(agent.hooks)\n * try { await agent.run({ prompt }) }\n * finally { uninstall() }\n * ```\n */\nexport function createRunSummaryCollector(\n options: RunSummaryCollectorOptions = {},\n): RunSummaryCollector {\n let last: RunSummary | undefined\n\n return {\n latest: () => last,\n install(hooks: Hookable<AgentHooks>): () => void {\n // Per-run in-progress accumulators. The hookable bus serializes\n // agent.run lifecycles per agent — we reset between runs on\n // `agent:start` and consume on `agent:done`.\n let runId: string | undefined\n let parentRunId: string | undefined\n let depth = 0\n let agentName: string | undefined\n let startedAt = Date.now()\n let aborted = false\n const errors: RunSummaryError[] = []\n const blocks: RunSummaryBlock[] = []\n const validationRejects: RunSummaryValidation[] = []\n const budgetEvents: RunSummaryBudget[] = []\n const repeatGuardEvents: RunSummaryRepeatGuard[] = []\n const pairingRepairs: Record<string, number> = {}\n const children: RunSummary[] = []\n\n function resetForNewRun(): void {\n aborted = false\n errors.length = 0\n blocks.length = 0\n validationRejects.length = 0\n budgetEvents.length = 0\n repeatGuardEvents.length = 0\n for (const k of Object.keys(pairingRepairs))\n delete pairingRepairs[k]\n children.length = 0\n }\n\n const unregisters: Array<() => void> = []\n\n unregisters.push(hooks.hook('agent:start', (ctx) => {\n resetForNewRun()\n runId = ctx.runId\n parentRunId = ctx.parentRunId\n depth = ctx.depth\n agentName = ctx.agentName\n startedAt = ctx.startedAt\n }))\n\n unregisters.push(hooks.hook('agent:abort', () => {\n aborted = true\n }))\n\n unregisters.push(hooks.hook('stream:error', (ctx) => {\n const msg = ctx.err instanceof Error ? ctx.err.message : String(ctx.err)\n const errorType = ctx.err instanceof Error ? ctx.err.name : 'unknown'\n errors.push({\n kind: 'stream',\n message: msg,\n errorType,\n turnId: ctx.turnId,\n ...(ctx.statusCode !== undefined ? { statusCode: ctx.statusCode } : {}),\n ...(ctx.requestId !== undefined ? { requestId: ctx.requestId } : {}),\n })\n }))\n\n unregisters.push(hooks.hook('tool:error', (ctx) => {\n errors.push({\n kind: 'tool',\n message: ctx.error.message,\n errorType: ctx.error.name,\n turnId: ctx.turnId,\n callId: ctx.callId,\n toolName: ctx.name,\n })\n }))\n\n unregisters.push(hooks.hook('mcp:tool:error', (ctx) => {\n errors.push({\n kind: 'mcp-tool',\n message: ctx.error.message,\n errorType: ctx.error.name,\n turnId: ctx.turnId,\n callId: ctx.callId,\n server: ctx.server,\n toolName: ctx.displayName,\n })\n }))\n\n unregisters.push(hooks.hook('mcp:error', (ctx) => {\n errors.push({\n kind: 'mcp',\n message: ctx.error.message,\n errorType: ctx.error.name,\n server: ctx.name,\n })\n }))\n\n unregisters.push(hooks.hook('spawn:error', (ctx) => {\n errors.push({\n kind: 'spawn',\n message: ctx.error.message,\n errorType: ctx.error.name,\n childId: ctx.id,\n })\n }))\n\n unregisters.push(hooks.hook('tool:dispatched', (ctx) => {\n if (ctx.outcome === 'gate-block' || ctx.outcome === 'unknown' || ctx.outcome === 'invalid-input') {\n blocks.push({\n callId: ctx.callId,\n toolName: ctx.name,\n outcome: ctx.outcome,\n ...(ctx.reason ? { reason: ctx.reason } : {}),\n })\n }\n }))\n\n unregisters.push(hooks.hook('validation:reject', (ctx) => {\n validationRejects.push({\n callId: ctx.callId,\n toolName: ctx.name,\n reason: ctx.reason,\n })\n }))\n\n unregisters.push(hooks.hook('budget:exceeded', (ctx) => {\n budgetEvents.push({\n kind: 'bytes',\n observed: ctx.bytes,\n limit: ctx.budget,\n turnId: ctx.turnId,\n })\n }))\n\n unregisters.push(hooks.hook('tool-budget:exceeded', (ctx) => {\n budgetEvents.push({\n kind: 'tool-count',\n toolName: ctx.tool,\n mode: ctx.mode,\n observed: ctx.count,\n limit: ctx.max,\n turnId: ctx.turnId,\n })\n }))\n\n unregisters.push(hooks.hook('repeat-guard:exceeded', (ctx) => {\n repeatGuardEvents.push({\n toolName: ctx.tool,\n count: ctx.count,\n threshold: ctx.threshold,\n action: ctx.action,\n turnId: ctx.turnId,\n })\n }))\n\n unregisters.push(hooks.hook('pairing:repair', (ctx) => {\n pairingRepairs[ctx.mode] = (pairingRepairs[ctx.mode] ?? 0) + 1\n }))\n\n unregisters.push(hooks.hook('agent:done', (stats) => {\n const endedAt = Date.now()\n\n // Build per-model rollup via the existing `statsByModel` helper\n // so we stay in lockstep with how the rest of the harness\n // attributes cost and tokens by model id.\n const byModel: RunSummaryByModel[] = []\n for (const [modelId, usage] of statsByModel(stats)) {\n byModel.push({\n modelId,\n input: usage.input,\n output: usage.output,\n cacheRead: usage.cacheRead,\n cacheCreation: usage.cacheCreation,\n cost: usage.cost,\n turns: usage.turns,\n })\n }\n\n // Flatten child stats into nested summaries. We don't have the\n // child's full event lists here (those landed on the child's\n // own hooks), so the nested entry is a minimal totals-only\n // record — enough for a flat per-run audit trail; consumers\n // wanting full per-child event lists install a collector on\n // each subagent.\n for (const c of stats.children ?? []) {\n children.push(minimalSummaryFromStats(c.stats, {\n depth: c.depth ?? depth + 1,\n status: c.status === 'aborted' ? 'aborted' : 'completed',\n }))\n }\n\n const summary: RunSummary = {\n ...(runId ? { runId } : {}),\n ...(parentRunId ? { parentRunId } : {}),\n depth,\n ...(agentName ? { agentName } : {}),\n startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n status: aborted ? 'aborted' : 'completed',\n turns: stats.turns,\n totals: buildTotals(stats),\n byModel,\n errors: errors.slice(),\n blocks: blocks.slice(),\n validationRejects: validationRejects.slice(),\n budgetEvents: budgetEvents.slice(),\n repeatGuardEvents: repeatGuardEvents.slice(),\n pairingRepairs: { ...pairingRepairs },\n ...(children.length > 0 ? { children: children.slice() } : {}),\n }\n\n last = summary\n try {\n options.onSummary?.(summary)\n }\n catch {\n // Sink errors are not the collector's concern.\n }\n }))\n\n let disposed = false\n return function uninstall() {\n if (disposed)\n return\n disposed = true\n for (const un of unregisters) {\n try {\n un()\n }\n catch { /* ignore */ }\n }\n }\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction buildTotals(stats: AgentStats): RunSummaryTokens {\n return {\n input: stats.totalIn,\n output: stats.totalOut,\n cacheRead: stats.totalCacheRead,\n cacheCreation: stats.totalCacheCreation,\n ...(typeof stats.cost === 'number' ? { cost: stats.cost } : {}),\n ...(typeof stats.timeTillFirstTokenMs === 'number' ? { ttftMs: stats.timeTillFirstTokenMs } : {}),\n }\n}\n\nfunction minimalSummaryFromStats(\n stats: AgentStats,\n meta: { depth: number, status: 'completed' | 'aborted' },\n): RunSummary {\n const byModel: RunSummaryByModel[] = []\n for (const [modelId, usage] of statsByModel(stats)) {\n byModel.push({\n modelId,\n input: usage.input,\n output: usage.output,\n cacheRead: usage.cacheRead,\n cacheCreation: usage.cacheCreation,\n cost: usage.cost,\n turns: usage.turns,\n })\n }\n const children: RunSummary[] = []\n for (const c of stats.children ?? []) {\n children.push(minimalSummaryFromStats(c.stats, {\n depth: c.depth ?? meta.depth + 1,\n status: c.status === 'aborted' ? 'aborted' : 'completed',\n }))\n }\n return {\n depth: meta.depth,\n startedAt: 0,\n endedAt: 0,\n durationMs: stats.elapsed,\n status: meta.status,\n turns: stats.turns,\n totals: buildTotals(stats),\n byModel,\n errors: [],\n blocks: [],\n validationRejects: [],\n budgetEvents: [],\n repeatGuardEvents: [],\n pairingRepairs: {},\n ...(children.length > 0 ? { children } : {}),\n }\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 { Hookable } from 'hookable'\nimport type { AgentHooks, AgentOptions } from './agent'\nimport type { ExecutionContext } from './contexts'\nimport type { Provider } from './providers'\nimport type { RunSummary } from './run-summary'\nimport type { Session, SessionStore } from './session'\nimport type { PairingRepair } from './session/messages'\nimport type { ToolDef } from './tools'\nimport type {\n AgentStats,\n McpServerConfig,\n PromptPart,\n SessionContentBlock,\n SessionTurn,\n ThinkingLevel,\n ToolResultContent,\n ToolResultDocumentContent,\n TurnFinishReason,\n} from './types'\nimport { createAgent } from './agent'\nimport { createProcessContext } from './contexts'\nimport { basic } from './presets'\nimport { createRunSummaryCollector } from './run-summary'\nimport { createMemoryStore, createSession, toAnthropic } from './session'\nimport { ensureToolResultPairing } from './session/messages'\nimport { audioFormatFromMediaType } from './tools/media-sniff'\nimport { assertResolvedMediaBlock, documentBlockMarker, toolResultToText } from './types'\n\n// ---------------------------------------------------------------------------\n// Public shapes\n// ---------------------------------------------------------------------------\n\nexport type HeadlessStatus = 'completed' | 'aborted' | 'error' | 'timeout'\n\nexport interface HeadlessUsage {\n input: number\n output: number\n cacheRead: number\n cacheCreation: number\n /** Cumulative USD cost when the provider/registry could price the run. */\n cost?: number\n}\n\nexport interface HeadlessErrorInfo {\n message: string\n /** Typed-error class name (`AgentAbortedError`, `AgentContextExceededError`, …). */\n type: string\n}\n\n/**\n * Strictly JSON-serializable postmortem of one headless run. Everything an RL\n * reward function needs: the final answer (`finalText`), the verifiable\n * structured output (`output`, present iff a `schema` was set), usage/turns,\n * and the lossless `transcript` (the SFT training data).\n */\nexport interface HeadlessResult {\n status: HeadlessStatus\n /** Concatenated text of the last assistant turn that produced any text. */\n finalText: string\n /** Schema-enforced structured output (only when `opts.schema` is set). */\n output?: Record<string, unknown>\n usage: HeadlessUsage\n turns: number\n durationMs: number\n /** Total `tool_call` blocks across the whole transcript. */\n numToolCalls: number\n /** Finish reason of the final turn that reported one. */\n finishReason?: TurnFinishReason\n error?: HeadlessErrorInfo\n sessionId: string\n /** Incident postmortem (errors, gate blocks, budget events) via run-summary. */\n summary?: RunSummary\n /** Lossless transcript — raw `session.turns`. Thinking stripped when `includeThinking: false`. */\n transcript: SessionTurn[]\n}\n\nexport type HeadlessOutputFormat = 'zidane' | 'provider'\n\nexport type ProviderTranscriptFormat = 'anthropic' | 'openai'\n\nexport type FormattedHeadlessResult\n = | HeadlessResult\n | unknown[]\n\nexport type FormattedHeadlessTurnEvent\n = | Extract<HeadlessEvent, { type: 'turn' }>\n | unknown[]\n\nexport function exitCodeForHeadlessResult(result: HeadlessResult): number {\n switch (result.status) {\n case 'completed': return 0\n case 'timeout': return 124\n case 'aborted': return 130\n case 'error':\n default: return 1\n }\n}\n\n/**\n * Live event union — the in-process equivalent of a `stream-json` line. Every\n * member is JSON-serializable; render to JSONL with {@link headlessEventToJsonl}.\n */\nexport type HeadlessEvent\n = | { type: 'start', runId: string, provider?: string }\n | { type: 'text', delta: string }\n | { type: 'thinking', delta: string }\n | { type: 'tool_call', callId: string, name: string, input: Record<string, unknown> }\n | { type: 'tool_result', callId: string, name: string, output: string, isError: boolean }\n | { type: 'turn', index: number, turn: SessionTurn }\n | { type: 'spawn', event: 'before' | 'complete' | 'error', id: string, info?: Record<string, unknown> }\n | { type: 'error', message: string, errorType?: string }\n | { type: 'result', result: HeadlessResult }\n\n/** Serialize one event as a newline-terminated JSON line (stream-json). */\nexport function headlessEventToJsonl(event: HeadlessEvent): string {\n return `${JSON.stringify(event)}\\n`\n}\n\nexport function formattedHeadlessTurnEventToJsonl(event: FormattedHeadlessTurnEvent): string {\n return `${JSON.stringify(event)}\\n`\n}\n\nexport function providerTranscriptFormatForProvider(providerName: string): ProviderTranscriptFormat {\n return providerName === 'anthropic' ? 'anthropic' : 'openai'\n}\n\nexport function transcriptToProviderMessages(\n turns: SessionTurn[],\n providerName: string,\n): unknown[] {\n const format = providerTranscriptFormatForProvider(providerName)\n if (format === 'anthropic') {\n return turns\n .filter((turn): turn is SessionTurn & { role: 'user' | 'assistant' } => turn.role === 'user' || turn.role === 'assistant')\n .map(turn => toAnthropic({ role: turn.role, content: turn.content }))\n }\n return transcriptToOpenAIMessages(turns, { strictToolPairing: false })\n}\n\nexport function formatHeadlessResult(\n result: HeadlessResult,\n options: { format: HeadlessOutputFormat, providerName: string },\n): FormattedHeadlessResult {\n if (options.format === 'zidane')\n return result\n return transcriptToProviderMessages(result.transcript, options.providerName)\n}\n\nexport function formatHeadlessTurnEvent(\n event: Extract<HeadlessEvent, { type: 'turn' }>,\n options: { format: HeadlessOutputFormat, providerName: string },\n): FormattedHeadlessTurnEvent {\n if (options.format === 'zidane')\n return event\n return transcriptToProviderMessages([event.turn], options.providerName)\n}\n\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?: string\n /** Override the preset system prompt for this run. */\n system?: string\n thinking?: ThinkingLevel\n maxTurns?: number\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 mcpServers?: McpServerConfig[]\n skills?: AgentOptions['skills']\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 */\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 const behavior: NonNullable<AgentOptions['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 ...basic,\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 })\n\n const collector = createRunSummaryCollector()\n const uninstallSummary = collector.install(agent.hooks)\n const uninstallEvents = opts.onEvent ? installHeadlessEventAdapter(agent.hooks, opts.onEvent) : 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 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\n// ---------------------------------------------------------------------------\n// Transcript → OpenAI chat messages (SFT-ready)\n// ---------------------------------------------------------------------------\n\nexport interface OpenAIChatMessage {\n role: 'system' | 'user' | 'assistant' | 'tool'\n content: string | null | OpenAIChatContentPart[]\n tool_calls?: Array<{ id: string, type: 'function', function: { name: string, arguments: string } }>\n tool_call_id?: string\n}\n\nexport type OpenAIChatContentPart\n = | { type: 'text', text: string }\n | { type: 'image_url', image_url: { url: string } }\n | { type: 'input_audio', input_audio: { data: string, format: string } }\n | { type: 'video_url', video_url: { url: string } }\n\n/**\n * Convert raw `session.turns` into standard OpenAI chat-completion messages:\n * assistant turns carry `tool_calls`, and each `tool_result` becomes its own\n * `role: 'tool'` message. This is the drop-in shape for an SFT renderer —\n * unlike `toOpenAI` (session/messages.ts), which emits an internal `_tag`\n * envelope meant for re-sending to a provider, not for training data.\n *\n * Fails closed on corrupt raw turns instead of fabricating tool results; silent\n * placeholders would create structurally-valid but semantically-poisoned SFT\n * examples.\n */\nexport function transcriptToOpenAIMessages(\n turns: SessionTurn[],\n options: { strictToolPairing?: boolean } = {},\n): OpenAIChatMessage[] {\n const { strictToolPairing = true } = options\n const messages: OpenAIChatMessage[] = []\n let chunk: Array<{ role: 'user' | 'assistant', content: SessionContentBlock[] }> = []\n const flushChunk = () => {\n if (chunk.length === 0)\n return\n let paired = chunk\n if (strictToolPairing) {\n const repairs: PairingRepair[] = []\n paired = ensureToolResultPairing(chunk, { onRepair: repair => repairs.push(repair) })\n if (repairs.length > 0) {\n throw new Error(\n `Cannot convert transcript to OpenAI messages: tool pairing repair required (${repairs.map(r => r.mode).join(', ')})`,\n )\n }\n }\n for (const msg of paired)\n pushOpenAIChatMessage(messages, msg)\n chunk = []\n }\n\n for (const turn of turns) {\n if (turn.role === 'system') {\n flushChunk()\n messages.push({ role: 'system', content: textOf(turn.content) })\n continue\n }\n chunk.push({ role: turn.role, content: turn.content })\n }\n flushChunk()\n\n return messages\n}\n\nfunction pushOpenAIChatMessage(messages: OpenAIChatMessage[], msg: { role: 'user' | 'assistant', content: SessionContentBlock[] }): void {\n const text = textOf(msg.content)\n\n if (msg.role === 'assistant') {\n const toolCalls = msg.content.filter((b): b is ToolCallBlock => b.type === 'tool_call')\n const out: OpenAIChatMessage = { role: 'assistant', content: text || null }\n if (toolCalls.length > 0) {\n out.tool_calls = toolCalls.map(b => ({\n id: b.id,\n type: 'function' as const,\n function: { name: b.name, arguments: JSON.stringify(b.input) },\n }))\n }\n messages.push(out)\n return\n }\n\n // user turn — may carry prompt text/images and/or tool_result blocks\n const userParts = contentPartsFromBlocks(msg.content)\n if (userParts.length > 0)\n messages.push({ role: 'user', content: simplifyOpenAIContent(userParts) })\n\n for (const tr of msg.content.filter((b): b is ToolResultBlock => b.type === 'tool_result')) {\n const { text, images } = summarizeToolResultForOpenAI(tr.output)\n if (images.length === 0) {\n messages.push({ role: 'tool', tool_call_id: tr.callId, content: text })\n continue\n }\n\n const noun = images.length === 1 ? 'image' : 'images'\n const marker = `[${images.length} ${noun} attached — see next user message]`\n messages.push({\n role: 'tool',\n tool_call_id: tr.callId,\n content: text.length > 0 ? `${text}\\n\\n${marker}` : marker,\n })\n messages.push({\n role: 'user',\n content: [\n ...images.map(toOpenAIImagePart),\n { type: 'text', text: `(${noun} returned by tool call ${tr.callId})` },\n ],\n })\n }\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\ntype TextBlock = Extract<SessionContentBlock, { type: 'text' }>\ntype ToolCallBlock = Extract<SessionContentBlock, { type: 'tool_call' }>\ntype ToolResultBlock = Extract<SessionContentBlock, { type: 'tool_result' }>\n\nfunction noop(): void {}\n\nfunction textOf(content: SessionContentBlock[]): string {\n return content.filter((b): b is TextBlock => b.type === 'text').map(b => b.text).join('')\n}\n\nfunction contentPartsFromBlocks(content: SessionContentBlock[]): OpenAIChatContentPart[] {\n const parts: OpenAIChatContentPart[] = []\n for (const block of content) {\n if (block.type === 'image') {\n assertResolvedMediaBlock(block, 'OpenAI transcript messages')\n parts.push(toOpenAIImagePart(block))\n }\n else if (block.type === 'audio') {\n parts.push({ type: 'input_audio', input_audio: { data: block.data, format: audioFormatFromMediaType(block.mediaType) } })\n }\n else if (block.type === 'video') {\n parts.push({ type: 'video_url', video_url: { url: `data:${block.mediaType};base64,${block.data}` } })\n }\n else if (block.type === 'document') {\n assertResolvedMediaBlock(block, 'OpenAI transcript messages')\n parts.push({ type: 'text', text: documentMarker(block) })\n }\n else if (block.type === 'text' && block.text.length > 0) {\n parts.push({ type: 'text', text: block.text })\n }\n }\n return parts\n}\n\nfunction simplifyOpenAIContent(parts: OpenAIChatContentPart[]): string | OpenAIChatContentPart[] {\n if (parts.length === 1 && parts[0].type === 'text')\n return parts[0].text\n return parts\n}\n\nfunction toOpenAIImagePart(image: { mediaType: string, data: string }): OpenAIChatContentPart {\n return {\n type: 'image_url',\n image_url: { url: `data:${image.mediaType};base64,${image.data}` },\n }\n}\n\nfunction summarizeToolResultForOpenAI(output: string | ToolResultContent[]): {\n text: string\n images: Array<{ mediaType: string, data: string }>\n} {\n if (typeof output === 'string')\n return { text: output, images: [] }\n\n const texts: string[] = []\n const images: Array<{ mediaType: string, data: string }> = []\n for (const block of output) {\n if (block.type === 'text') {\n texts.push(block.text)\n }\n else if (block.type === 'image') {\n assertResolvedMediaBlock(block, 'OpenAI transcript messages')\n images.push({ mediaType: block.mediaType, data: block.data })\n }\n else if (block.type === 'audio') {\n texts.push(`[audio: ${block.mediaType}]`)\n }\n else if (block.type === 'video') {\n texts.push(`[video: ${block.mediaType}]`)\n }\n else {\n assertResolvedMediaBlock(block, 'OpenAI transcript messages')\n texts.push(documentMarker(block))\n }\n }\n return { text: texts.join('\\n'), images }\n}\n\nfunction documentMarker(doc: ToolResultDocumentContent): string {\n return documentBlockMarker(doc, 'document omitted')\n}\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\nexport function installHeadlessEventAdapter(\n hooks: Hookable<AgentHooks>,\n onEvent: (event: HeadlessEvent) => void,\n): () => void {\n const unregs: Array<() => void> = []\n const emittedTurnIds = new Set<string>()\n const emit = (event: HeadlessEvent): void => {\n try {\n onEvent(event)\n }\n catch {\n // A consumer's sink throwing is not the adapter's concern.\n }\n }\n\n unregs.push(hooks.hook('agent:start', ctx => emit({\n type: 'start',\n runId: ctx.runId,\n ...(ctx.providerName ? { provider: ctx.providerName } : {}),\n })))\n unregs.push(hooks.hook('stream:text', ctx => emit({ type: 'text', delta: ctx.delta })))\n unregs.push(hooks.hook('stream:thinking', ctx => emit({ type: 'thinking', delta: ctx.delta })))\n unregs.push(hooks.hook('tool:before', ctx => emit({\n type: 'tool_call',\n callId: ctx.callId,\n name: ctx.name,\n input: ctx.input,\n })))\n unregs.push(hooks.hook('tool:after', ctx => emit({\n type: 'tool_result',\n callId: ctx.callId,\n name: ctx.name,\n output: toolResultToText(ctx.result),\n isError: false,\n })))\n unregs.push(hooks.hook('tool:error', ctx => emit({\n type: 'tool_result',\n callId: ctx.callId,\n name: ctx.name,\n output: ctx.error.message,\n isError: true,\n })))\n unregs.push(hooks.hook('session:turns', (ctx) => {\n const startIndex = ctx.count - ctx.turns.length\n ctx.turns.forEach((turn, i) => {\n if (emittedTurnIds.has(turn.id))\n return\n emittedTurnIds.add(turn.id)\n emit({ type: 'turn', index: startIndex + i, turn })\n })\n }))\n unregs.push(hooks.hook('spawn:before', ctx => emit({ type: 'spawn', event: 'before', id: ctx.id })))\n unregs.push(hooks.hook('spawn:complete', ctx => emit({\n type: 'spawn',\n event: 'complete',\n id: ctx.id,\n info: { status: ctx.status ?? 'completed' },\n })))\n unregs.push(hooks.hook('spawn:error', ctx => emit({\n type: 'spawn',\n event: 'error',\n id: ctx.id,\n info: { message: ctx.error.message },\n })))\n unregs.push(hooks.hook('stream:error', ctx => emit({\n type: 'error',\n message: ctx.err instanceof Error ? ctx.err.message : String(ctx.err),\n ...(ctx.err instanceof Error ? { errorType: ctx.err.name } : {}),\n })))\n\n return () => {\n for (const un of unregs) {\n try {\n un()\n }\n catch {\n // ignore\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6KA,SAAgB,0BACd,UAAsC,CAAC,GAClB;CACrB,IAAI;CAEJ,OAAO;EACL,cAAc;EACd,QAAQ,OAAyC;GAI/C,IAAI;GACJ,IAAI;GACJ,IAAI,QAAQ;GACZ,IAAI;GACJ,IAAI,YAAY,KAAK,IAAI;GACzB,IAAI,UAAU;GACd,MAAM,SAA4B,CAAC;GACnC,MAAM,SAA4B,CAAC;GACnC,MAAM,oBAA4C,CAAC;GACnD,MAAM,eAAmC,CAAC;GAC1C,MAAM,oBAA6C,CAAC;GACpD,MAAM,iBAAyC,CAAC;GAChD,MAAM,WAAyB,CAAC;GAEhC,SAAS,iBAAuB;IAC9B,UAAU;IACV,OAAO,SAAS;IAChB,OAAO,SAAS;IAChB,kBAAkB,SAAS;IAC3B,aAAa,SAAS;IACtB,kBAAkB,SAAS;IAC3B,KAAK,MAAM,KAAK,OAAO,KAAK,cAAc,GACxC,OAAO,eAAe;IACxB,SAAS,SAAS;GACpB;GAEA,MAAM,cAAiC,CAAC;GAExC,YAAY,KAAK,MAAM,KAAK,gBAAgB,QAAQ;IAClD,eAAe;IACf,QAAQ,IAAI;IACZ,cAAc,IAAI;IAClB,QAAQ,IAAI;IACZ,YAAY,IAAI;IAChB,YAAY,IAAI;GAClB,CAAC,CAAC;GAEF,YAAY,KAAK,MAAM,KAAK,qBAAqB;IAC/C,UAAU;GACZ,CAAC,CAAC;GAEF,YAAY,KAAK,MAAM,KAAK,iBAAiB,QAAQ;IACnD,MAAM,MAAM,IAAI,eAAe,QAAQ,IA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, c as runHeadless, 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-
|
|
1
|
+
import { a as headlessEventToJsonl, c as runHeadless, 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-0O6HMNBQ.js";
|
|
2
2
|
export { exitCodeForHeadlessResult, formatHeadlessResult, formatHeadlessTurnEvent, formattedHeadlessTurnEventToJsonl, headlessEventToJsonl, installHeadlessEventAdapter, providerTranscriptFormatForProvider, runHeadless, transcriptToOpenAIMessages, transcriptToProviderMessages };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as joinSystemPrompt, C as sanitizeToolSchema, D as appendDynamicSection, E as SYSTEM_PROMPT_BOUNDARY, M as replaceDynamicSection, N as splitSystemPrompt, O as appendStaticSection, a as detectTurnInterruption, b as openaiCompat, c as filterUnresolvedToolUses, d as remintDuplicateToolCallIds, g as OpenAICompatHttpError, h as toWireMessages, i as autoDetectAndConvert, j as renderSystemForWire, k as hasSystemPromptBoundary, l as fromAnthropic, m as toOpenAI, n as SYNTHETIC_TOOL_RESULT_PLACEHOLDER, o as ensureEndsWithUserMessage, p as toAnthropic, r as TOOL_USE_INTERRUPTED_MARKER, s as ensureToolResultPairing, t as ORPHANED_TOOL_RESULT_MARKER, u as fromOpenAI, v as classifyOpenAICompatError, w as sanitizeToolSpecs, y as mapOAIFinishReason } from "./messages-
|
|
2
|
-
import { $ as stripImagesFromTurns, A as PERSISTENCE_PREVIEW_BYTES, B as selectRecentFiles, C as stableStringify, D as TOOL_USE_SKIPPED_MESSAGE, E as TOOL_USE_CANCELLED_MESSAGE, F as resolvePersistDir, G as buildCompactPrompt, H as BASE_INSTRUCTIONS, I as resolveTasksDir, J as buildTailCompactPrompt, K as buildFromCompactPrompt, L as buildPostCompactAttachments, M as cleanupPersistedSession, N as maybePersistToolResult, O as validateToolArgs, Q as sliceForCompaction, R as selectFilesFromReadState, S as normalizeShellCommand, T as SHELL_CASCADE_CANCEL_MESSAGE, U as NO_TOOLS_PREAMBLE, V as compactConversation, W as TRAILER, X as ANCHOR_PREVIEW_MAX_CHARS, Y as buildUpToCompactPrompt, Z as anchorPreviewFor, _ as createSkillsReadTool, a as multiEdit, b as defaultRepeatGuardNormalize, c as grep, ct as effectiveContextWindow, d as createAgent, et as summaryToTurn, g as createSkillsRunScriptTool, h as createSkillsUseTool, it as OperationTimeoutError, j as buildPersistedStub, k as PERSISTED_STUB_PREFIX, l as glob, lt as shouldAutoCompact, n as createSpawnTool, nt as CompactInvalidInputError, ot as AUTO_COMPACT_MIN_GROWTH_FRACTION, p as waitTask, q as buildFullCompactPrompt, rt as CompactPromptTooLongError, s as createInteractionTool, st as OUTPUT_RESERVE_TOKENS, tt as truncateHeadForPtlRetry, u as edit, v as createShellTool, w as INTERRUPT_MESSAGE_FOR_TOOL_USE, x as defaultRepeatGuardTracked, z as selectFilesFromSession } from "./tools-
|
|
1
|
+
import { A as joinSystemPrompt, C as sanitizeToolSchema, D as appendDynamicSection, E as SYSTEM_PROMPT_BOUNDARY, M as replaceDynamicSection, N as splitSystemPrompt, O as appendStaticSection, a as detectTurnInterruption, b as openaiCompat, c as filterUnresolvedToolUses, d as remintDuplicateToolCallIds, g as OpenAICompatHttpError, h as toWireMessages, i as autoDetectAndConvert, j as renderSystemForWire, k as hasSystemPromptBoundary, l as fromAnthropic, m as toOpenAI, n as SYNTHETIC_TOOL_RESULT_PLACEHOLDER, o as ensureEndsWithUserMessage, p as toAnthropic, r as TOOL_USE_INTERRUPTED_MARKER, s as ensureToolResultPairing, t as ORPHANED_TOOL_RESULT_MARKER, u as fromOpenAI, v as classifyOpenAICompatError, w as sanitizeToolSpecs, y as mapOAIFinishReason } from "./messages-DEsLGBB9.js";
|
|
2
|
+
import { $ as stripImagesFromTurns, A as PERSISTENCE_PREVIEW_BYTES, B as selectRecentFiles, C as stableStringify, D as TOOL_USE_SKIPPED_MESSAGE, E as TOOL_USE_CANCELLED_MESSAGE, F as resolvePersistDir, G as buildCompactPrompt, H as BASE_INSTRUCTIONS, I as resolveTasksDir, J as buildTailCompactPrompt, K as buildFromCompactPrompt, L as buildPostCompactAttachments, M as cleanupPersistedSession, N as maybePersistToolResult, O as validateToolArgs, Q as sliceForCompaction, R as selectFilesFromReadState, S as normalizeShellCommand, T as SHELL_CASCADE_CANCEL_MESSAGE, U as NO_TOOLS_PREAMBLE, V as compactConversation, W as TRAILER, X as ANCHOR_PREVIEW_MAX_CHARS, Y as buildUpToCompactPrompt, Z as anchorPreviewFor, _ as createSkillsReadTool, a as multiEdit, b as defaultRepeatGuardNormalize, c as grep, ct as effectiveContextWindow, d as createAgent, et as summaryToTurn, g as createSkillsRunScriptTool, h as createSkillsUseTool, it as OperationTimeoutError, j as buildPersistedStub, k as PERSISTED_STUB_PREFIX, l as glob, lt as shouldAutoCompact, n as createSpawnTool, nt as CompactInvalidInputError, ot as AUTO_COMPACT_MIN_GROWTH_FRACTION, p as waitTask, q as buildFullCompactPrompt, rt as CompactPromptTooLongError, s as createInteractionTool, st as OUTPUT_RESERVE_TOKENS, tt as truncateHeadForPtlRetry, u as edit, v as createShellTool, w as INTERRUPT_MESSAGE_FOR_TOOL_USE, x as defaultRepeatGuardTracked, z as selectFilesFromSession } from "./tools-DhzKzB1y.js";
|
|
3
3
|
import { n as estimateTokens, r as utf8ByteLength, t as BYTES_PER_TOKEN } from "./utils-ngQzYzZD.js";
|
|
4
4
|
import { n as createSandboxContext, r as createProcessContext, t as resolveDetachedTasksCapability } from "./contexts-DHi8LPCp.js";
|
|
5
5
|
import { a as toolOutputByteLength, i as toolOutputBudgetByteLength, o as toolResultToText } from "./types-DxHDaqN7.js";
|
|
@@ -8,13 +8,13 @@ import { a as AgentToolNotAllowedError, f as matchesContextExceeded, i as AgentP
|
|
|
8
8
|
import { _ as validateResourcePath, a as writeSkillsToDisk, b as validateSkillName, d as buildCatalog, f as IMPLICITLY_ALLOWED_SKILL_TOOLS, g as parseAllowedToolPattern, h as matchesAllowedTool, i as writeSkillToDisk, m as isToolAllowedByUnion, n as stripShellInterpolations, o as discoverSkills, p as installAllowedToolsGate, r as resolveSkills, t as interpolateShellCommands, u as parseSkillFile, v as validateResourcePathReal, x as createSkillActivationState, y as validateSkillForWrite } from "./interpolate-ConAiXGy.js";
|
|
9
9
|
import { i as statsByModel, n as flattenTurns } from "./stats-DAKBEKjc.js";
|
|
10
10
|
import { a as normalizeMcpServers, d as createMemoryMcpCredentialStore, f as hasAuthorizationHeader, i as normalizeMcpBlocks, n as connectMcpServers, o as resultToString, u as McpOAuthProvider } from "./mcp-C_TIj91j.js";
|
|
11
|
-
import { i as basic_default, n as definePreset, r as basicTools } from "./presets-
|
|
12
|
-
import { a as headlessEventToJsonl, c as runHeadless, d as createRunSummaryCollector, l as transcriptToOpenAIMessages } from "./headless-
|
|
13
|
-
import { a as createMemoryStore, i as createRemoteStore, o as createFileMapStore, r as loadSession, t as createSession } from "./session-
|
|
11
|
+
import { i as basic_default, n as definePreset, r as basicTools } from "./presets-HDIxliiq.js";
|
|
12
|
+
import { a as headlessEventToJsonl, c as runHeadless, d as createRunSummaryCollector, l as transcriptToOpenAIMessages } from "./headless-0O6HMNBQ.js";
|
|
13
|
+
import { a as createMemoryStore, i as createRemoteStore, o as createFileMapStore, r as loadSession, t as createSession } from "./session-BDWZZaYa.js";
|
|
14
14
|
import { EFFICIENCY_METRICS, EvalMetricError, artifactPath, buildEvalRunSummary, buildRegisteredEvals, buildTrajectory, clearRegisteredEvals, computeEvalTagScores, createEvalAgent, createEvalRunReporter, createReusableExecutionContext, defineEval, defineMetrics, efficiencyMetricValues, emitEfficiencyMetrics, fileContains, fileContentQuality, fileExists, fileExistsOneOf, finalizeEvalMetrics, formatEvalCaseSummary, formatEvalRunSummary, formatTrajectoryLine, functionalityMetric, llmJudge, normalizeMetric, registerEvalTests, relativeArtifactPath, runEvalCase, statusCompleted } from "./eval.js";
|
|
15
15
|
import { i as jsonSink, n as createLogger, r as createLoggingHooks, t as consoleSink } from "./logger-Ktm-lj1s.js";
|
|
16
16
|
import { n as startOAuthCallback, t as loginMcpServer } from "./login-D5rb4IG8.js";
|
|
17
|
-
import { a as local, f as arcee, i as openai, l as cerebras, m as applyAnthropicCacheBreakpoints, p as anthropic, r as openrouter, t as xai, u as baseten } from "./providers-
|
|
17
|
+
import { a as local, f as arcee, i as openai, l as cerebras, m as applyAnthropicCacheBreakpoints, p as anthropic, r as openrouter, t as xai, u as baseten } from "./providers-Cz-RNYZO.js";
|
|
18
18
|
import { defineSkill } from "./skills.js";
|
|
19
19
|
//#region src/cache-telemetry.ts
|
|
20
20
|
const FNV_OFFSET = 2166136261;
|
|
@@ -2980,6 +2980,6 @@ function autoDetectAndConvert(msg) {
|
|
|
2980
2980
|
return fromAnthropic(msg);
|
|
2981
2981
|
}
|
|
2982
2982
|
//#endregion
|
|
2983
|
-
export { joinSystemPrompt as A, sanitizeToolSchema as C, appendDynamicSection as D, SYSTEM_PROMPT_BOUNDARY as E, canonicalizePrompt as F,
|
|
2983
|
+
export { joinSystemPrompt as A, sanitizeToolSchema as C, appendDynamicSection as D, SYSTEM_PROMPT_BOUNDARY as E, canonicalizePrompt as F, defaultPromptMessage as I, unsupportedMediaError as L, replaceDynamicSection as M, splitSystemPrompt as N, appendStaticSection as O, buildPromptMessage as P, fnv1aBase36 as R, userMessage as S, fillEstimatedCost as T, assistantMessage as _, detectTurnInterruption as a, openaiCompat as b, filterUnresolvedToolUses as c, remintDuplicateToolCallIds as d, resolveContentRefsInMessages as f, OpenAICompatHttpError as g, toWireMessages as h, autoDetectAndConvert as i, renderSystemForWire as j, hasSystemPromptBoundary as k, fromAnthropic as l, toOpenAI as m, SYNTHETIC_TOOL_RESULT_PLACEHOLDER as n, ensureEndsWithUserMessage as o, toAnthropic as p, TOOL_USE_INTERRUPTED_MARKER as r, ensureToolResultPairing as s, ORPHANED_TOOL_RESULT_MARKER as t, fromOpenAI as u, classifyOpenAICompatError as v, sanitizeToolSpecs as w, toolResultsMessage as x, mapOAIFinishReason as y };
|
|
2984
2984
|
|
|
2985
|
-
//# sourceMappingURL=messages-
|
|
2985
|
+
//# sourceMappingURL=messages-DEsLGBB9.js.map
|