zidane 6.1.12 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/{acp-D-k-L0DX.js → acp-0JO-UBEv.js} +2 -2
  2. package/dist/{acp-D-k-L0DX.js.map → acp-0JO-UBEv.js.map} +1 -1
  3. package/dist/acp-cli.js +2 -2
  4. package/dist/acp.d.ts +1 -1
  5. package/dist/acp.js +1 -1
  6. package/dist/{agent-BJ1NC1pA.js → agent-25moybsj.js} +75 -13
  7. package/dist/agent-25moybsj.js.map +1 -0
  8. package/dist/agent.d.ts +1 -1
  9. package/dist/agent.js +1 -1
  10. package/dist/chat/pure.d.ts +3 -3
  11. package/dist/chat/pure.js +2 -2
  12. package/dist/chat.d.ts +5 -5
  13. package/dist/chat.d.ts.map +1 -1
  14. package/dist/chat.js +7 -7
  15. package/dist/{completion-core-CXYSVhZo.js → completion-core-BRo86R_L.js} +23 -10
  16. package/dist/completion-core-BRo86R_L.js.map +1 -0
  17. package/dist/contexts/daytona.d.ts +1 -1
  18. package/dist/contexts/e2b.d.ts +1 -1
  19. package/dist/eval.d.ts +1 -1
  20. package/dist/extensions.d.ts +2 -2
  21. package/dist/extensions.js +2 -2
  22. package/dist/headless.d.ts +1 -1
  23. package/dist/headless.js +1 -1
  24. package/dist/{index-2MYNIBnZ.d.ts → index-mUT8TI9j.d.ts} +249 -13
  25. package/dist/index-mUT8TI9j.d.ts.map +1 -0
  26. package/dist/index.d.ts +2 -2
  27. package/dist/index.js +7 -7
  28. package/dist/{generate-data-WL_yGVL6.js → inline-autocomplete-w_O3SVtN.js} +186 -6
  29. package/dist/inline-autocomplete-w_O3SVtN.js.map +1 -0
  30. package/dist/{login-DhnmYiia.js → login-Bp_tRj_e.js} +2 -2
  31. package/dist/{login-DhnmYiia.js.map → login-Bp_tRj_e.js.map} +1 -1
  32. package/dist/mcp.d.ts +1 -1
  33. package/dist/output/stream-json.d.ts +1 -1
  34. package/dist/output/terminal.d.ts +1 -1
  35. package/dist/presets.d.ts +1 -1
  36. package/dist/presets.js +1 -1
  37. package/dist/providers/anthropic.d.ts +1 -1
  38. package/dist/providers/arcee.d.ts +1 -1
  39. package/dist/providers/baseten.d.ts +1 -1
  40. package/dist/providers/cerebras.d.ts +1 -1
  41. package/dist/providers/local.d.ts +1 -1
  42. package/dist/providers/openai-compat.d.ts +1 -1
  43. package/dist/providers/openai.d.ts +1 -1
  44. package/dist/providers/openrouter.d.ts +1 -1
  45. package/dist/providers/xai.d.ts +1 -1
  46. package/dist/providers.d.ts +1 -1
  47. package/dist/{resolve-CC8Lmwcj.js → resolve-HtxmBWs9.js} +11 -3
  48. package/dist/resolve-HtxmBWs9.js.map +1 -0
  49. package/dist/restate.d.ts +1 -1
  50. package/dist/session/sqlite.d.ts +1 -1
  51. package/dist/session.d.ts +1 -1
  52. package/dist/{skills-BjeXSRlQ.js → skills-BlmY7QhV.js} +2 -2
  53. package/dist/{skills-BjeXSRlQ.js.map → skills-BlmY7QhV.js.map} +1 -1
  54. package/dist/skills.d.ts +1 -1
  55. package/dist/skills.js +2 -2
  56. package/dist/{tool-formatters-BWzn4rp_.d.ts → tool-formatters-DOcJz_J9.d.ts} +2 -2
  57. package/dist/{tool-formatters-BWzn4rp_.d.ts.map → tool-formatters-DOcJz_J9.d.ts.map} +1 -1
  58. package/dist/tools/fetch-url.d.ts +1 -1
  59. package/dist/tools/web-search.d.ts +1 -1
  60. package/dist/tools.d.ts +1 -1
  61. package/dist/tools.js +1 -1
  62. package/dist/{transcript-anchors-BNpLnru1.js → transcript-anchors-CO-WnuYQ.js} +15 -8
  63. package/dist/transcript-anchors-CO-WnuYQ.js.map +1 -0
  64. package/dist/{transcript-anchors-CzLl7Y1I.d.ts → transcript-anchors-CzMMNrhJ.d.ts} +2 -2
  65. package/dist/{transcript-anchors-CzLl7Y1I.d.ts.map → transcript-anchors-CzMMNrhJ.d.ts.map} +1 -1
  66. package/dist/tui.d.ts +11 -4
  67. package/dist/tui.d.ts.map +1 -1
  68. package/dist/tui.js +345 -39
  69. package/dist/tui.js.map +1 -1
  70. package/dist/{turn-operations-BrYae3Rp.d.ts → turn-operations-CrCrJnvo.d.ts} +3 -3
  71. package/dist/{turn-operations-BrYae3Rp.d.ts.map → turn-operations-CrCrJnvo.d.ts.map} +1 -1
  72. package/dist/{turn-operations-BkGio0n2.js → turn-operations-D9p-y9EC.js} +8 -4
  73. package/dist/turn-operations-D9p-y9EC.js.map +1 -0
  74. package/dist/types.d.ts +1 -1
  75. package/docs/EXTENSIONS.md +37 -1
  76. package/package.json +3 -2
  77. package/dist/agent-BJ1NC1pA.js.map +0 -1
  78. package/dist/completion-core-CXYSVhZo.js.map +0 -1
  79. package/dist/generate-data-WL_yGVL6.js.map +0 -1
  80. package/dist/index-2MYNIBnZ.d.ts.map +0 -1
  81. package/dist/resolve-CC8Lmwcj.js.map +0 -1
  82. package/dist/transcript-anchors-BNpLnru1.js.map +0 -1
  83. package/dist/turn-operations-BkGio0n2.js.map +0 -1
@@ -1,3 +1,6 @@
1
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
2
+ import { readdirSync } from "node:fs";
3
+ import { homedir } from "node:os";
1
4
  //#region src/chat/commands.ts
2
5
  /**
3
6
  * Persisted form of output blocks inside a display-only `command` turn:
@@ -70,17 +73,29 @@ function commandSteps(command) {
70
73
  * what keeps mid-prompt `/skill` mentions routed to the skills provider:
71
74
  * `"summarize /research"` is not a command, `"/research foo"` is.
72
75
  *
73
- * `knownNames` is matched case-insensitively; the returned `name` is the
74
- * canonical (registered) casing.
76
+ * `known` is matched case-insensitively; entries may be bare names or
77
+ * `{ name, aliases }` records — an alias hit canonicalizes to the entry's
78
+ * `name` (registered casing), so dispatch-by-name downstream just works.
75
79
  */
76
- function parseCommandInvocation(prompt, knownNames) {
80
+ function parseCommandInvocation(prompt, known) {
77
81
  const body = prompt.trimStart();
78
82
  if (body[0] !== "/") return null;
79
83
  const afterSlash = body.slice(1);
80
84
  const wsIdx = afterSlash.search(/\s/);
81
85
  const typed = (wsIdx === -1 ? afterSlash : afterSlash.slice(0, wsIdx)).toLowerCase();
82
86
  if (typed.length === 0) return null;
83
- const canonical = knownNames.find((n) => n.toLowerCase() === typed);
87
+ let canonical;
88
+ for (const entry of known) {
89
+ const name = typeof entry === "string" ? entry : entry.name;
90
+ if (name.toLowerCase() === typed) {
91
+ canonical = name;
92
+ break;
93
+ }
94
+ if (typeof entry !== "string" && entry.aliases?.some((a) => a.toLowerCase() === typed)) {
95
+ canonical = name;
96
+ break;
97
+ }
98
+ }
84
99
  if (canonical === void 0) return null;
85
100
  const args = (wsIdx === -1 ? "" : afterSlash.slice(wsIdx + 1)).trim();
86
101
  return {
@@ -319,6 +334,171 @@ async function generateStructuredData(options) {
319
334
  return payload;
320
335
  }
321
336
  //#endregion
322
- export { isStandardSchema as a, commandBlockToEvent as c, executeCommand as d, parseCommandInvocation as f, shouldAutoGenerateTitle as i, commandBlocksToContent as l, cleanTitle as n, resolveSchemaInput as o, generateSessionTitle as r, zodToJsonSchema as s, generateStructuredData as t, commandSteps as u };
337
+ //#region src/chat/inline-autocomplete.ts
338
+ /**
339
+ * Inline (ghost-text) autocomplete for the prompt.
340
+ *
341
+ * Distinct from the trigger-based completion popover (`@` files, `/`
342
+ * commands): providers here suggest plain text SUFFIX candidates to
343
+ * append at the cursor — the first renders as dim ghost text, up/down
344
+ * rotates through the rest, Tab accepts. No popover.
345
+ *
346
+ * Providers are queried in registration order with a shared AbortSignal;
347
+ * the engine returns the first provider's non-empty candidate list.
348
+ * Extensions add providers via `ctx.registerInlineAutocompleteProvider`
349
+ * — the built-in path provider ({@link createPathAutocompleteProvider})
350
+ * is always first.
351
+ */
352
+ /** Per-provider deadline — a hung provider is treated as "no suggestion". */
353
+ const PROVIDER_DEADLINE_MS = 150;
354
+ /**
355
+ * Query `providers` in order; the first provider yielding a non-empty
356
+ * candidate list wins (a bare string normalizes to a 1-element list).
357
+ * Provider errors are swallowed (a broken extension provider must not
358
+ * break typing), and each provider races a {@link PROVIDER_DEADLINE_MS}
359
+ * deadline so one hung provider can't permanently suppress the ghosts of
360
+ * providers behind it. Returns null when aborted or nothing matched.
361
+ */
362
+ async function resolveInlineSuggestion(providers, ctx, deadlineMs = PROVIDER_DEADLINE_MS) {
363
+ const TIMEOUT = Symbol("timeout");
364
+ for (const provider of providers) {
365
+ if (ctx.signal.aborted) return null;
366
+ try {
367
+ let timer;
368
+ const result = await Promise.race([Promise.resolve(provider.suggest(ctx)), new Promise((r) => {
369
+ timer = setTimeout(r, deadlineMs, TIMEOUT);
370
+ })]);
371
+ if (timer !== void 0) clearTimeout(timer);
372
+ if (result === TIMEOUT) continue;
373
+ if (ctx.signal.aborted) return null;
374
+ const suffixes = (typeof result === "string" ? [result] : result ?? []).filter((s) => typeof s === "string" && s.length > 0);
375
+ if (suffixes.length > 0) return {
376
+ suffixes,
377
+ providerId: provider.id
378
+ };
379
+ } catch {}
380
+ }
381
+ return null;
382
+ }
383
+ /**
384
+ * Extract the whitespace-delimited token that ends at `cursor`. Returns
385
+ * null when the cursor sits right after whitespace (nothing to complete).
386
+ */
387
+ function tokenEndingAtCursor(text, cursor) {
388
+ const match = text.slice(0, cursor).match(/\S+$/);
389
+ return match ? match[0] : null;
390
+ }
391
+ /**
392
+ * Does this token carry an explicit path shape (`/` separator or a `~`
393
+ * prefix)? Path-shaped tokens complete from the first character after
394
+ * the separator; bare tokens (`sr` → `c/`) still complete against the
395
+ * cwd listing but need ≥2 chars first — see the provider.
396
+ */
397
+ function looksLikePath(token) {
398
+ return token.includes("/") || token.startsWith("~");
399
+ }
400
+ /**
401
+ * Cap on candidates returned for an ambiguous fragment — rotation past
402
+ * a dozen-odd entries stops being faster than typing another character.
403
+ */
404
+ const MAX_PATH_CANDIDATES = 16;
405
+ function defaultReaddir(dir) {
406
+ return readdirSync(dir, { withFileTypes: true }).map((e) => ({
407
+ name: e.name,
408
+ isDirectory: e.isDirectory()
409
+ }));
410
+ }
411
+ /**
412
+ * Built-in provider: complete filesystem paths under `cwd` (or absolute /
413
+ * `~` paths). Given the token `src/chat/comp`, lists `src/chat/` and
414
+ * returns every matching continuation of `comp` as a candidate list —
415
+ * directories first, alphabetical, `/`-terminated for directories so
416
+ * typing can continue. The host ghosts the first candidate and rotates
417
+ * through the rest on up/down.
418
+ *
419
+ * Bare tokens (no `/` yet) are matched against the cwd listing too, so
420
+ * a directory ghost appears as soon as the first characters of `src`
421
+ * are typed — but only from the second character on, so 1-letter prose
422
+ * words don't ghost-spam.
423
+ *
424
+ * Dotfiles are only offered when the typed fragment itself starts with
425
+ * `.` — the usual completion convention.
426
+ */
427
+ function createPathAutocompleteProvider(opts = {}) {
428
+ const readdir = opts.io?.readdir ?? defaultReaddir;
429
+ const fallbackCwd = opts.cwd ?? (() => process.cwd());
430
+ return {
431
+ id: "paths",
432
+ suggest(ctx) {
433
+ const token = tokenEndingAtCursor(ctx.text, ctx.cursor);
434
+ if (!token) return null;
435
+ if (!looksLikePath(token) && token.length < 2) return null;
436
+ const expanded = token.startsWith("~") ? join(homedir(), token.slice(1)) : token;
437
+ const endsWithSep = expanded.endsWith("/");
438
+ const dirPart = endsWithSep ? expanded : dirname(expanded);
439
+ const fragment = endsWithSep ? "" : basename(expanded);
440
+ const baseCwd = ctx.cwd || fallbackCwd();
441
+ const dir = isAbsolute(dirPart) ? dirPart : resolve(baseCwd, dirPart);
442
+ let entries;
443
+ try {
444
+ entries = readdir(dir);
445
+ } catch {
446
+ return null;
447
+ }
448
+ const matches = entries.filter((e) => e.name.startsWith(fragment) && (fragment.startsWith(".") || !e.name.startsWith(".")));
449
+ matches.sort((a, b) => a.isDirectory !== b.isDirectory ? a.isDirectory ? -1 : 1 : a.name.localeCompare(b.name));
450
+ const suffixes = matches.map((e) => e.name.slice(fragment.length) + (e.isDirectory ? "/" : "")).filter((s) => s.length > 0).slice(0, MAX_PATH_CANDIDATES);
451
+ return suffixes.length > 0 ? suffixes : null;
452
+ }
453
+ };
454
+ }
455
+ /**
456
+ * Optimistically transform the current ghost across a buffer edit so it
457
+ * stays visible while the debounced provider re-query is in flight —
458
+ * without this, every keystroke inside a completable token blinks the
459
+ * ghost (hide → 120 ms → reshow).
460
+ *
461
+ * Two edits are reconcilable (everything else returns null and waits for
462
+ * the authoritative result):
463
+ * - typing FORWARD along the suggestion (`bi` → `bin` with ghost
464
+ * `n/`): candidates are filtered to those starting with the typed
465
+ * chars and trimmed;
466
+ * - deleting BACKWARD within the token (`bin` → `bi` with ghost `/`):
467
+ * the deleted chars are re-prepended to every candidate. Guarded to
468
+ * non-whitespace so crossing a token boundary drops the ghost.
469
+ *
470
+ * The patched ghost is provisional — the provider's answer replaces it
471
+ * (and may add candidates the patch couldn't know about).
472
+ */
473
+ function patchInlineGhost(prev, text, cursor) {
474
+ if (!prev) return null;
475
+ if (text === prev.text && cursor === prev.cursor) return prev;
476
+ if (text.slice(cursor) !== prev.text.slice(prev.cursor)) return null;
477
+ if (cursor > prev.cursor) {
478
+ if (text.slice(0, prev.cursor) !== prev.text.slice(0, prev.cursor)) return null;
479
+ const typed = text.slice(prev.cursor, cursor);
480
+ const shown = prev.suffixes[prev.index];
481
+ const suffixes = prev.suffixes.filter((s) => s.startsWith(typed) && s.length > typed.length).map((s) => s.slice(typed.length));
482
+ if (suffixes.length === 0) return null;
483
+ const shownTrimmed = shown.startsWith(typed) ? shown.slice(typed.length) : null;
484
+ return {
485
+ suffixes,
486
+ index: shownTrimmed !== null ? Math.max(0, suffixes.indexOf(shownTrimmed)) : 0,
487
+ text,
488
+ cursor
489
+ };
490
+ }
491
+ if (prev.text.slice(0, cursor) !== text.slice(0, cursor)) return null;
492
+ const deleted = prev.text.slice(cursor, prev.cursor);
493
+ if (deleted.length === 0 || /\s/.test(deleted)) return null;
494
+ return {
495
+ suffixes: prev.suffixes.map((s) => deleted + s),
496
+ index: prev.index,
497
+ text,
498
+ cursor
499
+ };
500
+ }
501
+ //#endregion
502
+ export { generateStructuredData as a, shouldAutoGenerateTitle as c, zodToJsonSchema as d, commandBlockToEvent as f, parseCommandInvocation as g, executeCommand as h, tokenEndingAtCursor as i, isStandardSchema as l, commandSteps as m, patchInlineGhost as n, cleanTitle as o, commandBlocksToContent as p, resolveInlineSuggestion as r, generateSessionTitle as s, createPathAutocompleteProvider as t, resolveSchemaInput as u };
323
503
 
324
- //# sourceMappingURL=generate-data-WL_yGVL6.js.map
504
+ //# sourceMappingURL=inline-autocomplete-w_O3SVtN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inline-autocomplete-w_O3SVtN.js","names":[],"sources":["../src/chat/commands.ts","../src/zod.ts","../src/chat/generate-title.ts","../src/chat/generate-data.ts","../src/chat/inline-autocomplete.ts"],"sourcesContent":["/**\n * `/` command model — an extension-contributed workflow invoked by typing\n * `/<name> [args]` as the whole prompt. A command is an ordered list of\n * handler **steps**; a bare `run` is sugar for a single step. Steps share a\n * mutable `data` bag, emit local output blocks (rendered in the transcript,\n * never sent to the model), and can drive the agent via `ctx.runAgent` so a\n * workflow can interact with the LLM mid-flight.\n *\n * This module is renderer-free and node-free: the types are the authoring\n * surface extensions compile against, and `executeCommand` / the parse\n * helper are pure so they're unit-testable without a TUI. The host supplies\n * the side-effecting capabilities on the step context: `emit` (render +\n * persist local output), `runAgent` (interactive sub-run), `generateData`\n * (silent schema-pinned JSON), and the optional `session` (read-only view)\n * and `interaction` (confirm / forms / plan approval) surfaces.\n */\n\nimport type { Logger } from '../logger'\nimport type { SessionRun } from '../session'\nimport type { JsonValue, SessionTurn } from '../types'\nimport type { InferSchemaOutput, SchemaInput, StandardSchemaLike } from '../zod'\nimport type { AnswerValue, PlanPayload, PlanResponse, QuestionPayload } from './interactions'\nimport type { StreamEvent } from './types'\n\n/**\n * A block of local output a step renders into the chat.\n *\n * Plain blocks (`text` only) render as full markdown, both live and on\n * reload — use them for the output the user should read in full (e.g. a\n * final commit message). Blocks with `detail` render as a collapsed\n * `command-detail` row instead (dim `▸ label` + line-capped body with\n * \"… N more lines\") — use them for bulky supporting output (diffs, logs,\n * listings) that shouldn't drown the transcript.\n */\nexport interface CommandOutputBlock {\n /**\n * The block body — full markdown, the detail body, or (for `custom`\n * blocks) the MANDATORY fallback markdown rendered wherever the\n * renderer isn't available: extension uninstalled or disabled,\n * headless host, GUI, renderer threw. The fallback is what persists\n * as the block's output, so pre-custom hosts render it natively.\n */\n text: string\n /**\n * Render as a collapsed detail row (dim `▸ label` + line-capped body)\n * instead of full markdown. `syntax: 'diff'` additionally colors\n * `+N` / `−N` count tokens (added green / deleted red) in both label\n * and body — for diff-stat-style output.\n */\n detail?: { label?: string, syntax?: 'diff' }\n /**\n * Render through an extension-registered custom renderer\n * (`ctx.tui.registerRenderer`). `renderer` must be the NAMESPACED id\n * (`<extension>/<id>`) — `ctx.appendNote` auto-prefixes bare ids for\n * its own extension; command `emit` requires the full form. `data`\n * must be JSON-safe (it persists in the session). Takes precedence\n * over `detail` when both are set.\n */\n custom?: { renderer: string, data?: JsonValue }\n}\n\n/**\n * User-interaction surface for commands — the same prompt-slot primitives\n * the `ask_user` / `present_plan` TOOLS render, but WITHOUT the tools: a\n * command enqueues directly into the host's interaction queue. No tool\n * calls, no turns, no model involvement — the answer routes straight back\n * to the awaiting step. Every method rejects on cancel/esc, which the\n * executor classifies as a quiet abort.\n */\nexport interface CommandInteraction {\n /**\n * One-tap yes/no — sugar over a single `confirm`-type question:\n *\n * if (await ctx.interaction.confirm('Push to origin/main?')) …\n */\n confirm: (prompt: string, opts?: {\n /** Optional context shown above the question (Markdown). */\n intro?: string\n /** Label for the affirmative option. Default `'yes'`. */\n affirmLabel?: string\n /** Label for the negative option. Default `'no'`. */\n denyLabel?: string\n }) => Promise<boolean>\n /**\n * Show a form (text / textarea / select / confirm questions — identical\n * UI to the ask_user tool) and resolve with the answers keyed by\n * `Question.id` (`string` for text/select, `boolean` for confirm,\n * `string[]` of choice ids for `multi: true` selects).\n */\n askUser: (form: QuestionPayload) => Promise<Readonly<Record<string, AnswerValue>>>\n /**\n * Present a plan for the full approval ceremony (approve / reject /\n * revise + optional comment — identical UI to present_plan). For\n * lightweight gating prefer {@link confirm}.\n */\n presentPlan: (plan: PlanPayload) => Promise<PlanResponse>\n}\n\n/**\n * Read-only view over the session a command runs inside — live getters, so\n * turns appended mid-workflow (e.g. by a `runAgent` sub-run) are visible on\n * the next read. Deliberately projection-only: no mutators, so commands\n * can't bypass the display-only `command`-turn contract or the wire guard\n * (`isWireTurn`). Persisting output goes through `emit`; driving the\n * conversation goes through `runAgent`.\n */\nexport interface CommandSessionView {\n readonly id: string\n /** Full persisted history, including display-only `command` turns. */\n readonly turns: readonly SessionTurn[]\n /** Run records (status, usage, cost, `origin`, …), newest last. */\n readonly runs: readonly SessionRun[]\n readonly metadata: Readonly<Record<string, unknown>>\n}\n\n/** Options for `ctx.generateData` — a silent, schema-pinned model call. */\nexport interface CommandGenerateDataOptions {\n /** Instruction describing the value to produce. */\n prompt: string\n /**\n * Shape of the result — a zod v4 schema (return type inferred, no casts)\n * or a plain JSON Schema object (name the type via the generic).\n */\n schema: SchemaInput\n /** Optional system prompt override. */\n system?: string\n /**\n * Fold a compacted transcript of the recent conversation into the call as\n * context. Default false — most workflow values derive from data the\n * command already gathered itself.\n */\n includeConversation?: boolean\n /**\n * Model id to run the call on (must exist in the host's model catalog —\n * see `ctx.runtime.models()` on the extension context). Omit to use the\n * session's active model.\n */\n model?: string\n}\n\n/** One task for {@link CommandStepContext.spawnAgents} — an isolated child agent run. */\nexport interface CommandSpawnTask {\n /** Task prompt for the child agent. Brief it like a colleague — it has no conversation context. */\n prompt: string\n /**\n * Model id from the host catalog (`ctx.runtime.models()` on the extension\n * context). Omit to inherit the session's active model. Unknown ids reject\n * the task (`status: 'rejected'`) without running anything.\n */\n model?: string\n /** System prompt override for the child. Inherits the agent's system prompt when omitted. */\n system?: string\n /** Short display label carried back on the result (defaults to the child id). */\n label?: string\n}\n\n/** Outcome of one {@link CommandSpawnTask}. */\nexport interface CommandSpawnResult {\n /** The task's `label` (or the child id when none was given). */\n label: string\n /** Model the task asked for, when pinned. */\n model?: string\n /** Terminal status. `'rejected'` = refused before running (unknown model, caps). */\n status: 'completed' | 'aborted' | 'timeout' | 'error' | 'rejected'\n /** The child's final assistant text. Empty unless `status === 'completed'`. */\n text: string\n /** Full formatted result / diagnostic (always set; useful for non-completed statuses). */\n message: string\n}\n\n/** Result of driving the agent from within a step via `ctx.runAgent`. */\nexport interface CommandAgentResult {\n /** The assistant's final text for this sub-run. */\n text: string\n}\n\n/** Capabilities + inputs handed to every step. */\nexport interface CommandStepContext {\n /** Raw text after `/<name>` (trimmed of the leading space). */\n readonly args: string\n /** `args` split on whitespace, empties removed. */\n readonly argv: readonly string[]\n /** Mutable bag threaded across steps; a step's returned `data` is merged in. */\n readonly data: Record<string, unknown>\n /** Render + persist a local output block. */\n readonly emit: (block: CommandOutputBlock) => void\n /**\n * Drive one agent run to completion and return its result. The prompt is\n * injected as a real user turn (model-visible, unchanged on the wire) and\n * the response streams into the transcript. Serialized with the host's run\n * slot, so a workflow can interleave deterministic steps with LLM\n * interaction. Any output `emit`ted before this call is flushed first,\n * preserving transcript order.\n *\n * `opts.display` replaces the full-prompt echo in the transcript with a\n * short line (the full prompt still renders beneath it as a collapsed\n * detail row, and still reaches the model verbatim) — pass it when the\n * prompt embeds bulky material like a diff.\n */\n readonly runAgent: (prompt: string, opts?: { readonly display?: string }) => Promise<CommandAgentResult>\n /**\n * Generate schema-conforming JSON with ONE silent model call — no session\n * turns, no transcript output, nothing added to the conversation (the\n * workflow presents results itself via `emit`). Reach for this when a\n * step needs a VALUE (a commit message, a classification, extracted\n * fields); reach for `runAgent` when it needs an interactive sub-run\n * with tools and streaming.\n */\n readonly generateData: {\n /** zod v4 schema → the result type is inferred from the schema. */\n <S extends StandardSchemaLike>(opts: Omit<CommandGenerateDataOptions, 'schema'> & { schema: S }): Promise<InferSchemaOutput<S>>\n /** Plain JSON Schema → name the result type explicitly. */\n <T = unknown>(opts: CommandGenerateDataOptions): Promise<T>\n }\n /** Logger with a `command=<name>` binding, routed to the host's log funnel. */\n readonly logger: Logger\n /** Aborts when the user presses esc during execution. */\n readonly signal: AbortSignal\n /** Working directory the command runs against. */\n readonly cwd: string\n /**\n * The surrounding session, when the host runs commands inside one (the\n * TUI always does). ABSENT in session-less contexts — a command that\n * reads it must guard (`if (!ctx.session) …`) or degrade gracefully.\n */\n readonly session?: CommandSessionView\n /**\n * User interaction (confirm / forms / plan approval), when the host has\n * an interactive surface (the TUI always does). ABSENT on UI-less hosts\n * — guard (`if (!ctx.interaction) …`) and degrade gracefully.\n */\n readonly interaction?: CommandInteraction\n /**\n * Run one or more ISOLATED child agents — each with its own context\n * window and the full tool set, optionally pinned to a different model\n * — and resolve when the whole batch settles. Tasks run in parallel\n * (bounded by `opts.maxConcurrent`, default 3). Children stream and\n * persist into the transcript exactly like `spawn`-tool subagents, so\n * the user sees their activity live and on reload; their context stays\n * isolated from the conversation.\n *\n * Complements {@link runAgent}: `runAgent` drives THE conversation\n * (model-visible turns, active model, serialized); `spawnAgents` fans\n * work out to throwaway workers. Results come back to the command —\n * persist what matters via {@link emit} (user-facing) and\n * {@link appendContext} (model-facing).\n *\n * ABSENT on hosts without an agent (guard like `session`).\n */\n readonly spawnAgents?: (\n tasks: readonly CommandSpawnTask[],\n opts?: { readonly maxConcurrent?: number },\n ) => Promise<readonly CommandSpawnResult[]>\n /**\n * Persist a compact MODEL-VISIBLE context note — a real user-role turn,\n * sent on the wire unchanged from the next run onward, without\n * triggering a run now. This is how a command's outcome becomes part of\n * the conversation: the next user prompt sees what the workflow\n * found/did without replaying subagent transcripts.\n *\n * `opts.display` swaps the transcript echo for a short one-line marker —\n * live AND on reload (the marker persists on the turn; replay renders it\n * with the full note as a collapsed detail), so note bodies the command\n * also emitted never display twice. Keep notes compact regardless — they\n * occupy context for the rest of the conversation. ABSENT on session-less\n * hosts.\n */\n readonly appendContext?: (text: string, opts?: { readonly display?: string }) => Promise<void>\n}\n\n/** Optional per-step return — `data` is merged into the shared bag for later steps. */\nexport interface CommandStepResult {\n data?: Record<string, unknown>\n}\n\nexport type CommandStepFn = (\n ctx: CommandStepContext,\n) => void | CommandStepResult | Promise<void | CommandStepResult>\n\nexport interface CommandStep {\n run: CommandStepFn\n}\n\n/** One argument suggestion returned by {@link Command.completeArgs}. */\nexport interface CommandArgSuggestion {\n /** Text inserted after `/<name> ` on accept. */\n value: string\n /** Display label. Defaults to `value`. */\n label?: string\n description?: string\n}\n\n/** An extension-contributed `/` command. Provide EITHER `run` (one step) or `steps`. */\nexport interface Command {\n /** Invoked as `/<name>`. Lowercase, no whitespace. */\n name: string\n /**\n * Alternate invocation names (same constraints as `name`). `/alias`\n * dispatches to this command; the popover shows the canonical name and\n * lists aliases in the description. Aliases participate in the same\n * first-registration-wins dedupe as names.\n */\n aliases?: readonly string[]\n /**\n * Grouping key for completion — the registry stamps the source\n * extension's name here, so typing `/<extension>` in the popover lists\n * every command that extension contributes. Not an invocation name:\n * `parseCommandInvocation` ignores it.\n */\n group?: string\n /** One-line summary shown in the completion popover. */\n description: string\n /** Single-step sugar. */\n run?: CommandStepFn\n /** Explicit ordered pipeline. Takes precedence over `run` when both are set. */\n steps?: readonly CommandStep[]\n /**\n * Argument completion — called while the user types `/<name> <prefix>▌`\n * with everything after the command name (may itself contain spaces).\n * Return suggestions to show in the `/` popover; return `[]`/`undefined`\n * for none. Sync or async.\n */\n completeArgs?: (argsPrefix: string) => readonly CommandArgSuggestion[] | undefined | Promise<readonly CommandArgSuggestion[] | undefined>\n}\n\n/**\n * Persisted form of output blocks inside a display-only `command` turn:\n * plain blocks → `text` content; `detail` blocks → `tool_result` content\n * with the label/syntax carried in namespaced metadata (rebuilt into the\n * collapsed rendering on reload). Shared by the command emit flush and\n * `ctx.appendNote` so both persist identically.\n */\nexport function commandBlocksToContent(blocks: readonly CommandOutputBlock[]): SessionTurn['content'] {\n return blocks.map((block) => {\n if (!block.detail && !block.custom)\n return { type: 'text' as const, text: block.text }\n // Custom blocks persist with the FALLBACK as the output — an older\n // zidane (or any host without the renderer) reads this turn as a\n // plain detail block and renders the fallback natively. The renderer\n // binding rides namespaced metadata, exactly like detail label/syntax.\n const commandMeta: Record<string, JsonValue> = block.custom\n ? { custom: { renderer: block.custom.renderer, ...(block.custom.data !== undefined ? { data: block.custom.data } : {}) } }\n : {\n ...(block.detail?.label ? { label: block.detail.label } : {}),\n ...(block.detail?.syntax ? { syntax: block.detail.syntax } : {}),\n }\n return {\n type: 'tool_result' as const,\n callId: `command_detail_${crypto.randomUUID()}`,\n output: block.text,\n ...(Object.keys(commandMeta).length > 0 ? { metadata: { command: commandMeta } } : {}),\n }\n })\n}\n\n/**\n * Map ONE command-output block to its LIVE transcript event — the\n * in-memory mirror of {@link commandBlocksToContent}'s persisted shape\n * (whose replay side lives in `eventsFromTurns`). One definition shared\n * by the command emit flush and the `ctx.appendNote` host impl so live\n * rendering can never drift from reloaded rendering — the exact drift\n * that shipped `custom` blocks rendering only after a reload.\n *\n * Precedence matches the persisted side: `custom` > `detail` > markdown.\n */\nexport function commandBlockToEvent(block: CommandOutputBlock): StreamEvent {\n if (block.custom) {\n return {\n kind: 'custom',\n text: block.text,\n custom: {\n renderer: block.custom.renderer,\n ...(block.custom.data !== undefined ? { data: block.custom.data } : {}),\n },\n }\n }\n if (block.detail) {\n return {\n kind: 'command-detail',\n text: block.text,\n ...(block.detail.label ? { label: block.detail.label } : {}),\n ...(block.detail.syntax ? { syntax: block.detail.syntax } : {}),\n }\n }\n return { kind: 'markdown', text: block.text, streaming: false }\n}\n\n/** Normalize a command to its ordered step list (`steps` wins over `run`). */\nexport function commandSteps(command: Command): readonly CommandStep[] {\n if (command.steps && command.steps.length > 0)\n return command.steps\n if (command.run)\n return [{ run: command.run }]\n return []\n}\n\n/** Parsed `/<name> [args]` invocation. */\nexport interface CommandInvocation {\n name: string\n /** Text after the name, trimmed. */\n args: string\n /** `args` split on whitespace. */\n argv: string[]\n}\n\n/**\n * Parse a prompt as a command invocation, but only when the command token is\n * the LEADING token of the whole prompt and names a known command. This is\n * what keeps mid-prompt `/skill` mentions routed to the skills provider:\n * `\"summarize /research\"` is not a command, `\"/research foo\"` is.\n *\n * `known` is matched case-insensitively; entries may be bare names or\n * `{ name, aliases }` records — an alias hit canonicalizes to the entry's\n * `name` (registered casing), so dispatch-by-name downstream just works.\n */\nexport function parseCommandInvocation(\n prompt: string,\n known: readonly (string | Pick<Command, 'name' | 'aliases'>)[],\n): CommandInvocation | null {\n const body = prompt.trimStart()\n if (body[0] !== '/')\n return null\n // First token = the command name; the remainder (after the first run of\n // whitespace) is the args. Linear scan — no backtracking-prone regex.\n const afterSlash = body.slice(1)\n const wsIdx = afterSlash.search(/\\s/)\n const typed = (wsIdx === -1 ? afterSlash : afterSlash.slice(0, wsIdx)).toLowerCase()\n if (typed.length === 0)\n return null\n let canonical: string | undefined\n for (const entry of known) {\n const name = typeof entry === 'string' ? entry : entry.name\n if (name.toLowerCase() === typed) {\n canonical = name\n break\n }\n if (typeof entry !== 'string' && entry.aliases?.some(a => a.toLowerCase() === typed)) {\n canonical = name\n break\n }\n }\n if (canonical === undefined)\n return null\n const args = (wsIdx === -1 ? '' : afterSlash.slice(wsIdx + 1)).trim()\n return { name: canonical, args, argv: args.length > 0 ? args.split(/\\s+/) : [] }\n}\n\n/** Outcome of a command run. `error` is set when a step threw (pipeline stops). */\nexport interface CommandExecution {\n ok: boolean\n /** Number of steps that ran (including the one that threw). */\n ranSteps: number\n error?: unknown\n /** True when the run stopped because `ctx.signal` aborted. */\n aborted?: boolean\n}\n\n/**\n * Run a command's steps in order, threading `ctx.data`. Stops at the first\n * step that throws (error isolated + returned, not rethrown) or when the\n * signal aborts. Pure orchestration — all I/O lives in the host-supplied\n * `ctx` capabilities.\n */\nexport async function executeCommand(\n command: Command,\n ctx: CommandStepContext,\n): Promise<CommandExecution> {\n const steps = commandSteps(command)\n let ranSteps = 0\n for (const step of steps) {\n if (ctx.signal.aborted)\n return { ok: false, ranSteps, aborted: true }\n ranSteps++\n try {\n const result = await step.run(ctx)\n if (result && result.data)\n Object.assign(ctx.data, result.data)\n }\n catch (error) {\n // An esc mid-step usually surfaces as a thrown AbortError from whatever\n // I/O the handler had in flight. Classify by the signal so hosts can\n // stay quiet on user-initiated aborts instead of painting an error.\n if (ctx.signal.aborted)\n return { ok: false, ranSteps, aborted: true }\n return { ok: false, ranSteps, error }\n }\n }\n return { ok: true, ranSteps }\n}\n","/**\n * Zod v4 integration helpers.\n *\n * Zod is an OPTIONAL peer dependency, so this module never imports it at the\n * top level. Schema-accepting APIs (`ctx.generateData`, `generateStructuredData`)\n * take either a plain JSON Schema object or any Standard-Schema-carrying\n * value (https://standardschema.dev — zod v4 implements it). Zod schemas are\n * detected structurally by vendor and converted with a lazy\n * `import('zod')` — safe because whoever constructed the schema necessarily\n * has zod installed. Result types are inferred from the standard-schema\n * `types.output` slot, so callers get full typing without a single cast:\n *\n * const CommitMessage = z.object({ subject: z.string(), body: z.string().optional() })\n * const msg = await ctx.generateData({ prompt, schema: CommitMessage })\n * // ^? { subject: string, body?: string }\n */\n\n/**\n * Structural stand-in for a Standard Schema (zod v4 et al.) — enough surface\n * to detect the vendor and infer the output type WITHOUT importing zod's\n * types into our public API.\n */\nexport interface StandardSchemaLike<Output = unknown> {\n readonly '~standard': {\n readonly version: number\n readonly vendor: string\n /** Type-level only (undefined at runtime) — carries the inferred output type. */\n readonly types?: { readonly output: Output } | undefined\n }\n}\n\n/** Output type carried by a {@link StandardSchemaLike}; `unknown` for plain JSON Schema. */\nexport type InferSchemaOutput<S> = S extends StandardSchemaLike<infer O> ? O : unknown\n\n/** A schema-accepting input: plain JSON Schema, or a Standard Schema (e.g. zod v4). */\nexport type SchemaInput = Record<string, unknown> | StandardSchemaLike\n\nexport function isStandardSchema(value: unknown): value is StandardSchemaLike {\n if (typeof value !== 'object' || value === null)\n return false\n const marker = (value as Record<string, unknown>)['~standard']\n return typeof marker === 'object' && marker !== null\n && typeof (marker as Record<string, unknown>).vendor === 'string'\n}\n\n/**\n * Resolve a {@link SchemaInput} to the plain JSON Schema object providers\n * expect. Zod schemas convert via the lazily-imported `z.toJSONSchema`\n * (v4 native); other Standard Schema vendors are rejected with a clear\n * error — conversion is vendor-specific and only zod is wired today.\n */\nexport async function resolveSchemaInput(schema: SchemaInput): Promise<Record<string, unknown>> {\n if (!isStandardSchema(schema))\n return schema\n const vendor = schema['~standard'].vendor\n if (vendor !== 'zod') {\n throw new Error(\n `unsupported schema vendor \"${vendor}\" — pass a zod v4 schema or a plain JSON Schema object`,\n )\n }\n // Lazy + guarded: zod is an optional peer, but a zod schema in hand means\n // the caller's process has zod — this import only fails on truly broken\n // installs, and then with an actionable message.\n let toJSONSchema: (schema: unknown) => Record<string, unknown>\n try {\n const zod = await import('zod')\n toJSONSchema = zod.z.toJSONSchema as typeof toJSONSchema\n }\n catch {\n throw new Error('a zod schema was passed but the \"zod\" package could not be imported — install zod >= 4')\n }\n return zodToJsonSchema(toJSONSchema(schema))\n}\n\n/**\n * Normalize a JSON Schema (e.g. from zod v4's z.toJSONSchema()) for use\n * as a ToolSpec.inputSchema.\n *\n * Strips the $schema key that some providers reject.\n */\nexport function zodToJsonSchema(jsonSchema: Record<string, unknown>): Record<string, unknown> {\n const { $schema, ...rest } = jsonSchema\n return rest\n}\n","/**\n * One-shot title generation for an existing session — feeds the last N\n * turns to the provider with a \"write me a title\" system prompt and\n * returns the cleaned-up result.\n *\n * Provider-agnostic: works with anything implementing the renderer-\n * shared `Provider` interface. No tools, no session mutation, no\n * caching — this is a cheap, isolated completion that should be safe to\n * fire even mid-session without touching the live agent loop.\n */\n\nimport type { Provider } from '../providers'\nimport type { SessionTurn } from '../types'\n\n/** Hard cap on the result length. Anything longer is truncated client-side. */\nconst TITLE_MAX_CHARS = 60\n\n/** Default turn count fed to the model. 10 covers most exchanges without bloat. */\nconst DEFAULT_MAX_TURNS = 10\n\n/** Tokens budgeted for the model's reply. 64 fits any sane title with headroom. */\nconst TITLE_RESPONSE_MAX_TOKENS = 64\n\n/** Per-turn body cap when assembling the prompt — keeps the request payload tight. */\nconst PROMPT_TURN_CHAR_MAX = 2000\n\nexport interface GenerateSessionTitleOptions {\n provider: Provider\n /** Model id used for the call. */\n model: string\n /** Conversation history to summarize. Empty → throws synchronously. */\n turns: readonly SessionTurn[]\n /** Cap on how many trailing turns to feed the model. Defaults to 10. */\n maxTurns?: number\n /** Optional cancellation signal — forwarded to the provider's stream. */\n signal?: AbortSignal\n}\n\n/**\n * Drive the provider's `stream()` once and return a concise title for\n * the conversation represented by `turns`. Throws when:\n * - `turns` contains no text-bearing content (nothing to summarize),\n * - the provider stream completes with no output text,\n * - `signal` is aborted (rethrown verbatim).\n *\n * Output is trimmed, single-line, with surrounding quotes / trailing\n * punctuation stripped, and truncated to `TITLE_MAX_CHARS`.\n */\nexport async function generateSessionTitle({\n provider,\n model,\n turns,\n maxTurns = DEFAULT_MAX_TURNS,\n signal,\n}: GenerateSessionTitleOptions): Promise<string> {\n const slice = turns.slice(-Math.max(1, maxTurns))\n const transcript = renderTurnsForPrompt(slice)\n if (!transcript)\n throw new Error('No text content in the recent turns to summarize.')\n\n const system = [\n 'You generate concise, descriptive titles for chat conversations.',\n 'Reply with ONLY the title — no quotes, no markdown, no trailing punctuation,',\n 'no preamble (do not say \"Title:\" or similar).',\n `Aim for 3 to 7 words and stay under ${TITLE_MAX_CHARS} characters.`,\n ].join(' ')\n\n const userPrompt = `Generate a title for this conversation:\\n\\n${transcript}`\n\n let text = ''\n const result = await provider.stream(\n {\n model,\n system,\n tools: [],\n messages: [provider.userMessage(userPrompt)],\n maxTokens: TITLE_RESPONSE_MAX_TOKENS,\n ...(signal ? { signal } : {}),\n },\n {\n onText: (delta) => { text += delta },\n },\n )\n // Prefer the streamed-text accumulator (driven by deltas) but fall\n // back to the provider's already-concatenated `result.text` for\n // adapters that batch on the final frame instead of emitting deltas.\n const raw = text.trim().length > 0 ? text : result.text\n return cleanTitle(raw)\n}\n\n/**\n * Decide whether a session is ready for one-shot automatic titling.\n *\n * Returns `true` iff the conversation has had its first exchange — at\n * least two turns, i.e. the opening user message plus the assistant's\n * reply (this is exactly the \"N turns\" count the sessions list shows) —\n * AND no explicit title has been set yet. An existing `metadata.title`\n * (a previous auto-generation, or a manual title from the session-details\n * \"generate title\" action) is never clobbered.\n *\n * Pure + total. The runtime layers its own \"is one already in flight?\"\n * and \"is a provider picked?\" guards on top of this; the predicate only\n * encodes the content-level rule so it can be pinned in tests without a\n * mock provider — same rationale as the exported {@link cleanTitle}.\n */\nexport function shouldAutoGenerateTitle(\n turns: readonly SessionTurn[],\n metadata?: Record<string, unknown>,\n): boolean {\n const existing = typeof metadata?.title === 'string' ? metadata.title.trim() : ''\n if (existing.length > 0)\n return false\n return turns.length >= 2\n}\n\n/**\n * Compact a turn list into a transcript-style prompt:\n *\n * user: …\n * assistant: …\n * user: …\n *\n * Tool calls and tool results are summarized to keep the request\n * payload small — the model needs the rough flow of the conversation,\n * not full JSON blobs. Per-turn text is clipped at `PROMPT_TURN_CHAR_MAX`\n * so a single huge code dump doesn't blow the budget.\n *\n * Returns an empty string when the slice has no text-bearing content\n * (e.g. a turn list that's only tool plumbing).\n *\n * Exported for reuse by other silent one-shot helpers (`generate-data`'s\n * optional conversation context) so every side-channel inference compacts\n * history the same way.\n */\nexport function renderTurnsForPrompt(turns: readonly SessionTurn[]): string {\n const lines: string[] = []\n for (const turn of turns) {\n const body = textBodyOf(turn)\n if (!body)\n continue\n const role = turn.role === 'assistant' ? 'assistant' : turn.role === 'user' ? 'user' : 'system'\n lines.push(`${role}: ${clip(body, PROMPT_TURN_CHAR_MAX)}`)\n }\n return lines.join('\\n\\n')\n}\n\nfunction textBodyOf(turn: SessionTurn): string {\n const parts: string[] = []\n for (const block of turn.content) {\n if (block.type === 'text' && block.text.trim())\n parts.push(block.text.trim())\n else if (block.type === 'tool_call')\n parts.push(`[tool: ${block.name}]`)\n else if (block.type === 'tool_result')\n parts.push(`[tool result]`)\n }\n return parts.join(' ')\n}\n\n/**\n * Normalize a model-generated title into the shape we want to persist:\n *\n * - Collapse internal whitespace + take the first line only (some\n * models emit \"Title: foo\\n\\nReason: …\" despite instructions).\n * - Strip surrounding quote characters (`\"foo\"`, `'foo'`, `` `foo` ``).\n * - Strip a leading `Title:` / `title -` prefix if the model added one.\n * - Strip trailing punctuation (`.`, `!`, `?`) — titles read cleaner\n * without it.\n * - Truncate to `TITLE_MAX_CHARS` with a trailing `…` when over.\n *\n * Exported as `cleanTitle` so tests can pin the normalization rules\n * without going through a mock provider.\n */\nexport function cleanTitle(raw: string): string {\n let s = raw.split('\\n')[0]?.trim() ?? ''\n // Strip a \"Title:\" / \"Title -\" preamble the model sometimes adds.\n s = s.replace(/^\\s*title\\s*[:\\-–—]\\s*/i, '')\n // Strip surrounding matched quotes.\n if (s.length >= 2) {\n const first = s.charAt(0)\n const last = s.charAt(s.length - 1)\n const matched = (first === '\"' && last === '\"')\n || (first === '\\'' && last === '\\'')\n || (first === '`' && last === '`')\n || (first === '“' && last === '”')\n if (matched)\n s = s.slice(1, -1).trim()\n }\n // Trim trailing terminal punctuation — titles don't take periods.\n s = s.replace(/[.!?]+$/, '').trim()\n if (s.length === 0)\n throw new Error('Model returned an empty title.')\n return s.length > TITLE_MAX_CHARS ? `${s.slice(0, TITLE_MAX_CHARS - 1)}…` : s\n}\n\nfunction clip(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max)}…` : text\n}\n","/**\n * Silent structured-output generation — one provider call that returns\n * schema-conforming JSON without touching the session or the transcript.\n *\n * Modeled on the two proven side-channel patterns in the codebase:\n * - `generate-title.ts`: a single `provider.stream()` with no session\n * writes and no transcript events (optionally seeded with a compacted\n * conversation transcript), and\n * - the loop's `__output__` schema enforcement: a synthetic tool whose\n * `inputSchema` IS the requested JSON Schema, with `toolChoice` pinned\n * so the model must answer with a conforming payload.\n *\n * Used by `/` commands via `ctx.generateData` to derive values from the\n * model (or from the conversation) mid-workflow without bloating the chat\n * history — e.g. `/commit` generating `{ subject, body }` from a diff.\n * For genuinely interactive sub-runs (real turns, streaming, tools), use\n * `ctx.runAgent` instead.\n */\n\nimport type { Provider, ToolSpec } from '../providers'\nimport type { SessionTurn } from '../types'\nimport type { InferSchemaOutput, SchemaInput, StandardSchemaLike } from '../zod'\nimport { resolveSchemaInput } from '../zod'\nimport { renderTurnsForPrompt } from './generate-title'\n\n/** Synthetic forced-choice tool name (never persisted — the call is side-channel only). */\nconst DATA_TOOL_NAME = '__data__'\n\n/** Default cap on conversation turns folded into the context block. */\nconst DEFAULT_CONTEXT_TURNS = 12\n\nexport interface GenerateStructuredDataOptions {\n provider: Provider\n model: string\n /** Instruction describing the value to produce. */\n prompt: string\n /**\n * Shape of the result — a plain JSON Schema object, or a zod v4 schema\n * (converted automatically; the return type is then inferred from it).\n * Becomes the forced tool's inputSchema.\n */\n schema: SchemaInput\n /** Optional system prompt. Defaults to a terse data-extraction persona. */\n system?: string\n /**\n * Conversation turns to fold in as compacted context (same clipping as\n * session auto-titling). Omit or pass empty for a context-free call.\n */\n turns?: readonly SessionTurn[]\n /** Cap on turns rendered into the context block. Default 12 (most recent). */\n maxContextTurns?: number\n signal?: AbortSignal\n}\n\n/**\n * Drive one schema-pinned provider call and return the conforming payload.\n * Throws when the provider returns no structured payload (and rethrows\n * aborts verbatim). The caller owns presentation — nothing is rendered or\n * persisted here.\n *\n * Pass a zod v4 schema and the return type is inferred from it; pass a\n * plain JSON Schema object and name the type via the generic.\n */\nexport async function generateStructuredData<S extends StandardSchemaLike>(\n options: GenerateStructuredDataOptions & { schema: S },\n): Promise<InferSchemaOutput<S>>\nexport async function generateStructuredData<T = unknown>(\n options: GenerateStructuredDataOptions,\n): Promise<T>\nexport async function generateStructuredData(\n options: GenerateStructuredDataOptions,\n): Promise<unknown> {\n const { provider, model, prompt, signal } = options\n const spec: ToolSpec = {\n name: DATA_TOOL_NAME,\n description: 'Return the result. The input of this call IS the answer — it must conform to the schema.',\n inputSchema: await resolveSchemaInput(options.schema),\n }\n\n const contextTurns = options.turns && options.turns.length > 0\n ? options.turns.slice(-(options.maxContextTurns ?? DEFAULT_CONTEXT_TURNS))\n : []\n const transcript = contextTurns.length > 0 ? renderTurnsForPrompt(contextTurns) : ''\n const userPrompt = transcript\n ? `<conversation>\\n${transcript}\\n</conversation>\\n\\n${prompt}`\n : prompt\n\n const result = await provider.stream(\n {\n model,\n system: options.system\n ?? `You produce structured data. Call the ${DATA_TOOL_NAME} tool exactly once with the requested value. No prose.`,\n tools: provider.formatTools([spec]),\n messages: [provider.userMessage(userPrompt)],\n toolChoice: { type: 'tool', name: DATA_TOOL_NAME },\n ...(signal ? { signal } : {}),\n },\n {\n onText: () => {},\n },\n )\n\n const payload = result.toolCalls.find(tc => tc.name === DATA_TOOL_NAME)?.input\n if (payload === undefined)\n throw new Error('generateStructuredData: the model returned no structured payload')\n return payload\n}\n","/**\n * Inline (ghost-text) autocomplete for the prompt.\n *\n * Distinct from the trigger-based completion popover (`@` files, `/`\n * commands): providers here suggest plain text SUFFIX candidates to\n * append at the cursor — the first renders as dim ghost text, up/down\n * rotates through the rest, Tab accepts. No popover.\n *\n * Providers are queried in registration order with a shared AbortSignal;\n * the engine returns the first provider's non-empty candidate list.\n * Extensions add providers via `ctx.registerInlineAutocompleteProvider`\n * — the built-in path provider ({@link createPathAutocompleteProvider})\n * is always first.\n */\n\nimport { readdirSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { basename, dirname, isAbsolute, join, resolve } from 'node:path'\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface InlineAutocompleteContext {\n /** Full prompt buffer. */\n text: string\n /** Cursor offset into `text`. Suggestions complete the token ENDING here. */\n cursor: number\n /** Workspace directory relative paths resolve against. */\n cwd: string\n /** Aborted when the buffer changes before the provider resolves. */\n signal: AbortSignal\n}\n\nexport interface InlineAutocompleteProvider {\n /** Stable id — used for first-wins dedupe across extensions. */\n id: string\n /**\n * Return the ghost suffix (or an ordered list of candidate suffixes —\n * the host shows the first and lets the user rotate with up/down) to\n * append at the cursor, or null/''/[] for no suggestion. Must be cheap\n * or promptly abortable — it runs per keystroke (debounced by the\n * host).\n */\n suggest: (ctx: InlineAutocompleteContext) => string | readonly string[] | null | Promise<string | readonly string[] | null>\n}\n\n// ---------------------------------------------------------------------------\n// Engine\n// ---------------------------------------------------------------------------\n\n/** Per-provider deadline — a hung provider is treated as \"no suggestion\". */\nconst PROVIDER_DEADLINE_MS = 150\n\n/**\n * Query `providers` in order; the first provider yielding a non-empty\n * candidate list wins (a bare string normalizes to a 1-element list).\n * Provider errors are swallowed (a broken extension provider must not\n * break typing), and each provider races a {@link PROVIDER_DEADLINE_MS}\n * deadline so one hung provider can't permanently suppress the ghosts of\n * providers behind it. Returns null when aborted or nothing matched.\n */\nexport async function resolveInlineSuggestion(\n providers: readonly InlineAutocompleteProvider[],\n ctx: InlineAutocompleteContext,\n deadlineMs = PROVIDER_DEADLINE_MS,\n): Promise<{ suffixes: readonly string[], providerId: string } | null> {\n const TIMEOUT = Symbol('timeout')\n for (const provider of providers) {\n if (ctx.signal.aborted)\n return null\n try {\n let timer: ReturnType<typeof setTimeout> | undefined\n const result = await Promise.race([\n Promise.resolve(provider.suggest(ctx)),\n new Promise<typeof TIMEOUT>((r) => { timer = setTimeout(r, deadlineMs, TIMEOUT) }),\n ])\n if (timer !== undefined)\n clearTimeout(timer)\n if (result === TIMEOUT)\n continue\n if (ctx.signal.aborted)\n return null\n const suffixes = (typeof result === 'string' ? [result] : result ?? [])\n .filter(s => typeof s === 'string' && s.length > 0)\n if (suffixes.length > 0)\n return { suffixes, providerId: provider.id }\n }\n catch {\n // Isolation-first: skip broken providers.\n }\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Built-in path provider\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the whitespace-delimited token that ends at `cursor`. Returns\n * null when the cursor sits right after whitespace (nothing to complete).\n */\nexport function tokenEndingAtCursor(text: string, cursor: number): string | null {\n const before = text.slice(0, cursor)\n const match = before.match(/\\S+$/)\n return match ? match[0] : null\n}\n\n/**\n * Does this token carry an explicit path shape (`/` separator or a `~`\n * prefix)? Path-shaped tokens complete from the first character after\n * the separator; bare tokens (`sr` → `c/`) still complete against the\n * cwd listing but need ≥2 chars first — see the provider.\n */\nfunction looksLikePath(token: string): boolean {\n return token.includes('/') || token.startsWith('~')\n}\n\n/**\n * Cap on candidates returned for an ambiguous fragment — rotation past\n * a dozen-odd entries stops being faster than typing another character.\n */\nconst MAX_PATH_CANDIDATES = 16\n\n/** Directory listing seam — injectable for tests. */\nexport interface PathProviderIo {\n readdir?: (dir: string) => { name: string, isDirectory: boolean }[]\n}\n\nfunction defaultReaddir(dir: string): { name: string, isDirectory: boolean }[] {\n return readdirSync(dir, { withFileTypes: true }).map(e => ({ name: e.name, isDirectory: e.isDirectory() }))\n}\n\n/**\n * Built-in provider: complete filesystem paths under `cwd` (or absolute /\n * `~` paths). Given the token `src/chat/comp`, lists `src/chat/` and\n * returns every matching continuation of `comp` as a candidate list —\n * directories first, alphabetical, `/`-terminated for directories so\n * typing can continue. The host ghosts the first candidate and rotates\n * through the rest on up/down.\n *\n * Bare tokens (no `/` yet) are matched against the cwd listing too, so\n * a directory ghost appears as soon as the first characters of `src`\n * are typed — but only from the second character on, so 1-letter prose\n * words don't ghost-spam.\n *\n * Dotfiles are only offered when the typed fragment itself starts with\n * `.` — the usual completion convention.\n */\nexport function createPathAutocompleteProvider(opts: {\n cwd?: () => string\n io?: PathProviderIo\n} = {}): InlineAutocompleteProvider {\n const readdir = opts.io?.readdir ?? defaultReaddir\n // Prefer the per-invocation `ctx.cwd` (host truth); fall back to the\n // factory-supplied getter, then `process.cwd()`.\n const fallbackCwd = opts.cwd ?? (() => process.cwd())\n return {\n id: 'paths',\n suggest(ctx) {\n const token = tokenEndingAtCursor(ctx.text, ctx.cursor)\n if (!token)\n return null\n // Bare tokens complete against the cwd listing (dirname('sr') is '.',\n // so the resolution below just works) but require ≥2 typed chars.\n if (!looksLikePath(token) && token.length < 2)\n return null\n // Resolve the directory being completed and the fragment typed so\n // far. A trailing `/` means \"complete entries of this directory\".\n const expanded = token.startsWith('~')\n ? join(homedir(), token.slice(1))\n : token\n const endsWithSep = expanded.endsWith('/')\n const dirPart = endsWithSep ? expanded : dirname(expanded)\n const fragment = endsWithSep ? '' : basename(expanded)\n const baseCwd = ctx.cwd || fallbackCwd()\n const dir = isAbsolute(dirPart) ? dirPart : resolve(baseCwd, dirPart)\n let entries: { name: string, isDirectory: boolean }[]\n try {\n entries = readdir(dir)\n }\n catch {\n return null\n }\n const matches = entries.filter(e =>\n e.name.startsWith(fragment)\n && (fragment.startsWith('.') || !e.name.startsWith('.')),\n )\n // Directories first (they're what you're navigating through), then\n // alphabetical within each group.\n matches.sort((a, b) =>\n a.isDirectory !== b.isDirectory\n ? (a.isDirectory ? -1 : 1)\n : a.name.localeCompare(b.name))\n const suffixes = matches\n .map(e => e.name.slice(fragment.length) + (e.isDirectory ? '/' : ''))\n .filter(s => s.length > 0)\n .slice(0, MAX_PATH_CANDIDATES)\n return suffixes.length > 0 ? suffixes : null\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Host-side ghost reconciliation\n// ---------------------------------------------------------------------------\n\nexport interface InlineGhost {\n suffixes: readonly string[]\n index: number\n text: string\n cursor: number\n}\n\n/**\n * Optimistically transform the current ghost across a buffer edit so it\n * stays visible while the debounced provider re-query is in flight —\n * without this, every keystroke inside a completable token blinks the\n * ghost (hide → 120 ms → reshow).\n *\n * Two edits are reconcilable (everything else returns null and waits for\n * the authoritative result):\n * - typing FORWARD along the suggestion (`bi` → `bin` with ghost\n * `n/`): candidates are filtered to those starting with the typed\n * chars and trimmed;\n * - deleting BACKWARD within the token (`bin` → `bi` with ghost `/`):\n * the deleted chars are re-prepended to every candidate. Guarded to\n * non-whitespace so crossing a token boundary drops the ghost.\n *\n * The patched ghost is provisional — the provider's answer replaces it\n * (and may add candidates the patch couldn't know about).\n */\nexport function patchInlineGhost(prev: InlineGhost | null, text: string, cursor: number): InlineGhost | null {\n if (!prev)\n return null\n if (text === prev.text && cursor === prev.cursor)\n return prev\n // The text after the caret must be untouched — edits there invalidate\n // the completion context entirely.\n if (text.slice(cursor) !== prev.text.slice(prev.cursor))\n return null\n if (cursor > prev.cursor) {\n if (text.slice(0, prev.cursor) !== prev.text.slice(0, prev.cursor))\n return null\n const typed = text.slice(prev.cursor, cursor)\n const shown = prev.suffixes[prev.index]\n const suffixes = prev.suffixes\n .filter(s => s.startsWith(typed) && s.length > typed.length)\n .map(s => s.slice(typed.length))\n if (suffixes.length === 0)\n return null\n // Keep the rotated-to candidate selected when it survives the filter.\n const shownTrimmed = shown.startsWith(typed) ? shown.slice(typed.length) : null\n const index = shownTrimmed !== null ? Math.max(0, suffixes.indexOf(shownTrimmed)) : 0\n return { suffixes, index, text, cursor }\n }\n if (prev.text.slice(0, cursor) !== text.slice(0, cursor))\n return null\n const deleted = prev.text.slice(cursor, prev.cursor)\n if (deleted.length === 0 || /\\s/.test(deleted))\n return null\n return { suffixes: prev.suffixes.map(s => deleted + s), index: prev.index, text, cursor }\n}\n"],"mappings":";;;;;;;;;;;AA4UA,SAAgB,uBAAuB,QAA+D;CACpG,OAAO,OAAO,KAAK,UAAU;EAC3B,IAAI,CAAC,MAAM,UAAU,CAAC,MAAM,QAC1B,OAAO;GAAE,MAAM;GAAiB,MAAM,MAAM;EAAK;EAKnD,MAAM,cAAyC,MAAM,SACjD,EAAE,QAAQ;GAAE,UAAU,MAAM,OAAO;GAAU,GAAI,MAAM,OAAO,SAAS,KAAA,IAAY,EAAE,MAAM,MAAM,OAAO,KAAK,IAAI,CAAC;EAAG,EAAE,IACvH;GACE,GAAI,MAAM,QAAQ,QAAQ,EAAE,OAAO,MAAM,OAAO,MAAM,IAAI,CAAC;GAC3D,GAAI,MAAM,QAAQ,SAAS,EAAE,QAAQ,MAAM,OAAO,OAAO,IAAI,CAAC;EAChE;EACJ,OAAO;GACL,MAAM;GACN,QAAQ,kBAAkB,OAAO,WAAW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AM,QAAQ,KAAK,SAAS,KAAK;EACjC,MAAM,WAAW,KAAK,SACnB,QAAO,MAAK,EAAE,WAAW,KAAK,KAAK,EAAE,SAAS,MAAM,MAAM,CAAC,CAC3D,KAAI,MAAK,EAAE,MAAM,MAAM,MAAM,CAAC;EACjC,IAAI,SAAS,WAAW,GACtB,OAAO;EAET,MAAM,eAAe,MAAM,WAAW,KAAK,IAAI,MAAM,MAAM,MAAM,MAAM,IAAI;EAE3E,OAAO;GAAE;GAAU,OADL,iBAAiB,OAAO,KAAK,IAAI,GAAG,SAAS,QAAQ,YAAY,CAAC,IAAI;GAC1D;GAAM;EAAO;CACzC;CACA,IAAI,KAAK,KAAK,MAAM,GAAG,MAAM,MAAM,KAAK,MAAM,GAAG,MAAM,GACrD,OAAO;CACT,MAAM,UAAU,KAAK,KAAK,MAAM,QAAQ,KAAK,MAAM;CACnD,IAAI,QAAQ,WAAW,KAAK,KAAK,KAAK,OAAO,GAC3C,OAAO;CACT,OAAO;EAAE,UAAU,KAAK,SAAS,KAAI,MAAK,UAAU,CAAC;EAAG,OAAO,KAAK;EAAO;EAAM;CAAO;AAC1F"}
@@ -1,5 +1,5 @@
1
1
  import { c as createTolerantClient, l as sseToJsonFetchIfNeeded, p as isOAuthTokenRejectionError, u as McpOAuthProvider } from "./mcp-CkHUripi.js";
2
- import { t as defineSkill } from "./skills-BjeXSRlQ.js";
2
+ import { t as defineSkill } from "./skills-BlmY7QhV.js";
3
3
  import { createRequire } from "node:module";
4
4
  import { basename, dirname, join, resolve } from "node:path";
5
5
  import { existsSync } from "node:fs";
@@ -545,4 +545,4 @@ async function raceLoginCallback(handle, timeoutMs, signal) {
545
545
  //#endregion
546
546
  export { buildZidaneExtensionSkill as a, resolveExtensionDocsDir as c, ZIDANE_EXTENSION_SKILL_NAME as i, withZidaneExtensionSkill as l, startOAuthCallback as n, extensionDirForCwd as o, EXTENSION_EDIT_METADATA_KEY as r, extensionScaffold as s, loginMcpServer as t };
547
547
 
548
- //# sourceMappingURL=login-DhnmYiia.js.map
548
+ //# sourceMappingURL=login-Bp_tRj_e.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"login-DhnmYiia.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, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\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.remov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AAS,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-Bp_tRj_e.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, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\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,WAA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2 @@
1
- import { Hd as McpServerConfig, Sc as wrapDiscoveredMcpTools, Wd as McpToolSchema, _c as connectMcpServers, bc as normalizeMcpServers, gc as attachStderrWarnPump, hc as McpConnection, mc as ConnectMcpServersOptions, vc as deriveMcpToolMeta, xc as resultToString, yc as normalizeMcpBlocks } from "./index-2MYNIBnZ.js";
1
+ import { Cc as deriveMcpToolMeta, Dc as wrapDiscoveredMcpTools, Ec as resultToString, Sc as connectMcpServers, Tc as normalizeMcpServers, bc as McpConnection, ef as McpServerConfig, nf as McpToolSchema, wc as normalizeMcpBlocks, xc as attachStderrWarnPump, yc as ConnectMcpServersOptions } from "./index-mUT8TI9j.js";
2
2
  export { ConnectMcpServersOptions, McpConnection, type McpServerConfig, type McpToolSchema, attachStderrWarnPump, connectMcpServers, deriveMcpToolMeta, normalizeMcpBlocks, normalizeMcpServers, resultToString, wrapDiscoveredMcpTools };