zidane 6.2.10 → 6.2.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{acp-DuEMbOoQ.js → acp-C-auiVTk.js} +2 -2
- package/dist/{acp-DuEMbOoQ.js.map → acp-C-auiVTk.js.map} +1 -1
- package/dist/acp-cli.js +4 -4
- package/dist/acp.d.ts +1 -1
- package/dist/acp.js +1 -1
- package/dist/{agent-6iGNP46b.js → agent-DhfdXgL2.js} +81 -1
- package/dist/{agent-6iGNP46b.js.map → agent-DhfdXgL2.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +1 -1
- package/dist/{anthropic-BD-lwEKp.js → anthropic-uXfsormU.js} +87 -2
- package/dist/anthropic-uXfsormU.js.map +1 -0
- package/dist/{auth-BH6G59RL.js → auth-TZg3MVi2.js} +2 -2
- package/dist/{auth-BH6G59RL.js.map → auth-TZg3MVi2.js.map} +1 -1
- package/dist/chat/pure.d.ts +3 -3
- package/dist/chat.d.ts +43 -4
- package/dist/chat.d.ts.map +1 -1
- package/dist/chat.js +3 -3
- package/dist/contexts/daytona.d.ts +1 -1
- package/dist/contexts/e2b.d.ts +1 -1
- package/dist/eval.d.ts +1 -1
- package/dist/extensions.d.ts +1 -1
- package/dist/extensions.js +1 -1
- package/dist/headless.d.ts +1 -1
- package/dist/headless.js +1 -1
- package/dist/{index-BFNt9GAs.d.ts → index-l0wehkWU.d.ts} +44 -6
- package/dist/index-l0wehkWU.d.ts.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +4 -4
- package/dist/{login-B5nMPF8w.js → login-Clf-R27F.js} +2 -2
- package/dist/{login-B5nMPF8w.js.map → login-Clf-R27F.js.map} +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/output/stream-json.d.ts +1 -1
- package/dist/output/terminal.d.ts +1 -1
- package/dist/presets.d.ts +1 -1
- package/dist/presets.js +1 -1
- package/dist/providers/anthropic.d.ts +1 -1
- package/dist/providers/anthropic.js +1 -1
- package/dist/providers/arcee.d.ts +1 -1
- package/dist/providers/baseten.d.ts +1 -1
- package/dist/providers/cerebras.d.ts +1 -1
- package/dist/providers/local.d.ts +1 -1
- package/dist/providers/openai-compat.d.ts +1 -1
- package/dist/providers/openai.d.ts +1 -1
- package/dist/providers/openrouter.d.ts +1 -1
- package/dist/providers/xai.d.ts +1 -1
- package/dist/providers.d.ts +2 -2
- package/dist/providers.js +1 -1
- package/dist/restate.d.ts +1 -1
- package/dist/session/sqlite.d.ts +1 -1
- package/dist/session.d.ts +1 -1
- package/dist/{skills-CDpejYOf.js → skills-DKWqoaYH.js} +4 -3
- package/dist/skills-DKWqoaYH.js.map +1 -0
- package/dist/skills.d.ts +1 -1
- package/dist/skills.js +1 -1
- package/dist/{tool-formatters-B_zQsYfa.d.ts → tool-formatters-BSwVkSX2.d.ts} +2 -2
- package/dist/{tool-formatters-B_zQsYfa.d.ts.map → tool-formatters-BSwVkSX2.d.ts.map} +1 -1
- package/dist/tools/fetch-url.d.ts +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tools.d.ts +1 -1
- package/dist/tools.js +1 -1
- package/dist/{transcript-anchors-BUigMBQt.js → transcript-anchors-BzcuKnq8.js} +108 -37
- package/dist/transcript-anchors-BzcuKnq8.js.map +1 -0
- package/dist/{transcript-anchors-C1Zqb8uS.d.ts → transcript-anchors-DKjXpQ0h.d.ts} +3 -42
- package/dist/transcript-anchors-DKjXpQ0h.d.ts.map +1 -0
- package/dist/tui.d.ts +3 -3
- package/dist/tui.d.ts.map +1 -1
- package/dist/tui.js +199 -150
- package/dist/tui.js.map +1 -1
- package/dist/{turn-operations-DVA52KMG.d.ts → turn-operations-CjkgQKmR.d.ts} +3 -3
- package/dist/{turn-operations-DVA52KMG.d.ts.map → turn-operations-CjkgQKmR.d.ts.map} +1 -1
- package/dist/types.d.ts +1 -1
- package/package.json +1 -1
- package/dist/anthropic-BD-lwEKp.js.map +0 -1
- package/dist/index-BFNt9GAs.d.ts.map +0 -1
- package/dist/skills-CDpejYOf.js.map +0 -1
- package/dist/transcript-anchors-BUigMBQt.js.map +0 -1
- package/dist/transcript-anchors-C1Zqb8uS.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"login-B5nMPF8w.js","names":[],"sources":["../src/extension-authoring.ts","../src/mcp/oauth-callback.ts","../src/mcp/login.ts"],"sourcesContent":["/**\n * Host glue for the \"edit / create extension\" authoring flow (TUI + GUI).\n *\n * Pure, renderer-neutral helpers consumed by the hosts — deliberately kept OUT\n * of `src/extensions/**` (the extension loader / registry core) so the\n * authoring UX can never entangle with discovery / registration. Imports only\n * the skills lib and node builtins.\n *\n * - {@link extensionScaffold} — minimal `index.ts` for a new extension.\n * - {@link resolveExtensionDocsDir} — locate the shipped `docs/` directory.\n * - {@link buildZidaneExtensionSkill} — the inline docs skill.\n * - {@link withZidaneExtensionSkill} — inject it into a `SkillsConfig`.\n * - {@link EXTENSION_EDIT_METADATA_KEY} / {@link ZIDANE_EXTENSION_SKILL_NAME}\n * — constants shared by both hosts.\n */\nimport type { SkillConfig, SkillsConfig } from './skills'\nimport { existsSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { defineSkill } from './skills'\n\n/**\n * Session-metadata key marking an \"edit / create extension\" session. The value\n * is an {@link ExtensionEditMarker}. Both hosts stamp it at session creation so\n * the agent build can scope the docs skill to exactly these sessions (and it\n * survives reload because metadata is persisted).\n */\nexport const EXTENSION_EDIT_METADATA_KEY = 'zidane.extensionEdit'\n\n/** Name of the inline docs skill auto-activated in extension edit sessions. */\nexport const ZIDANE_EXTENSION_SKILL_NAME = 'zidane-extension'\n\n/** Per-edit-session marker persisted on `session.metadata[EXTENSION_EDIT_METADATA_KEY]`. */\nexport interface ExtensionEditMarker {\n /** Absolute path to the extension's directory (the session's cwd). */\n dir: string\n}\n\n/**\n * Minimal valid extension module for a freshly-created extension. `name` MUST\n * equal the folder name or the loader rejects it (see `src/extensions/discovery`).\n * Does nothing by default — the author registers contributions via `ctx.*`\n * inside `setup`; the auto-activated docs skill guides them from there.\n */\nexport function extensionScaffold(name: string): string {\n return `import { defineExtension } from 'zidane'\n\n/**\n * ${name} — a zidane extension.\n *\n * Register tools / hooks / skills / MCP servers / subagents / config / themes /\n * agents / keybindings via the \\`ctx\\` surface inside \\`setup\\`.\n *\n * Authoring reference: activate the \\`${ZIDANE_EXTENSION_SKILL_NAME}\\` skill — it carries\n * the full \\`ctx\\` API + invariants and is available whenever you open this\n * folder in zidane (or run \\`zidane\\` from inside it).\n */\nexport default defineExtension({\n name: '${name}',\n setup(ctx) {\n // e.g. ctx.registerTool('${name}_hello', {\n // spec: { name: '${name}_hello', description: 'say hi', inputSchema: { type: 'object', properties: {} } },\n // isConcurrencySafe: true,\n // async execute() { return 'hello from ${name}' },\n // })\n },\n})\n`\n}\n\n/**\n * Locate the shipped `docs/` directory (`docs/EXTENSIONS.md` + siblings).\n *\n * The docs ship via `package.json` `files`, so an installed consumer has\n * `<root>/node_modules/zidane/docs` and the repo itself has `<repo>/docs`.\n * Returns the first existing candidate, or `null` (the skill then falls back to\n * the literal `node_modules/zidane/docs` hint, which the model's file tools can\n * still attempt from cwd).\n */\nexport function resolveExtensionDocsDir(cwd: string = process.cwd()): string | null {\n const candidates: string[] = []\n\n // 1) The installed (or self-linked) zidane package, via its package.json\n // (exposed through `exports[\"./package.json\"]`).\n try {\n const req = createRequire(import.meta.url)\n candidates.push(join(dirname(req.resolve('zidane/package.json')), 'docs'))\n }\n catch {\n // No resolvable package (compiled binary / odd layout) — fall through.\n }\n\n // 2) Relative to this module: `dist/extension-authoring.js` -> `../docs`, or\n // walking up from `src/` when running from source.\n try {\n let dir = dirname(fileURLToPath(import.meta.url))\n for (let i = 0; i < 6; i++) {\n if (existsSync(join(dir, 'docs', 'EXTENSIONS.md'))) {\n candidates.push(join(dir, 'docs'))\n break\n }\n dir = dirname(dir)\n }\n }\n catch {\n // `import.meta.url` is virtual under `bun build --compile` — fall through.\n }\n\n // 3) cwd-relative — the project the author is actually editing.\n candidates.push(join(cwd, 'node_modules', 'zidane', 'docs'))\n\n for (const candidate of candidates) {\n if (existsSync(join(candidate, 'EXTENSIONS.md')))\n return candidate\n }\n return null\n}\n\n/** Entry-file probe order for an extension dir (mirrors the loader's discovery). */\nconst EXTENSION_ENTRY_FILES = ['index.ts', 'index.tsx', 'index.mjs', 'index.js'] as const\n\n/**\n * If `cwd` sits inside a zidane extension, return that extension's root dir,\n * else `null`. Mirrors the discovery layout\n * `<scope>/.{agents,zidane}/extensions/<name>/` — the root is the `<name>` dir\n * (parent `extensions`, grandparent `.agents` / `.zidane`) holding an entry\n * file. Walks up from `cwd`, so the nearest enclosing extension wins. Lets the\n * hosts surface the authoring skill for a plain `zidane` launched from an\n * extension folder, not just sessions opened through the edit/create flow.\n */\nexport function extensionDirForCwd(cwd: string = process.cwd()): string | null {\n let dir = resolve(cwd)\n // Bounded walk to the filesystem root (the `parent === dir` guard is the real\n // terminator; the cap is just belt-and-braces against pathological inputs).\n for (let i = 0; i < 64; i++) {\n const parent = dirname(dir)\n if (\n basename(parent) === 'extensions'\n && (basename(dirname(parent)) === '.agents' || basename(dirname(parent)) === '.zidane')\n && EXTENSION_ENTRY_FILES.some(f => existsSync(join(dir, f)))\n ) {\n return dir\n }\n if (parent === dir)\n break\n dir = parent\n }\n return null\n}\n\n/**\n * The authoring reference embedded into the skill body. Kept INLINE (not a\n * filesystem path) on purpose: a `bun build --compile` TUI binary has no\n * resolvable `node_modules/zidane/docs`, no real `import.meta.url`, and the\n * edited extension's own cwd has no `node_modules` — so a path reference dead-\n * ends there. The model gets the API verbatim on activation regardless of host.\n *\n * Mirrors `ExtensionContext` (src/extensions/types.ts) — keep in sync when the\n * `ctx.*` surface changes.\n */\nconst EXTENSION_AUTHORING_CHEATSHEET = `## defineExtension\n\nA zidane extension is a module at \\`<scope>/.{agents,zidane}/extensions/<name>/index.{ts,tsx,mjs,js}\\`\nthat default-exports \\`defineExtension({ ... })\\`. It runs in-process in the host (TUI / GUI / SDK).\n\n\\`\\`\\`ts\nimport { defineExtension } from 'zidane'\n\nexport default defineExtension({\n name: 'my-ext', // MUST equal the folder name\n apiVersion: 1, // optional; omitted means v1\n version: '0.1.0', // optional — shown in Settings → Extensions\n displayName: 'My Ext', // optional UI label\n description: 'what it does',\n capabilities: ['tools'], // optional descriptive manifest labels\n permissions: [], // optional descriptive labels; not a sandbox\n setup(ctx) { /* register everything here; may be async */ },\n teardown() {}, // optional, reserved (no hot-reload yet)\n})\n\\`\\`\\`\n\nZero-import form — required INSIDE compiled binaries, which can't \\`import 'zidane'\\` at runtime:\n\\`\\`\\`ts\nimport type { ExtensionContext } from 'zidane' // type-only: erased at runtime\nexport default {\n name: 'my-ext',\n setup(ctx: ExtensionContext) { /* ... */ },\n}\n\\`\\`\\`\n\n## ctx surface (call everything inside setup)\n\nIdentity / utilities:\n- ctx.name / ctx.version / ctx.dir / ctx.scope ('project' | 'user' | 'inline' | 'builtin')\n- ctx.logger — Logger namespaced \\`extension:<name>\\`\n- ctx.config — read THIS extension's config, default-first: \\`ctx.config.get(key)\\`\n- ctx.paths — cwd/projectRoot/dataDir/cacheDir/configDir/stateDir\n- ctx.storage.path(scope, ...segments) — extension-scoped storage path\n- ctx.session — JSON-only per-session state: get / set / delete\n\nRenderer-agnostic registration:\n- ctx.registerTool(name, toolDef)\n- ctx.registerHook(event, handler) — an AgentHooks event; fires on the PARENT agent (use child:* for subagents)\n- ctx.registerMcpServer(config)\n- ctx.registerSkill(skillConfig) — a defineSkill() shape\n- ctx.registerCompletionProvider(provider) — single-char '/' '@' '!' trigger\n- ctx.tui.notify(text, { tone? }) — one-shot transcript line (info/warn/error); buffered pre-mount\n- ctx.tui.setStatus(text | null, { loader?, timeout? }) — single dim status line (transcript-tail slot); loader glyph, auto-clear ms\n- ctx.tui.setBanner(lines | null, { timeout? }) — short block above the prompt (stacked with the todo indicator); auto-clear ms\n- ctx.submitPrompt(text, { delivery? }) — submit as the user: 'auto' (run-or-queue), 'steer', 'followUp'; false when detached\n- ctx.registerToolPolicy({ tools?, decide }) — gate tool calls: allow / { block } / { patch } (patches re-validated by the loop)\n- ctx.registerToolResultTransform(fn) — middleware over finished tool results (chained)\n- ctx.registerContextTransform(fn) — rewrite wire messages before each provider call\n- ctx.registerPromptTransform(fn) — transform or consume submitted prompts (after / commands, before skills)\n- ctx.runtime / ctx.sessions — late-bound host controls: model()/thinking()/setThinking(), sessions list/switch/create\n- ctx.appendNote(blocks) — durable display-only transcript note (command-output block vocabulary)\n- ctx.workspace.exec/readFile/writeFile/listFiles/fileSize — shell + files through the SESSION'S execution context (sandbox-correct; host child_process silently targets the wrong filesystem under docker/e2b). Detached ⇒ rejects; guard with \\`await ctx.workspace.available()\\`.\n- ctx.tui.registerToolRenderer({ tools?, render }) — custom view for tool-result rows; return null to fall through to the default. View-layer only: never persisted, error-bounded per row, TUI-scoped.\n- ctx.tui.registerRenderer(id, render) + emit/appendNote \\`custom: { renderer, data }\\` blocks — custom components in the transcript. \\`data\\` must be JSON-safe (it persists); the block's \\`text\\` is the MANDATORY markdown fallback (disabled extension, headless host, GUI, renderer throw). appendNote auto-prefixes bare ids; command emit needs \\`<ext>/<id>\\`.\n- Renderer components: import \\`react\\` / \\`@opentui/react\\` BARE (never as your own dependency) — the host maps them to its live instances at load time, so hooks work. Async data: render() stays sync; return a component that fetches with useState/useEffect.\n- Renderer async caching: \\`useSessionState(id, initial)\\` (per-row, session-persisted — rehydrates on reload) + \\`useRowVisible()\\` (latched viewport gate) from \\`zidane/tui\\` — fetch once, only when scrolled in.\n- ctx.registerCommand(command) — a '/<name>' workflow (handler or steps[]); step ctx: emit (local output),\n runAgent (interactive sub-run), generateData (silent zod/JSON-Schema JSON),\n session? (read-only turns/runs view), interaction? (confirm / askUser forms /\n presentPlan approval — both optional; guard for bare hosts)\n- ctx.registerTheme(theme)\n- ctx.registerAgent(profile) — extra agent profile in the picker\n- ctx.registerSubagent(def) — spawnable subagent (the spawn tool's subagent_type)\n- ctx.registerSubagentOverride(name, fn) — edit/delete an existing subagent\n- ctx.registerProvider(descriptor)\n- ctx.registerSystemPromptFragment(text)\n- ctx.registerContextBreakdownSection(fn) — render extension-owned rows in the context panel\n- ctx.registerContextPanelSection(section) — richer context panel section with rows/load\n- ctx.registerToolResultMetadata(registration) — project namespaced tool-result metadata into context\n- ctx.registerRunTransform(fn) — sync rewrite of agent.run options\n- ctx.registerBehaviorTransform(fn) — sync rewrite of resolved behavior\n- ctx.registerProviderMiddleware(fn) — wrap provider instances\n- ctx.registerToolCatalogTransform(fn) — shape/hide/rename tools before disclosure/execution\n- ctx.registerMcpConfigTransform(fn) — rewrite MCP server configs before connect\n- ctx.registerSkillPolicy(policy) — auto-activate skills by run context\n- ctx.registerConfigCategory(category)\n- ctx.registerConfigItem([categoryId,] item) — typed setting; supports scope/onChange metadata\n\nTUI-only (ctx.tui.* — silently ignored on non-TUI hosts):\n- ctx.tui.registerKeybinding(binding)\n- ctx.tui.registerFooterHint(hint)\n- ctx.tui.registerModal(modal) — keep UI lazy: \\`node: () => import('./panel')\\`\n\nGUI-only:\n- ctx.gui.registerPanel(panel) — collected, not rendered yet\n\nCompletion providers may also implement submit hooks:\n- resolveReferences(refs, ctx, signal)\n- onSubmit({ text, cursor, references }, signal)\nBoth TUI and GUI call these before dispatching a submitted prompt.\n\n## ToolDef shape\n\\`\\`\\`ts\nctx.registerTool('my_tool', {\n spec: { name: 'my_tool', description: '...', inputSchema: { type: 'object', properties: {} } },\n isConcurrencySafe: true, // default false (barrier/write); true = read-only, fans out in parallel\n async execute(args) { return 'result' },\n})\n\\`\\`\\`\n\n## Invariants\n- The folder name MUST equal \\`name\\`, or the loader rejects the extension.\n- Optional metadata lives in \\`extension.json\\` or \\`package.json#zidane\\`; unsupported \\`apiVersion\\` is rejected.\n- Export as \\`default\\` (or a named \\`extension\\` export).\n- Register ONLY inside \\`setup\\` — calls after it resolves are dropped (logger.warn).\n- A throw in \\`setup\\` is caught and shown on the extension's Settings row; the rest of boot continues.\n- Discovery order, first per name wins: project \\`.agents\\` → project \\`.zidane\\` → \\`~/.agents\\` → \\`~/.zidane\\`.\n- \\`/reload\\` is a TRUE hot-reload: re-discover + re-run setup, and each extension's module graph is re-imported fresh — code edits (deep imports included) apply live. Module-level state resets; clean up external resources in \\`teardown\\`.\n\n## Distribution\n- Users install via Settings → Extensions → \\`ctrl+g\\` (source input + scope picker) — GitHub (\\`owner/repo[#ref][:sub/dir]\\`, tree URLs) or npm (\\`pkg[@version]\\`, exact versions / dist-tags).\n- Update / remove: Settings → Extensions, \\`ctrl+u\\` / \\`ctrl+x\\` on the focused row (update replays the recorded \\`.install.json\\` provenance in place, skipping when the recorded commit/version still matches the remote).\n- Shape your repo/package as a root \\`index.ts\\` (single extension) or \\`extensions/<name>/index.*\\` dirs (collection).\n- Reference packages to copy: \\`extensions/git-flow\\` in the zidane repo (zero-dep \\`/commit\\` command) and \\`extensions/headroom\\` (hooks + tool + config).\n- Declare runtime deps in \\`package.json#dependencies\\` — installed with bun/npm/… WITHOUT lifecycle scripts; don't rely on postinstall.\n- The installed folder is named from your exported \\`definition.name\\` — pick it to be folder-safe ([A-Za-z0-9_.-]).`\n\n/**\n * The inline `zidane-extension` skill. Carries the authoring reference IN its\n * body ({@link EXTENSION_AUTHORING_CHEATSHEET}) so it works in every host —\n * incl. compiled binaries where the on-disk docs aren't resolvable. The shipped\n * `EXTENSIONS.md` (prose long-form) is appended as a \"see also\" only when found\n * on disk. `source: 'inline'` (the `defineSkill` default) survives the\n * project-trust gate.\n */\nexport function buildZidaneExtensionSkill(opts: { cwd?: string } = {}): SkillConfig {\n const docsDir = resolveExtensionDocsDir(opts.cwd)\n const seeAlso = docsDir\n ? `\\n\\n---\\nFull prose reference on disk: ${join(docsDir, 'EXTENSIONS.md')}\\n`\n + 'Sibling docs cover related surfaces (ARCHITECTURE.md, CHAT.md, TUI.md, SKILL.md, HEADLESS.md, …).'\n : '\\n\\n---\\nFuller prose reference, when present: node_modules/zidane/docs/EXTENSIONS.md '\n + '(often absent in compiled binaries — the API above is authoritative).'\n return defineSkill({\n name: ZIDANE_EXTENSION_SKILL_NAME,\n description:\n 'Authoring or editing a zidane extension (a module calling defineExtension, under '\n + '.zidane/extensions/** or .agents/extensions/**). Carries the extension authoring reference.',\n instructions:\n `You are authoring / editing a zidane extension. Authoritative API reference:\\n\\n${\n EXTENSION_AUTHORING_CHEATSHEET\n }${seeAlso}`,\n })\n}\n\n/**\n * Inject the `zidane-extension` skill into an already-merged {@link SkillsConfig}.\n *\n * Call this on the FINAL merged skills object (after folding extension / preset\n * skills): `composePresets` is last-wins on `catalog`, so injecting earlier\n * would be silently dropped whenever an extension also contributes skills.\n *\n * Adds the skill to the catalog and, when an `enabled` allowlist is in force,\n * force-includes the name so the allowlist filter can't hide it (mirrors how\n * extension-contributed skill names are force-included). When skills are fully\n * disabled (`enabled === false`), the edit session still gets just this skill.\n */\nexport function withZidaneExtensionSkill(skills: SkillsConfig, opts: { cwd?: string } = {}): SkillsConfig {\n const skill = buildZidaneExtensionSkill(opts)\n const catalog = [...(skills.catalog ?? []), skill]\n const enabled = skills.enabled\n const nextEnabled: SkillsConfig['enabled']\n = enabled === undefined\n ? undefined\n : Array.isArray(enabled)\n ? (enabled.includes(ZIDANE_EXTENSION_SKILL_NAME) ? enabled : [...enabled, ZIDANE_EXTENSION_SKILL_NAME])\n : [ZIDANE_EXTENSION_SKILL_NAME]\n return {\n ...skills,\n catalog,\n ...(nextEnabled !== undefined ? { enabled: nextEnabled } : {}),\n }\n}\n","/**\n * Local loopback HTTP callback for OAuth 2.0 authorization code flows.\n *\n * Stands up a one-shot server on `127.0.0.1:<random>` that captures the\n * `?code=...` redirect from a browser-driven OAuth flow and resolves a\n * promise with the code. Used as the `redirectUrl` half of the MCP SDK's\n * `OAuthClientProvider` (the persistence half lives separately).\n *\n * Design:\n * - Loopback-only (`127.0.0.1`) — the OAuth spec treats `http://127.0.0.1:<port>`\n * as a public-client redirect URI per RFC 8252 §7.3. Browsers do NOT block it,\n * and Anthropic / OpenAI / Linear / GitHub all accept it.\n * - Random port (`port = 0`) — the OS picks an unused one. We read the actual\n * port back from `server.address()` after `listen()`.\n * - Single-shot — the first GET to `path` with a `code` (or `error`) wins;\n * subsequent requests get 404. The server keeps listening (in case the user\n * hits \"back\" and re-authorizes), so callers must `close()` once they have\n * the code or have given up.\n * - Abort-aware — wiring an external `AbortSignal` rejects the promise and\n * closes the server immediately. Required for the TUI's \"esc cancels login\"\n * UX.\n * - No HTML framework — a single inline `<html>` string keeps this isolated\n * from any UI dependency.\n */\n\nimport type { AddressInfo } from 'node:net'\nimport { createServer } from 'node:http'\n\n/**\n * Result of a successful callback. `state` is forwarded verbatim from the\n * query string — callers verify it against their pre-flight value to defend\n * against CSRF (the MCP SDK does this internally when it controls `state`).\n */\nexport interface OAuthCallbackResult {\n code: string\n state?: string\n}\n\nexport interface OAuthCallbackHandle {\n /**\n * Full URI to register with the authorization server, e.g.\n * `http://127.0.0.1:51823/callback`. Stable for the lifetime of the\n * handle.\n */\n redirectUri: string\n /**\n * Resolves with `{ code, state }` on a successful callback. Rejects with:\n * - The OAuth-spec `error` field (`access_denied`, `server_error`, ...)\n * when the authorization server redirects with `?error=...`.\n * - `'OAuth callback aborted'` when the external `AbortSignal` fires.\n * - `'OAuth callback server closed'` when `close()` is called before any\n * callback arrives.\n *\n * Single-shot — only the first matching request resolves the promise.\n */\n promise: Promise<OAuthCallbackResult>\n /**\n * Idempotent shutdown. Safe to call from a `finally` block whether the\n * flow succeeded, failed, or was aborted. Resolves once the server stops\n * accepting connections.\n */\n close: () => Promise<void>\n}\n\nexport interface OAuthCallbackOptions {\n /** Cancels the flow — rejects `promise` and closes the server. */\n signal?: AbortSignal\n /**\n * Path component the authorization server should redirect to. Defaults\n * to `/callback`. Useful when matching a pre-registered URI that uses a\n * different path.\n */\n path?: string\n /**\n * Override the loopback host. Defaults to `127.0.0.1`. Don't bind to\n * `0.0.0.0` here — the OAuth code is a one-time secret and the server\n * would otherwise accept it from any host on the LAN.\n */\n host?: string\n /**\n * Override the port. Defaults to `0` (OS-assigned). Pin to a fixed port\n * only when the authorization server requires a pre-registered redirect\n * URI; the random-port path is preferred so concurrent flows don't clash.\n */\n port?: number\n}\n\nconst DEFAULT_PATH = '/callback'\nconst DEFAULT_HOST = '127.0.0.1'\n\nconst SUCCESS_HTML = `<!doctype html>\n<html><head><meta charset=\"utf-8\"><title>Logged in</title>\n<style>body{font:14px/1.5 -apple-system,system-ui,sans-serif;margin:6rem auto;max-width:28rem;text-align:center;color:#1d1d1f}.ok{color:#1f8a4c;font-weight:600}</style>\n</head><body>\n<p class=\"ok\">Logged in.</p>\n<p>You can close this tab and return to the terminal.</p>\n</body></html>`\n\nfunction errorHtml(message: string): string {\n // No interpolation into HTML attributes — message goes only inside <p> text\n // where the SAMEORIGIN browser context is rendering. Escape angle brackets\n // and ampersands defensively anyway: a malicious authorization server could\n // theoretically craft an `error_description` containing markup, and we\n // don't want stored XSS even in a one-shot loopback page.\n const escaped = message\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n return `<!doctype html>\n<html><head><meta charset=\"utf-8\"><title>Login failed</title>\n<style>body{font:14px/1.5 -apple-system,system-ui,sans-serif;margin:6rem auto;max-width:28rem;text-align:center;color:#1d1d1f}.err{color:#c43c2c;font-weight:600}</style>\n</head><body>\n<p class=\"err\">Login failed.</p>\n<p>${escaped}</p>\n<p>You can close this tab and return to the terminal.</p>\n</body></html>`\n}\n\n/**\n * Start a one-shot OAuth callback server. The returned handle's `redirectUri`\n * should be passed to the authorization server as the `redirect_uri` query\n * parameter; `promise` resolves once the user finishes the browser flow.\n *\n * Always `await handle.close()` in a `finally` block — even on success, the\n * server stays open until told to shut down (so it can serve the\n * \"you can close this tab\" page).\n */\nexport async function startOAuthCallback(\n opts: OAuthCallbackOptions = {},\n): Promise<OAuthCallbackHandle> {\n const path = opts.path ?? DEFAULT_PATH\n const host = opts.host ?? DEFAULT_HOST\n const port = opts.port ?? 0\n\n if (!path.startsWith('/'))\n throw new Error(`OAuth callback path must start with \"/\" (got: ${JSON.stringify(path)})`)\n\n if (opts.signal?.aborted)\n throw new Error('OAuth callback aborted')\n\n let resolveResult: (value: OAuthCallbackResult) => void\n let rejectResult: (error: Error) => void\n const promise = new Promise<OAuthCallbackResult>((resolve, reject) => {\n resolveResult = resolve\n rejectResult = reject\n })\n // Attach a default no-op catch so a rejection without a consumer doesn't\n // raise an unhandled-rejection warning. Callers that DO `await promise`\n // still receive the rejection — Promises fan out to all listeners.\n promise.catch(() => {})\n\n let settled = false\n const resolveOnce = (value: OAuthCallbackResult) => {\n if (settled)\n return\n settled = true\n resolveResult(value)\n }\n const rejectOnce = (error: Error) => {\n if (settled)\n return\n settled = true\n rejectResult(error)\n }\n\n const server = createServer((req, res) => {\n const url = new URL(req.url ?? '/', `http://${host}`)\n if (url.pathname !== path) {\n res.writeHead(404, { 'content-type': 'text/plain' })\n res.end('Not Found')\n return\n }\n\n // `no-store` prevents the browser from replaying the page (with the\n // now-spent code in its URL bar) when the user hits back, refreshes,\n // or restores the tab from history. The code is a one-time secret.\n const htmlHeaders = {\n 'content-type': 'text/html; charset=utf-8',\n 'cache-control': 'no-store',\n }\n\n const error = url.searchParams.get('error')\n if (error) {\n const desc = url.searchParams.get('error_description') ?? error\n res.writeHead(400, htmlHeaders)\n res.end(errorHtml(desc))\n rejectOnce(new Error(`OAuth authorization failed: ${desc}`))\n return\n }\n\n const code = url.searchParams.get('code')\n if (!code) {\n // No code, no error — likely a stray probe. Serve a minimal page,\n // don't resolve. The browser will eventually arrive with the real\n // redirect, or the caller will time out via signal.\n res.writeHead(400, { 'content-type': 'text/plain' })\n res.end('Missing \"code\" query parameter.')\n return\n }\n\n const state = url.searchParams.get('state') ?? undefined\n res.writeHead(200, htmlHeaders)\n res.end(SUCCESS_HTML)\n resolveOnce({ code, state })\n })\n\n // Surface socket errors that arrive before the request handler — e.g. EADDRINUSE\n // on a pinned port, or an early TLS-style probe that the parser rejects.\n server.on('error', (err) => {\n rejectOnce(err instanceof Error ? err : new Error(String(err)))\n })\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject)\n server.listen(port, host, () => {\n server.off('error', reject)\n resolve()\n })\n })\n\n const addr = server.address() as AddressInfo | null\n if (!addr || typeof addr === 'string') {\n server.close()\n throw new Error('OAuth callback server did not bind to a TCP port')\n }\n\n // `closeServer` and `onAbort` reference each other — pre-declare both so\n // either ordering reads cleanly and the lint doesn't trip on the cycle.\n let closing: Promise<void> | undefined\n let closeServer: () => Promise<void>\n const onAbort = () => {\n rejectOnce(new Error('OAuth callback aborted'))\n void closeServer()\n }\n closeServer = (): Promise<void> => {\n if (closing)\n return closing\n closing = new Promise<void>((resolve) => {\n // `close()` on a Node http server waits for in-flight requests to drain.\n // The flow has already settled (or is being aborted), so we also call\n // `closeAllConnections()` to drop keep-alive sockets immediately — a\n // browser keeps the connection open after the success page, which would\n // otherwise hang the close for the keep-alive timeout (~5s).\n const anyServer = server as { closeAllConnections?: () => void }\n anyServer.closeAllConnections?.()\n server.close(() => {\n opts.signal?.removeEventListener('abort', onAbort)\n // If neither a callback nor an abort happened before close(), reject\n // pending awaits so callers don't hang. Tag the rejection as\n // 'aborted' when the signal already fired — Bun fires the abort\n // listener via a microtask, so server.close() may resolve first\n // even though semantically the abort came first.\n if (opts.signal?.aborted)\n rejectOnce(new Error('OAuth callback aborted'))\n else\n rejectOnce(new Error('OAuth callback server closed'))\n resolve()\n })\n })\n return closing\n }\n opts.signal?.addEventListener('abort', onAbort, { once: true })\n\n return {\n redirectUri: `http://${host}:${addr.port}${path}`,\n promise,\n close: closeServer,\n }\n}\n","/**\n * Interactive OAuth login orchestrator for one MCP server.\n *\n * Composes the three pieces shipped separately:\n * - `startOAuthCallback` (`./oauth-callback`) — local loopback HTTP\n * listener that catches the `?code=...` redirect.\n * - `McpOAuthProvider` (`./oauth-provider`) — SDK adapter that persists\n * tokens / client info via an injected `McpCredentialStore`.\n * - The MCP SDK's transport `authProvider` + `finishAuth` plumbing —\n * `client.connect()` triggers the SDK to call `redirectToAuthorization`\n * (which opens the browser); we wait for the loopback callback to\n * deliver the code, hand it to `transport.finishAuth`, and reconnect.\n *\n * Returns once tokens are persisted. Caller decides whether to immediately\n * reconnect the server (re-run `connectMcpServers` / `agent.warmup()`) or\n * defer to the next session activation. The returned `tools` array is\n * provided as a convenience — callers that want the connection live in\n * this call rather than rebuilding can wire them in directly.\n */\n\nimport type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js'\nimport type { Hookable } from 'hookable'\nimport type { AgentHooks } from '../agent'\nimport type { McpServerConfig } from '../types'\nimport type { OAuthCallbackHandle } from './oauth-callback'\nimport type { McpCredentialStore } from './oauth-provider'\nimport { startOAuthCallback } from './oauth-callback'\nimport { isOAuthTokenRejectionError, McpOAuthProvider } from './oauth-provider'\nimport { sseToJsonFetchIfNeeded } from './sse-to-json-fetch'\nimport { createTolerantClient } from './tolerant-client'\n\nexport interface LoginMcpServerOptions {\n /** Persistence — same store the bootstrap path reads from. */\n store: McpCredentialStore\n /**\n * Invoked with the authorization URL once it's ready. Hosts typically\n * (a) emit `mcp:auth:url` for the TUI, and (b) call `tryOpenBrowser`.\n * The URL is identical to the one passed to the `mcp:auth:url` hook\n * fired automatically — this callback is a synchronous hook for callers\n * that don't want to wire the agent hook machinery.\n */\n onAuthorizationUrl?: (url: URL) => void | Promise<void>\n /** Cancels the flow (esc / close modal / SIGINT). */\n signal?: AbortSignal\n /** Agent hooks. The flow emits `mcp:auth:url`/`success`/`error` when wired. */\n hooks?: Hookable<AgentHooks>\n /** Override `client_name` shown on consent screens. Default: 'zidane'. */\n clientName?: string\n /** Override the requested OAuth scope. */\n scope?: string\n /**\n * Override the loopback callback path. Default: `/callback`. Useful only\n * for servers that pinned a different path during registration.\n */\n callbackPath?: string\n /**\n * Maximum time to wait for the user to complete the browser flow, in ms.\n * The user can also cancel via `signal`. Default: 5 minutes.\n */\n timeoutMs?: number\n}\n\nexport interface LoginMcpServerResult {\n /** Stored OAuth tokens after a successful exchange. */\n tokens: NonNullable<ReturnType<McpOAuthProvider['tokens']>>\n /**\n * Upstream tool descriptors discovered after re-connecting with the new\n * tokens. Already filtered by the server's `enabledTools` / `disabledTools`\n * is NOT applied here — that's a bootstrap concern. Hosts that want filtering\n * should pass the result through `connectMcpServers` rebuild on the next\n * session activation rather than reusing this list verbatim.\n */\n tools: Array<{ name: string, description?: string | null, inputSchema?: unknown }>\n}\n\nconst DEFAULT_LOGIN_TIMEOUT_MS = 5 * 60_000\n\n/**\n * Run the full interactive OAuth flow for `config`. Only supports `sse` and\n * `streamable-http` transports — `stdio` MCP servers don't speak OAuth.\n *\n * Throws on:\n * - Wrong transport.\n * - Abort signal.\n * - Browser-side error (user denied, server rejected, etc.).\n * - Code exchange failure.\n * - Post-exchange connect failure.\n *\n * Always closes the loopback callback server before returning, success or\n * failure.\n */\nexport async function loginMcpServer(\n config: McpServerConfig,\n options: LoginMcpServerOptions,\n): Promise<LoginMcpServerResult> {\n if (config.transport !== 'sse' && config.transport !== 'streamable-http')\n throw new Error(`MCP OAuth: cannot login for transport \"${config.transport}\" — only sse / streamable-http are supported`)\n if (!config.url)\n throw new Error(`MCP OAuth: server \"${config.name}\" is missing a url`)\n\n const hooks = options.hooks\n\n let callback: OAuthCallbackHandle | undefined\n try {\n callback = await startOAuthCallback({\n signal: options.signal,\n path: options.callbackPath,\n })\n\n const handle = callback\n const provider = new McpOAuthProvider({\n name: config.name,\n store: options.store,\n redirectUri: handle.redirectUri,\n clientName: options.clientName,\n scope: options.scope,\n onAuthorizationUrl: async (url) => {\n await hooks?.callHook('mcp:auth:url', { name: config.name, url: url.toString() })\n await options.onAuthorizationUrl?.(url)\n },\n })\n\n let transport = await createInteractiveTransport(config, provider)\n const client = await createTolerantClient({ name: 'zidane', version: '1.0.0' })\n\n // First connect → SDK has no tokens, so it calls\n // `provider.redirectToAuthorization(url)` (which routes to our\n // `onAuthorizationUrl`), then throws `UnauthorizedError`. This is the\n // expected path — we catch and wait on the loopback for the code.\n //\n // With STALE tokens stored, the SDK first attempts a refresh instead —\n // and when the refresh token itself is dead, `auth()` rethrows the\n // token-endpoint rejection (`InvalidGrantError`) WITHOUT opening the\n // browser. Wipe the dead tokens and retry once: the tokenless retry\n // routes straight to the authorization redirect. Without this, a\n // revoked refresh token made the panel re-login itself fail — the one\n // flow that's supposed to recover from dead credentials.\n let needsAuth = false\n for (let attempt = 0; ; attempt++) {\n try {\n await client.connect(transport)\n break\n }\n catch (err) {\n if (isUnauthorizedError(err)) {\n needsAuth = true\n break\n }\n if (attempt === 0 && isOAuthTokenRejectionError(err)) {\n await provider.invalidateCredentials('tokens')\n await transport.close().catch(() => {})\n transport = await createInteractiveTransport(config, provider)\n continue\n }\n await client.close().catch(() => {})\n throw err\n }\n }\n\n if (needsAuth) {\n const { code } = await raceLoginCallback(handle, options.timeoutMs ?? DEFAULT_LOGIN_TIMEOUT_MS, options.signal)\n // SDK exchanges code → tokens; provider.saveTokens persists them.\n await (transport as { finishAuth: (code: string) => Promise<void> }).finishAuth(code)\n // Reconnect with a FRESH transport. The previous one is already in\n // the \"started\" state from the failed connect — reusing it throws\n // \"StreamableHTTPClientTransport already started!\" inside\n // `transport.start()`. The SDK's canonical example\n // (`simpleOAuthClient.js`) uses the same pattern: recurse with a\n // new transport, reuse the client. Close the stale transport\n // first so its abort controllers + sockets don't leak.\n await transport.close().catch(() => {})\n const freshTransport = await createInteractiveTransport(config, provider)\n await client.connect(freshTransport)\n }\n\n const { tools } = await client.listTools()\n await client.close()\n\n const tokens = provider.tokens()\n if (!tokens)\n throw new Error(`MCP OAuth: login for \"${config.name}\" returned no tokens (server may have rejected the exchange silently)`)\n\n await hooks?.callHook('mcp:auth:success', { name: config.name })\n return { tokens, tools }\n }\n catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n await hooks?.callHook('mcp:auth:error', { name: config.name, error })\n throw error\n }\n finally {\n await callback?.close()\n }\n}\n\n/**\n * Build an `sse` / `streamable-http` transport pre-wired with `authProvider`.\n * Mirrors the bootstrap-side `createTransport` shape but inlined here so the\n * login flow doesn't depend on the bootstrap module's private export.\n */\nasync function createInteractiveTransport(config: McpServerConfig, authProvider: OAuthClientProvider) {\n if (config.transport === 'sse') {\n const { SSEClientTransport } = await import('@modelcontextprotocol/sdk/client/sse.js')\n return new SSEClientTransport(new URL(config.url!), {\n requestInit: config.headers ? { headers: config.headers } : undefined,\n authProvider,\n })\n }\n // streamable-http\n const { StreamableHTTPClientTransport } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js')\n return new StreamableHTTPClientTransport(new URL(config.url!), {\n requestInit: config.headers ? { headers: config.headers } : undefined,\n fetch: sseToJsonFetchIfNeeded(),\n authProvider,\n })\n}\n\nfunction isUnauthorizedError(err: unknown): boolean {\n if (!err || typeof err !== 'object')\n return false\n const e = err as { name?: string, message?: string, constructor?: { name?: string } }\n if (e.name === 'UnauthorizedError' || e.constructor?.name === 'UnauthorizedError')\n return true\n return typeof e.message === 'string' && e.message.toLowerCase().startsWith('unauthorized')\n}\n\n/**\n * Wait on the callback handle, with a hard timeout AND honor the external\n * abort signal. Unlike `callback.promise` alone, this provides a deterministic\n * failure mode for \"user opened the browser then walked away\" — the modal\n * doesn't hang forever waiting for a redirect that may never come.\n */\nasync function raceLoginCallback(\n handle: OAuthCallbackHandle,\n timeoutMs: number,\n signal: AbortSignal | undefined,\n): Promise<{ code: string, state?: string }> {\n if (signal?.aborted)\n throw new Error('OAuth login aborted')\n let timer: ReturnType<typeof setTimeout> | undefined\n let onAbort: (() => void) | undefined\n try {\n return await new Promise<{ code: string, state?: string }>((resolve, reject) => {\n timer = setTimeout(\n () => reject(new Error(`OAuth login timed out after ${timeoutMs}ms`)),\n timeoutMs,\n )\n if (signal) {\n onAbort = () => reject(new Error('OAuth login aborted'))\n signal.addEventListener('abort', onAbort, { once: true })\n }\n handle.promise.then(resolve, reject)\n })\n }\n finally {\n if (timer)\n clearTimeout(timer)\n if (signal && onAbort)\n signal.removeEventListener('abort', onAbort)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA4BA,MAAa,8BAA8B;;AAG3C,MAAa,8BAA8B;;;;;;;AAc3C,SAAgB,kBAAkB,MAAsB;CACtD,OAAO;;;KAGJ,KAAK;;;;;yCAK+B,4BAA4B;;;;;WAK1D,KAAK;;gCAEgB,KAAK;0BACX,KAAK;;gDAEiB,KAAK;;;;;AAKrD;;;;;;;;;;AAWA,SAAgB,wBAAwB,MAAc,QAAQ,IAAI,GAAkB;CAClF,MAAM,aAAuB,CAAC;CAI9B,IAAI;EACF,MAAM,MAAM,cAAc,OAAO,KAAK,GAAG;EACzC,WAAW,KAAK,KAAK,QAAQ,IAAI,QAAQ,qBAAqB,CAAC,GAAG,MAAM,CAAC;CAC3E,QACM,CAEN;CAIA,IAAI;EACF,IAAI,MAAM,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC;EAChD,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK;GAC1B,IAAI,WAAW,KAAK,KAAK,QAAQ,eAAe,CAAC,GAAG;IAClD,WAAW,KAAK,KAAK,KAAK,MAAM,CAAC;IACjC;GACF;GACA,MAAM,QAAQ,GAAG;EACnB;CACF,QACM,CAEN;CAGA,WAAW,KAAK,KAAK,KAAK,gBAAgB,UAAU,MAAM,CAAC;CAE3D,KAAK,MAAM,aAAa,YACtB,IAAI,WAAW,KAAK,WAAW,eAAe,CAAC,GAC7C,OAAO;CAEX,OAAO;AACT;;AAGA,MAAM,wBAAwB;CAAC;CAAY;CAAa;CAAa;AAAU;;;;;;;;;;AAW/E,SAAgB,mBAAmB,MAAc,QAAQ,IAAI,GAAkB;CAC7E,IAAI,MAAM,QAAQ,GAAG;CAGrB,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK;EAC3B,MAAM,SAAS,QAAQ,GAAG;EAC1B,IAC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O,QAAQ,UACzB,OAAO;CACT,MAAM,IAAI;CACV,IAAI,EAAE,SAAS,uBAAuB,EAAE,aAAa,SAAS,qBAC5D,OAAO;CACT,OAAO,OAAO,EAAE,YAAY,YAAY,EAAE,QAAQ,YAAY,CAAC,CAAC,WAAW,cAAc;AAC3F;;;;;;;AAQA,eAAe,kBACb,QACA,WACA,QAC2C;CAC3C,IAAI,QAAQ,SACV,MAAM,IAAI,MAAM,qBAAqB;CACvC,IAAI;CACJ,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,IAAI,SAA2C,SAAS,WAAW;GAC9E,QAAQ,iBACA,uBAAO,IAAI,MAAM,+BAA+B,UAAU,GAAG,CAAC,GACpE,SACF;GACA,IAAI,QAAQ;IACV,gBAAgB,uBAAO,IAAI,MAAM,qBAAqB,CAAC;IACvD,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;GAC1D;GACA,OAAO,QAAQ,KAAK,SAAS,MAAM;EACrC,CAAC;CACH,UACQ;EACN,IAAI,OACF,aAAa,KAAK;EACpB,IAAI,UAAU,SACZ,OAAO,oBAAoB,SAAS,OAAO;CAC/C;AACF"}
|
|
1
|
+
{"version":3,"file":"login-Clf-R27F.js","names":[],"sources":["../src/extension-authoring.ts","../src/mcp/oauth-callback.ts","../src/mcp/login.ts"],"sourcesContent":["/**\n * Host glue for the \"edit / create extension\" authoring flow (TUI + GUI).\n *\n * Pure, renderer-neutral helpers consumed by the hosts — deliberately kept OUT\n * of `src/extensions/**` (the extension loader / registry core) so the\n * authoring UX can never entangle with discovery / registration. Imports only\n * the skills lib and node builtins.\n *\n * - {@link extensionScaffold} — minimal `index.ts` for a new extension.\n * - {@link resolveExtensionDocsDir} — locate the shipped `docs/` directory.\n * - {@link buildZidaneExtensionSkill} — the inline docs skill.\n * - {@link withZidaneExtensionSkill} — inject it into a `SkillsConfig`.\n * - {@link EXTENSION_EDIT_METADATA_KEY} / {@link ZIDANE_EXTENSION_SKILL_NAME}\n * — constants shared by both hosts.\n */\nimport type { SkillConfig, SkillsConfig } from './skills'\nimport { existsSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { defineSkill } from './skills'\n\n/**\n * Session-metadata key marking an \"edit / create extension\" session. The value\n * is an {@link ExtensionEditMarker}. Both hosts stamp it at session creation so\n * the agent build can scope the docs skill to exactly these sessions (and it\n * survives reload because metadata is persisted).\n */\nexport const EXTENSION_EDIT_METADATA_KEY = 'zidane.extensionEdit'\n\n/** Name of the inline docs skill auto-activated in extension edit sessions. */\nexport const ZIDANE_EXTENSION_SKILL_NAME = 'zidane-extension'\n\n/** Per-edit-session marker persisted on `session.metadata[EXTENSION_EDIT_METADATA_KEY]`. */\nexport interface ExtensionEditMarker {\n /** Absolute path to the extension's directory (the session's cwd). */\n dir: string\n}\n\n/**\n * Minimal valid extension module for a freshly-created extension. `name` MUST\n * equal the folder name or the loader rejects it (see `src/extensions/discovery`).\n * Does nothing by default — the author registers contributions via `ctx.*`\n * inside `setup`; the auto-activated docs skill guides them from there.\n */\nexport function extensionScaffold(name: string): string {\n return `import { defineExtension } from 'zidane'\n\n/**\n * ${name} — a zidane extension.\n *\n * Register tools / hooks / skills / MCP servers / subagents / config / themes /\n * agents / keybindings via the \\`ctx\\` surface inside \\`setup\\`.\n *\n * Authoring reference: activate the \\`${ZIDANE_EXTENSION_SKILL_NAME}\\` skill — it carries\n * the full \\`ctx\\` API + invariants and is available whenever you open this\n * folder in zidane (or run \\`zidane\\` from inside it).\n */\nexport default defineExtension({\n name: '${name}',\n setup(ctx) {\n // e.g. ctx.registerTool('${name}_hello', {\n // spec: { name: '${name}_hello', description: 'say hi', inputSchema: { type: 'object', properties: {} } },\n // isConcurrencySafe: true,\n // async execute() { return 'hello from ${name}' },\n // })\n },\n})\n`\n}\n\n/**\n * Locate the shipped `docs/` directory (`docs/EXTENSIONS.md` + siblings).\n *\n * The docs ship via `package.json` `files`, so an installed consumer has\n * `<root>/node_modules/zidane/docs` and the repo itself has `<repo>/docs`.\n * Returns the first existing candidate, or `null` (the skill then falls back to\n * the literal `node_modules/zidane/docs` hint, which the model's file tools can\n * still attempt from cwd).\n */\nexport function resolveExtensionDocsDir(cwd: string = process.cwd()): string | null {\n const candidates: string[] = []\n\n // 1) The installed (or self-linked) zidane package, via its package.json\n // (exposed through `exports[\"./package.json\"]`).\n try {\n const req = createRequire(import.meta.url)\n candidates.push(join(dirname(req.resolve('zidane/package.json')), 'docs'))\n }\n catch {\n // No resolvable package (compiled binary / odd layout) — fall through.\n }\n\n // 2) Relative to this module: `dist/extension-authoring.js` -> `../docs`, or\n // walking up from `src/` when running from source.\n try {\n let dir = dirname(fileURLToPath(import.meta.url))\n for (let i = 0; i < 6; i++) {\n if (existsSync(join(dir, 'docs', 'EXTENSIONS.md'))) {\n candidates.push(join(dir, 'docs'))\n break\n }\n dir = dirname(dir)\n }\n }\n catch {\n // `import.meta.url` is virtual under `bun build --compile` — fall through.\n }\n\n // 3) cwd-relative — the project the author is actually editing.\n candidates.push(join(cwd, 'node_modules', 'zidane', 'docs'))\n\n for (const candidate of candidates) {\n if (existsSync(join(candidate, 'EXTENSIONS.md')))\n return candidate\n }\n return null\n}\n\n/** Entry-file probe order for an extension dir (mirrors the loader's discovery). */\nconst EXTENSION_ENTRY_FILES = ['index.ts', 'index.tsx', 'index.mjs', 'index.js'] as const\n\n/**\n * If `cwd` sits inside a zidane extension, return that extension's root dir,\n * else `null`. Mirrors the discovery layout\n * `<scope>/.{agents,zidane}/extensions/<name>/` — the root is the `<name>` dir\n * (parent `extensions`, grandparent `.agents` / `.zidane`) holding an entry\n * file. Walks up from `cwd`, so the nearest enclosing extension wins. Lets the\n * hosts surface the authoring skill for a plain `zidane` launched from an\n * extension folder, not just sessions opened through the edit/create flow.\n */\nexport function extensionDirForCwd(cwd: string = process.cwd()): string | null {\n let dir = resolve(cwd)\n // Bounded walk to the filesystem root (the `parent === dir` guard is the real\n // terminator; the cap is just belt-and-braces against pathological inputs).\n for (let i = 0; i < 64; i++) {\n const parent = dirname(dir)\n if (\n basename(parent) === 'extensions'\n && (basename(dirname(parent)) === '.agents' || basename(dirname(parent)) === '.zidane')\n && EXTENSION_ENTRY_FILES.some(f => existsSync(join(dir, f)))\n ) {\n return dir\n }\n if (parent === dir)\n break\n dir = parent\n }\n return null\n}\n\n/**\n * The authoring reference embedded into the skill body. Kept INLINE (not a\n * filesystem path) on purpose: a `bun build --compile` TUI binary has no\n * resolvable `node_modules/zidane/docs`, no real `import.meta.url`, and the\n * edited extension's own cwd has no `node_modules` — so a path reference dead-\n * ends there. The model gets the API verbatim on activation regardless of host.\n *\n * Mirrors `ExtensionContext` (src/extensions/types.ts) — keep in sync when the\n * `ctx.*` surface changes.\n */\nconst EXTENSION_AUTHORING_CHEATSHEET = `## defineExtension\n\nA zidane extension is a module at \\`<scope>/.{agents,zidane}/extensions/<name>/index.{ts,tsx,mjs,js}\\`\nthat default-exports \\`defineExtension({ ... })\\`. It runs in-process in the host (TUI / GUI / SDK).\n\n\\`\\`\\`ts\nimport { defineExtension } from 'zidane'\n\nexport default defineExtension({\n name: 'my-ext', // MUST equal the folder name\n apiVersion: 1, // optional; omitted means v1\n version: '0.1.0', // optional — shown in Settings → Extensions\n displayName: 'My Ext', // optional UI label\n description: 'what it does',\n capabilities: ['tools'], // optional descriptive manifest labels\n permissions: [], // optional descriptive labels; not a sandbox\n setup(ctx) { /* register everything here; may be async */ },\n teardown() {}, // optional, reserved (no hot-reload yet)\n})\n\\`\\`\\`\n\nZero-import form — required INSIDE compiled binaries, which can't \\`import 'zidane'\\` at runtime:\n\\`\\`\\`ts\nimport type { ExtensionContext } from 'zidane' // type-only: erased at runtime\nexport default {\n name: 'my-ext',\n setup(ctx: ExtensionContext) { /* ... */ },\n}\n\\`\\`\\`\n\n## ctx surface (call everything inside setup)\n\nIdentity / utilities:\n- ctx.name / ctx.version / ctx.dir / ctx.scope ('project' | 'user' | 'inline' | 'builtin')\n- ctx.logger — Logger namespaced \\`extension:<name>\\`\n- ctx.config — read THIS extension's config, default-first: \\`ctx.config.get(key)\\`\n- ctx.paths — cwd/projectRoot/dataDir/cacheDir/configDir/stateDir\n- ctx.storage.path(scope, ...segments) — extension-scoped storage path\n- ctx.session — JSON-only per-session state: get / set / delete\n\nRenderer-agnostic registration:\n- ctx.registerTool(name, toolDef)\n- ctx.registerHook(event, handler) — an AgentHooks event; fires on the PARENT agent (use child:* for subagents)\n- ctx.registerMcpServer(config)\n- ctx.registerSkill(skillConfig) — a defineSkill() shape\n- ctx.registerCompletionProvider(provider) — single-char '/' '@' '!' trigger\n- ctx.tui.notify(text, { tone? }) — one-shot transcript line (info/warn/error); buffered pre-mount\n- ctx.tui.setStatus(text | null, { loader?, timeout? }) — single dim status line (transcript-tail slot); loader glyph, auto-clear ms\n- ctx.tui.setBanner(lines | null, { timeout? }) — short block above the prompt (stacked with the todo indicator); auto-clear ms\n- ctx.submitPrompt(text, { delivery? }) — submit as the user: 'auto' (run-or-queue), 'steer', 'followUp'; false when detached\n- ctx.registerToolPolicy({ tools?, decide }) — gate tool calls: allow / { block } / { patch } (patches re-validated by the loop)\n- ctx.registerToolResultTransform(fn) — middleware over finished tool results (chained)\n- ctx.registerContextTransform(fn) — rewrite wire messages before each provider call\n- ctx.registerPromptTransform(fn) — transform or consume submitted prompts (after / commands, before skills)\n- ctx.runtime / ctx.sessions — late-bound host controls: model()/thinking()/setThinking(), sessions list/switch/create\n- ctx.appendNote(blocks) — durable display-only transcript note (command-output block vocabulary)\n- ctx.workspace.exec/readFile/writeFile/listFiles/fileSize — shell + files through the SESSION'S execution context (sandbox-correct; host child_process silently targets the wrong filesystem under docker/e2b). Detached ⇒ rejects; guard with \\`await ctx.workspace.available()\\`.\n- ctx.tui.registerToolRenderer({ tools?, render }) — custom view for tool-result rows; return null to fall through to the default. View-layer only: never persisted, error-bounded per row, TUI-scoped.\n- ctx.tui.registerRenderer(id, render) + emit/appendNote \\`custom: { renderer, data }\\` blocks — custom components in the transcript. \\`data\\` must be JSON-safe (it persists); the block's \\`text\\` is the MANDATORY markdown fallback (disabled extension, headless host, GUI, renderer throw). appendNote auto-prefixes bare ids; command emit needs \\`<ext>/<id>\\`.\n- Renderer components: import \\`react\\` / \\`@opentui/react\\` BARE (never as your own dependency) — the host maps them to its live instances at load time, so hooks work. Async data: render() stays sync; return a component that fetches with useState/useEffect.\n- Renderer async caching: \\`useSessionState(id, initial)\\` (per-row, session-persisted — rehydrates on reload) + \\`useRowVisible()\\` (latched viewport gate) from \\`zidane/tui\\` — fetch once, only when scrolled in.\n- ctx.registerCommand(command) — a '/<name>' workflow (handler or steps[]); step ctx: emit (local output),\n runAgent (interactive sub-run), generateData (silent zod/JSON-Schema JSON),\n session? (read-only turns/runs view), interaction? (confirm / askUser forms /\n presentPlan approval — both optional; guard for bare hosts)\n- ctx.registerTheme(theme)\n- ctx.registerAgent(profile) — extra agent profile in the picker\n- ctx.registerSubagent(def) — spawnable subagent (the spawn tool's subagent_type)\n- ctx.registerSubagentOverride(name, fn) — edit/delete an existing subagent\n- ctx.registerProvider(descriptor)\n- ctx.registerSystemPromptFragment(text)\n- ctx.registerContextBreakdownSection(fn) — render extension-owned rows in the context panel\n- ctx.registerContextPanelSection(section) — richer context panel section with rows/load\n- ctx.registerToolResultMetadata(registration) — project namespaced tool-result metadata into context\n- ctx.registerRunTransform(fn) — sync rewrite of agent.run options\n- ctx.registerBehaviorTransform(fn) — sync rewrite of resolved behavior\n- ctx.registerProviderMiddleware(fn) — wrap provider instances\n- ctx.registerToolCatalogTransform(fn) — shape/hide/rename tools before disclosure/execution\n- ctx.registerMcpConfigTransform(fn) — rewrite MCP server configs before connect\n- ctx.registerSkillPolicy(policy) — auto-activate skills by run context\n- ctx.registerConfigCategory(category)\n- ctx.registerConfigItem([categoryId,] item) — typed setting; supports scope/onChange metadata\n\nTUI-only (ctx.tui.* — silently ignored on non-TUI hosts):\n- ctx.tui.registerKeybinding(binding)\n- ctx.tui.registerFooterHint(hint)\n- ctx.tui.registerModal(modal) — keep UI lazy: \\`node: () => import('./panel')\\`\n\nGUI-only:\n- ctx.gui.registerPanel(panel) — collected, not rendered yet\n\nCompletion providers may also implement submit hooks:\n- resolveReferences(refs, ctx, signal)\n- onSubmit({ text, cursor, references }, signal)\nBoth TUI and GUI call these before dispatching a submitted prompt.\n\n## ToolDef shape\n\\`\\`\\`ts\nctx.registerTool('my_tool', {\n spec: { name: 'my_tool', description: '...', inputSchema: { type: 'object', properties: {} } },\n isConcurrencySafe: true, // default false (barrier/write); true = read-only, fans out in parallel\n async execute(args) { return 'result' },\n})\n\\`\\`\\`\n\n## Invariants\n- The folder name MUST equal \\`name\\`, or the loader rejects the extension.\n- Optional metadata lives in \\`extension.json\\` or \\`package.json#zidane\\`; unsupported \\`apiVersion\\` is rejected.\n- Export as \\`default\\` (or a named \\`extension\\` export).\n- Register ONLY inside \\`setup\\` — calls after it resolves are dropped (logger.warn).\n- A throw in \\`setup\\` is caught and shown on the extension's Settings row; the rest of boot continues.\n- Discovery order, first per name wins: project \\`.agents\\` → project \\`.zidane\\` → \\`~/.agents\\` → \\`~/.zidane\\`.\n- \\`/reload\\` is a TRUE hot-reload: re-discover + re-run setup, and each extension's module graph is re-imported fresh — code edits (deep imports included) apply live. Module-level state resets; clean up external resources in \\`teardown\\`.\n\n## Distribution\n- Users install via Settings → Extensions → \\`ctrl+g\\` (source input + scope picker) — GitHub (\\`owner/repo[#ref][:sub/dir]\\`, tree URLs) or npm (\\`pkg[@version]\\`, exact versions / dist-tags).\n- Update / remove: Settings → Extensions, \\`ctrl+u\\` / \\`ctrl+x\\` on the focused row (update replays the recorded \\`.install.json\\` provenance in place, skipping when the recorded commit/version still matches the remote).\n- Shape your repo/package as a root \\`index.ts\\` (single extension) or \\`extensions/<name>/index.*\\` dirs (collection).\n- Reference packages to copy: \\`extensions/git-flow\\` in the zidane repo (zero-dep \\`/commit\\` command) and \\`extensions/headroom\\` (hooks + tool + config).\n- Declare runtime deps in \\`package.json#dependencies\\` — installed with bun/npm/… WITHOUT lifecycle scripts; don't rely on postinstall.\n- The installed folder is named from your exported \\`definition.name\\` — pick it to be folder-safe ([A-Za-z0-9_.-]).`\n\n/**\n * The inline `zidane-extension` skill. Carries the authoring reference IN its\n * body ({@link EXTENSION_AUTHORING_CHEATSHEET}) so it works in every host —\n * incl. compiled binaries where the on-disk docs aren't resolvable. The shipped\n * `EXTENSIONS.md` (prose long-form) is appended as a \"see also\" only when found\n * on disk. `source: 'inline'` (the `defineSkill` default) survives the\n * project-trust gate.\n */\nexport function buildZidaneExtensionSkill(opts: { cwd?: string } = {}): SkillConfig {\n const docsDir = resolveExtensionDocsDir(opts.cwd)\n const seeAlso = docsDir\n ? `\\n\\n---\\nFull prose reference on disk: ${join(docsDir, 'EXTENSIONS.md')}\\n`\n + 'Sibling docs cover related surfaces (ARCHITECTURE.md, CHAT.md, TUI.md, SKILL.md, HEADLESS.md, …).'\n : '\\n\\n---\\nFuller prose reference, when present: node_modules/zidane/docs/EXTENSIONS.md '\n + '(often absent in compiled binaries — the API above is authoritative).'\n return defineSkill({\n name: ZIDANE_EXTENSION_SKILL_NAME,\n description:\n 'Authoring or editing a zidane extension (a module calling defineExtension, under '\n + '.zidane/extensions/** or .agents/extensions/**). Carries the extension authoring reference.',\n instructions:\n `You are authoring / editing a zidane extension. Authoritative API reference:\\n\\n${\n EXTENSION_AUTHORING_CHEATSHEET\n }${seeAlso}`,\n })\n}\n\n/**\n * Inject the `zidane-extension` skill into an already-merged {@link SkillsConfig}.\n *\n * Call this on the FINAL merged skills object (after folding extension / preset\n * skills): `composePresets` is last-wins on `catalog`, so injecting earlier\n * would be silently dropped whenever an extension also contributes skills.\n *\n * Adds the skill to the catalog and, when an `enabled` allowlist is in force,\n * force-includes the name so the allowlist filter can't hide it (mirrors how\n * extension-contributed skill names are force-included). When skills are fully\n * disabled (`enabled === false`), the edit session still gets just this skill.\n */\nexport function withZidaneExtensionSkill(skills: SkillsConfig, opts: { cwd?: string } = {}): SkillsConfig {\n const skill = buildZidaneExtensionSkill(opts)\n const catalog = [...(skills.catalog ?? []), skill]\n const enabled = skills.enabled\n const nextEnabled: SkillsConfig['enabled']\n = enabled === undefined\n ? undefined\n : Array.isArray(enabled)\n ? (enabled.includes(ZIDANE_EXTENSION_SKILL_NAME) ? enabled : [...enabled, ZIDANE_EXTENSION_SKILL_NAME])\n : [ZIDANE_EXTENSION_SKILL_NAME]\n return {\n ...skills,\n catalog,\n ...(nextEnabled !== undefined ? { enabled: nextEnabled } : {}),\n }\n}\n","/**\n * Local loopback HTTP callback for OAuth 2.0 authorization code flows.\n *\n * Stands up a one-shot server on `127.0.0.1:<random>` that captures the\n * `?code=...` redirect from a browser-driven OAuth flow and resolves a\n * promise with the code. Used as the `redirectUrl` half of the MCP SDK's\n * `OAuthClientProvider` (the persistence half lives separately).\n *\n * Design:\n * - Loopback-only (`127.0.0.1`) — the OAuth spec treats `http://127.0.0.1:<port>`\n * as a public-client redirect URI per RFC 8252 §7.3. Browsers do NOT block it,\n * and Anthropic / OpenAI / Linear / GitHub all accept it.\n * - Random port (`port = 0`) — the OS picks an unused one. We read the actual\n * port back from `server.address()` after `listen()`.\n * - Single-shot — the first GET to `path` with a `code` (or `error`) wins;\n * subsequent requests get 404. The server keeps listening (in case the user\n * hits \"back\" and re-authorizes), so callers must `close()` once they have\n * the code or have given up.\n * - Abort-aware — wiring an external `AbortSignal` rejects the promise and\n * closes the server immediately. Required for the TUI's \"esc cancels login\"\n * UX.\n * - No HTML framework — a single inline `<html>` string keeps this isolated\n * from any UI dependency.\n */\n\nimport type { AddressInfo } from 'node:net'\nimport { createServer } from 'node:http'\n\n/**\n * Result of a successful callback. `state` is forwarded verbatim from the\n * query string — callers verify it against their pre-flight value to defend\n * against CSRF (the MCP SDK does this internally when it controls `state`).\n */\nexport interface OAuthCallbackResult {\n code: string\n state?: string\n}\n\nexport interface OAuthCallbackHandle {\n /**\n * Full URI to register with the authorization server, e.g.\n * `http://127.0.0.1:51823/callback`. Stable for the lifetime of the\n * handle.\n */\n redirectUri: string\n /**\n * Resolves with `{ code, state }` on a successful callback. Rejects with:\n * - The OAuth-spec `error` field (`access_denied`, `server_error`, ...)\n * when the authorization server redirects with `?error=...`.\n * - `'OAuth callback aborted'` when the external `AbortSignal` fires.\n * - `'OAuth callback server closed'` when `close()` is called before any\n * callback arrives.\n *\n * Single-shot — only the first matching request resolves the promise.\n */\n promise: Promise<OAuthCallbackResult>\n /**\n * Idempotent shutdown. Safe to call from a `finally` block whether the\n * flow succeeded, failed, or was aborted. Resolves once the server stops\n * accepting connections.\n */\n close: () => Promise<void>\n}\n\nexport interface OAuthCallbackOptions {\n /** Cancels the flow — rejects `promise` and closes the server. */\n signal?: AbortSignal\n /**\n * Path component the authorization server should redirect to. Defaults\n * to `/callback`. Useful when matching a pre-registered URI that uses a\n * different path.\n */\n path?: string\n /**\n * Override the loopback host. Defaults to `127.0.0.1`. Don't bind to\n * `0.0.0.0` here — the OAuth code is a one-time secret and the server\n * would otherwise accept it from any host on the LAN.\n */\n host?: string\n /**\n * Override the port. Defaults to `0` (OS-assigned). Pin to a fixed port\n * only when the authorization server requires a pre-registered redirect\n * URI; the random-port path is preferred so concurrent flows don't clash.\n */\n port?: number\n}\n\nconst DEFAULT_PATH = '/callback'\nconst DEFAULT_HOST = '127.0.0.1'\n\nconst SUCCESS_HTML = `<!doctype html>\n<html><head><meta charset=\"utf-8\"><title>Logged in</title>\n<style>body{font:14px/1.5 -apple-system,system-ui,sans-serif;margin:6rem auto;max-width:28rem;text-align:center;color:#1d1d1f}.ok{color:#1f8a4c;font-weight:600}</style>\n</head><body>\n<p class=\"ok\">Logged in.</p>\n<p>You can close this tab and return to the terminal.</p>\n</body></html>`\n\nfunction errorHtml(message: string): string {\n // No interpolation into HTML attributes — message goes only inside <p> text\n // where the SAMEORIGIN browser context is rendering. Escape angle brackets\n // and ampersands defensively anyway: a malicious authorization server could\n // theoretically craft an `error_description` containing markup, and we\n // don't want stored XSS even in a one-shot loopback page.\n const escaped = message\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n return `<!doctype html>\n<html><head><meta charset=\"utf-8\"><title>Login failed</title>\n<style>body{font:14px/1.5 -apple-system,system-ui,sans-serif;margin:6rem auto;max-width:28rem;text-align:center;color:#1d1d1f}.err{color:#c43c2c;font-weight:600}</style>\n</head><body>\n<p class=\"err\">Login failed.</p>\n<p>${escaped}</p>\n<p>You can close this tab and return to the terminal.</p>\n</body></html>`\n}\n\n/**\n * Start a one-shot OAuth callback server. The returned handle's `redirectUri`\n * should be passed to the authorization server as the `redirect_uri` query\n * parameter; `promise` resolves once the user finishes the browser flow.\n *\n * Always `await handle.close()` in a `finally` block — even on success, the\n * server stays open until told to shut down (so it can serve the\n * \"you can close this tab\" page).\n */\nexport async function startOAuthCallback(\n opts: OAuthCallbackOptions = {},\n): Promise<OAuthCallbackHandle> {\n const path = opts.path ?? DEFAULT_PATH\n const host = opts.host ?? DEFAULT_HOST\n const port = opts.port ?? 0\n\n if (!path.startsWith('/'))\n throw new Error(`OAuth callback path must start with \"/\" (got: ${JSON.stringify(path)})`)\n\n if (opts.signal?.aborted)\n throw new Error('OAuth callback aborted')\n\n let resolveResult: (value: OAuthCallbackResult) => void\n let rejectResult: (error: Error) => void\n const promise = new Promise<OAuthCallbackResult>((resolve, reject) => {\n resolveResult = resolve\n rejectResult = reject\n })\n // Attach a default no-op catch so a rejection without a consumer doesn't\n // raise an unhandled-rejection warning. Callers that DO `await promise`\n // still receive the rejection — Promises fan out to all listeners.\n promise.catch(() => {})\n\n let settled = false\n const resolveOnce = (value: OAuthCallbackResult) => {\n if (settled)\n return\n settled = true\n resolveResult(value)\n }\n const rejectOnce = (error: Error) => {\n if (settled)\n return\n settled = true\n rejectResult(error)\n }\n\n const server = createServer((req, res) => {\n const url = new URL(req.url ?? '/', `http://${host}`)\n if (url.pathname !== path) {\n res.writeHead(404, { 'content-type': 'text/plain' })\n res.end('Not Found')\n return\n }\n\n // `no-store` prevents the browser from replaying the page (with the\n // now-spent code in its URL bar) when the user hits back, refreshes,\n // or restores the tab from history. The code is a one-time secret.\n const htmlHeaders = {\n 'content-type': 'text/html; charset=utf-8',\n 'cache-control': 'no-store',\n }\n\n const error = url.searchParams.get('error')\n if (error) {\n const desc = url.searchParams.get('error_description') ?? error\n res.writeHead(400, htmlHeaders)\n res.end(errorHtml(desc))\n rejectOnce(new Error(`OAuth authorization failed: ${desc}`))\n return\n }\n\n const code = url.searchParams.get('code')\n if (!code) {\n // No code, no error — likely a stray probe. Serve a minimal page,\n // don't resolve. The browser will eventually arrive with the real\n // redirect, or the caller will time out via signal.\n res.writeHead(400, { 'content-type': 'text/plain' })\n res.end('Missing \"code\" query parameter.')\n return\n }\n\n const state = url.searchParams.get('state') ?? undefined\n res.writeHead(200, htmlHeaders)\n res.end(SUCCESS_HTML)\n resolveOnce({ code, state })\n })\n\n // Surface socket errors that arrive before the request handler — e.g. EADDRINUSE\n // on a pinned port, or an early TLS-style probe that the parser rejects.\n server.on('error', (err) => {\n rejectOnce(err instanceof Error ? err : new Error(String(err)))\n })\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject)\n server.listen(port, host, () => {\n server.off('error', reject)\n resolve()\n })\n })\n\n const addr = server.address() as AddressInfo | null\n if (!addr || typeof addr === 'string') {\n server.close()\n throw new Error('OAuth callback server did not bind to a TCP port')\n }\n\n // `closeServer` and `onAbort` reference each other — pre-declare both so\n // either ordering reads cleanly and the lint doesn't trip on the cycle.\n let closing: Promise<void> | undefined\n let closeServer: () => Promise<void>\n const onAbort = () => {\n rejectOnce(new Error('OAuth callback aborted'))\n void closeServer()\n }\n closeServer = (): Promise<void> => {\n if (closing)\n return closing\n closing = new Promise<void>((resolve) => {\n // `close()` on a Node http server waits for in-flight requests to drain.\n // The flow has already settled (or is being aborted), so we also call\n // `closeAllConnections()` to drop keep-alive sockets immediately — a\n // browser keeps the connection open after the success page, which would\n // otherwise hang the close for the keep-alive timeout (~5s).\n const anyServer = server as { closeAllConnections?: () => void }\n anyServer.closeAllConnections?.()\n server.close(() => {\n opts.signal?.removeEventListener('abort', onAbort)\n // If neither a callback nor an abort happened before close(), reject\n // pending awaits so callers don't hang. Tag the rejection as\n // 'aborted' when the signal already fired — Bun fires the abort\n // listener via a microtask, so server.close() may resolve first\n // even though semantically the abort came first.\n if (opts.signal?.aborted)\n rejectOnce(new Error('OAuth callback aborted'))\n else\n rejectOnce(new Error('OAuth callback server closed'))\n resolve()\n })\n })\n return closing\n }\n opts.signal?.addEventListener('abort', onAbort, { once: true })\n\n return {\n redirectUri: `http://${host}:${addr.port}${path}`,\n promise,\n close: closeServer,\n }\n}\n","/**\n * Interactive OAuth login orchestrator for one MCP server.\n *\n * Composes the three pieces shipped separately:\n * - `startOAuthCallback` (`./oauth-callback`) — local loopback HTTP\n * listener that catches the `?code=...` redirect.\n * - `McpOAuthProvider` (`./oauth-provider`) — SDK adapter that persists\n * tokens / client info via an injected `McpCredentialStore`.\n * - The MCP SDK's transport `authProvider` + `finishAuth` plumbing —\n * `client.connect()` triggers the SDK to call `redirectToAuthorization`\n * (which opens the browser); we wait for the loopback callback to\n * deliver the code, hand it to `transport.finishAuth`, and reconnect.\n *\n * Returns once tokens are persisted. Caller decides whether to immediately\n * reconnect the server (re-run `connectMcpServers` / `agent.warmup()`) or\n * defer to the next session activation. The returned `tools` array is\n * provided as a convenience — callers that want the connection live in\n * this call rather than rebuilding can wire them in directly.\n */\n\nimport type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js'\nimport type { Hookable } from 'hookable'\nimport type { AgentHooks } from '../agent'\nimport type { McpServerConfig } from '../types'\nimport type { OAuthCallbackHandle } from './oauth-callback'\nimport type { McpCredentialStore } from './oauth-provider'\nimport { startOAuthCallback } from './oauth-callback'\nimport { isOAuthTokenRejectionError, McpOAuthProvider } from './oauth-provider'\nimport { sseToJsonFetchIfNeeded } from './sse-to-json-fetch'\nimport { createTolerantClient } from './tolerant-client'\n\nexport interface LoginMcpServerOptions {\n /** Persistence — same store the bootstrap path reads from. */\n store: McpCredentialStore\n /**\n * Invoked with the authorization URL once it's ready. Hosts typically\n * (a) emit `mcp:auth:url` for the TUI, and (b) call `tryOpenBrowser`.\n * The URL is identical to the one passed to the `mcp:auth:url` hook\n * fired automatically — this callback is a synchronous hook for callers\n * that don't want to wire the agent hook machinery.\n */\n onAuthorizationUrl?: (url: URL) => void | Promise<void>\n /** Cancels the flow (esc / close modal / SIGINT). */\n signal?: AbortSignal\n /** Agent hooks. The flow emits `mcp:auth:url`/`success`/`error` when wired. */\n hooks?: Hookable<AgentHooks>\n /** Override `client_name` shown on consent screens. Default: 'zidane'. */\n clientName?: string\n /** Override the requested OAuth scope. */\n scope?: string\n /**\n * Override the loopback callback path. Default: `/callback`. Useful only\n * for servers that pinned a different path during registration.\n */\n callbackPath?: string\n /**\n * Maximum time to wait for the user to complete the browser flow, in ms.\n * The user can also cancel via `signal`. Default: 5 minutes.\n */\n timeoutMs?: number\n}\n\nexport interface LoginMcpServerResult {\n /** Stored OAuth tokens after a successful exchange. */\n tokens: NonNullable<ReturnType<McpOAuthProvider['tokens']>>\n /**\n * Upstream tool descriptors discovered after re-connecting with the new\n * tokens. Already filtered by the server's `enabledTools` / `disabledTools`\n * is NOT applied here — that's a bootstrap concern. Hosts that want filtering\n * should pass the result through `connectMcpServers` rebuild on the next\n * session activation rather than reusing this list verbatim.\n */\n tools: Array<{ name: string, description?: string | null, inputSchema?: unknown }>\n}\n\nconst DEFAULT_LOGIN_TIMEOUT_MS = 5 * 60_000\n\n/**\n * Run the full interactive OAuth flow for `config`. Only supports `sse` and\n * `streamable-http` transports — `stdio` MCP servers don't speak OAuth.\n *\n * Throws on:\n * - Wrong transport.\n * - Abort signal.\n * - Browser-side error (user denied, server rejected, etc.).\n * - Code exchange failure.\n * - Post-exchange connect failure.\n *\n * Always closes the loopback callback server before returning, success or\n * failure.\n */\nexport async function loginMcpServer(\n config: McpServerConfig,\n options: LoginMcpServerOptions,\n): Promise<LoginMcpServerResult> {\n if (config.transport !== 'sse' && config.transport !== 'streamable-http')\n throw new Error(`MCP OAuth: cannot login for transport \"${config.transport}\" — only sse / streamable-http are supported`)\n if (!config.url)\n throw new Error(`MCP OAuth: server \"${config.name}\" is missing a url`)\n\n const hooks = options.hooks\n\n let callback: OAuthCallbackHandle | undefined\n try {\n callback = await startOAuthCallback({\n signal: options.signal,\n path: options.callbackPath,\n })\n\n const handle = callback\n const provider = new McpOAuthProvider({\n name: config.name,\n store: options.store,\n redirectUri: handle.redirectUri,\n clientName: options.clientName,\n scope: options.scope,\n onAuthorizationUrl: async (url) => {\n await hooks?.callHook('mcp:auth:url', { name: config.name, url: url.toString() })\n await options.onAuthorizationUrl?.(url)\n },\n })\n\n let transport = await createInteractiveTransport(config, provider)\n const client = await createTolerantClient({ name: 'zidane', version: '1.0.0' })\n\n // First connect → SDK has no tokens, so it calls\n // `provider.redirectToAuthorization(url)` (which routes to our\n // `onAuthorizationUrl`), then throws `UnauthorizedError`. This is the\n // expected path — we catch and wait on the loopback for the code.\n //\n // With STALE tokens stored, the SDK first attempts a refresh instead —\n // and when the refresh token itself is dead, `auth()` rethrows the\n // token-endpoint rejection (`InvalidGrantError`) WITHOUT opening the\n // browser. Wipe the dead tokens and retry once: the tokenless retry\n // routes straight to the authorization redirect. Without this, a\n // revoked refresh token made the panel re-login itself fail — the one\n // flow that's supposed to recover from dead credentials.\n let needsAuth = false\n for (let attempt = 0; ; attempt++) {\n try {\n await client.connect(transport)\n break\n }\n catch (err) {\n if (isUnauthorizedError(err)) {\n needsAuth = true\n break\n }\n if (attempt === 0 && isOAuthTokenRejectionError(err)) {\n await provider.invalidateCredentials('tokens')\n await transport.close().catch(() => {})\n transport = await createInteractiveTransport(config, provider)\n continue\n }\n await client.close().catch(() => {})\n throw err\n }\n }\n\n if (needsAuth) {\n const { code } = await raceLoginCallback(handle, options.timeoutMs ?? DEFAULT_LOGIN_TIMEOUT_MS, options.signal)\n // SDK exchanges code → tokens; provider.saveTokens persists them.\n await (transport as { finishAuth: (code: string) => Promise<void> }).finishAuth(code)\n // Reconnect with a FRESH transport. The previous one is already in\n // the \"started\" state from the failed connect — reusing it throws\n // \"StreamableHTTPClientTransport already started!\" inside\n // `transport.start()`. The SDK's canonical example\n // (`simpleOAuthClient.js`) uses the same pattern: recurse with a\n // new transport, reuse the client. Close the stale transport\n // first so its abort controllers + sockets don't leak.\n await transport.close().catch(() => {})\n const freshTransport = await createInteractiveTransport(config, provider)\n await client.connect(freshTransport)\n }\n\n const { tools } = await client.listTools()\n await client.close()\n\n const tokens = provider.tokens()\n if (!tokens)\n throw new Error(`MCP OAuth: login for \"${config.name}\" returned no tokens (server may have rejected the exchange silently)`)\n\n await hooks?.callHook('mcp:auth:success', { name: config.name })\n return { tokens, tools }\n }\n catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n await hooks?.callHook('mcp:auth:error', { name: config.name, error })\n throw error\n }\n finally {\n await callback?.close()\n }\n}\n\n/**\n * Build an `sse` / `streamable-http` transport pre-wired with `authProvider`.\n * Mirrors the bootstrap-side `createTransport` shape but inlined here so the\n * login flow doesn't depend on the bootstrap module's private export.\n */\nasync function createInteractiveTransport(config: McpServerConfig, authProvider: OAuthClientProvider) {\n if (config.transport === 'sse') {\n const { SSEClientTransport } = await import('@modelcontextprotocol/sdk/client/sse.js')\n return new SSEClientTransport(new URL(config.url!), {\n requestInit: config.headers ? { headers: config.headers } : undefined,\n authProvider,\n })\n }\n // streamable-http\n const { StreamableHTTPClientTransport } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js')\n return new StreamableHTTPClientTransport(new URL(config.url!), {\n requestInit: config.headers ? { headers: config.headers } : undefined,\n fetch: sseToJsonFetchIfNeeded(),\n authProvider,\n })\n}\n\nfunction isUnauthorizedError(err: unknown): boolean {\n if (!err || typeof err !== 'object')\n return false\n const e = err as { name?: string, message?: string, constructor?: { name?: string } }\n if (e.name === 'UnauthorizedError' || e.constructor?.name === 'UnauthorizedError')\n return true\n return typeof e.message === 'string' && e.message.toLowerCase().startsWith('unauthorized')\n}\n\n/**\n * Wait on the callback handle, with a hard timeout AND honor the external\n * abort signal. Unlike `callback.promise` alone, this provides a deterministic\n * failure mode for \"user opened the browser then walked away\" — the modal\n * doesn't hang forever waiting for a redirect that may never come.\n */\nasync function raceLoginCallback(\n handle: OAuthCallbackHandle,\n timeoutMs: number,\n signal: AbortSignal | undefined,\n): Promise<{ code: string, state?: string }> {\n if (signal?.aborted)\n throw new Error('OAuth login aborted')\n let timer: ReturnType<typeof setTimeout> | undefined\n let onAbort: (() => void) | undefined\n try {\n return await new Promise<{ code: string, state?: string }>((resolve, reject) => {\n timer = setTimeout(\n () => reject(new Error(`OAuth login timed out after ${timeoutMs}ms`)),\n timeoutMs,\n )\n if (signal) {\n onAbort = () => reject(new Error('OAuth login aborted'))\n signal.addEventListener('abort', onAbort, { once: true })\n }\n handle.promise.then(resolve, reject)\n })\n }\n finally {\n if (timer)\n clearTimeout(timer)\n if (signal && onAbort)\n signal.removeEventListener('abort', onAbort)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA4BA,MAAa,8BAA8B;;AAG3C,MAAa,8BAA8B;;;;;;;AAc3C,SAAgB,kBAAkB,MAAsB;CACtD,OAAO;;;KAGJ,KAAK;;;;;yCAK+B,4BAA4B;;;;;WAK1D,KAAK;;gCAEgB,KAAK;0BACX,KAAK;;gDAEiB,KAAK;;;;;AAKrD;;;;;;;;;;AAWA,SAAgB,wBAAwB,MAAc,QAAQ,IAAI,GAAkB;CAClF,MAAM,aAAuB,CAAC;CAI9B,IAAI;EACF,MAAM,MAAM,cAAc,OAAO,KAAK,GAAG;EACzC,WAAW,KAAK,KAAK,QAAQ,IAAI,QAAQ,qBAAqB,CAAC,GAAG,MAAM,CAAC;CAC3E,QACM,CAEN;CAIA,IAAI;EACF,IAAI,MAAM,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC;EAChD,KAAK,IAAI,IAAI,GAAG,IAAI,G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OAAO,oBAAoB,SAAS,OAAO;CAC/C;AACF"}
|
package/dist/mcp.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Cc as connectMcpServers, Dc as resultToString, Ec as normalizeMcpServers, Oc as wrapDiscoveredMcpTools, Sc as attachStderrWarnPump, Tc as normalizeMcpBlocks, bc as ConnectMcpServersOptions, rf as McpToolSchema, tf as McpServerConfig, wc as deriveMcpToolMeta, xc as McpConnection } from "./index-
|
|
1
|
+
import { Cc as connectMcpServers, Dc as resultToString, Ec as normalizeMcpServers, Oc as wrapDiscoveredMcpTools, Sc as attachStderrWarnPump, Tc as normalizeMcpBlocks, bc as ConnectMcpServersOptions, rf as McpToolSchema, tf as McpServerConfig, wc as deriveMcpToolMeta, xc as McpConnection } from "./index-l0wehkWU.js";
|
|
2
2
|
export { ConnectMcpServersOptions, McpConnection, type McpServerConfig, type McpToolSchema, attachStderrWarnPump, connectMcpServers, deriveMcpToolMeta, normalizeMcpBlocks, normalizeMcpServers, resultToString, wrapDiscoveredMcpTools };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { An as FormattedHeadlessTurnEvent, Fn as HeadlessResult, Mn as HeadlessEvent, Pi as Agent, Pn as HeadlessOutputFormat, kn as FormattedHeadlessResult } from "../index-
|
|
1
|
+
import { An as FormattedHeadlessTurnEvent, Fn as HeadlessResult, Mn as HeadlessEvent, Pi as Agent, Pn as HeadlessOutputFormat, kn as FormattedHeadlessResult } from "../index-l0wehkWU.js";
|
|
2
2
|
|
|
3
3
|
//#region src/output/stream-json.d.ts
|
|
4
4
|
type StreamJsonOutputFormat = HeadlessOutputFormat;
|
package/dist/presets.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Fi as AgentHookMap, a as basicTools, i as _default, n as composePresets, r as definePreset, t as Preset } from "./index-
|
|
1
|
+
import { Fi as AgentHookMap, a as basicTools, i as _default, n as composePresets, r as definePreset, t as Preset } from "./index-l0wehkWU.js";
|
|
2
2
|
export { type AgentHookMap, Preset, _default as basic, basicTools, composePresets, definePreset };
|
package/dist/presets.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { ct as basicTools, lt as basic_default, ot as composePresets, st as definePreset } from "./agent-
|
|
1
|
+
import { ct as basicTools, lt as basic_default, ot as composePresets, st as definePreset } from "./agent-DhfdXgL2.js";
|
|
2
2
|
export { basic_default as basic, basicTools, composePresets, definePreset };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $m as
|
|
1
|
+
import { $m as AnthropicContextManagement, ah as defaultAnthropicMaxTokens, ch as resolveAnthropicMaxOutput, eh as AnthropicParams, ih as classifyAnthropicError, nh as anthropic, oh as planAnthropicThinking, rh as applyAnthropicCacheBreakpoints, sh as resolveAnthropicBetas, th as AnthropicThinkingPlan } from "../index-l0wehkWU.js";
|
|
2
2
|
export { AnthropicContextManagement, AnthropicParams, AnthropicThinkingPlan, anthropic, applyAnthropicCacheBreakpoints, classifyAnthropicError, defaultAnthropicMaxTokens, planAnthropicThinking, resolveAnthropicBetas, resolveAnthropicMaxOutput };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as planAnthropicThinking, i as defaultAnthropicMaxTokens, n as applyAnthropicCacheBreakpoints, o as resolveAnthropicBetas, r as classifyAnthropicError, s as resolveAnthropicMaxOutput, t as anthropic } from "../anthropic-
|
|
1
|
+
import { a as planAnthropicThinking, i as defaultAnthropicMaxTokens, n as applyAnthropicCacheBreakpoints, o as resolveAnthropicBetas, r as classifyAnthropicError, s as resolveAnthropicMaxOutput, t as anthropic } from "../anthropic-uXfsormU.js";
|
|
2
2
|
export { anthropic, applyAnthropicCacheBreakpoints, classifyAnthropicError, defaultAnthropicMaxTokens, planAnthropicThinking, resolveAnthropicBetas, resolveAnthropicMaxOutput };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Qm as arcee, Zm as ArceeParams } from "../index-l0wehkWU.js";
|
|
2
2
|
export { ArceeParams, arcee };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Jm as
|
|
1
|
+
import { Jm as BasetenParams, Xm as planBasetenReasoning, Ym as baseten } from "../index-l0wehkWU.js";
|
|
2
2
|
export { BasetenParams, baseten, planBasetenReasoning };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Km as CerebrasParams, qm as cerebras } from "../index-l0wehkWU.js";
|
|
2
2
|
export { CerebrasParams, cerebras };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Hm as
|
|
1
|
+
import { Hm as LocalParams, Um as local } from "../index-l0wehkWU.js";
|
|
2
2
|
export { LocalParams, local };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Am as
|
|
1
|
+
import { Am as formatTools, Cm as TOOL_RESULTS_TAG, Dm as buildAssistantContent, Em as assistantMessage, Fm as toolResultsMessage, Im as userMessage, Mm as openAICompatPromptMessage, Nm as openaiCompat, Om as classifyOpenAICompatError, Pm as toOAIMessages, Sm as OpenAICompatStreamError, Tm as applyOAIToolCacheBreakpoint, _m as OAIMessage, bm as OpenAICompatHttpError, gm as ASSISTANT_TOOL_CALLS_TAG, jm as mapOAIFinishReason, km as consumeSSE, vm as OAITool, wm as applyOAICacheBreakpoints, xm as OpenAICompatParams, ym as OpenAICompatAuthHeader } from "../index-l0wehkWU.js";
|
|
2
2
|
export { ASSISTANT_TOOL_CALLS_TAG, OAIMessage, OAITool, OpenAICompatAuthHeader, OpenAICompatHttpError, OpenAICompatParams, OpenAICompatStreamError, TOOL_RESULTS_TAG, applyOAICacheBreakpoints, applyOAIToolCacheBreakpoint, assistantMessage, buildAssistantContent, classifyOpenAICompatError, consumeSSE, formatTools, mapOAIFinishReason, openAICompatPromptMessage, openaiCompat, toOAIMessages, toolResultsMessage, userMessage };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Bm as
|
|
1
|
+
import { Bm as openai, Lm as OpenAIParams, Rm as classifyOpenAIError, Vm as toPiMessages, zm as mapCodexStopReason } from "../index-l0wehkWU.js";
|
|
2
2
|
export { OpenAIParams, classifyOpenAIError, mapCodexStopReason, openai, toPiMessages };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { hm as openrouter, mm as normalizeOpenRouterModelId, pm as OpenRouterParams } from "../index-l0wehkWU.js";
|
|
2
2
|
export { OpenRouterParams, normalizeOpenRouterModelId, openrouter };
|
package/dist/providers/xai.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { om as XaiParams, sm as xai } from "../index-l0wehkWU.js";
|
|
2
2
|
export { XaiParams, xai };
|
package/dist/providers.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $
|
|
2
|
-
export { type AnthropicParams, type ArceeParams, type BasetenParams, type CerebrasParams, type CursorParams, type LocalParams, type OpenAICompatAuthHeader, OpenAICompatHttpError, type OpenAICompatParams, type OpenAIParams, type OpenRouterParams, Provider, ProviderCapabilities, type SchemaSanitizeOptions, type SchemaSanitizeProfile, type SchemaSanitizeResult, StreamCallbacks, StreamOptions, TokenCountPayload, ToolCall, ToolResult, ToolSpec, TurnResult, type XaiParams, anthropic, applyAnthropicCacheBreakpoints, arcee, baseten, cerebras, classifyOpenAICompatError, cursor, local, mapOAIFinishReason, openai, openaiCompat, openrouter, planBasetenReasoning, sanitizeToolSchema, sanitizeToolSpecs, xai };
|
|
1
|
+
import { $p as StreamCallbacks, Bm as openai, Gm as cursor, Hm as LocalParams, Jm as BasetenParams, Km as CerebrasParams, Lm as OpenAIParams, Nm as openaiCompat, Om as classifyOpenAICompatError, Qm as arcee, Qp as ProviderCapabilities, Um as local, Wm as CursorParams, Xm as planBasetenReasoning, Xp as HistoryRepair, Ym as baseten, Zm as ArceeParams, Zp as Provider, am as TurnResult, bm as OpenAICompatHttpError, cm as SchemaSanitizeOptions, dm as sanitizeToolSchema, eh as AnthropicParams, em as StreamOptions, fm as sanitizeToolSpecs, hm as openrouter, im as ToolSpec, jm as mapOAIFinishReason, lm as SchemaSanitizeProfile, nh as anthropic, nm as ToolCall, om as XaiParams, pm as OpenRouterParams, qm as cerebras, rh as applyAnthropicCacheBreakpoints, rm as ToolResult, sm as xai, tm as TokenCountPayload, um as SchemaSanitizeResult, xm as OpenAICompatParams, ym as OpenAICompatAuthHeader } from "./index-l0wehkWU.js";
|
|
2
|
+
export { type AnthropicParams, type ArceeParams, type BasetenParams, type CerebrasParams, type CursorParams, HistoryRepair, type LocalParams, type OpenAICompatAuthHeader, OpenAICompatHttpError, type OpenAICompatParams, type OpenAIParams, type OpenRouterParams, Provider, ProviderCapabilities, type SchemaSanitizeOptions, type SchemaSanitizeProfile, type SchemaSanitizeResult, StreamCallbacks, StreamOptions, TokenCountPayload, ToolCall, ToolResult, ToolSpec, TurnResult, type XaiParams, anthropic, applyAnthropicCacheBreakpoints, arcee, baseten, cerebras, classifyOpenAICompatError, cursor, local, mapOAIFinishReason, openai, openaiCompat, openrouter, planBasetenReasoning, sanitizeToolSchema, sanitizeToolSpecs, xai };
|
package/dist/providers.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { f as mapOAIFinishReason, l as classifyOpenAICompatError, m as openaiCompat, n as OpenAICompatHttpError, v as sanitizeToolSchema, y as sanitizeToolSpecs } from "./openai-compat-J_JZ7qsw.js";
|
|
2
|
-
import { n as applyAnthropicCacheBreakpoints, t as anthropic } from "./anthropic-
|
|
2
|
+
import { n as applyAnthropicCacheBreakpoints, t as anthropic } from "./anthropic-uXfsormU.js";
|
|
3
3
|
import { arcee } from "./providers/arcee.js";
|
|
4
4
|
import { baseten, planBasetenReasoning } from "./providers/baseten.js";
|
|
5
5
|
import { cerebras } from "./providers/cerebras.js";
|
package/dist/restate.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Bd as AgentBehavior, Bi as McpToolWrap, Kf as ToolContext, Nf as ToolResultContent, Vd as AgentClock, Zp as Provider, em as StreamOptions, hp as SessionStore, kf as ToolBatchExecutor, qf as ToolDef, zi as McpToolMeta } from "./index-l0wehkWU.js";
|
|
2
2
|
import { h as TaskExitInfo, l as ExecutionHandle, m as TaskEntry, o as DetachedTasksCapability } from "./types-BDccavwj.js";
|
|
3
3
|
|
|
4
4
|
//#region src/restate/types.d.ts
|
package/dist/session/sqlite.d.ts
CHANGED
package/dist/session.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Cp as withExtensionSession, Dp as FileMapAdapter, Ep as createMemoryStore, Gp as fromOpenAI, Jp as toOpenAI, Lp as ToWireMessagesOptions, Op as FileMapStoreOptions, Sp as setExtensionSessionState, Tf as SessionTurn, Tp as createRemoteStore, Wp as fromAnthropic, Yp as toWireMessages, _p as currentExtensionSession, bp as getExtensionSessionState, dp as Session, fp as SessionData, gp as createSession, hp as SessionStore, kp as createFileMapStore, mp as SessionRun, pp as SessionMetaRow, qp as toAnthropic, up as CreateSessionOptions, vp as deleteExtensionSessionState, wf as SessionMessage, wp as RemoteStoreOptions, xf as SessionContentBlock, xp as loadSession, yp as demoteStaleRunningStatus, zp as autoDetectAndConvert } from "./index-
|
|
1
|
+
import { Cp as withExtensionSession, Dp as FileMapAdapter, Ep as createMemoryStore, Gp as fromOpenAI, Jp as toOpenAI, Lp as ToWireMessagesOptions, Op as FileMapStoreOptions, Sp as setExtensionSessionState, Tf as SessionTurn, Tp as createRemoteStore, Wp as fromAnthropic, Yp as toWireMessages, _p as currentExtensionSession, bp as getExtensionSessionState, dp as Session, fp as SessionData, gp as createSession, hp as SessionStore, kp as createFileMapStore, mp as SessionRun, pp as SessionMetaRow, qp as toAnthropic, up as CreateSessionOptions, vp as deleteExtensionSessionState, wf as SessionMessage, wp as RemoteStoreOptions, xf as SessionContentBlock, xp as loadSession, yp as demoteStaleRunningStatus, zp as autoDetectAndConvert } from "./index-l0wehkWU.js";
|
|
2
2
|
export { CreateSessionOptions, type FileMapAdapter, type FileMapStoreOptions, type RemoteStoreOptions, Session, type SessionContentBlock, SessionData, type SessionMessage, SessionMetaRow, SessionRun, SessionStore, type SessionTurn, type ToWireMessagesOptions, autoDetectAndConvert, createFileMapStore, createMemoryStore, createRemoteStore, createSession, currentExtensionSession, deleteExtensionSessionState, demoteStaleRunningStatus, fromAnthropic, fromOpenAI, getExtensionSessionState, loadSession, setExtensionSessionState, toAnthropic, toOpenAI, toWireMessages, withExtensionSession };
|
|
@@ -196,8 +196,9 @@ async function validateSkillCandidate(candidate) {
|
|
|
196
196
|
async function installSkillFromSpec(opts) {
|
|
197
197
|
const which = (opts.io ?? {}).which ?? defaultWhich;
|
|
198
198
|
const spec = parseSkillInstallSpec(opts.source);
|
|
199
|
-
const
|
|
200
|
-
|
|
199
|
+
const batchMode = opts.all === true || (opts.skills?.length ?? 0) > 0;
|
|
200
|
+
const skillSelector = opts.skill ?? (batchMode ? void 0 : spec.skill);
|
|
201
|
+
if (!batchMode && skillSelector !== void 0 && (opts.preferSkillsCli ?? true) && which("skills")) return await installViaSkillsCli(spec, skillSelector, opts);
|
|
201
202
|
return await installNatively(spec, skillSelector, opts);
|
|
202
203
|
}
|
|
203
204
|
/**
|
|
@@ -416,4 +417,4 @@ function defineSkill(config) {
|
|
|
416
417
|
//#endregion
|
|
417
418
|
export { listSkillCandidates as a, installSkillFromSpec as i, SKILL_PROVENANCE_FILE as n, parseSkillInstallSpec as o, SkillInstallError as r, readSkillProvenance as s, defineSkill as t };
|
|
418
419
|
|
|
419
|
-
//# sourceMappingURL=skills-
|
|
420
|
+
//# sourceMappingURL=skills-DKWqoaYH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"skills-DKWqoaYH.js","names":[],"sources":["../src/skills/install.ts","../src/skills/index.ts"],"sourcesContent":["/**\n * Skill installation — fetch a skill (or a collection of skills) from\n * GitHub / npm / skills.sh and land it under the zidane skills root,\n * where the existing discovery scan picks it up.\n *\n * Built on the shared install layer (`src/install/source.ts`), so the\n * spec grammar, transports, download caps, and subdir containment are\n * byte-identical with the extensions installer. What differs:\n *\n * - **Validation never executes code.** A skill is data: candidates\n * are validated by parsing `SKILL.md` (lenient parser, same one\n * discovery uses) — unlike extensions, whose validation must import\n * the module. Installing a hostile skill can plant instructions,\n * never run a process.\n * - **skills.sh interop, two-way.** The spec grammar accepts pasted\n * `https://skills.sh/<owner>/<repo>[/<skill>]` catalog URLs (mapped\n * to the GitHub repo + a skill selector — skills.sh uses GitHub as\n * its registry). And when the `skills` CLI is on PATH,\n * {@link installSkillFromSpec} delegates to it (`skills add … -y`)\n * so installs land in the user's cross-agent `.agents/skills/`\n * layout and feed the skills.sh lockfile/leaderboard; without the\n * CLI the native fetch path installs the same repos directly.\n * - **Target roots**: `~/.zidane/skills/<name>` (user) or\n * `<gitRoot>/.zidane/skills/<name>` (project) — both already on\n * discovery's default scan paths.\n *\n * Same hardening as extensions: staged `mkdtemp` fetch, physical\n * symlink containment for `:subdir`, folder-safe names, overwrite with\n * backup/rollback, and a provenance file (`.zidane-install.json`) so a\n * future update flow can replay the spec.\n */\n\nimport type { InstallIo, InstallScope, InstallSource } from '../install/source'\nimport { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { basename, join, resolve } from 'node:path'\nimport { projectUserPaths } from '../chat/project-user-paths'\nimport { errorMessage } from '../errors'\nimport { defaultExec, defaultWhich, fetchInstallSource, InstallSourceError, lastLine, parseInstallSource, resolveSubdirRoot } from '../install/source'\nimport { parseSkillFile } from './discovery'\nimport { validateSkillName } from './validate'\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\nexport type SkillInstallErrorCode\n = | 'invalid-source'\n | 'fetch-failed'\n | 'no-skill'\n | 'multiple-candidates'\n | 'validate-failed'\n | 'exists'\n | 'cli-failed'\n | 'io-failed'\n\nexport class SkillInstallError extends InstallSourceError {\n declare readonly code: SkillInstallErrorCode\n /**\n * Frontmatter metadata per candidate, parallel to `candidates` — set on\n * the selector-less `multiple-candidates` error so host pickers can show\n * descriptions without re-fetching the source. Best-effort: candidates\n * whose SKILL.md fails to parse appear with no description.\n */\n readonly details?: readonly SkillCandidateDetail[]\n constructor(code: SkillInstallErrorCode, message: string, candidates?: readonly string[], details?: readonly SkillCandidateDetail[]) {\n super(code, message, candidates)\n this.name = 'SkillInstallError'\n if (details)\n this.details = details\n }\n}\n\n/** One pickable candidate surfaced to host UIs — see {@link SkillInstallError.details}. */\nexport interface SkillCandidateDetail {\n /** Root-relative path — the unambiguous selector (`skills` option). */\n rel: string\n /** Frontmatter description, when the candidate's SKILL.md parses. */\n description?: string\n}\n\nfunction rethrowAsSkillError(err: unknown): never {\n if (err instanceof InstallSourceError && !(err instanceof SkillInstallError))\n throw new SkillInstallError(err.code as SkillInstallErrorCode, err.message, err.candidates)\n throw err\n}\n\n// ---------------------------------------------------------------------------\n// Spec parsing (shared grammar + the skills.sh catalog URL form)\n// ---------------------------------------------------------------------------\n\nconst SKILLS_SH_URL_RE = /^(?:https?:\\/\\/)?(?:www\\.)?skills\\.sh\\/([\\w.-]+)\\/([\\w.-]+)(?:\\/([\\w.-]+))?\\/?$/\n\n/**\n * Pasted install commands, as printed by skill READMEs and skills.sh\n * pages — `npx skills add owner/repo`, `bunx skills add …`,\n * `pnpm dlx skills add … --skill x`, or a bare `skills add …`. The\n * runner + `add` verb are stripped and the remaining tokens re-enter\n * the normal grammar, so users can copy a whole command into the\n * install input verbatim.\n */\nconst SKILLS_CLI_COMMAND_RE = /^(?:(?:npx|bunx|yarn\\s+dlx|pnpm\\s+dlx)\\s+)?skills(?:@\\S+)?\\s+add\\s+(\\S.*)$/i\n\nexport interface SkillInstallSpec {\n source: InstallSource\n /**\n * Skill name selector for multi-skill sources. From a skills.sh URL's\n * third segment or the caller's explicit pick after a\n * `multiple-candidates` error.\n */\n skill?: string\n /**\n * The spec string to hand the `skills` CLI (its `add` argument).\n * skills.sh URLs pass through verbatim — the CLI understands them —\n * while parsed shorthand re-serializes to `owner/repo`.\n */\n cliSpec: string\n}\n\n/**\n * Parse a raw skill source. Accepts everything the shared grammar does\n * (`owner/repo[#ref][:subdir]`, GitHub URLs, `pkg@version`, …) plus\n * pasted skills.sh catalog URLs — `skills.sh/vercel-labs/agent-skills/\n * react-best-practices` maps to the backing GitHub repo with the third\n * segment as the skill selector.\n */\nexport function parseSkillInstallSpec(raw: string): SkillInstallSpec {\n const spec = raw.trim()\n const cliCommand = SKILLS_CLI_COMMAND_RE.exec(spec)\n if (cliCommand)\n return parseCliAddCommand(cliCommand[1] as string)\n const skillsSh = SKILLS_SH_URL_RE.exec(spec)\n if (skillsSh) {\n return {\n source: { kind: 'github', owner: skillsSh[1] as string, repo: skillsSh[2] as string },\n ...(skillsSh[3] ? { skill: skillsSh[3] } : {}),\n cliSpec: `${skillsSh[1]}/${skillsSh[2]}`,\n }\n }\n try {\n const source = parseInstallSource(spec)\n return { source, cliSpec: spec }\n }\n catch (err) {\n rethrowAsSkillError(err)\n }\n}\n\n/**\n * Parse the argument tail of a pasted `skills add …` command. Honors\n * `--skill <name>` / `--skill=<name>` (their per-skill selector — an\n * explicit selector in the URL/shorthand form wins over it), ignores\n * flags that are the dialog's job here (`-y`, `-g`, `--global`, …),\n * and routes the first non-flag token back through\n * {@link parseSkillInstallSpec} so URLs and shorthands inside the\n * command parse identically to a bare paste.\n */\nfunction parseCliAddCommand(rest: string): SkillInstallSpec {\n const tokens = rest.split(/\\s+/).filter(t => t.length > 0)\n let sourceToken: string | undefined\n let skill: string | undefined\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i] as string\n if (token === '--skill' || token === '-s') {\n skill = tokens[i + 1]\n i += 1\n continue\n }\n const inline = /^--skill=(.+)$/.exec(token)\n if (inline) {\n skill = inline[1] as string\n continue\n }\n if (token.startsWith('-'))\n continue\n if (sourceToken === undefined)\n sourceToken = token\n }\n if (sourceToken === undefined)\n throw new SkillInstallError('invalid-source', 'Pasted skills command has no source — expected “skills add <owner/repo>”.')\n const parsed = parseSkillInstallSpec(sourceToken)\n return { ...parsed, ...(skill !== undefined && parsed.skill === undefined ? { skill } : {}) }\n}\n\n// ---------------------------------------------------------------------------\n// Candidate enumeration + validation (data-only — no code execution)\n// ---------------------------------------------------------------------------\n\nexport interface SkillInstallCandidate {\n /** Directory name candidate (validated against SKILL.md frontmatter later). */\n name: string\n dir: string\n /**\n * Root-relative path (`engineering/tdd`) — the unambiguous selector\n * when the same skill NAME exists in several category directories.\n */\n rel: string\n}\n\n/**\n * How deep the candidate walk descends. Real-world collections nest\n * skills under category directories (`skills/engineering/tdd/SKILL.md`\n * in mattpocock/skills; `.github/skills/…` elsewhere) — one-level\n * enumeration missed all of them. Four levels covers every observed\n * layout while keeping the walk trivially bounded on the staged tree.\n */\nconst CANDIDATE_WALK_MAX_DEPTH = 4\n\n/**\n * List installable skills inside a fetched tree.\n *\n * A skill is ANY directory containing a `SKILL.md` — found by a\n * bounded recursive walk (depth {@link CANDIDATE_WALK_MAX_DEPTH}),\n * skipping dot-dirs and `node_modules`, and never descending INTO a\n * skill (its `references/` / `scripts/` subtree ships with it, it\n * doesn't nest further candidates). A root-level `SKILL.md` means\n * \"repo IS the skill\" and short-circuits, named from the fallback.\n *\n * Candidates carry their root-relative path (`rel`) so same-named\n * skills in different categories stay individually addressable.\n * Sorted by `rel`.\n */\nexport function listSkillCandidates(dir: string, fallbackName: string): SkillInstallCandidate[] {\n if (existsSync(join(dir, 'SKILL.md')))\n return [{ name: sanitizeName(fallbackName), dir, rel: '.' }]\n const out: SkillInstallCandidate[] = []\n const walk = (current: string, rel: string, depth: number): void => {\n if (depth > CANDIDATE_WALK_MAX_DEPTH)\n return\n for (const entry of readdirSync(current, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === 'node_modules')\n continue\n const childDir = join(current, entry.name)\n const childRel = rel.length === 0 ? entry.name : `${rel}/${entry.name}`\n if (existsSync(join(childDir, 'SKILL.md')))\n out.push({ name: entry.name, dir: childDir, rel: childRel })\n else\n walk(childDir, childRel, depth + 1)\n }\n }\n walk(dir, '', 1)\n return out.sort((a, b) => a.rel.localeCompare(b.rel))\n}\n\n/**\n * Frontmatter details for a host picker, parallel to the candidate list.\n * Parsing is best-effort per candidate — a malformed SKILL.md yields a\n * detail row without a description rather than failing the enumeration.\n */\nasync function candidateDetails(candidates: readonly SkillInstallCandidate[]): Promise<SkillCandidateDetail[]> {\n return Promise.all(candidates.map(async (c) => {\n const parsed = await parseSkillFile(join(c.dir, 'SKILL.md')).catch(() => null)\n const description = parsed?.description.trim()\n return { rel: c.rel, ...(description ? { description } : {}) }\n }))\n}\n\n/** Human-readable candidate list for error messages — capped, rel-qualified when ambiguous. */\nfunction describeCandidates(candidates: readonly SkillInstallCandidate[]): string {\n const nameCounts = new Map<string, number>()\n for (const c of candidates)\n nameCounts.set(c.name, (nameCounts.get(c.name) ?? 0) + 1)\n const labels = candidates.map(c => ((nameCounts.get(c.name) ?? 0) > 1 ? c.rel : c.name))\n const shown = labels.slice(0, 20)\n const more = labels.length - shown.length\n return shown.join(', ') + (more > 0 ? `, … and ${more} more` : '')\n}\n\n/**\n * Validate a staged candidate by PARSING its SKILL.md — the same lenient\n * parser discovery runs, so \"installs cleanly\" and \"discovers cleanly\"\n * are the same predicate. Returns the frontmatter name (which wins over\n * the directory-derived candidate name for the target folder).\n */\nasync function validateSkillCandidate(candidate: SkillInstallCandidate): Promise<{ name: string }> {\n const parsed = await parseSkillFile(join(candidate.dir, 'SKILL.md'))\n if (!parsed)\n throw new SkillInstallError('validate-failed', `${candidate.dir}/SKILL.md is not a valid skill (missing name or description in frontmatter).`)\n const name = parsed.name\n if (!validateSkillName(name))\n throw new SkillInstallError('validate-failed', `Skill name \"${name}\" is invalid (lowercase alphanumerics + single hyphens, max 64 chars).`)\n return { name }\n}\n\n// ---------------------------------------------------------------------------\n// Install\n// ---------------------------------------------------------------------------\n\nexport interface SkillInstallOptions {\n /** Raw source spec — see {@link parseSkillInstallSpec} for the grammar. */\n source: string\n scope: InstallScope\n /** Pick one skill from a multi-skill source (names from the `multiple-candidates` error). */\n skill?: string\n /**\n * Install EVERY skill a multi-skill source contains (the affirmative\n * answer to the host's \"import all?\" prompt after a\n * `multiple-candidates` error). Native engine only — already-installed\n * names are skipped (reported via `SkillInstallResult.skipped`) rather\n * than failing the batch, unless `overwrite` is also set. Overrides a\n * selector embedded in the source string; ignored when an explicit\n * `skill` option is present.\n */\n all?: boolean\n /**\n * Install a picked SUBSET of a multi-skill source — the host's checkbox\n * picker over the `multiple-candidates` list. Entries match a skill's\n * name or its root-relative path (same rules as `skill`); duplicates\n * collapse. Batch semantics mirror `all` (skip existing, pre-validate,\n * native engine). Takes precedence over `all` and over a selector\n * embedded in the source string; ignored when an explicit `skill`\n * option is present.\n */\n skills?: readonly string[]\n /** Overwrite an existing install of the same name. */\n overwrite?: boolean\n cwd?: string\n home?: string\n /** Storage prefix (default `.zidane`) — mirrors `ResolvedConfig.prefix`. */\n prefix?: string\n io?: InstallIo\n onProgress?: (message: string) => void\n /**\n * Prefer the skills.sh CLI when `skills` is on PATH (default true).\n * The CLI owns scope + layout decisions (`.agents/skills/`, their\n * lockfile); the native path is the fallback and the forced path in\n * tests. Set false to always install natively.\n */\n preferSkillsCli?: boolean\n}\n\nexport interface SkillInstallResult {\n /** Final skill name(s) installed. The CLI path reports the spec, not names. */\n installed: readonly string[]\n /** Names skipped during an `all` import because they were already installed. */\n skipped?: readonly string[]\n /** Candidate paths excluded from an `all` import because they failed validation. */\n failed?: readonly string[]\n /** Absolute target directory (native path only — the CLI owns its layout). */\n dir?: string\n /** `skills-cli` when delegated to the skills.sh CLI, else `native`. */\n engine: 'skills-cli' | 'native'\n provenance?: string\n}\n\n/**\n * Install a skill (or one skill out of a multi-skill source).\n *\n * Engine selection: targeted installs (an explicit skill selector) go\n * through the skills.sh CLI when present on PATH (unless\n * `preferSkillsCli: false`) — keeping their cross-agent layout and\n * lockfile — else the native fetch pipeline. Selector-less installs are\n * ALWAYS native: only native enumeration can tell single- from\n * multi-skill sources, and the host's \"import all?\" prompt rides on the\n * `multiple-candidates` error — delegating them to `skills add … -y`\n * would let the CLI's own multi-skill behavior silently decide instead.\n * `all: true` batches are native for the same reason (skip-existing +\n * per-skill provenance are our semantics).\n */\nexport async function installSkillFromSpec(opts: SkillInstallOptions): Promise<SkillInstallResult> {\n const io = opts.io ?? {}\n const which = io.which ?? defaultWhich\n const spec = parseSkillInstallSpec(opts.source)\n\n // Batch modes (`all` / `skills` subset) are always native — see JSDoc.\n // They also override a selector derived from the SOURCE string (a\n // skills.sh URL's third segment, a pasted `--skill`): the host's picker\n // re-runs with the same source after an ambiguous-selector error, and\n // keeping the spec selector would just re-throw the same error in a\n // loop. An explicit `opts.skill` still wins over everything.\n const batchMode = opts.all === true || (opts.skills?.length ?? 0) > 0\n const skillSelector = opts.skill ?? (batchMode ? undefined : spec.skill)\n if (!batchMode && skillSelector !== undefined && (opts.preferSkillsCli ?? true) && which('skills'))\n return await installViaSkillsCli(spec, skillSelector, opts)\n\n return await installNatively(spec, skillSelector, opts)\n}\n\n/**\n * Delegate to the skills.sh CLI. Non-interactive by construction: `-y`\n * skips confirmation prompts, `-g` maps our `user` scope to their\n * global scope (project scope is their default, keyed off cwd). The CLI\n * decides the on-disk layout (`.agents/skills/`), which zidane's\n * discovery already scans.\n */\nasync function installViaSkillsCli(\n spec: SkillInstallSpec,\n skillSelector: string | undefined,\n opts: SkillInstallOptions,\n): Promise<SkillInstallResult> {\n const exec = opts.io?.exec ?? defaultExec\n const args = ['add', spec.cliSpec, '-y']\n if (skillSelector)\n args.push('--skill', skillSelector)\n if (opts.scope === 'user')\n args.push('-g')\n opts.onProgress?.(`skills add ${spec.cliSpec}${skillSelector ? ` --skill ${skillSelector}` : ''}…`)\n const res = await exec('skills', args, { cwd: opts.cwd ?? process.cwd() })\n if (!res.ok)\n throw new SkillInstallError('cli-failed', `skills.sh CLI failed: ${lastLine(res.stderr) || lastLine(res.stdout) || 'unknown error'}`)\n return {\n installed: [skillSelector ?? spec.cliSpec],\n engine: 'skills-cli',\n }\n}\n\nasync function installNatively(\n spec: SkillInstallSpec,\n skillSelector: string | undefined,\n opts: SkillInstallOptions,\n): Promise<SkillInstallResult> {\n const io = opts.io ?? {}\n const source = spec.source\n const stage = mkdtempSync(join(tmpdir(), 'zidane-skill-install-'))\n try {\n const fetchedInto = join(stage, 'fetched')\n mkdirSync(fetchedInto, { recursive: true })\n let provenance: string\n try {\n provenance = (await fetchInstallSource(source, fetchedInto, io, opts.onProgress)).provenance\n }\n catch (err) {\n rethrowAsSkillError(err)\n }\n\n // `:subdir` re-roots the search — same physical containment as\n // extensions (hostile symlinks must not walk out of the stage).\n let candidateRoot = fetchedInto\n let fallbackName = source.kind === 'github' ? source.repo : source.pkg\n if (source.kind === 'github' && source.subdir) {\n const rooted = resolveSubdirRoot(fetchedInto, source.subdir)\n if (!rooted.ok) {\n if (rooted.reason === 'missing')\n throw new SkillInstallError('no-skill', `\"${source.subdir}\" is not a directory in ${source.owner}/${source.repo}.`)\n throw new SkillInstallError('invalid-source', `Subdirectory \"${source.subdir}\" escapes the repository root${rooted.reason === 'escape-symlink' ? ' through a symlink' : ''}.`)\n }\n candidateRoot = rooted.dir\n fallbackName = basename(resolve(fetchedInto, source.subdir))\n }\n\n const candidates = listSkillCandidates(candidateRoot, fallbackName)\n if (candidates.length === 0)\n throw new SkillInstallError('no-skill', `No skill found in ${opts.source} — no SKILL.md anywhere in the tree (searched ${CANDIDATE_WALK_MAX_DEPTH} levels deep).`)\n let picked: SkillInstallCandidate[]\n if (!skillSelector && opts.skills && opts.skills.length > 0) {\n // Host-picked subset (checkbox picker over the `multiple-candidates`\n // list). Each entry resolves with the same name-or-rel-path rules as\n // the single selector; duplicate picks collapse to one install.\n const byRel = new Map<string, SkillInstallCandidate>()\n for (const sel of opts.skills) {\n const matches = candidates.filter(c => c.name === sel || c.rel === sel)\n if (matches.length === 0)\n throw new SkillInstallError('no-skill', `No skill named \"${sel}\" in ${opts.source}. Available: ${describeCandidates(candidates)}`, candidates.map(c => c.rel))\n if (matches.length > 1)\n throw new SkillInstallError('multiple-candidates', `\"${sel}\" is ambiguous in ${opts.source} — pick a path: ${matches.map(c => c.rel).join(', ')}`, matches.map(c => c.rel))\n const match = matches[0] as SkillInstallCandidate\n byRel.set(match.rel, match)\n }\n picked = [...byRel.values()]\n }\n else if (skillSelector) {\n // Selector matches the skill name OR its root-relative path — the\n // path form disambiguates same-named skills in different category\n // directories (`engineering/tdd` vs `personal/tdd`).\n const matches = candidates.filter(c => c.name === skillSelector || c.rel === skillSelector)\n if (matches.length === 0)\n throw new SkillInstallError('no-skill', `No skill named \"${skillSelector}\" in ${opts.source}. Available: ${describeCandidates(candidates)}`, candidates.map(c => c.rel))\n if (matches.length > 1)\n throw new SkillInstallError('multiple-candidates', `\"${skillSelector}\" is ambiguous in ${opts.source} — pick a path: ${matches.map(c => c.rel).join(', ')}`, matches.map(c => c.rel))\n picked = [matches[0] as SkillInstallCandidate]\n }\n else if (candidates.length > 1 && !opts.all) {\n throw new SkillInstallError(\n 'multiple-candidates',\n `${opts.source} contains ${candidates.length} skills — pick one: ${describeCandidates(candidates)}`,\n candidates.map(c => c.rel),\n await candidateDetails(candidates),\n )\n }\n else {\n picked = [...candidates]\n }\n\n const root = scopeRoot(opts)\n const installed: string[] = []\n const skipped: string[] = []\n const failed: string[] = []\n let lastDir: string | undefined\n const batch = picked.length > 1\n\n // Validate the whole batch BEFORE installing anything — one malformed\n // candidate must not abort a half-applied import. Batch mode collects\n // failures (reported via `SkillInstallResult.failed`) and installs the\n // rest; a targeted single install keeps the hard throw.\n const resolved: Array<{ candidate: SkillInstallCandidate, name: string }> = []\n // Intra-batch name conflicts: two candidates whose frontmatter\n // validates to the same name (`engineering/tdd` + `personal/tdd`)\n // would otherwise install the first and mislabel the second as\n // \"already installed\" (or, with overwrite, silently last-wins).\n // First occurrence wins; later ones are reported as conflicts.\n const nameToRel = new Map<string, string>()\n for (const candidate of picked) {\n try {\n // Frontmatter name wins over the directory-derived candidate name —\n // mirrors \"target folder is named from the VALIDATED definition\".\n const { name } = await validateSkillCandidate(candidate)\n const conflict = nameToRel.get(name)\n if (conflict !== undefined) {\n // Only reachable in batch mode — a single pick can't conflict.\n failed.push(candidate.rel)\n opts.onProgress?.(`skipping \"${candidate.rel}\" — name \"${name}\" conflicts with \"${conflict}\"`)\n continue\n }\n nameToRel.set(name, candidate.rel)\n resolved.push({ candidate, name })\n }\n catch (err) {\n if (!batch)\n throw err\n failed.push(candidate.rel)\n opts.onProgress?.(`skipping \"${candidate.rel}\" — ${errorMessage(err)}`)\n }\n }\n\n for (const { candidate, name } of resolved) {\n const targetDir = join(root, name)\n const backupDir = `${targetDir}.zidane-backup`\n if (existsSync(targetDir) && !opts.overwrite) {\n // Batch imports skip collisions (already-installed skills are the\n // common case when re-importing a repo); a targeted single install\n // keeps the hard error so the overwrite decision stays explicit.\n if (batch) {\n skipped.push(name)\n opts.onProgress?.(`skipping \"${name}\" — already installed`)\n continue\n }\n throw new SkillInstallError('exists', `Skill \"${name}\" is already installed at ${targetDir}. Overwrite to replace it.`)\n }\n\n mkdirSync(root, { recursive: true })\n const hadPrevious = existsSync(targetDir)\n if (hadPrevious) {\n rmSync(backupDir, { recursive: true, force: true })\n renameSync(targetDir, backupDir)\n }\n try {\n // `dereference` materializes in-tree symlinked files so the install\n // has no dangling links once the stage is deleted.\n cpSync(candidate.dir, targetDir, { recursive: true, dereference: true })\n writeProvenance(targetDir, { spec: opts.source, ...(skillSelector ? { skill: skillSelector } : {}), scope: opts.scope, provenance, installedAt: Date.now() })\n }\n catch (err) {\n rmSync(targetDir, { recursive: true, force: true })\n if (hadPrevious)\n renameSync(backupDir, targetDir)\n throw new SkillInstallError('io-failed', `Writing ${targetDir} failed: ${errorMessage(err)}`)\n }\n rmSync(backupDir, { recursive: true, force: true })\n installed.push(name)\n lastDir = targetDir\n if (batch)\n opts.onProgress?.(`installed \"${name}\" (${installed.length}/${resolved.length})`)\n }\n\n if (installed.length === 0 && skipped.length > 0)\n throw new SkillInstallError('exists', `All ${skipped.length} installable skills from ${opts.source} are already installed: ${skipped.join(', ')}. Overwrite to replace them.`)\n if (installed.length === 0 && failed.length > 0)\n throw new SkillInstallError('validate-failed', `No skill from ${opts.source} was installable — invalid: ${failed.join(', ')}.`)\n\n return {\n installed,\n ...(skipped.length > 0 ? { skipped } : {}),\n ...(failed.length > 0 ? { failed } : {}),\n ...(lastDir !== undefined ? { dir: lastDir } : {}),\n engine: 'native',\n provenance,\n }\n }\n finally {\n rmSync(stage, { recursive: true, force: true })\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Provenance sidecar — lets a future update flow replay the recorded spec. */\nexport const SKILL_PROVENANCE_FILE = '.zidane-install.json'\n\ninterface SkillProvenance {\n spec: string\n skill?: string\n scope: InstallScope\n provenance: string\n installedAt: number\n}\n\nfunction writeProvenance(dir: string, data: SkillProvenance): void {\n writeFileSync(join(dir, SKILL_PROVENANCE_FILE), `${JSON.stringify(data, null, 2)}\\n`)\n}\n\n/** Read a skill directory's install provenance, `null` for hand-authored skills. */\nexport function readSkillProvenance(dir: string): (SkillProvenance & { spec: string }) | null {\n try {\n const raw = JSON.parse(readFileSync(join(dir, SKILL_PROVENANCE_FILE), 'utf8')) as Partial<SkillProvenance>\n return typeof raw.spec === 'string' && raw.spec.length > 0 ? (raw as SkillProvenance) : null\n }\n catch {\n return null\n }\n}\n\n/**\n * Native-install target root: the `<prefix>/skills` flavor of the\n * project/user convention (`~/.zidane/skills`, `<gitRoot>/.zidane/skills`).\n * The `.agents/skills` siblings stay read-only for us — they belong to\n * the cross-agent ecosystem (and the skills.sh CLI writes there).\n */\nfunction scopeRoot(opts: SkillInstallOptions): string {\n const roots = projectUserPaths({\n subPath: 'skills',\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n ...(opts.home ? { home: opts.home } : {}),\n ...(opts.prefix ? { prefix: opts.prefix } : {}),\n })\n const root = roots.find(r => r.source === opts.scope && r.path.includes(`.${(opts.prefix ?? '.zidane').replace(/^\\./, '')}`))\n if (!root)\n throw new SkillInstallError('io-failed', `No ${opts.scope} skills root resolved.`)\n return root.path\n}\n\nfunction sanitizeName(raw: string): string {\n const cleaned = raw.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').replace(/-{2,}/g, '-')\n return cleaned.length > 0 ? cleaned : 'skill'\n}\n","import type { SkillConfig } from './types'\nimport { validateSkillForWrite } from './validate'\n\nexport {\n type ActivationVia,\n type ActiveSkill,\n createSkillActivationState,\n type DeactivationReason,\n type SkillActivationState,\n type SkillActivationStateOptions,\n} from './activation'\nexport {\n IMPLICITLY_ALLOWED_SKILL_TOOLS,\n installAllowedToolsGate,\n} from './allowed-tools'\nexport { buildCatalog } from './catalog'\nexport {\n discoverSkills,\n getDefaultScanPaths,\n inferSource,\n parseFrontmatter,\n parseSkillFile,\n} from './discovery'\nexport type { SourcedScanPath } from './discovery'\nexport {\n installSkillFromSpec,\n listSkillCandidates,\n parseSkillInstallSpec,\n readSkillProvenance,\n SKILL_PROVENANCE_FILE,\n SkillInstallError,\n} from './install'\nexport type {\n SkillCandidateDetail,\n SkillInstallCandidate,\n SkillInstallErrorCode,\n SkillInstallOptions,\n SkillInstallResult,\n SkillInstallSpec,\n} from './install'\nexport { interpolateShellCommands, stripShellInterpolations } from './interpolate'\nexport type { InterpolateShellCommandsOptions } from './interpolate'\nexport { resolveSkills } from './resolve'\nexport type {\n ShellInterpolationApproval,\n SkillConfig,\n SkillDiagnostic,\n SkillResource,\n SkillsConfig,\n SkillSource,\n} from './types'\nexport {\n isToolAllowedByUnion,\n matchesAllowedTool,\n parseAllowedToolPattern,\n validateResourcePath,\n validateResourcePathReal,\n validateSkillForWrite,\n validateSkillName,\n} from './validate'\nexport type { SkillValidationIssue, SkillValidationResult } from './validate'\nexport { writeSkillsToDisk, writeSkillToDisk } from './writer'\n\n// ---------------------------------------------------------------------------\n// defineSkill helper\n// ---------------------------------------------------------------------------\n\n/**\n * Define an inline skill configuration.\n *\n * Strict-validates at author-time — throws if the config would be rejected by\n * `writeSkillToDisk` or the spec. Source defaults to `'inline'`.\n */\nexport function defineSkill(config: Omit<SkillConfig, 'source'> & { source?: SkillConfig['source'] }): SkillConfig {\n const normalized: SkillConfig = {\n ...config,\n source: config.source ?? 'inline',\n }\n const result = validateSkillForWrite(normalized)\n if (!result.valid) {\n const summary = result.errors.map(e => ` - [${e.code}] ${e.message}`).join('\\n')\n throw new Error(`Invalid skill \"${normalized.name}\":\\n${summary}`)\n }\n return normalized\n}\n"],"mappings":";;;;;;AAwDA,IAAa,oBAAb,cAAuC,mBAAmB;;;;;;;CAQxD;CACA,YAAY,MAA6B,SAAiB,YAAgC,SAA2C;EACnI,MAAM,MAAM,SAAS,UAAU;EAC/B,KAAK,OAAO;EACZ,IAAI,SACF,KAAK,UAAU;CACnB;AACF;AAUA,SAAS,oBAAoB,KAAqB;CAChD,IAAI,eAAe,sBAAsB,EAAE,eAAe,oBACxD,MAAM,IAAI,kBAAkB,IAAI,MAA+B,IAAI,SAAS,IAAI,UAAU;CAC5F,MAAM;AACR;AAMA,MAAM,mBAAmB;;;;;;;;;AAUzB,MAAM,wBAAwB;;;;;;;;AAyB9B,SAAgB,sBAAsB,KAA+B;CACnE,MAAM,OAAO,IAAI,KAAK;CACtB,MAAM,aAAa,sBAAsB,KAAK,IAAI;CAClD,IAAI,YACF,OAAO,mBAAmB,WAAW,EAAY;CACnD,MAAM,WAAW,iBAAiB,KAAK,IAAI;CAC3C,IAAI,UACF,OAAO;EACL,QAAQ;GAAE,MAAM;GAAU,OAAO,SAAS;GAAc,MAAM,SAAS;EAAa;EACpF,GAAI,SAAS,KAAK,EAAE,OAAO,SAAS,GAAG,IAAI,CAAC;EAC5C,SAAS,GAAG,SAAS,GAAG,GAAG,SAAS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;AACT"}
|
package/dist/skills.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $s as SkillInstallResult, Bs as validateResourcePathReal, Fs as SkillValidationResult, Gs as interpolateShellCommands, Hs as validateSkillName, Is as isToolAllowedByUnion, Js as SkillCandidateDetail, Ks as stripShellInterpolations, Ls as matchesAllowedTool, Ms as writeSkillToDisk, Ns as writeSkillsToDisk, Ps as SkillValidationIssue, Qs as SkillInstallOptions, Rs as parseAllowedToolPattern, Us as resolveSkills, Vs as validateSkillForWrite, Ws as InterpolateShellCommandsOptions, Xs as SkillInstallError, Ys as SkillInstallCandidate, Zs as SkillInstallErrorCode, _c as SkillActivationState, ac as SourcedScanPath, ap as SkillConfig, cc as inferSource, cp as SkillSource, dc as buildCatalog, ec as SkillInstallSpec, fc as IMPLICITLY_ALLOWED_SKILL_TOOLS, gc as DeactivationReason, hc as ActiveSkill, ic as readSkillProvenance, ip as ShellInterpolationApproval, js as defineSkill, lc as parseFrontmatter, lp as SkillsConfig, mc as ActivationVia, nc as listSkillCandidates, oc as discoverSkills, op as SkillDiagnostic, pc as installAllowedToolsGate, qs as SKILL_PROVENANCE_FILE, rc as parseSkillInstallSpec, sc as getDefaultScanPaths, sp as SkillResource, tc as installSkillFromSpec, uc as parseSkillFile, vc as SkillActivationStateOptions, yc as createSkillActivationState, zs as validateResourcePath } from "./index-
|
|
1
|
+
import { $s as SkillInstallResult, Bs as validateResourcePathReal, Fs as SkillValidationResult, Gs as interpolateShellCommands, Hs as validateSkillName, Is as isToolAllowedByUnion, Js as SkillCandidateDetail, Ks as stripShellInterpolations, Ls as matchesAllowedTool, Ms as writeSkillToDisk, Ns as writeSkillsToDisk, Ps as SkillValidationIssue, Qs as SkillInstallOptions, Rs as parseAllowedToolPattern, Us as resolveSkills, Vs as validateSkillForWrite, Ws as InterpolateShellCommandsOptions, Xs as SkillInstallError, Ys as SkillInstallCandidate, Zs as SkillInstallErrorCode, _c as SkillActivationState, ac as SourcedScanPath, ap as SkillConfig, cc as inferSource, cp as SkillSource, dc as buildCatalog, ec as SkillInstallSpec, fc as IMPLICITLY_ALLOWED_SKILL_TOOLS, gc as DeactivationReason, hc as ActiveSkill, ic as readSkillProvenance, ip as ShellInterpolationApproval, js as defineSkill, lc as parseFrontmatter, lp as SkillsConfig, mc as ActivationVia, nc as listSkillCandidates, oc as discoverSkills, op as SkillDiagnostic, pc as installAllowedToolsGate, qs as SKILL_PROVENANCE_FILE, rc as parseSkillInstallSpec, sc as getDefaultScanPaths, sp as SkillResource, tc as installSkillFromSpec, uc as parseSkillFile, vc as SkillActivationStateOptions, yc as createSkillActivationState, zs as validateResourcePath } from "./index-l0wehkWU.js";
|
|
2
2
|
export { type ActivationVia, type ActiveSkill, type DeactivationReason, IMPLICITLY_ALLOWED_SKILL_TOOLS, type InterpolateShellCommandsOptions, SKILL_PROVENANCE_FILE, type ShellInterpolationApproval, type SkillActivationState, type SkillActivationStateOptions, type SkillCandidateDetail, type SkillConfig, type SkillDiagnostic, type SkillInstallCandidate, SkillInstallError, type SkillInstallErrorCode, type SkillInstallOptions, type SkillInstallResult, type SkillInstallSpec, type SkillResource, type SkillSource, type SkillValidationIssue, type SkillValidationResult, type SkillsConfig, type SourcedScanPath, buildCatalog, createSkillActivationState, defineSkill, discoverSkills, getDefaultScanPaths, inferSource, installAllowedToolsGate, installSkillFromSpec, interpolateShellCommands, isToolAllowedByUnion, listSkillCandidates, matchesAllowedTool, parseAllowedToolPattern, parseFrontmatter, parseSkillFile, parseSkillInstallSpec, readSkillProvenance, resolveSkills, stripShellInterpolations, validateResourcePath, validateResourcePathReal, validateSkillForWrite, validateSkillName, writeSkillToDisk, writeSkillsToDisk };
|
package/dist/skills.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { A as validateSkillName, C as stripShellInterpolations, D as validateResourcePath, E as parseAllowedToolPattern, O as validateResourcePathReal, S as interpolateShellCommands, T as matchesAllowedTool, a as getDefaultScanPaths, c as parseSkillFile, d as installAllowedToolsGate, f as createSkillActivationState, i as discoverSkills, k as validateSkillForWrite, l as buildCatalog, n as writeSkillToDisk, o as inferSource, r as writeSkillsToDisk, s as parseFrontmatter, t as resolveSkills, u as IMPLICITLY_ALLOWED_SKILL_TOOLS, w as isToolAllowedByUnion } from "./resolve-HtxmBWs9.js";
|
|
2
|
-
import { a as listSkillCandidates, i as installSkillFromSpec, n as SKILL_PROVENANCE_FILE, o as parseSkillInstallSpec, r as SkillInstallError, s as readSkillProvenance, t as defineSkill } from "./skills-
|
|
2
|
+
import { a as listSkillCandidates, i as installSkillFromSpec, n as SKILL_PROVENANCE_FILE, o as parseSkillInstallSpec, r as SkillInstallError, s as readSkillProvenance, t as defineSkill } from "./skills-DKWqoaYH.js";
|
|
3
3
|
export { IMPLICITLY_ALLOWED_SKILL_TOOLS, SKILL_PROVENANCE_FILE, SkillInstallError, buildCatalog, createSkillActivationState, defineSkill, discoverSkills, getDefaultScanPaths, inferSource, installAllowedToolsGate, installSkillFromSpec, interpolateShellCommands, isToolAllowedByUnion, listSkillCandidates, matchesAllowedTool, parseAllowedToolPattern, parseFrontmatter, parseSkillFile, parseSkillInstallSpec, readSkillProvenance, resolveSkills, stripShellInterpolations, validateResourcePath, validateResourcePathReal, validateSkillForWrite, validateSkillName, writeSkillToDisk, writeSkillsToDisk };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $u as ProviderKey, Bu as StreamEvent, Qu as ProviderAuth, rd as ModelInfo, zu as Settings } from "./index-
|
|
1
|
+
import { $u as ProviderKey, Bu as StreamEvent, Qu as ProviderAuth, rd as ModelInfo, zu as Settings } from "./index-l0wehkWU.js";
|
|
2
2
|
import { ReactNode } from "react";
|
|
3
3
|
|
|
4
4
|
//#region src/chat/turn-selection.d.ts
|
|
@@ -432,4 +432,4 @@ declare function displayNameFor(name: string, input?: Record<string, unknown>):
|
|
|
432
432
|
declare function formatToolCall(name: string, input: Record<string, unknown>): ToolFormatLine | null;
|
|
433
433
|
//#endregion
|
|
434
434
|
export { turnSelectionOwnership as A, useSafeModeActions as C, isTurnHighlighted as D, isEditErrorResult as E, isVisible as O, SafeModeProvider as S, EDIT_TOOL_NAMES as T, splitMarkdownCodeBlocks as _, formatToolCall as a, RequestApproval as b, splitPromptSegments as c, filterModelCatalog as d, indexOfEntry as f, normalizeMarkdownCodeFences as g, chunkMarkdownForRender as h, displayNameFor as i, selectableTurnIds as k, CatalogEntry as l, MarkdownSegment as m, ToolDisplayMeta as n, PromptSegment as o, MARKDOWN_RENDER_CHUNK_TARGET_BYTES as p, ToolFormatLine as r, PromptSegmentRef as s, TOOL_DISPLAY as t, buildModelCatalog as u, ApprovalDecision as v, useSafeModeQueue as w, SafeModeActions as x, ApprovalRequest as y };
|
|
435
|
-
//# sourceMappingURL=tool-formatters-
|
|
435
|
+
//# sourceMappingURL=tool-formatters-BSwVkSX2.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-formatters-
|
|
1
|
+
{"version":3,"file":"tool-formatters-BSwVkSX2.d.ts","names":[],"sources":["../src/chat/turn-selection.ts","../src/chat/safe-mode-context.tsx","../src/chat/markdown-segments.ts","../src/chat/model-catalog.ts","../src/chat/prompt-segments.ts","../src/chat/tool-formatters.ts"],"mappings":";;;;;cAaa,eAAA,EAAiB,WAAW;;AAAzC;;;;AAAyC;AAmBzC;;;;AAA8C;AAqE9C;;;;;;iBArEgB,iBAAA,CAAkB,IAAY;;;;;;;AAoLN;AA6BxC;;;;;;iBA5IgB,SAAA,CAAU,KAAA,EAAO,WAAA,EAAa,QAAA,EAAU,QAAQ;;;AA8I3C;;;;AChNrB;;;;AAK6B;AAQ7B;;;;;;;;AAE4B;AAE5B;;;;;;;iBD4GgB,sBAAA,CAAuB,MAAA,WAAiB,WAAA,KAAgB,GAAG;;;;;;;;;;;ACtG1C;iBDuJjB,iBAAA,CACd,KAAA,EAAO,IAAA,CAAK,WAAA,aACZ,cAAA,iBACA,SAAA,EAAW,WAAA;;;;;;;;;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AAQ7B;;;;;AAR6B,iBImVb,cAAA,CAAe,IAAA,UAAc,KAAA,EAAO,MAAA,oBAA0B,cAAc"}
|
package/dist/tools.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $f as hashContent, $n as waitTask, As as matchModelEntries, Cr as glob, Cs as SubagentOverride, Ds as SpawnModelEntry, Es as isSpawnTool, Jf as ToolMap, Kf as ToolContext, Os as createModelSearchTool, Qf as getReadState, Qn as WAIT_TASK_TIMED_OUT_PREFIX, Sr as grep, Ss as SubagentDef, Ts as createSpawnTool, Xf as ReadStateEntry, Yf as HydrateReadStateOptions, Zf as ReadStateMap, Zn as writeFile, _r as readFile, _s as SpawnTaskInput, ar as ToolSearchToolOptions, br as InteractionToolOptions, bs as SpawnToolOptions, cr as createSkillsUseTool, dr as SkillsReadToolOptions, ep as hydrateReadStateFromSession, er as ValidationResult, fr as createSkillsReadTool, gr as shell, gs as ExtensionSubagentDef, hr as createShellTool, hs as ChildAgent, ir as LazyToolEntry, ks as formatModelLine, lr as SkillsRunScriptToolOptions, mr as CreateShellToolOptions, np as readStateKey, nr as TailTruncateOptions, or as createToolSearchTool, pr as shellKill, qf as ToolDef, rp as resolveReadStateMap, rr as tailTruncate, sr as SkillsUseToolOptions, tp as hydrateReadStateFromSessionAsync, tr as validateToolArgs, ur as createSkillsRunScriptTool, vr as multiEdit, vs as SpawnTaskOutcome, wr as edit, ws as SubagentRegistry, xr as createInteractionTool, xs as SpawnToolState, yr as listFiles, ys as SpawnTool } from "./index-
|
|
1
|
+
import { $f as hashContent, $n as waitTask, As as matchModelEntries, Cr as glob, Cs as SubagentOverride, Ds as SpawnModelEntry, Es as isSpawnTool, Jf as ToolMap, Kf as ToolContext, Os as createModelSearchTool, Qf as getReadState, Qn as WAIT_TASK_TIMED_OUT_PREFIX, Sr as grep, Ss as SubagentDef, Ts as createSpawnTool, Xf as ReadStateEntry, Yf as HydrateReadStateOptions, Zf as ReadStateMap, Zn as writeFile, _r as readFile, _s as SpawnTaskInput, ar as ToolSearchToolOptions, br as InteractionToolOptions, bs as SpawnToolOptions, cr as createSkillsUseTool, dr as SkillsReadToolOptions, ep as hydrateReadStateFromSession, er as ValidationResult, fr as createSkillsReadTool, gr as shell, gs as ExtensionSubagentDef, hr as createShellTool, hs as ChildAgent, ir as LazyToolEntry, ks as formatModelLine, lr as SkillsRunScriptToolOptions, mr as CreateShellToolOptions, np as readStateKey, nr as TailTruncateOptions, or as createToolSearchTool, pr as shellKill, qf as ToolDef, rp as resolveReadStateMap, rr as tailTruncate, sr as SkillsUseToolOptions, tp as hydrateReadStateFromSessionAsync, tr as validateToolArgs, ur as createSkillsRunScriptTool, vr as multiEdit, vs as SpawnTaskOutcome, wr as edit, ws as SubagentRegistry, xr as createInteractionTool, xs as SpawnToolState, yr as listFiles, ys as SpawnTool } from "./index-l0wehkWU.js";
|
|
2
2
|
export { type ChildAgent, type CreateShellToolOptions, type ExtensionSubagentDef, type HydrateReadStateOptions, type InteractionToolOptions, type LazyToolEntry, type ReadStateEntry, type ReadStateMap, type SkillsReadToolOptions, type SkillsRunScriptToolOptions, type SkillsUseToolOptions, type SpawnModelEntry, type SpawnTaskInput, type SpawnTaskOutcome, type SpawnTool, type SpawnToolOptions, type SpawnToolState, type SubagentDef, type SubagentOverride, type SubagentRegistry, type TailTruncateOptions, type ToolContext, type ToolDef, type ToolMap, type ToolSearchToolOptions, type ValidationResult, WAIT_TASK_TIMED_OUT_PREFIX, createInteractionTool, createModelSearchTool, createShellTool, createSkillsReadTool, createSkillsRunScriptTool, createSkillsUseTool, createSpawnTool, createToolSearchTool, edit, formatModelLine, getReadState, glob, grep, hashContent, hydrateReadStateFromSession, hydrateReadStateFromSessionAsync, isSpawnTool, listFiles, matchModelEntries, multiEdit, readFile, readStateKey, resolveReadStateMap, shell, shellKill, tailTruncate, validateToolArgs, waitTask, writeFile };
|