@sayknow-cli/coding-agent 0.3.10 → 0.3.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +0 -13
  2. package/dist/types/build-metadata.d.ts +7 -0
  3. package/dist/types/capability/mcp.d.ts +3 -1
  4. package/dist/types/commands/mcp.d.ts +1 -1
  5. package/dist/types/config/keybindings.d.ts +2 -2
  6. package/dist/types/modes/acp/acp-event-mapper.d.ts +2 -0
  7. package/dist/types/modes/components/hook-selector.d.ts +1 -0
  8. package/dist/types/modes/components/status-line/types.d.ts +6 -0
  9. package/dist/types/modes/components/status-line.d.ts +1 -0
  10. package/dist/types/modes/components/welcome.d.ts +1 -0
  11. package/dist/types/modes/rpc/rpc-client.d.ts +7 -2
  12. package/dist/types/modes/utils/ui-helpers.d.ts +12 -0
  13. package/dist/types/notifications/telegram-daemon.d.ts +2 -0
  14. package/dist/types/runtime-mcp/config-writer.d.ts +4 -3
  15. package/dist/types/runtime-mcp/types.d.ts +4 -3
  16. package/dist/types/session/agent-session.d.ts +16 -0
  17. package/dist/types/session/session-manager.d.ts +1 -0
  18. package/dist/types/tools/skill.d.ts +9 -8
  19. package/dist/types/utils/linkedom.d.ts +4 -0
  20. package/dist/types/utils/pasted-image-path.d.ts +5 -3
  21. package/package.json +7 -7
  22. package/scripts/build-binary.ts +2 -43
  23. package/scripts/compile-args.ts +106 -0
  24. package/scripts/generate-docs-index.ts +1 -0
  25. package/src/build-metadata.ts +104 -0
  26. package/src/capability/mcp.ts +3 -1
  27. package/src/cli/mcp-cli.ts +108 -26
  28. package/src/cli.ts +21 -0
  29. package/src/commands/mcp.ts +8 -8
  30. package/src/commands/stats.ts +6 -2
  31. package/src/config/keybindings.ts +2 -2
  32. package/src/config/mcp-schema.json +21 -17
  33. package/src/config/model-profiles.ts +23 -23
  34. package/src/discovery/builtin.ts +14 -0
  35. package/src/discovery/mcp-json.ts +14 -0
  36. package/src/eval/js/executor.ts +7 -1
  37. package/src/internal-urls/docs-index.generated.ts +3 -2
  38. package/src/internal-urls/skc-protocol.ts +14 -1
  39. package/src/modes/acp/acp-agent.ts +72 -16
  40. package/src/modes/acp/acp-client-bridge.ts +27 -5
  41. package/src/modes/acp/acp-event-mapper.ts +39 -1
  42. package/src/modes/components/assistant-message.ts +1 -1
  43. package/src/modes/components/hook-selector.ts +4 -0
  44. package/src/modes/components/model-selector.ts +17 -6
  45. package/src/modes/components/session-selector.ts +2 -2
  46. package/src/modes/components/status-line/presets.ts +5 -19
  47. package/src/modes/components/status-line/segments.ts +14 -0
  48. package/src/modes/components/status-line/types.ts +6 -0
  49. package/src/modes/components/status-line.ts +13 -6
  50. package/src/modes/components/tool-execution.ts +1 -1
  51. package/src/modes/components/welcome.ts +4 -1
  52. package/src/modes/controllers/command-controller.ts +1 -1
  53. package/src/modes/controllers/event-controller.ts +9 -9
  54. package/src/modes/controllers/input-controller.ts +8 -2
  55. package/src/modes/controllers/selector-controller.ts +7 -3
  56. package/src/modes/interactive-mode.ts +12 -4
  57. package/src/modes/rpc/rpc-client.ts +30 -6
  58. package/src/modes/utils/ui-helpers.ts +154 -32
  59. package/src/notifications/telegram-daemon.ts +28 -2
  60. package/src/prompts/tools/skill.md +2 -2
  61. package/src/runtime-mcp/config-writer.ts +4 -3
  62. package/src/runtime-mcp/config.ts +1 -0
  63. package/src/runtime-mcp/types.ts +4 -3
  64. package/src/session/agent-session.ts +117 -3
  65. package/src/session/session-manager.ts +68 -40
  66. package/src/skc-runtime/state-runtime.ts +105 -12
  67. package/src/skc-runtime/workflow-manifest.generated.json +4 -28
  68. package/src/skc-runtime/workflow-manifest.ts +1 -7
  69. package/src/slash-commands/builtin-registry.ts +9 -4
  70. package/src/tools/bash-interactive.ts +9 -4
  71. package/src/tools/browser/readable.ts +2 -2
  72. package/src/tools/fetch.ts +5 -5
  73. package/src/tools/skill.ts +14 -11
  74. package/src/utils/linkedom.ts +14 -0
  75. package/src/utils/pasted-image-path.ts +23 -9
  76. package/src/web/scrapers/arxiv.ts +2 -2
  77. package/src/web/scrapers/go-pkg.ts +2 -2
  78. package/src/web/scrapers/iacr.ts +2 -2
  79. package/src/web/scrapers/readthedocs.ts +2 -2
  80. package/src/web/scrapers/twitter.ts +3 -2
  81. package/src/web/scrapers/wikipedia.ts +2 -2
@@ -1,4 +1,5 @@
1
1
  // Auto-generated by scripts/generate-docs-index.ts - DO NOT EDIT
2
+ Reflect.set(globalThis, Symbol.for("skc.docs-index.generated.loaded"), true);
2
3
 
3
4
  export const EMBEDDED_DOC_FILENAMES: readonly string[] = ["ERRATA-GPT5-HARMONY.md","FORK_MAINTENANCE.md","REBRANDING_PLAN_260525.md","ai-schema-normalize.md","analyze-me-with-skc.md","aside-integration.md","auth-broker-gateway.md","bash-tool-runtime.md","blob-artifact-architecture.md","bot-integration.md","brand-assets.md","bridge.md","codebase-overview.md","codegraph-custom-tool.md","compaction.md","composer-codex-parity.md","computer-use/README.md","environment-variables.md","external-control-readiness.md","extragoal-skill-template.md","fs-scan-cache-architecture.md","geobench.md","git-daemon.md","grok-build-provider-design.md","handoff-generation-pipeline.md","hermes-mcp-bridge.md","hotspot-map-successor.md","keybindings.md","lsp-config.md","memory.md","models.md","multi-vendor-profiles.md","native-ffi-optimization-policy.md","natives-addon-loader-runtime.md","natives-architecture.md","natives-binding-contract.md","natives-build-release-debugging.md","natives-media-system-utils.md","natives-package-split-plan.md","natives-rust-task-cancellation.md","natives-shell-pty-process.md","natives-text-search-pipeline.md","non-compaction-retry-policy.md","notebook-tool-runtime.md","notifications-sdk.md","onboarding-packet.md","onboarding-receipt.md","ooo-bridge-extension-contract.md","openclaw-hermes-rpc-integration.md","perf-profiling-corpus.md","porting-from-pi-mono.md","porting-to-natives.md","prompt-architect-reports/README.md","prompt-architect-reports/recovered-context/0-ToolPrompts.recovered.md","prompt-architect-reports/recovered-context/1-SystemPrompts.recovered.md","prompt-architect-reports/recovered-context/3-SkillMiscPrompts.recovered.md","prompt-architect-reports/recovery-summary.md","prompt-architect-reports/system-prompts.raw.md","prompt-architect-reports/tool-prompts.raw.md","provider-streaming-internals.md","python-repl.md","readme/README.de.md","readme/README.es.md","readme/README.fr.md","readme/README.ja.md","readme/README.ko.md","readme/README.zh.md","render-mermaid.md","research-plan-ledger.md","resolve-tool-runtime.md","rpc.md","rulebook-matching-pipeline.md","sayknow-remote.md","sdk.md","secrets.md","session-operations-export-share-fork-resume.md","session-switching-and-recent-listing.md","session-tree-plan.md","session.md","skc-dogfood-skill-template.md","skc-plugins.md","skc-session-clawhip-routing.md","standalone-mcp.md","telegram-onboarding.md","telegram-remote.md","theme.md","tools/ask.md","tools/ast-edit.md","tools/ast-grep.md","tools/bash.md","tools/bisect.md","tools/browser.md","tools/calc.md","tools/checkpoint.md","tools/computer.md","tools/cron.md","tools/debug.md","tools/edit.md","tools/eval.md","tools/find.md","tools/github.md","tools/irc.md","tools/job.md","tools/lsp.md","tools/monitor.md","tools/read.md","tools/recipe.md","tools/render_mermaid.md","tools/resolve.md","tools/rewind.md","tools/search.md","tools/search_tool_bm25.md","tools/ssh.md","tools/task.md","tools/todo_write.md","tools/web_search.md","tools/write.md","tree.md","ttsr-injection-lifecycle.md","tui-runtime-internals.md","ui-design-visual-qa.md"];
4
5
 
@@ -8,7 +9,7 @@ export const EMBEDDED_DOCS: Readonly<Record<string, string>> = {
8
9
  "REBRANDING_PLAN_260525.md": "# SKC Rebranding Plan — 2026-05-26\n\n## Status\n\nApproved plan for the sayknow-cli/SKC rebrand and visible UI redesign. This document records the implementation contract to track in GitHub and preserve in-repo.\nGitHub tracking issue: https://github.com/jaybeyond/Sayknow_CLI/issues/3\n\n## Decision\n\nRedesign the visible SKC terminal, export, and documentation surfaces around a coherent red-octopus sayknow-cli identity while preserving clegacyatibility boundaries.\n\nThe default-visible product should read as **sayknow-cli / SKC**, not legacy upstream branding or a generic inherited terminal skin. Red-claw becomes the default dark visual direction for users without an explicit override. Session exports and README screenshots should show the same brand direction, while exported transcript content remains neutral and readable.\n\n## Principles\n\n1. **SKC-first visible identity** — Default-visible UI should present sayknow-cli/red-octopus as the current product identity.\n2. **Clegacyatibility preservation** — Keep `skc`, `skc-stats`, `skc-swarm`, `@sayknow-cli/*`, legacy runtime roots/env aliases, and explicit attribution/history.\n3. **Semantic color integrity** — Brand red/coral/shell colors must stay distinct from error, warning, and diff-removal semantics.\n4. **Readable fallbacks** — Truecolor, 256-color, Unicode, Nerd Font, ASCII, narrow terminal, and imperfect-font modes must remain usable.\n5. **Audit-friendly exports** — HTML exports and docs use SKC header/accent/metadata branding without making transcript content decorative or hard to review.\n6. **Visible workflow minimization** — Default repo-shipped visible skills/workflows remain limited to `deep-interview`, `ralplan`, `team`, and `ultragoal`.\n\n## Scope\n\n### In scope\n\n- Default dark theme and bundled red-octopus palette.\n- Visible TUI surfaces: welcome, status line, footer/keybinding hints, message frames, assistant/user/custom/system messages, tool execution cards, ask/approval cards, selectors/settings, todo/plan surfaces, transcript chrome, diff/tool output styling.\n- Status-line identity cutover away from default-visible legacy/Pi/powerline styling.\n- Session HTML export header/accent/metadata branding while preserving transcript readability.\n- README screenshots/alt text and docs pages that present current SKC UI/export identity.\n- Static scans and tests for current-product brand leaks, clegacyatibility names, theme defaults, fallback readability, and export branding.\n\n### Out of scope\n\n- Renaming `skc`, `skc-stats`, `skc-swarm`, or `@sayknow-cli/*` package surfaces.\n- Removing legacy runtime roots, env aliases, clegacyatibility internals, migration notes, generated/vendor content, or attribution/history solely because they mention legacy/Pi.\n- Copying OpenAI code provider, SST/opencode, Anthropic Code, or legacy upstream visuals verbatim.\n- Making exports decorative enough to reduce audit readability.\n- Replacing the TUI framework as part of the brand redesign.\n\n## Implementation Plan\n\n### Phase 1 — Inventory and allowlist\n\n- Search active visible UI/docs/export surfaces for old-brand and inherited UI identity markers: legacy upstream markers, `skc`, `pi`, `powerline`, and generic export labels.\n- Classify hits as current product identity, explicit user opt-in setting labels, clegacyatibility internals, attribution/history/migration notes, or generated/vendor content.\n- Build or update verification gates so current-product visible leaks fail, but clegacyatibility and attribution do not.\n\n### Phase 2 — Theme defaults and palette semantics\n\n- Make red-octopus the default dark visual direction for users without explicit theme overrides.\n- Separate brand tokens (`brandRed`, `claw`, `coral`, `shell`) from semantic tokens (`dangerRed`, `warningAmber`, `diffRemovalRed`).\n- Ensure accents, borders, markdown, status-line identity, and export header variables use brand tokens while errors, warnings, and removals use semantic tokens.\n- Add focused tests for default theme resolution and token separation.\n\n### Phase 3 — Status-line identity cutover\n\n- Remove Pi from bundled default-visible status presets or replace it with clegacyact SKC/claw identity.\n- Preserve legacy segment/symbol clegacyatibility only as explicit opt-in or internal alias behavior.\n- Change default separators away from powerline-like styling; keep powerline variants available only as explicit user choices.\n- Verify status-line overflow, narrow-width, and ASCII/minimal-symbol behavior.\n\n### Phase 4 — Coherent TUI clegacyonent pass\n\nUse existing theme tokens rather than a new UI framework abstraction.\n\n- Apply shell/ink backgrounds, coral/claw accents, clegacyact borders, and lower-noise hierarchy across visible clegacyonents.\n- Refresh welcome, status line, footer hints, message frames, tool cards, ask/approval cards, selectors/settings, todo/plan surfaces, and transcript chrome.\n- Keep high-frequency tool cards inspectable: tool name, path/args, status, diff preview, truncation/expand hints, and error states remain clearer than decoration.\n- Confirm Unicode/Nerd/ASCII fallbacks for new visible symbols.\n\n### Phase 5 — Export and docs alignment\n\n- Update HTML export title/header/metadata to present SKC session export branding.\n- Keep message bodies, code blocks, tool output, system prlegacyts, and transcript content neutral and high contrast.\n- Regenerate derived export templates if required by the repository workflow.\n- Update README screenshots/alt text and docs references so the demonstrated TUI/export direction matches the implemented default.\n\n### Phase 6 — Verification and review\n\n- Run focused theme/status/export/static-scan tests first.\n- Run package-local checks after focused tests pass.\n- Run cleanup/refactor review on changed files.\n- Rerun verification after cleanup.\n- Run final code review and resolve blockers before considering the implementation clegacylete.\n\n## Acceptance Criteria\n\n- [ ] Default dark theme resolves to red-octopus/SKC for users without explicit theme override.\n- [ ] Brand/accent tokens are distinct from error, warning, and diff-removal tokens.\n- [ ] Default-visible status-line identity no longer leads with legacy/Pi-style branding.\n- [ ] Default-visible status separators no longer use powerline-style styling unless explicitly opted in.\n- [ ] Visible TUI clegacyonents share one coherent SKC language across welcome, status line, footer hints, message frames, tool execution cards, ask/approval cards, selectors/settings, and todo/plan surfaces.\n- [ ] Static scans of active UI/docs/export surfaces do not present legacy/Pi as current product identity; clegacyatibility internals, attribution/history, generated/vendor content, and migration notes remain allowlisted.\n- [ ] Full session HTML export includes SKC header/accent/metadata branding while preserving neutral readable transcript content.\n- [ ] README screenshots and alt text show the same SKC/red-octopus brand direction as the TUI/export surfaces.\n- [ ] Redesign remains readable under fallback terminal modes, including ASCII/minimal-symbol operation.\n- [ ] Focused verification covers default theme, visible brand allowlist, export branding, and preserved clegacyatibility names.\n\n## Planned Evidence\n\nFocused tests/probes after implementation:\n\n```bash\nbun test packages/coding-agent/test/skc-ui-redesign.test.ts\nbun test packages/coding-agent/test/theme-auto-detection.test.ts packages/coding-agent/test/status-line-overflow.test.ts packages/coding-agent/test/status-line-path.test.ts\nbun scripts/verify-skc-ui-redesign.ts\nbun --cwd=packages/coding-agent run check\n```\n\nManual/render probes:\n\n1. Launch with no explicit theme config and capture welcome/status/footer/tool-card flow.\n2. Launch with explicit non-red theme config and confirm it is not overwritten.\n3. Render status line at normal and narrow widths for default, clegacyact, full, Nerd, ASCII, and preserved custom settings.\n4. Render representative tool executions: pending, success, error, diff added/removed, spilled/truncated output, and image fallback.\n5. Render selectors/settings and ask/approval cards under red-octopus and ASCII/minimal-symbol mode.\n6. Generate a full session HTML export and inspect header/title/metadata/accent variables plus transcript readability.\n7. Inspect README screenshots/alt text and clegacyare them against the generated full-session export direction.\n\n## Risks and Mitigations\n\n- **Brand red becomes error/removal red** — Add token-level tests and rendered probes for brand, error, warning, and diff states.\n- **User-selected themes/status settings are overwritten** — Change defaults and bundled presets only; test explicit non-red theme/custom status preservation.\n- **Visible legacy/Pi removal breaks legacy configs** — Keep clegacyatibility aliases internally or opt-in, while removing current-product default visibility.\n- **Visual pass becomes subjective churn** — Centralize design in existing theme tokens and focused snapshots/probes; avoid framework replacement.\n- **Exports become too decorative for audits** — Brand only header/accent/metadata; keep transcript/code/tool content neutral and high contrast.\n- **Terminal fallback regressions** — Verify ASCII/minimal-symbol and narrow-width render paths.\n\n## Approval State\n\nThis plan is approved for tracking. Implementation still requires normal code review and verification before clegacyletion.\n",
9
10
  "ai-schema-normalize.md": "# AI tool-schema normalization\n\n`@sayknow-cli/ai` exposes one unified schema normalizer that providers consume\nbefore tools are sent on the wire. All walkers live in\n`packages/ai/src/utils/schema/normalize.ts`; the operational contract is\n`packages/ai/src/utils/schema/CONSTRAINTS.md`.\n\nThere is no separate `strict-mode.ts` module any more — OpenAI strict-mode\nsanitization, OpenAI Responses `oneOf` rewriting, Google/Vertex/Gemini-CLI\nsanitization, Cloud Code Assist Anthropic sanitization, and MCP sanitization all\nshare the same option-driven walk.\n\n## Entry points\n\nAll exports live under `@sayknow-cli/ai/utils/schema`:\n\n- `normalizeSchema(value, options)` — generic option-driven walker.\n- `normalizeSchemaForGoogle(value)` — Gemini / Vertex / Gemini CLI.\n- `normalizeSchemaForCCA(value)` — Cloud Code Assist Anthropic (Antigravity + GCA).\n- `normalizeSchemaForMCP(value)` — MCP inputSchemas before they enter the\n custom-tool registry. `tool-bridge.ts` runs every MCP `inputSchema` through\n this dispatcher.\n- `normalizeSchemaForOpenAIResponses(schema)` (alias\n `sanitizeSchemaForOpenAIResponses`) — rewrites `oneOf` → `anyOf` for the\n Responses family.\n- `sanitizeSchemaForStrictMode(schema)` and\n `enforceStrictSchema(schema)` / `tryEnforceStrictSchema(schema)` — the\n OpenAI strict-mode pipeline (sanitize → enforce). All three are exported\n from `normalize.ts`.\n- `adaptSchemaForStrict(schema, strict)` from `./adapt` — thin composer that\n wraps `tryEnforceStrictSchema` for provider call sites and consults\n `SKC_NO_STRICT` (env `SKC_NO_STRICT`) for the global bypass.\n\nRemoved in the unified-flow refactor:\n\n- `strict-mode.ts` (merged into `normalize.ts`).\n- `sanitize-google.ts` and `normalize-cca.ts` (replaced by\n `normalizeSchemaFor*` dispatchers).\n- `StringEnum` helper — use `z.enum([...])` directly; Zod's emitted JSON\n Schema is already wire-compatible with Google and other providers.\n- `sanitizeSchemaFor{Google,CCA,MCP}` / `prepareSchemaForCCA` — renamed to\n `normalizeSchemaFor{Google,CCA,MCP}`.\n\n## Dispatcher mapping\n\n| Provider transport(s) | Dispatcher |\n| -------------------------------------------------------------------- | -------------------------------------------- |\n| `openai-completions`, `openai-responses`, `openai-code-responses` | `adaptSchemaForStrict` (sanitize + enforce) |\n| `openai-responses` family (`oneOf` → `anyOf` only) | `normalizeSchemaForOpenAIResponses` |\n| `google-generative-ai`, `google-vertex`, Gemini CLI | `normalizeSchemaForGoogle` |\n| Cloud Code Assist Anthropic (Antigravity + GCA, `anthropic-model-*` model ids) | `normalizeSchemaForCCA` |\n| MCP `inputSchema` ingestion | `normalizeSchemaForMCP` |\n| `anthropic-messages` (native, not CCA) | per-provider whitelist in `anthropic.ts` |\n\nGemini CLI / Antigravity CCA MUST run the full `normalizeSchemaForCCA`\npipeline (not just the first keyword-stripping pass) to keep parity with the\nshared Google Anthropic path.\n\n## Walk semantics\n\n`normalizeSchema` first upgrades the input to JSON Schema 2020-12, then\nwalks the tree with the option set pinned by the dispatcher. Each node:\n\n1. Inlines `$ref` (see \"Edge cases\" below).\n2. Renames `snake_case` combinator/property keys to camelCase\n (`any_of` → `anyOf`, etc.; collisions follow python-genai\n `pop(from)`/`set(to)` semantics — snake_case wins).\n3. Applies the `handle_null_fields` collapse for nullable unions before\n recursing into children.\n4. Strips keys the target provider does not support, optionally lifting\n human-meaningful keys (`pattern`, `format`, min/max, `default`,\n `examples`, ...) into the sibling `description` via the spill formatter\n (`spill.ts`). Structural/meta keys (`$ref`, `$defs`,\n `additionalProperties`) are not spilled.\n5. Normalizes type unions (`type: [\"T\", \"null\"]` → `type: \"T\"` + nullable\n marker on Google, plain `type: \"T\"` on CCA).\n6. Collapses object-only / same-type combiners, optionally lossy-collapses\n mixed-type combiners (CCA only), and runs the residual-combiner fixpoint.\n7. Validates against AJV 2020 when `validateAndFallback` is set (CCA path)\n and emits the per-tool fallback `{ \"type\": \"object\", \"properties\": {} }`\n on residual incompatibility — `type` array, `type: \"null\"`, `nullable`\n key, or any remaining `anyOf`/`oneOf`/`allOf`.\n\n## OpenAI strict-mode pipeline\n\n`adaptSchemaForStrict(schema, strict)` runs `tryEnforceStrictSchema`,\nwhich composes:\n\n1. **Sanitize** (`sanitizeSchemaForStrictMode`): strips non-structural\n keywords (`format`, `pattern`, min/max, `examples`, `default`,\n `if`/`then`/`else`, `not`, `unevaluated*`, `patternProperties`,\n `dependent*`, `content*`, `min/maxProperties`, `$dynamicRef`, etc.). The\n `default` value is inlined into the sibling `description` as\n ` (default: X)` before being dropped, unless `description` already\n contains `(default:` or no `description` exists.\n2. **Enforce** (`enforceStrictSchema`): every object node gets\n `additionalProperties: false`, every property goes into `required`, and\n optional properties become nullable unions\n (`anyOf: [<original>, { \"type\": \"null\" }]`). Tuple `prefixItems` are\n strictified recursively.\n\nThe two passes share node-level caches and the same epoch-based cycle\nguard, so a single walk on the wire path normalizes refs, allOf, and\nnullable wrapping consistently. `tryEnforceStrictSchema` is fail-open:\nif anything throws, it returns `{ strict: false, schema: original }` so\ncallers MUST emit `strict: true` only when enforcement actually succeeded.\n\n### Edge cases the strict-mode normalizer handles\n\n- **Local `$ref` inlining.** OpenAI strict mode rejects\n `{ \"$ref\": \"...\", \"description\": \"...\" }` with sibling keys. The\n sanitizer pre-resolves local `#/...` refs against the root and merges\n with **sibling keys winning** over the resolved def — same precedence\n as `openai-python`'s `_ensure_strict_json_schema`. Recursive refs are\n guarded by the per-walk epoch.\n- **Single-item `allOf`.** A `{ \"allOf\": [X], ...siblings }` collapses to\n `{ ...X, ...siblings }` with the inlined entry's keys winning over the\n original siblings (matches `openai-python`'s `_pydantic.py:79-83`). Multi-\n item `allOf` is left intact for the downstream validator to reject if\n needed.\n- **Type-array branches and nullable unions.** When a node has\n `type: [\"T\", \"U\"]`, the sanitizer emits one variant schema per type,\n pruning type-specific keywords (e.g. `properties`/`required` only stay on\n the `object` variant, `items` only on the `array` variant). The shared\n `description` is **hoisted onto the `anyOf` wrapper** instead of being\n duplicated on every branch — so a strict nullable union becomes\n `{ anyOf: [T, { type: \"null\" }], description: \"...\" }`, not\n `anyOf: [{ ..., description }, { ..., description }]`.\n- **Enum/const without a `type`.** Both sanitize and enforce paths call\n `inferStrictPrimitiveTypeFromEnumOrConst` to infer the primitive `type`\n from `enum` / `const` values. Mixed-primitive enums (`[1, \"two\", null]`),\n enums containing objects/arrays, and non-primitive `const` values\n (`{a:1}`, `[1,2,3]`) cannot be described by a single `type` keyword and\n trigger the strict-mode fail-open path — emitting a typeless schema\n would just be rejected on the wire by OpenAI.\n\n## Performance: static fingerprint cache\n\n`resolveProviderModels` in `packages/ai/src/model-manager.ts` and\n`readModelCache`/`writeModelCache` in `model-cache.ts` cooperate via a\nschema-v3 `static_fingerprint` column on the `model_cache` SQLite table.\n\n- `fingerprintStatic(staticModels)` hashes the static catalog slice\n (`Bun.hash(JSON.stringify(models))` in base36) and memoizes the result\n in a per-process `WeakMap` keyed by the array reference. Multiple\n cold-start arms calling `resolveProviderModels` with the same\n `staticModels` array pay the JSON+hash cost once.\n- On cache read, if the network fetch is being skipped, the cached row is\n fresh + authoritative, and the cached `static_fingerprint` matches the\n current one, `resolveProviderModels` returns the cached models verbatim\n — the cache already incorporates the same static state, so re-running\n `mergeDynamicModels(static, cache)` would just rebuild the same objects.\n- `mergeModelSources` and `mergeDynamicModels` short-circuit on\n empty-source inputs (the common shape after `(static, [])` or for\n providers without a static catalog), avoiding Map churn entirely.\n\nCache rows written before schema v3 are dropped by the cache-version\ncheck; the column defaults to `''` for any row that survives a version\nupgrade so the fingerprint-equality check naturally fails closed and the\nfull merge re-runs.\n\n## Related\n\n- `docs/models.md` — registry, equivalence, compat flags\n (`supportsStrictMode`, `toolStrictMode`, `disableStrictTools`).\n- `docs/provider-streaming-internals.md` — how the normalized schemas are\n used downstream during the provider stream loop.\n- `packages/ai/src/utils/schema/CONSTRAINTS.md` — operational contract for\n every normalization rule.\n",
10
11
  "analyze-me-with-skc.md": "# Analyze Me with SKC\n\nUse this prompt for meetup icebreakers where each participant asks SKC to introduce them from their own local SKC usage history.\n\nThe prompt is designed to be repeatable: it tells SKC what local artifacts to inspect, what patterns to extract, how to avoid leaking secrets, and how to turn the analysis into a short spoken self-introduction.\n\n## Full prompt\n\n```text\n~/.skc 에 있는 내 가재코드 사용내역을 바탕으로, 가재코드 밋업 아이스브레이킹용 “가재코드가 보는 나” 자기소개 글을 작성해줘.\n\n목표:\n- 내 실제 가재코드 사용패턴을 분석해서, 내가 어떤 개발자/빌더/운영자인지 소개하는 글을 써줘.\n- 단순 통계 나열이 아니라, 사용 습관과 관심사에서 드러나는 성향을 해석해줘.\n- 밋업에서 2~4분 정도 읽을 수 있는 분량으로 작성해줘.\n- 너무 딱딱한 리포트 말고, 사람 소개글처럼 재미있고 선명하게 써줘.\n- 과장하거나 없는 사실을 만들지 말고, 실제 ~/.skc 기록에서 관찰된 패턴만 근거로 삼아줘.\n\n분석 지시:\n1. ~/.skc 디렉터리 구조를 먼저 확인해줘.\n2. 가능한 경우 아래의 안전한 메타데이터 중심 자료만 분석해줘:\n - ~/.skc/agent/history.db 의 집계값\n - ~/.skc/agent/sessions/**/*.jsonl 의 세션 메타데이터(세션 제목, timestamp, cwd, 메시지 수, tool-call 수, 파일 크기, subagent/task 이름)\n - ~/.skc 내부의 추가 파일은 사용패턴 집계에 꼭 필요하고 민감정보가 없다고 판단되는 경우에만 읽어줘.\n - 기본적으로 ~/.skc/logs/*, auth/config/credential 파일, env dump, raw tool-result body, raw prompt body, secret-like 값은 읽지 마.\n3. history.db에서는 최소한 다음을 봐줘:\n - 전체 프롬프트 수\n - 기간 범위\n - 작업 디렉터리 / 레포지토리 분포\n - 자주 등장하는 주제어\n - 짧은 명령과 긴 프롬프트의 비율\n - /skill:ultragoal, /skill:ralplan, /skill:deep-interview, /skill:team 사용 빈도\n - continue, fix, review, merge, PR, CI, test, verify, implement, delegate 같은 실행/검증 관련 단어 빈도\n4. sessions jsonl에서는 가능하면 다음을 봐줘:\n - 메인 세션 수\n - 서브에이전트 / task 세션 수\n - 짧은 세션과 긴 세션의 분포\n - 세션 title 또는 worktree 이름에서 보이는 관심사\n - 장기 실행, 병렬 위임, 검증, 리뷰, 릴리스 운영 흔적\n5. 레포지토리와 주제 다양성을 꼭 반영해줘:\n - 어떤 레포지토리/워크트리에서 많이 일했는지\n - SKC core, 개인 프로젝트, 연구/quant, infra, UI, automation, image/media 등 주제 범위가 보이면 묶어서 설명해줘.\n6. 민감정보는 절대 노출하지 마:\n - API key, 토큰, credential, 개인 연락처, 로컬 secret, private URL, 인증정보는 출력하지 마.\n - 프롬프트 예시는 필요할 때만 짧게 paraphrase해서 써줘.\n - 파일 경로나 레포 이름은 자기소개에 필요한 수준으로만 언급해줘.\n - 분석 중에도 민감정보를 모델 컨텍스트에 올리지 않도록 metadata-first / aggregate-only 방식으로 처리해줘.\n\n출력 형식:\n\n먼저 아주 짧게 “분석한 근거”를 3~6개 bullet로 요약해줘.\n예:\n- 분석 기간:\n- 프롬프트 수:\n- 주요 작업 공간:\n- 세션 패턴:\n- 자주 보인 workflow/skill:\n- 주요 관심사:\n\n그 다음 아래 제목으로 자기소개 글을 써줘:\n\n# 가재코드가 보는 나\n\n글 스타일:\n- 한국어로 작성.\n- 살짝 위트 있게.\n- “당신은 …” 또는 “나는 …” 중 더 자연스러운 쪽을 선택해도 됨.\n- 밋업에서 읽기 좋게 문단을 나눠줘.\n- 너무 아부하지 말고, 사용패턴에서 드러나는 장점과 특이한 습관을 솔직하게 말해줘.\n- 마지막에는 한 문장으로 요약해줘:\n “한 문장으로 말하면, 나는 ___ 하는 사람이다.”\n\n추가로 마지막에 선택사항으로 아래 3개를 붙여줘:\n\n## 10초 버전\n한두 문장짜리 초단기 자기소개.\n\n## 한 줄 별명\n사용패턴 기반 별명 3개.\n\n## 밋업용 오프닝 멘트\n처음 인사할 때 바로 읽을 수 있는 20~30초짜리 멘트.\n\n주의:\n- 분석 없이 일반론으로 쓰지 마.\n- 실제 ~/.skc 기록을 읽고 나서 작성해.\n- 숫자를 말할 때는 실제로 확인한 숫자만 써.\n- 확인하지 못한 항목은 “확인 불가”라고 하지 말고, 그 항목을 빼고 자연스럽게 작성해.\n```\n\n## Short meetup prompt\n\nUse this when participants need a shorter copy/paste prompt.\n\n```text\n~/.skc 사용내역을 분석해서 밋업 아이스브레이킹용 “가재코드가 보는 나” 자기소개 글을 써줘.\n\n반드시 실제 ~/.skc 기록을 읽되, 안전한 메타데이터와 집계값 중심으로 근거 기반 작성해:\n- history.db의 프롬프트 수, 기간, cwd/레포 분포, 자주 쓰는 단어, skill 사용량\n- sessions jsonl의 세션 수, 세션 길이 다양성, subagent/task 사용 흔적\n- 레포지토리/주제 다양성\n- 짧은 명령 vs 긴 지시문 패턴\n- 실행/검증/리뷰/PR/CI/릴리스/위임 습관\n\n민감정보는 읽지도 출력하지도 마. API key, 토큰, private credential, 개인 secret, 긴 원문 프롬프트, raw tool-result body, ~/.skc/logs/*, auth/config/env dump는 기본적으로 건너뛰고, 필요한 경우에도 안전한 집계값과 짧은 paraphrase만 써.\n\n출력:\n1. 분석 근거 bullet 3~6개\n2. 제목: “가재코드가 보는 나”\n3. 밋업에서 2~4분 읽을 수 있는 한국어 자기소개 글\n4. 마지막에:\n - 10초 버전\n - 사용패턴 기반 별명 3개\n - 20~30초 오프닝 멘트\n\n스타일:\n- 재미있고 선명하게\n- 과장 없이\n- 통계 나열보다 “이 사람이 어떤 식으로 일하는 사람인지” 해석 중심\n- 마지막 문장은 “한 문장으로 말하면, 나는 ___ 하는 사람이다.”\n```\n\n## Optional: SayknowTI prompt\n\nA meetup host can also turn the same analysis into a playful, MBTI-like “SayknowTI” result. This is only an icebreaker taxonomy, not a psychological assessment.\n\n```text\n~/.skc 사용내역을 안전한 메타데이터와 집계값 중심으로 분석해서, 밋업 아이스브레이킹용 “가재TI”를 만들어줘.\n\n목표:\n- MBTI처럼 4글자 코드와 타입명을 만들되, 실제 성격검사가 아니라 가재코드 사용패턴 기반의 재미있는 작업 스타일 분류로 작성해.\n- 실제 ~/.skc 기록에서 확인한 사용패턴만 근거로 삼아줘.\n- 민감정보는 읽지도 출력하지도 마. API key, 토큰, private credential, 개인 secret, 긴 원문 프롬프트, raw tool-result body, ~/.skc/logs/*, auth/config/env dump는 기본적으로 건너뛰고, 안전한 집계값과 짧은 paraphrase만 써.\n\n먼저 아래 4개 축을 기준으로 타입을 판정해줘. 각 축은 한쪽을 고르되, 애매하면 근거와 함께 중간 성향이라고 설명해.\n\n1. E / P — Execute vs Plan\n - E: fix, implement, merge, ship, PR, CI, release처럼 실행/운영 명령이 강함.\n - P: deep-interview, ralplan, spec, architecture, review처럼 계획/정의/합의 흐름이 강함.\n\n2. S / M — Sprint vs Marathon\n - S: 짧은 명령, 빠른 follow-up, `continue`, 작은 세션이 많음.\n - M: 장기 세션, durable goal, 긴 프롬프트, 며칠짜리 작업 흐름이 많음.\n\n3. C / D — Craft vs Delegate\n - C: 직접 구현/수정/탐색 중심.\n - D: subagent, executor, architect, critic, team, parallel delegation 사용이 강함.\n\n4. X / O — Explore vs Operate\n - X: 새로운 모델/provider/tool/research/실험 주제가 많음.\n - O: PR, CI, release, changelog, version, production 운영/마감 흐름이 많음.\n\n분석할 최소 근거:\n- history.db의 프롬프트 수, 기간, cwd/레포 분포, 자주 쓰는 단어, skill 사용량\n- sessions jsonl의 세션 수, 세션 길이 다양성, subagent/task 흔적\n- 레포지토리/주제 다양성\n- 짧은 명령 vs 긴 지시문 패턴\n- 실행/검증/리뷰/PR/CI/릴리스/위임 습관\n\n출력 형식:\n\n# 나의 가재TI: <4글자 코드> — <타입명>\n\n## 판정 근거\n- E/P: <선택> — <실제 집계 또는 관찰 근거>\n- S/M: <선택> — <실제 집계 또는 관찰 근거>\n- C/D: <선택> — <실제 집계 또는 관찰 근거>\n- X/O: <선택> — <실제 집계 또는 관찰 근거>\n\n## 타입 설명\n밋업에서 1분 정도 읽을 수 있게, 이 사람이 가재코드를 어떻게 쓰는 사람인지 재미있게 설명해줘.\n\n## 강점\n3개 bullet.\n\n## 주의할 점\n놀리는 느낌은 살짝 있어도 되지만, 비하하지 말고 작업 습관상 조심할 점 2~3개.\n\n## 어울리는 밋업 별명\n3개.\n\n주의:\n- 이건 성격검사가 아니라 사용패턴 기반 밋업 놀이야.\n- 숫자는 실제로 확인한 값만 써.\n- 확인하지 못한 축은 억지로 단정하지 말고 “근거 부족” 또는 “혼합형”이라고 써.\n```\n",
11
- "aside-integration.md": "# Aside sidecar evaluation\n\nThis note records the safe first-step boundary for evaluating [Aside](https://aside.com/) with Sayknow-CLI (`skc`). It is intentionally docs-only: SKC does not ship an Aside adapter, does not auto-discover Aside, and does not enable browser-control behavior by default.\n\n## Current public surface\n\nOfficial Aside docs currently describe Aside as a browser agent that can run tasks across websites, accounts, browsing history, files, saved credentials, and browser state. The developer surface includes:\n\n- `aside \"...\"` for starting a browser task from the terminal.\n- `aside --session <session-id> \"...\"` for continuing a task.\n- `aside mcp` for exposing Aside to another agent or coding tool as an MCP server.\n- `aside repl` for direct browser automation REPL tasks.\n\nThose are useful evaluation hooks, but they are not a narrow SKC-native search API. The documented Aside product surface is broader than search/context retrieval, including browser actions, login-adjacent flows, files, payments, messages, and internal websites. SKC therefore treats Aside as an external, user-owned sidecar until a separate design approves a smaller protocol contract.\n\n## Supported SKC boundary\n\nUse Aside with SKC only when the user explicitly configures it. The safe default scope is:\n\n- search, source-heavy research, summarization, and context retrieval;\n- read-only inspection prompts where possible;\n- explicit user-provided endpoint, command, and credentials;\n- no raw browser/session/private payloads in logs, PRs, issues, or support bundles.\n\nOut of scope by default:\n\n- browser actions and form submissions;\n- login flows, credential autofill, MFA, account recovery, and password-manager operations;\n- payments, purchases, subscriptions, billing changes, posts, messages, or destructive actions;\n- internal-tool workflows, customer/admin dashboards, or privileged production data;\n- file writes or local computer control through Aside;\n- automatic import of Aside browser history, cookies, task transcripts, screenshots, or local profile data into SKC.\n\nIf a task needs any out-of-scope behavior, stop and require a separate explicit design and approval path. Do not smuggle that behavior through a generic “search” tool name.\n\n## Option A: local Aside MCP command\n\nWhen the Aside CLI is installed and the operator intentionally wants SKC to see the Aside MCP tools, register the MCP server explicitly:\n\n```sh\nskc mcp add aside aside mcp --project\n```\n\nUse `--project` for repo-local evaluation. Omit it only when the operator wants the server available to all local SKC sessions.\n\nAfter registration, inspect the redacted definition:\n\n```sh\nskc mcp list --json\n```\n\nDo not paste task transcripts, browser screenshots, cookies, saved credential state, or private Aside profile paths into issues or PRs. If you need to share evidence, summarize the tool list and a benign query result.\n\nRecommended prompt boundary for evaluation:\n\n```text\nUse the Aside sidecar only for read-only search/context retrieval. Do not click, submit, sign in, autofill credentials, use payment or billing flows, post messages, write files, or operate internal tools. Return a short answer with source titles/URLs only.\n```\n\n## Option B: future HTTP/SSE MCP endpoint\n\nIf Aside or a wrapper later exposes a narrow search/context MCP endpoint, keep endpoint and credentials user-owned:\n\n```sh\nexport ASIDE_MCP_URL=\"https://aside.example.invalid/mcp\"\nexport ASIDE_API_KEY=\"...\"\nskc mcp add aside-search --type http --url \"$ASIDE_MCP_URL\" --header Authorization=\"Bearer $ASIDE_API_KEY\" --project\n```\n\n`skc mcp list` and `skc mcp remove` redact header/auth values, but operators are still responsible for not echoing secrets in shell history, CI logs, screenshots, or copied terminal output. Prefer environment indirection over literals whenever possible.\n\nA future Aside search endpoint should be accepted only if it is narrower than browser automation. Minimum shape:\n\n- one or more read-only search/context tools;\n- no browser click/type/navigation tool in the same registered server unless explicitly approved;\n- no direct access to cookies, saved credentials, raw screenshots, raw task transcripts, or browser profile paths;\n- bounded response sizes with source titles/URLs and short snippets by default;\n- clear auth failure vs endpoint/network failure errors without dumping request headers or private response bodies.\n\n## Benign smoke checklist\n\nUse this checklist instead of a live login/payment/internal-site scenario:\n\n1. Register the MCP server with `skc mcp add ... --project`.\n2. Run `skc mcp list --json` and confirm secrets are redacted.\n3. Start a SKC session in a disposable repo/worktree.\n4. Ask one public, non-personal query, for example: `Find the Aside public help page that describes MCP support and summarize the documented command names.`\n5. Confirm the response includes only public page titles/URLs or short snippets.\n6. Confirm no API key, Authorization header, cookie, browser profile path, screenshot, raw task transcript, or private session payload appears in terminal output, logs, issue comments, or PR text.\n7. Remove the evaluation server if it is no longer needed:\n\n```sh\nskc mcp remove aside --project\n# or\nskc mcp remove aside-search --project\n```\n\n## Troubleshooting\n\n| Symptom | Check |\n| --- | --- |\n| `aside` command not found | Install the Aside CLI from Aside developer settings, then use the concrete CLI path as the MCP `command` if needed. |\n| MCP server does not appear | Re-run `skc mcp list --json`; confirm whether the registration was user-scoped or project-scoped. |\n| Auth failure | Rotate or re-enter the Aside-side token/API key. Do not paste it into SKC prompts or issue comments. |\n| Endpoint/network failure | Check the URL, proxy, and TLS path outside SKC with a benign health check; do not dump request headers. |\n| Retrieval misses context | Narrow the query to public sources first. Do not add browser history, cookies, screenshots, or account pages unless a separate approved design covers that data flow. |\n| Tool list includes browser actions | Treat the server as browser automation, not search-only. Keep it disabled for default SKC workflows unless an operator explicitly approves that broader sidecar for the session. |\n\n## Decision\n\nDocs-only is the smallest safe outcome for issue #1097. Existing SKC MCP registration can connect to a user-provided Aside MCP server, and Aside already documents `aside mcp`; no SKC adapter glue is required. The future-safe boundary is to keep Aside external and opt-in, document read/search/context-only use, and require a separate design before SKC claims support for browser actions, login, payment, internal-tool, or private browser-session workflows.\n",
12
+ "aside-integration.md": "# Aside sidecar evaluation\n\nThis note records the safe first-step boundary for evaluating [Aside](https://aside.com/) with Sayknow-CLI (`skc`). It is intentionally docs-only: SKC does not ship an Aside adapter, does not auto-discover Aside, and does not enable browser-control behavior by default.\n\n## Current public surface\n\nOfficial Aside docs currently describe Aside as a browser agent that can run tasks across websites, accounts, browsing history, files, saved credentials, and browser state. The developer surface includes:\n\n- `aside \"...\"` for starting a browser task from the terminal.\n- `aside --session <session-id> \"...\"` for continuing a task.\n- `aside mcp` for exposing Aside to another agent or coding tool as an MCP server.\n- `aside repl` for direct browser automation REPL tasks.\n\nThose are useful evaluation hooks, but they are not a narrow SKC-native search API. The documented Aside product surface is broader than search/context retrieval, including browser actions, login-adjacent flows, files, payments, messages, and internal websites. SKC therefore treats Aside as an external, user-owned sidecar until a separate design approves a smaller protocol contract.\n\n## Supported SKC boundary\n\nUse Aside with SKC only when the user explicitly configures it. The safe default scope is:\n\n- search, source-heavy research, summarization, and context retrieval;\n- read-only inspection prompts where possible;\n- explicit user-provided endpoint, command, and credentials;\n- no raw browser/session/private payloads in logs, PRs, issues, or support bundles.\n\nOut of scope by default:\n\n- browser actions and form submissions;\n- login flows, credential autofill, MFA, account recovery, and password-manager operations;\n- payments, purchases, subscriptions, billing changes, posts, messages, or destructive actions;\n- internal-tool workflows, customer/admin dashboards, or privileged production data;\n- file writes or local computer control through Aside;\n- automatic import of Aside browser history, cookies, task transcripts, screenshots, or local profile data into SKC.\n\nIf a task needs any out-of-scope behavior, stop and require a separate explicit design and approval path. Do not smuggle that behavior through a generic “search” tool name.\n\n## Option A: local Aside MCP command\n\nWhen the Aside CLI is installed and the operator wants to record the Aside MCP command for repo-local inspection, store the definition explicitly:\n\n```sh\nskc mcp add aside aside mcp --project\n```\n\nUse `--project` for repo-local evaluation records. Omit it only when the operator intentionally wants the stored definition in the user-level SKC MCP config; normal standalone SKC sessions do not consume either scope as runtime tools today.\n\nAfter registration, inspect the redacted definition:\n\n```sh\nskc mcp list --json\n```\n\nThis is storage-only recordkeeping today. `skc mcp add/list/remove` does not make Aside tools visible in normal `skc`, `skc --tmux`, or print-mode sessions. Do not paste task transcripts, browser screenshots, cookies, saved credential state, or private Aside profile paths into issues or PRs. If you need to share evidence, summarize the stored definition shape and any benign externally gathered result.\n\n\nRecommended prompt boundary for evaluation:\n\n```text\nUse the Aside sidecar only for read-only search/context retrieval. Do not click, submit, sign in, autofill credentials, use payment or billing flows, post messages, write files, or operate internal tools. Return a short answer with source titles/URLs only.\n```\n\n## Option B: future HTTP/SSE MCP endpoint\n\nIf Aside or a wrapper later exposes a narrow search/context MCP endpoint, keep endpoint and credentials user-owned:\n\n```sh\nexport ASIDE_MCP_URL=\"https://aside.example.invalid/mcp\"\nexport ASIDE_API_KEY=\"...\"\nskc mcp add aside-search --type http --url \"$ASIDE_MCP_URL\" --header Authorization=\"Bearer $ASIDE_API_KEY\" --project\n```\n\n`skc mcp list` and `skc mcp remove` redact header/auth values, but operators are still responsible for not echoing secrets in shell history, CI logs, screenshots, or copied terminal output. Prefer environment indirection over literals whenever possible.\n\nA future Aside search endpoint should be accepted only if it is narrower than browser automation. Minimum shape:\n\n- one or more read-only search/context tools;\n- no browser click/type/navigation tool in the same registered server unless explicitly approved;\n- no direct access to cookies, saved credentials, raw screenshots, raw task transcripts, or browser profile paths;\n- bounded response sizes with source titles/URLs and short snippets by default;\n- clear auth failure vs endpoint/network failure errors without dumping request headers or private response bodies.\n\n## Benign smoke checklist\n\nUse this checklist instead of a live login/payment/internal-site scenario:\n\n1. Register the MCP server definition with `skc mcp add ... --project`.\n2. Run `skc mcp list --json` and confirm secrets are redacted.\n3. Confirm the record is project-scoped or user-scoped as intended.\n4. Do not expect the registration to appear as model tools in a normal standalone SKC session today.\n5. If evaluating Aside behavior separately, run one public, non-personal query through the Aside-owned surface, for example: `Find the Aside public help page that describes MCP support and summarize the documented command names.`\n6. Confirm any shared evidence includes only public page titles/URLs or short snippets.\n7. Confirm no API key, Authorization header, cookie, browser profile path, screenshot, raw task transcript, or private session payload appears in terminal output, logs, issue comments, or PR text.\n8. Remove the evaluation server if it is no longer needed:\n\n```sh\nskc mcp remove aside --project\n# or\nskc mcp remove aside-search --project\n```\n\n## Troubleshooting\n\n| Symptom | Check |\n| --- | --- |\n| `aside` command not found | Install the Aside CLI from Aside developer settings, then use the concrete CLI path as the MCP `command` if needed. |\n| MCP server does not appear in `skc mcp list` | Re-run `skc mcp list --json`; confirm whether the registration was user-scoped or project-scoped. |\n| Aside tools do not appear in a normal SKC session | Expected today. `skc mcp` stores redacted definitions for recordkeeping/inspection; normal standalone `skc`, `skc --tmux`, and print-mode sessions do not load those registrations as runtime tools. |\n| Auth failure | Rotate or re-enter the Aside-side token/API key. Do not paste it into SKC prompts or issue comments. |\n| Endpoint/network failure | Check the URL, proxy, and TLS path outside SKC with a benign health check; do not dump request headers. |\n| Retrieval misses context | Narrow the query to public sources first. Do not add browser history, cookies, screenshots, or account pages unless a separate approved design covers that data flow. |\n| Stored definition points at browser-action tools | Treat the server as browser automation, not search-only. Keep it as recordkeeping only for default SKC workflows unless a separate approved design covers that broader sidecar for runtime use. |\n\n## Decision\n\nDocs-only is the smallest safe outcome for issue #1097. Existing SKC MCP registration can store a user-provided Aside MCP server definition for redacted inspection, and Aside already documents `aside mcp`; no SKC adapter glue is required. The future-safe boundary is to keep Aside external and opt-in, document read/search/context-only use, and require a separate design before SKC claims runtime support for browser actions, login, payment, internal-tool, or private browser-session workflows.\n",
12
13
  "auth-broker-gateway.md": "# Auth Broker and Auth Gateway\n\nThe auth broker and auth gateway are two cooperating HTTP services that move OAuth refresh tokens and provider access tokens off developer laptops and into a single broker host.\n\n- **`skc auth-broker serve`** holds the canonical SQLite credential vault, performs OAuth refreshes, and exposes a small REST API (`/v1/snapshot`, `/v1/credential/:id/refresh`, `/v1/credential/:id/disable`, `/v1/credential`, `/v1/usage`, `/v1/healthz`).\n- **`skc auth-gateway serve`** is a forward-proxy. It accepts OpenAI Chat Completions, Anthropic Messages, and OpenAI Responses requests, injects the broker-resolved access token, and forwards the bytes to the real provider. Clients (containerised skc, llm-git, the macOS usage widget, …) never see the access token.\n\nTransport security between operator, broker, and gateway is delegated to the operator (Tailscale / Wireguard / reverse proxy + TLS). Every endpoint except `/v1/healthz` (broker) and `/healthz` (gateway) requires a bearer token.\n\nSource: `packages/ai/src/auth-broker/`, `packages/ai/src/auth-gateway/`, `packages/coding-agent/src/cli/auth-broker-cli.ts`, `packages/coding-agent/src/cli/auth-gateway-cli.ts`, `packages/coding-agent/src/session/auth-broker-config.ts`.\n\n## Data flow\n\n```\n ┌────────────────────────────────────────────────────────────┐\n │ broker host │\n │ │\n developer ──▶ │ ┌──────────────────────────┐ ┌────────────────────┐ │\n laptop / │ │ skc auth-broker serve │◀──▶│ SQLite agent.db │ │\n CI / roboskc │ │ - holds refresh tokens │ │ (canonical writer)│ │\n │ │ - background refresher │ └────────────────────┘ │\n │ │ /v1/{snapshot,refresh,…}│ │\n │ └─────────┬────────────────┘ │\n │ │ bearer ($CONFIG_DIR/auth-broker.token) │\n │ ▼ │\n │ ┌──────────────────────────┐ │\n │ │ skc auth-gateway serve │ RemoteAuthCredentialStore │\n │ │ /v1/{chat,messages,…} │ pulls /v1/snapshot at boot, │\n │ │ /v1/usage, /v1/models │ refreshes credentials by id │\n │ └─────────┬────────────────┘ via the broker on expiry │\n └────────────┼───────────────────────────────────────────────┘\n │ bearer ($CONFIG_DIR/auth-gateway.token)\n ▼\n unauthenticated clients\n (llm-git, macOS widget, roboskc containers, IDE plugins, …)\n │\n ▼ same path is forwarded with Authorization\n api.anthropic.com / api.openai.com / …\n```\n\nThe broker is the only writer of OAuth refresh tokens. Clients (including the gateway itself) load a redacted snapshot in which every `refresh` field has been replaced with `REMOTE_REFRESH_SENTINEL`; when an access token expires the client calls `POST /v1/credential/:id/refresh` and the broker performs the refresh server-side. `RemoteAuthCredentialStore` rejects any local code path that tries to write through it, with an error pointing at `skc auth-broker login` / `skc auth-broker logout`.\n\n## auth-broker\n\n### CLI\n\n```\nskc auth-broker serve [--bind=host:port] # boot the broker\nskc auth-broker token [--regenerate] [--json] # print or rotate the bearer token\nskc auth-broker login <provider> [--via=user@host] [--dry-run]\nskc auth-broker logout <provider>\nskc auth-broker import <file|dir> [--provider=<id>] [--include-disabled] [--dry-run] [--json]\nskc auth-broker migrate --from-local [--dry-run] [--json]\nskc auth-broker status [--json]\n```\n\n- `serve` opens the local SQLite store at `getAgentDbPath()` and binds an HTTP listener (default `127.0.0.1:8765`). On startup a token is ensured at `<config-dir>/auth-broker.token` (mode `0600`, `0700` parent dir). The background refresher refreshes any OAuth credential whose `expires - Date.now() < refreshSkewMs` (default 5 min) every `refreshIntervalMs` (default 60 s).\n- `token` prints the cached bearer or generates a new one. `--regenerate` rotates it.\n- `login <provider>` runs the per-provider OAuth flow locally, or — with `--via=user@host` — `ssh -L <callback-port>:127.0.0.1:<callback-port> user@host skc auth-broker login <provider>` so the OAuth callback hits the local browser but the credential is written on the broker host. Built-in callback ports: `anthropic:54545`, `openai-code:1455`, `google-gemini-cli:8085`, `google-antigravity:51121`, `gitlab-duo:8080`.\n- `logout <provider>` deletes every credential row for `<provider>`.\n- `import <file|dir>` imports CLIProxyAPI-style JSON credentials into the local SQLite store. Maps `type` field → skc provider (`anthropic-model → anthropic`, `openai-code → openai-code`, `gemini → google-gemini-cli`, `antigravity → google-antigravity`, `gemini-cli → google-gemini-cli`).\n- `migrate --from-local` walks the local SQLite store + env-derived credentials and idempotently uploads them to the configured broker (`POST /v1/credential`).\n- `status` health-pings the configured remote broker.\n\n### Endpoints\n\n| Method | Path | Auth | Purpose |\n| ------ | ---- | ---- | ------- |\n| `GET` | `/v1/healthz` | none | Liveness + version |\n| `GET` | `/v1/snapshot` | bearer | Redacted snapshot (refresh tokens replaced by sentinel) |\n| `POST` | `/v1/credential` | bearer | Upsert one OAuth or API-key credential |\n| `POST` | `/v1/credential/:id/refresh` | bearer | Force-refresh one OAuth credential |\n| `POST` | `/v1/credential/:id/disable` | bearer | Disable one credential with a recorded cause |\n| `GET` | `/v1/usage` | bearer | Aggregate `UsageReport[]` across credentials |\n\nRequests use `Authorization: Bearer <token>`. The server compares against an in-memory token allow-list; the gateway’s implementation uses a timing-safe comparison.\n\n### Background refresher\n\n`AuthBrokerRefresher` iterates active OAuth credentials at `refreshIntervalMs` cadence and refreshes any within `refreshSkewMs` of expiry. Refreshes are single-flighted per credential id so a slow refresh cannot be retriggered. The refresher distinguishes:\n\n- **definitive failures** (`invalid_grant`, `invalid_token`, `revoked`, unauthorized refresh-token, 401/403 not from a network blip) — credentials are passed to `AuthStorage.disableCredentialById(id, cause)` so the next snapshot pull surfaces a clean delete on the client;\n- **transient failures** (timeout / ECONNREFUSED / fetch failed) — left in place for the next sweep.\n\n## auth-gateway\n\n### CLI\n\n```\nskc auth-gateway serve [--bind=host:port] [--no-auth]\nskc auth-gateway token [--regenerate] [--json]\nskc auth-gateway status [--json]\n```\n\n- `serve` requires `SKC_AUTH_BROKER_URL` (or `auth.broker.url` in `config.yml`) — the gateway is itself a broker client. It calls `AuthBrokerClient.fetchSnapshot()`, wraps it in `RemoteAuthCredentialStore`, and constructs an `AuthStorage` that resolves access tokens through the broker. Default bind is `127.0.0.1:4000`. The gateway token is stored at `<config-dir>/auth-gateway.token` (`0600`); `--no-auth` disables the bearer check entirely (loopback-only use).\n- `token` / `status` mirror the broker’s equivalents.\n\n### Endpoints\n\n| Method | Path | Auth | Purpose |\n| ------ | ---- | ---- | ------- |\n| `GET` | `/healthz` | none | Liveness + version |\n| `GET` | `/v1/usage` | bearer | Aggregate `UsageReport[]` (proxied through `AuthStorage`) |\n| `GET` | `/v1/models` | bearer | Bundled-model catalog filtered to providers with credentials |\n| `POST` | `/v1/chat/completions` | bearer | OpenAI Chat Completions wire format |\n| `POST` | `/v1/messages` | bearer | Anthropic Messages wire format |\n| `POST` | `/v1/responses` | bearer | OpenAI Responses wire format |\n\nThe model id is read from the top-level `model` field. The gateway picks the first bundled `Model<Api>` matching that id and:\n\n- **Passthrough fast-path** — when the inbound wire format matches the model’s native API (`openai-chat → openai-completions`, `anthropic-messages → anthropic-messages`, `openai-responses → openai-responses`), the request body is forwarded byte-for-byte with the client `Authorization`/`x-api-key` stripped and replaced by `Authorization: Bearer <resolved-access-token>`. Provider-specific fields (`cache_control`, `service_tier`, tool-choice extensions, …) flow through unmodified. Hop-by-hop headers (RFC 7230) plus `Content-Encoding`/`Content-Length` are stripped from the upstream response.\n- **Translate path** — when the inbound format and the resolved model’s API differ (e.g. `/v1/chat/completions` targeting an Anthropic model, or `/v1/responses` targeting `openai-code-responses` which runs over a websocket transport), the request is parsed against the wire schema, rebuilt into an skc `Context`, dispatched through `streamSimple()`, and re-encoded back to the inbound format (SSE for streamed responses).\n\n`idleTimeout` on the underlying `Bun.serve` is set to `255 s` so long thinking-budget calls do not get killed by Bun’s default idle timeout.\n\n## Usage cache: server-side 5-min jitter + client-side 15 s single-flight\n\nTwo layers cache the aggregate provider-usage report. Both are intentional and stacked.\n\n### Server-side cache (broker `AuthStorage`)\n\n`AuthStorage` caches each credential’s `UsageReport` in the broker’s SQLite store at a **5-minute per-credential TTL with ±25 % jitter**. Anthropic and OpenAI rate-limit `/usage` aggressively per source IP, and a synchronized 5-credential fan-out trips 429s every cycle; the jitter decorrelates refresh times within a few cycles. On fetch failure the store keeps the **last-good** report for up to 24 h with a short jittered re-poll window — so a transient upstream blip never blanks out the widget.\n\nConstants: `USAGE_REPORT_TTL_MS = 5 * 60_000`, `USAGE_LAST_GOOD_RETENTION_MS = 24 * 60 * 60_000` (`packages/ai/src/auth-storage.ts`).\n\n### Client-side single-flight (`RemoteAuthCredentialStore`)\n\nWhen the gateway (or any other broker client) calls `fetchUsageReports()` / `getUsageReport(provider, credential)`, `RemoteAuthCredentialStore` coalesces concurrent calls into a single `GET /v1/usage` round-trip and caches the result for **15 s** in memory.\n\n- `USAGE_CACHE_TTL_MS = 15_000` (`packages/ai/src/auth-broker/remote-store.ts`).\n- A single `#usageInflight` promise is shared across all callers; a per-caller `AbortSignal` is **raced** against the shared promise, not threaded into it, so one caller’s abort never cascades into a peer’s in-flight request.\n- On fetch failure the rejected promise is logged and the awaited value is `null` — callers (`AuthStorage.fetchUsageReports`, `#getUsageReport`) treat a `null` report as \"no usage signal for this cycle\" and proceed without it. **This is the 15 s TTL fallback**: the client absorbs transient broker outages by suppressing the error, returning `null` to ranking, and re-attempting after the 15 s window.\n\nThe 15 s client window deliberately sits below the broker’s 5 min server cache, so almost every client poll is served from the broker’s already-cached value; the client cache exists to absorb the parallel fan-out generated by `AuthStorage.#rankOAuthSelections` into a single broker round-trip.\n\n## Operator opt-in\n\nThe broker is **off** unless `SKC_AUTH_BROKER_URL` (or `auth.broker.url` in `config.yml`) is set. When set, `discoverAuthStorage` in `packages/coding-agent/src/sdk.ts` swaps the local SQLite credential store for `RemoteAuthCredentialStore` and every API call resolves credentials through the broker.\n\n### Environment variables\n\n| Variable | Purpose | Required when |\n| -------- | ------- | ------------- |\n| `SKC_AUTH_BROKER_URL` | Base URL of the remote auth-broker (e.g. `https://broker.tailnet:8765`). Selecting this puts the client in broker mode — local SQLite is bypassed. | Any time the skc client should resolve credentials through a broker (and required by `skc auth-gateway serve`). |\n| `SKC_AUTH_BROKER_TOKEN` | Bearer token used for every broker endpoint except `/v1/healthz`. | When `SKC_AUTH_BROKER_URL` is set and no token is available from `auth.broker.token` or `<config-dir>/auth-broker.token`. |\n\nResolution order in `resolveAuthBrokerConfig()`:\n\n1. `SKC_AUTH_BROKER_URL` env (else `auth.broker.url` from `config.yml`, with `$ENV_NAME` resolution);\n2. `SKC_AUTH_BROKER_TOKEN` env (else `auth.broker.token` from `config.yml`, else `<config-dir>/auth-broker.token`);\n3. URL set but no token resolvable → hard error pointing at the token file path.\n\nThe gateway has no dedicated env vars — it inherits `SKC_AUTH_BROKER_*` because it is itself a broker client.\n\n### `config.yml` keys\n\n| Key | Default | Purpose |\n| --- | ------- | ------- |\n| `auth.broker.url` | unset | Same as `SKC_AUTH_BROKER_URL`; env wins. Hidden from the settings UI. |\n| `auth.broker.token` | unset | Same as `SKC_AUTH_BROKER_TOKEN`; env wins. Values may be the literal token or `$ENV_NAME` to indirect through env. |\n\n### Token files\n\n| Path | Owner | Mode |\n| ---- | ----- | ---- |\n| `<config-dir>/auth-broker.token` | `skc auth-broker serve` (created at first start) | `0600` in a `0700` parent dir |\n| `<config-dir>/auth-gateway.token` | `skc auth-gateway serve` (skipped under `--no-auth`) | `0600` in a `0700` parent dir |\n\n`<config-dir>` resolves to `~/.skc/` (respecting `SKC_CONFIG_DIR`).\n\n## Interaction with the local API-key resolution order\n\nThe broker only owns OAuth credentials and provider-API-key credentials that were uploaded to it. The standard credential ladder in `models.md` (`Auth and API key resolution order`) is preserved, with one addition committed alongside the gateway:\n\n- `AuthStorage.setConfigApiKey / removeConfigApiKey / clearConfigApiKeys` let a `models.yml` `apiKey` beat a stored OAuth token **without** overriding an explicit `--api-key`. This is what allows a broker-resolved OAuth credential to be reliably shadowed by a per-environment `models.yml` config key when both are present.\n\n## See also\n\n- [`secrets.md`](./secrets.md) — secret obfuscation around tokens that *do* leak through (e.g. `SKC_AUTH_BROKER_TOKEN` in shell output).\n- [`models.md`](./models.md) — provider auth resolution order; the broker plugs in at layers 2–3 (stored credentials).\n- [`environment-variables.md`](./environment-variables.md) — full env reference including `SKC_AUTH_BROKER_URL` / `SKC_AUTH_BROKER_TOKEN`.\n",
13
14
  "bash-tool-runtime.md": "# Bash tool runtime\n\nThis document describes the **`bash` tool** runtime path used by agent tool calls, from command normalization to execution, truncation/artifacts, and rendering.\n\nIt also calls out where behavior diverges in interactive TUI, print mode, RPC mode, and user-initiated bang (`!`) shell execution.\n\n## Scope and runtime surfaces\n\nThere are two different bash execution surfaces in coding-agent:\n\n1. **Tool-call surface** (`toolName: \"bash\"`): used when the model calls the bash tool.\n - Entry point: `BashTool.execute()`.\n - Parameters include `command`, optional `env`, `timeout`, `cwd`, `head`, `tail`, `pty`, and, when `async.enabled` is true, `async`.\n2. **User bang-command surface** (`!cmd` from interactive input or RPC `bash` command): session-level helper path.\n - Entry point: `AgentSession.executeBash()`.\n\nBoth eventually use `executeBash()` in `src/exec/bash-executor.ts` for non-PTY execution, but only the tool-call path runs normalization/interception, optional managed background-job handling, and tool renderer logic.\n\n## End-to-end tool-call pipeline\n\n## 1) Input handling and parameter merge\n\n`BashTool.execute()` currently handles input before execution as follows:\n\n- validates optional `env` names against shell-variable syntax,\n- extracts a leading `cd <path> && ...` into `cwd` when `cwd` was not supplied,\n- rejects `async: true` when `async.enabled` is false,\n- uses only explicit `head`/`tail` tool args for post-run filtering.\n\n`normalizeBashCommand()` still exists in `src/tools/bash-normalize.ts`, but `BashTool.execute()` does not call it in the current source. Trailing shell pipes such as `| head -n 50` remain part of the shell command unless the caller uses the structured `head`/`tail` args.\n\n## 2) Optional interception (blocked-command path)\n\nIf `bashInterceptor.enabled` is true, `BashTool` loads rules from settings and runs `checkBashInterception()` against the normalized command.\n\nInterception behavior:\n\n- command is blocked **only** when:\n - regex rule matches, and\n - the suggested tool is present in `ctx.toolNames`.\n- invalid regex rules are silently skipped.\n- on block, `BashTool` throws `ToolError` with message:\n - `Blocked: ...`\n - original command included.\n\nDefault rule patterns (defined in code) target common misuses:\n\n- file readers (`cat`, `head`, `tail`, ...)\n- search tools (`grep`, `rg`, ...)\n- file finders (`find`, `fd`, ...)\n- in-place editors (`sed -i`, `perl -i`, `awk -i inplace`)\n- shell redirection writes (`echo ... > file`, heredoc redirection)\n\n### Caveat\n\n`InterceptionResult` includes `suggestedTool`, but `BashTool` currently surfaces only the message text (no structured suggested-tool field in `details`).\n\n## 3) CWD validation and timeout clamping\n\n`cwd` is resolved relative to session cwd (`resolveToCwd`), then validated via `stat`:\n\n- missing path -> `ToolError(\"Working directory does not exist: ...\")`\n- non-directory -> `ToolError(\"Working directory is not a directory: ...\")`\n\nTimeout is clamped to `[1, 3600]` seconds and converted to milliseconds.\n\n## 4) Artifact allocation\n\nBefore execution, the tool allocates an artifact path/id (best-effort) for truncated output storage.\n\n- artifact allocation failure is non-fatal (execution continues without artifact spill file),\n- artifact id/path are passed into execution path for full-output persistence on truncation.\n\n## 5) PTY vs non-PTY execution selection\n\n`BashTool` chooses PTY execution only when all are true:\n\n- tool input `pty === true`\n- `SKC_NO_PTY !== \"1\"`\n- tool context has UI (`ctx.hasUI === true` and `ctx.ui` set)\n\nOtherwise it uses non-interactive `executeBash()`.\n\nThat means print mode and non-UI RPC/tool contexts always use non-PTY.\n\n## Non-interactive execution engine (`executeBash`)\n\n## Shell session reuse model\n\n`executeBash()` caches native `Shell` instances in a process-global map keyed by:\n\n- shell path,\n- configured command prefix,\n- snapshot path,\n- serialized shell env,\n- optional agent session key.\n\nSession-level bang-command executions pass `sessionKey: this.sessionId`.\n\nTool-call executions pass `sessionKey: this.session.getSessionId?.()`, when available. In both surfaces, a session key isolates shell reuse per session; without one, reuse falls back to shell config/snapshot/env.\n\n## Shell config and snapshot behavior\n\nAt each call, executor loads settings shell config (`shell`, `env`, optional `prefix`).\n\nIf selected shell includes `bash`, it attempts `getOrCreateSnapshot()`:\n\n- snapshot captures aliases/functions/options from user rc,\n- snapshot creation is best-effort,\n- failure falls back to no snapshot.\n\nIf `prefix` is configured, command becomes:\n\n```text\n<prefix> <command>\n```\n\n## Streaming and cancellation\n\n`Shell.run()` streams chunks to `OutputSink` and optional `onChunk` callback.\n\nCancellation:\n\n- aborted signal triggers `shellSession.abort(...)`,\n- timeout from native result is mapped to `cancelled: true` + annotation text,\n- explicit cancellation similarly returns `cancelled: true` + annotation.\n\nNo exception is thrown inside executor for timeout/cancel; it returns structured `BashResult` and lets caller map error semantics.\n\n## Interactive PTY path (`runInteractiveBashPty`)\n\nWhen PTY is enabled, tool runs `runInteractiveBashPty()` which opens an overlay console component and drives a native `PtySession`.\n\nBehavior highlights:\n\n- xterm-headless virtual terminal renders viewport in overlay,\n- keyboard input is normalized (including Kitty sequences and application cursor mode handling),\n- `esc` while running kills the PTY session,\n- terminal resize propagates to PTY (`session.resize(cols, rows)`).\n\nEnvironment hardening defaults are injected for unattended runs:\n\n- pagers disabled (`PAGER=cat`, `GIT_PAGER=cat`, etc.),\n- editor prompts disabled (`GIT_EDITOR=true`, `EDITOR=true`, ...),\n- terminal/auth prompts reduced (`GIT_TERMINAL_PROMPT=0`, `SSH_ASKPASS=/usr/bin/false`, `CI=1`),\n- package-manager/tool automation flags for non-interactive behavior.\n\nPTY output is normalized (`CRLF`/`CR` to `LF`, `sanitizeText`) and written into `OutputSink`, including artifact spill support.\n\nOn PTY startup/runtime error, sink receives `PTY error: ...` line and command finalizes with undefined exit code.\n\n## Output handling: streaming, truncation, artifact spill\n\nBoth PTY and non-PTY paths use `OutputSink`.\n\n## OutputSink semantics\n\n- keeps an in-memory UTF-8-safe tail buffer (`DEFAULT_MAX_BYTES`, currently 50KB),\n- tracks total bytes/lines seen,\n- if artifact path exists and output overflows (or file already active), writes full stream to artifact file,\n- when memory threshold overflows, trims in-memory buffer to tail (UTF-8 boundary safe),\n- marks `truncated` when overflow/file spill occurs.\n\n`dump()` returns:\n\n- `output` (possibly annotated prefix),\n- `truncated`,\n- `totalLines/totalBytes`,\n- `outputLines/outputBytes`,\n- `artifactId` if artifact file was active.\n\n### Long-output caveat\n\nRuntime truncation is byte-threshold based in `OutputSink` (50KB default). It does not enforce a hard 2000-line cap in this code path.\n\n## Live tool updates and async jobs\n\nFor non-PTY foreground execution, `BashTool` uses a separate `TailBuffer` for partial updates and emits `onUpdate` snapshots while command is running.\n\nFor PTY execution, live rendering is handled by custom UI overlay, not by `onUpdate` text chunks.\n\nWhen `async.enabled` is true and the call passes `async: true`, `BashTool` starts a managed bash job, returns a running job result with a job id, and stores completion through the session managed-job path. Auto-backgrounding can also start this path after `bash.autoBackground.thresholdMs`.\n\n## Result shaping, metadata, and error mapping\n\nAfter execution:\n\n1. `cancelled` handling:\n - if abort signal is aborted -> throw `ToolAbortError` (abort semantics),\n - else -> throw `ToolError` (treated as tool failure).\n2. PTY `timedOut` -> throw `ToolError`.\n3. apply head/tail filters to final output text (`applyHeadTail`, head then tail).\n4. empty output becomes `(no output)`.\n5. attach truncation metadata via `toolResult(...).truncationFromSummary(result, { direction: \"tail\" })`.\n6. exit-code mapping:\n - missing exit code -> `ToolError(\"... missing exit status\")`\n - non-zero exit -> `ToolError(\"... Command exited with code N\")`\n - zero exit -> success result.\n\nSuccess payload structure:\n\n- `content`: text output,\n- `details.meta.truncation` when truncated, including:\n - `direction`, `truncatedBy`, total/output line+byte counts,\n - `shownRange`,\n - `artifactId` when available.\n\nBecause built-in tools are wrapped with `wrapToolWithMetaNotice()`, truncation notice text is appended to final text content automatically (for example: `Full: artifact://<id>`).\n\n## Rendering paths\n\n## Tool-call renderer (`bashToolRenderer`)\n\n`bashToolRenderer` is used for tool-call messages (`toolCall` / `toolResult`):\n\n- collapsed mode shows visual-line-truncated preview,\n- expanded mode shows all currently available output text,\n- warning line includes truncation reason and `artifact://<id>` when truncated,\n- timeout value (from args) is shown in footer metadata line.\n\n### Caveat: full artifact expansion\n\n`BashRenderContext` has `isFullOutput`, but current renderer context builder does not set it for bash tool results. Expanded view still uses the text already in result content (tail/truncated output) unless another caller provides full artifact content.\n\n## User bang-command component (`BashExecutionComponent`)\n\n`BashExecutionComponent` is for user `!` commands in interactive mode (not model tool calls):\n\n- streams chunks live,\n- collapsed preview keeps last 20 logical lines,\n- line clamp at 4000 chars per line,\n- shows truncation + artifact warnings when metadata is present,\n- marks cancelled/error/exit state separately.\n\nThis component is wired by `CommandController.handleBashCommand()` and fed from `AgentSession.executeBash()`.\n\n## Mode-specific behavior differences\n\n| Surface | Entry path | PTY eligible | Live output UX | Error surfacing |\n| ------------------------------ | ----------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------ |\n| Interactive tool call | `BashTool.execute` | Yes, when `pty=true` and UI exists and `SKC_NO_PTY!=1` | PTY overlay (interactive) or streamed tail updates | Tool errors become `toolResult.isError` |\n| Print mode tool call | `BashTool.execute` | No (no UI context) | No TUI overlay; output appears in event stream/final assistant text flow | Same tool error mapping |\n| RPC tool call (agent tooling) | `BashTool.execute` | Usually no UI -> non-PTY | Structured tool events/results | Same tool error mapping |\n| Interactive bang command (`!`) | `AgentSession.executeBash` + `BashExecutionComponent` | No (uses executor directly) | Dedicated bash execution component | Controller catches exceptions and shows UI error |\n| RPC `bash` command | `rpc-mode` -> `session.executeBash` | No | Returns `BashResult` directly | Consumer handles returned fields |\n\n## Operational caveats\n\n- Interceptor only blocks commands when suggested tool is currently available in context.\n- If artifact allocation fails, truncation still occurs but no `artifact://` back-reference is available.\n- Shell session cache has no explicit eviction in this module; lifetime is process-scoped.\n- PTY and non-PTY timeout surfaces differ:\n - PTY exposes explicit `timedOut` result field,\n - non-PTY maps timeout into `cancelled + annotation` summary.\n\n## Implementation files\n\n- [`src/tools/bash.ts`](../packages/coding-agent/src/tools/bash.ts) — tool entrypoint, input handling/interception, async and PTY/non-PTY selection, result/error mapping, bash tool renderer.\n- [`src/tools/bash-normalize.ts`](../packages/coding-agent/src/tools/bash-normalize.ts) — post-run head/tail filtering; also contains an unused command-normalization helper.\n- [`src/tools/bash-interceptor.ts`](../packages/coding-agent/src/tools/bash-interceptor.ts) — interceptor rule matching and blocked-command messages.\n- [`src/exec/bash-executor.ts`](../packages/coding-agent/src/exec/bash-executor.ts) — non-PTY executor, shell session reuse, cancellation wiring, output sink integration.\n- [`src/tools/bash-interactive.ts`](../packages/coding-agent/src/tools/bash-interactive.ts) — PTY runtime, overlay UI, input normalization, non-interactive env defaults.\n- [`src/session/streaming-output.ts`](../packages/coding-agent/src/session/streaming-output.ts) — `OutputSink`, `TailBuffer`, truncation/artifact spill, and summary metadata.\n- [`src/tools/output-meta.ts`](../packages/coding-agent/src/tools/output-meta.ts) — truncation metadata shape + notice injection wrapper.\n- [`src/session/agent-session.ts`](../packages/coding-agent/src/session/agent-session.ts) — session-level `executeBash`, message recording, abort lifecycle.\n- [`src/modes/components/bash-execution.ts`](../packages/coding-agent/src/modes/components/bash-execution.ts) — interactive `!` command execution component.\n- [`src/modes/controllers/command-controller.ts`](../packages/coding-agent/src/modes/controllers/command-controller.ts) — wiring for interactive `!` command UI stream/update completion.\n- [`src/modes/rpc/rpc-mode.ts`](../packages/coding-agent/src/modes/rpc/rpc-mode.ts) — RPC `bash` and `abort_bash` command surface.\n- [`src/internal-urls/artifact-protocol.ts`](../packages/coding-agent/src/internal-urls/artifact-protocol.ts) — `artifact://<id>` resolution.\n",
14
15
  "blob-artifact-architecture.md": "# Blob and artifact storage architecture\n\nThis document describes how coding-agent stores large/binary payloads outside session JSONL, how truncated tool output is persisted, and how internal URLs (`artifact://`, `agent://`) resolve back to stored data.\n\n## Why two storage systems exist\n\nThe runtime uses two different persistence mechanisms for different data shapes:\n\n- **Content-addressed blobs** (`blob:sha256:<hash>`): global storage used to externalize large image base64 payloads and provider image data URLs from persisted session entries.\n- **Session-scoped artifacts** (files under `<sessionFile-without-.jsonl>/`): per-session text files used for full tool outputs and subagent outputs.\n\nThey are intentionally separate:\n\n- blob storage optimizes deduplication and stable references by content hash,\n- artifact storage optimizes append-only session tooling and human/tool retrieval by local IDs.\n\n## Storage boundaries and on-disk layout\n\n## Blob store boundary (global)\n\n`SessionManager` constructs `BlobStore(getBlobsDir())`, so blob files live in a shared global blob directory (not in a session folder).\n\nBlob file naming:\n\n- file path: `<blobsDir>/<sha256-hex>`\n- no extension\n- reference string stored in entries: `blob:sha256:<sha256-hex>`\n\nImplications:\n\n- same binary content across sessions resolves to the same hash/path,\n- writes are idempotent at the content level,\n- blobs can outlive any individual session file.\n\n## Artifact boundary (session-local)\n\n`ArtifactManager` derives artifact directory from session file path:\n\n- session file: `.../<timestamp>_<sessionId>.jsonl`\n- artifacts directory: `.../<timestamp>_<sessionId>/` (strip `.jsonl`)\n\nArtifact types share this directory:\n\n- truncated tool output files: `<numericId>.<toolType>.log` (for `artifact://`)\n- subagent output files: `<outputId>.md` (for `agent://`)\n\n## ID and name allocation schemes\n\n## Blob IDs: content hash\n\n`BlobStore.put()` computes SHA-256 over the bytes it is given and returns:\n\n- `hash`: hex digest,\n- `path`: `<blobsDir>/<hash>`,\n- `ref`: `blob:sha256:<hash>`.\n\nNo session-local counter is used.\n\n## Artifact IDs: session-local monotonic integer\n\n`ArtifactManager` scans existing `*.log` artifact files on first use to find max existing numeric ID and sets `nextId = max + 1`.\n\nAllocation behavior:\n\n- file format: `{id}.{toolType}.log`\n- IDs are sequential strings (`\"0\"`, `\"1\"`, ...)\n- resume does not overwrite existing artifacts because scan happens before allocation.\n\nIf artifact directory is missing, scanning yields empty list and allocation starts from `0`.\n\n## Agent output IDs (`agent://`)\n\n`AgentOutputManager` allocates IDs for subagent outputs as `<index>-<requestedId>` (optionally nested under parent prefix, e.g. `0-Parent.1-Child`). It scans existing `.md` files on initialization to continue from the next index on resume.\n\n## Persistence dataflow\n\n## 1) Session entry persistence rewrite path\n\nBefore session entries are written (`#rewriteFile` / incremental persist), `SessionManager` calls `prepareEntryForPersistence()` (via `truncateForPersistence`).\n\nKey behaviors:\n\n1. **Large string truncation**: oversized strings are cut and suffixed with `\"[Session persistence truncated large content]\"`; signature fields (`thinkingSignature`, `thoughtSignature`, `textSignature`) are cleared instead of truncated.\n2. **Transient field stripping**: `partialJson` and `jsonlEvents` are removed from persisted entries.\n3. **Image externalization to blobs**:\n - image blocks in `content` arrays are externalized when `data` is not already a blob ref and base64 length is at least threshold (`BLOB_EXTERNALIZE_THRESHOLD = 1024`),\n - provider-style `image_url` data URLs are externalized when they start with `data:image/` and contain `;base64,`,\n - image block `data` is stored as decoded binary bytes,\n - provider data URLs are stored as the original UTF-8 data URL string,\n - persisted values are replaced with `blob:sha256:<hash>`.\n\nThis keeps session JSONL compact while preserving recoverability.\n\n## 2) Session load rehydration path\n\nWhen opening a session (`setSessionFile`), after migrations, `SessionManager` runs `resolveBlobRefsInEntries()`.\n\nFor message/custom-message image blocks with `blob:sha256:<hash>` and for persisted provider `image_url` fields with blob refs:\n\n- reads blob bytes from blob store,\n- converts image-block bytes back to base64,\n- converts provider `image_url` blobs back to the original string,\n- mutates in-memory entry fields for runtime consumers.\n\nIf blob is missing:\n\n- `resolveImageData()` logs warning,\n- returns original ref string unchanged,\n- load continues (no hard crash).\n\n## 3) Tool output spill/truncation path\n\n`OutputSink` powers streaming output in bash/python/ssh and related executors.\n\nBehavior:\n\n1. Every chunk is sanitized and appended to in-memory tail buffer.\n2. When in-memory bytes exceed spill threshold (`DEFAULT_MAX_BYTES`, 50KB), sink marks output truncated.\n3. If an artifact path is available, sink opens a file writer and writes:\n - existing buffered content once,\n - all subsequent chunks.\n4. In-memory buffer is always trimmed to tail window for display.\n5. `dump()` returns summary including `artifactId` only when file sink was successfully created.\n\nPractical effect:\n\n- UI/tool return shows truncated tail,\n- full output is preserved in artifact file and referenced as `artifact://<id>`.\n\nIf file sink creation fails (I/O error, missing path, etc.), sink silently falls back to in-memory truncation only; full output is not persisted.\n\n## URL access model\n\n## `blob:` references\n\n`blob:sha256:<hash>` is a persistence reference inside session entry payloads, not an internal URL scheme handled by the router. Resolution is done by `SessionManager` during session load.\n\n## `artifact://<id>`\n\nHandled by `ArtifactProtocolHandler`:\n\n- requires active session artifact directory,\n- ID must be numeric,\n- resolves by matching filename prefix `<id>.`,\n- returns raw text (`text/plain`) from the matched `.log` file,\n- when missing, error includes list of available artifact IDs.\n\nMissing directory behavior:\n\n- if artifacts directory does not exist, throws `No artifacts directory found`.\n\n## `agent://<id>`\n\nHandled by `AgentProtocolHandler` over `<artifactsDir>/<id>.md`:\n\n- plain form returns markdown text,\n- `/path` or `?q=` forms perform JSON extraction,\n- path and query extraction cannot be combined,\n- if extraction requested, file content must parse as JSON.\n\nMissing directory behavior:\n\n- throws `No artifacts directory found`.\n\nMissing output behavior:\n\n- throws `Not found: <id>` with available IDs from existing `.md` files.\n\nRead tool integration:\n\n- `read` supports offset/limit pagination for non-extraction internal URL reads,\n- rejects `offset/limit` when `agent://` extraction is used.\n\n## Resume, fork, and move semantics\n\n## Resume\n\n- `ArtifactManager` scans existing `{id}.*.log` files on first allocation and continues numbering.\n- `AgentOutputManager` scans existing `.md` output IDs and continues numbering.\n- `SessionManager` rehydrates blob refs to base64 on load.\n\n## Fork\n\n`SessionManager.fork()` creates a new session file with new session ID and `parentSession` link, then returns old/new file paths. Artifact copying is handled by `AgentSession.fork()`:\n\n- attempts recursive copy of old artifact directory to new artifact directory,\n- missing old directory is tolerated,\n- non-ENOENT copy errors are logged as warnings and fork still completes.\n\nID implications after fork:\n\n- if copy succeeded, artifact counters in new session continue after max copied ID,\n- if copy failed/skipped, new session artifact IDs start from `0`.\n\nBlob implications after fork:\n\n- blobs are global and content-addressed, so no blob directory copy is required.\n\n## Move to new cwd\n\n`SessionManager.moveTo()` renames both session file and artifact directory to the new default session directory, with rollback logic if a later step fails. This preserves artifact identity while relocating session scope.\n\n## Failure handling and fallback paths\n\n| Case | Behavior |\n| -------------------------------------------------------- | --------------------------------------------------------------------- |\n| Blob file missing during rehydration | Warn and keep `blob:sha256:` ref string in-memory |\n| Blob read ENOENT via `BlobStore.get` | Returns `null` |\n| Artifact directory missing (`ArtifactManager.listFiles`) | Returns empty list (allocation can start fresh) |\n| Artifact directory missing (`artifact://` / `agent://`) | Throws explicit `No artifacts directory found` |\n| Artifact ID not found | Throws with available IDs listing |\n| OutputSink artifact writer init fails | Continues with tail-only truncation (no full-output artifact) |\n| No session file (some task paths) | Task tool falls back to temp artifacts directory for subagent outputs |\n\n## Binary blob externalization vs text-output artifacts\n\n- **Blob externalization** is for image payloads inside persisted session entry content and provider image data URLs; it replaces inline payload strings in JSONL with stable content refs.\n- **Artifacts** are plain text files for execution output and subagent output; they are addressable by session-local IDs through internal URLs.\n\nThe two systems intersect only indirectly (both reduce session JSONL bloat) but have different identity, lifetime, and retrieval paths.\n\n## Implementation files\n\n- [`src/session/blob-store.ts`](../packages/coding-agent/src/session/blob-store.ts) — blob reference format, hashing, put/get, externalize/resolve helpers.\n- [`src/session/artifacts.ts`](../packages/coding-agent/src/session/artifacts.ts) — session artifact directory model and numeric artifact ID/path allocation.\n- [`src/session/streaming-output.ts`](../packages/coding-agent/src/session/streaming-output.ts) — `OutputSink` truncation/spill-to-file behavior and summary metadata.\n- [`src/session/session-manager.ts`](../packages/coding-agent/src/session/session-manager.ts) — persistence transforms, blob rehydration on load, session fork/move interactions.\n- [`src/session/agent-session.ts`](../packages/coding-agent/src/session/agent-session.ts) — artifact directory copy during interactive fork.\n- [`src/internal-urls/artifact-protocol.ts`](../packages/coding-agent/src/internal-urls/artifact-protocol.ts) — `artifact://` resolver.\n- [`src/internal-urls/agent-protocol.ts`](../packages/coding-agent/src/internal-urls/agent-protocol.ts) — `agent://` resolver + JSON extraction.\n- [`src/sdk.ts`](../packages/coding-agent/src/sdk.ts) — internal URL router wiring and artifacts-dir resolver.\n- [`src/task/output-manager.ts`](../packages/coding-agent/src/task/output-manager.ts) — session-scoped agent output ID allocation for `agent://`.\n- [`src/task/executor.ts`](../packages/coding-agent/src/task/executor.ts) — subagent output artifact writes (`<id>.md`) and temp artifact directory fallback.\n",
@@ -85,7 +86,7 @@ export const EMBEDDED_DOCS: Readonly<Record<string, string>> = {
85
86
  "skc-dogfood-skill-template.md": "# SKC dogfood local skill template\n\nIssue #93 requested a gaebal-sayknow/operator dogfood skill. The live issue has no comment approving a fifth bundled default workflow skill, so this stays a local template instead of changing the default workflow surface. Operators can copy it into a user or project override when they want SKC-first session guidance.\n\nThe installable skill body is everything from the first frontmatter marker down; the frontmatter must be the **first line** of the installed file or the skill scan silently skips it (the scan requires a parsed `description`). Install into the user-level scan location (`~/.skc/agent/skills/`, not `~/.skc/skills/`):\n\n```sh\nmkdir -p ~/.skc/agent/skills/skc-dogfood\nsed -n '/^---$/,$p' docs/skc-dogfood-skill-template.md > ~/.skc/agent/skills/skc-dogfood/SKILL.md\n```\n\nFor a single project, install to `<project>/.skc/skills/skc-dogfood/SKILL.md` with the same extraction. Do not commit that project `.skc` copy unless the project explicitly wants a local override.\n\nFilesystem skill discovery is off by default, so enable it once. Set `skills.enabled`, then enable **only the scan that matches where you installed** — `enablePiUser` and `enablePiProject` default to `false` in `DEFAULT_SKILL_DISCOVERY_SETTINGS`, and enabling the project scan opts every future session into repo-local `.skc/skills` discovery, so do not enable it for a user-only install:\n\n```sh\nskc config set skills.enabled true\n\n# for the user-level install (~/.skc/agent/skills/):\nskc config set skills.enablePiUser true\n\n# OR, for the project-level install (<project>/.skc/skills/):\nskc config set skills.enablePiProject true\n```\n\nThen verify in a new session: `/skill:skc-dogfood` should autocomplete.\n\n---\nname: skc-dogfood\ndescription: Use when running or reviewing work through SKC sessions, dogfooding Sayknow-CLI, or migrating an operator workflow from OMX to SKC.\n---\n\n# SKC Dogfood Operator Workflow\n\nUse SKC first for coding, review, planning, and follow-up sessions. Treat OMX as a fallback only when SKC is unavailable, broken, or missing a required capability.\n\n## Locate and launch SKC\n\n- Installed CLI: run `command -v skc` and then launch with `skc --tmux`.\n- Repository checkout: from the sayknow-cli repo, prefer `bun packages/coding-agent/src/cli.ts --tmux` when testing source changes before install.\n- Worktree isolation: for branch-specific work, either let SKC create a managed sibling worktree with `skc --tmux --worktree <branch-like-name>` or `cd <existing-worktree-path>` and run `skc --tmux` there. Do not pass filesystem paths to `--worktree`.\n- Name sessions explicitly with the project and issue, for example `sayknow-cli-93-dogfood-skill`, so tmux panes, logs, and exports remain traceable.\n\n## Start the session\n\n- Put git operations inside the SKC session: fetch, branch/worktree setup, focused commits, pushes, and PR creation should be visible in-session.\n- Submit the initial prompt with the issue URL, target branch, acceptance criteria, verification limits, and any existing plan/spec link.\n- Verify the prompt was accepted: the TUI should show the user prompt, an active assistant turn, or a tool/action request. If the session silently idles, resend once with a shorter prompt and capture the failure.\n- Verify working state before leaving the session unattended: confirm the target cwd/worktree, branch, and issue scope are visible in the transcript or command output.\n\n## During work\n\n- Keep session names and branch names issue-scoped.\n- Prefer SKC workflow skills only when they fit: `deep-interview` for unclear requirements, `ralplan` for planning, `ultragoal` for durable ledgers, and `team` for coordinated tmux execution.\n- Keep evidence in the session: issue reads, focused tests/checks, screenshots only when visual behavior matters, and PR URLs.\n- When SKC is weaker than OMX, finish the urgent work with the smallest safe fallback and file a sayknow-cli follow-up issue with the missing capability, exact command/session context, expected behavior, and evidence.\n\n## Fallback policy\n\nUse OMX or another operator path only when:\n\n- `skc` cannot be located or launched after checking installed and repo-local commands;\n- authentication, model routing, tmux, or prompt submission is broken;\n- SKC lacks a required capability that OMX already has;\n- an urgent production/review deadline would be missed by debugging SKC first.\n\nRecord the fallback reason and create or link the sayknow-cli issue that would make SKC sufficient next time.\n\n## Evidence checklist\n\nReport:\n\n- project, issue, branch/worktree, and session name;\n- whether SKC was installed or repo-local;\n- prompt acceptance and working-state evidence;\n- git operations performed in-session;\n- focused verification commands and results;\n- PR/issue URLs;\n- follow-up sayknow-cli issues for any SKC gap or fallback.\n",
86
87
  "skc-plugins.md": "# SKC Plugin Bundles\n\nSKC supports two distinct plugin families. Do not confuse them:\n\n1. **Legacy marketplace / npm plugins** (`packages/coding-agent/src/extensibility/plugins`) — installed through the existing `skc plugin install <marketplace-ref|npm-spec>` marketplace/npm flows. Unchanged by this system.\n2. **SKC plugin bundles** — directories whose root contains a **`sayknow-plugin.json`** manifest (`kind: \"sayknow-cli-plugin\"`). These *extend* existing SKC capabilities and are the subject of this document.\n\nA SKC plugin bundle may only **extend** existing skills/agents — it can never register a new top-level skill, slash-command, command, or agent. SKC exposes exactly four default workflow skills (`deep-interview`, `ralplan`, `team`, `ultragoal`) and four role agents (`executor`, `architect`, `planner`, `critic`); bundles add sub-skills/appendices/tools/hooks/MCPs to those existing parents only.\n\n## Manifest (`sayknow-plugin.json`)\n\n```json\n{\n \"kind\": \"sayknow-cli-plugin\",\n \"name\": \"example-domain-bundle\",\n \"version\": \"1.0.0\",\n \"subskills\": [\"subskills/ralplan-design/SKILL.md\"],\n \"tools\": [\n { \"name\": \"domain_note\", \"path\": \"tools/domain-note.ts\", \"description\": \"...\" }\n ],\n \"hooks\": [\n { \"name\": \"audit-read\", \"event\": \"tool_call\", \"target\": \"read\", \"phase\": \"before\", \"path\": \"hooks/audit-read.ts\" }\n ],\n \"mcps\": [\n { \"name\": \"domain_docs\", \"transport\": \"stdio\", \"command\": \"bun\", \"args\": [\"mcp/domain-docs.ts\"], \"cwd\": \".\" }\n ],\n \"system_appendix\": [{ \"name\": \"domain-policy\", \"path\": \"prompts/system-appendix.md\" }],\n \"agent-appendix\": [{ \"agent\": \"executor\", \"name\": \"domain-executor\", \"path\": \"prompts/executor-appendix.md\" }]\n}\n```\n\n### Surfaces (the only allowed extension points)\n\n| Surface | Purpose | Additive rule |\n|---------|---------|---------------|\n| `subskills` | Inline sub-skills bound to an existing skill/agent (`binds_to`/`phase`/`activation_arg`) | Two-tier (see below) |\n| `tools` | Always-on custom tools (object entries) or legacy subskill-scoped string paths | Additive; manifest-declared name is authoritative, never overwrites an existing tool |\n| `hooks` | Constrained event hooks bound to a declared `event`/`target`/`phase` | Additive; run alongside built-ins, never replace |\n| `mcps` | MCP servers (`stdio`/`http`/`sse`) | Additive; server-name collisions are hard errors |\n| `system_appendix` | Lower-authority text appended to the default agent system prompt | Append-only, never overrides base |\n| `agent-appendix` | Lower-authority text appended to an existing role agent's prompt | Append-only per named agent |\n\n### Forbidden / unsupported keys\n\n- **Forbidden** (`forbidden_surface`): `skills`, `slash-commands`, `commands`, `agents` — bundles may not register new top-level definitions.\n- **Unsupported** (`unsupported_surface`): `mcp`, `mcpServers` (use the canonical `mcps`), and any unknown top-level key.\n\n## Installation\n\n```sh\nskc plugin install <path|git-url|tarball> --user # install into the user root\nskc plugin install <path|git-url|tarball> --project # install into the project root\n```\n\nExactly one of `--user` / `--project` is required for SKC plugin bundles (there is no default root). A source containing `sayknow-plugin.json` is classified as a SKC bundle and routed to the bundle installer **before** the marketplace/npm path; non-bundle sources fall through to the legacy flow.\n\nInstall is **compile-validate-then-copy**:\n\n1. The bundle is compiled and validated **without importing any plugin code** (manifest, frontmatter, and declared files are read as bytes only).\n2. Collision and MCP security policy are enforced (the durable registry is the collision authority — never capability \"first-wins\").\n3. Only the validated, hashed files are copied into a temp sibling, then atomically renamed into place; the registry entry is written last under a per-scope lock. Nothing is mutated on failure.\n\nIdempotency: re-installing identical content is a no-op; different content requires `--force`.\n\n## Security model\n\n- **Install validation never executes plugin code.** Tool/hook names are manifest-declared; at runtime the loaded factory must return/register exactly the declared name/event or the surface is quarantined (`runtime_mismatch`).\n- **MCP policy** (install + runtime connect): HTTPS-only for `http`/`sse`; private/loopback/link-local/unique-local/multicast and the `169.254.169.254` metadata endpoint are denied across IPv4, IPv6, IPv4-mapped/compatible, zone-id and trailing-dot forms; URL credentials and CRLF headers are rejected; DNS is re-resolved before connect (rebinding defence). `stdio` servers are confined to the plugin root (allowed launchers `node`/`bun` or a root-confined executable; required bundled script argument; no eval/loader flags; no env expansion).\n- **Hooks** run through a *constrained* API: only a handler for the declared event may be registered. `registerCommand`, `sendMessage`, `appendEntry`, renderer registration, and shell `exec` are denied (`security_policy`). The broad first-party hook API is never exposed to bundle hooks.\n- **Appendices** render as lower-authority, delimited `<skc-plugin-system-appendix>` / `<skc-plugin-agent-appendix>` blocks appended after the base/project prompt; size-capped (8 KiB/appendix, 32 KiB total) fail-closed; content is escaped and control-char sanitized. They can never override base/developer instructions.\n- **Hash drift**: installed files are re-verified against the registry at session start; any drift quarantines the plugin (`runtime_mismatch`).\n\n## Sub-skills: Tier-1 vs Tier-2\n\n- **Tier-1 advertisement** (metadata-only): when a parent skill/agent prompt is built, installed sub-skills bound to it are advertised as a bounded list (`plugin` / `name` / `description` / `activation_arg` / `phase`; max 12 items, 200-char descriptions, 4 KiB block, with an overflow note). No body content; rendered only in the target parent prompt, never the global public-workflow surface.\n- **Tier-2 activation** (full body): on explicit activation (e.g. `deep-interview --autoresearch`) or an agent's contextual choice, the full sub-skill body is injected as a `<skc-subskill>` block at the matching phase.\n\n## Registry, enablement, and quarantine\n\nEach scope keeps a durable `registry.json` recording per-plugin: name/version, source (`path`/`git`/`tarball` + ref/sha), manifest hash, copied files (relative path + sha256 — the uninstall ownership boundary), per-surface extension IDs, `enabled` flag, `disabledSurfaceIds`, and any `quarantine` entries.\n\nExtension IDs are stable: `tool:<name>`, `hook:<event>:<phase>:<target>:<name>`, `mcp:<name>`, `system-appendix:<plugin>:<name>`, `agent-appendix:<agent>:<plugin>:<name>`, `subskill:<parent>:<phase>:<activation_arg>`. Disabled is user-controlled (not an error); quarantine is fail-closed and visible.\n\n## Status / scope notes\n\n- Always-on **tools**, **system appendices**, **agent appendices**, and **Tier-1 advertisement** activate at session start (additive; no-op when no bundle is installed).\n- **MCP runtime connection** and the **live hook runner** integration are gated behind the same validated registry + policy; consult the ledger/run notes for their wiring status.\n- Full enable/disable/uninstall/upgrade UX is a planned follow-up; the registry already records everything required for it (per-surface IDs + copied-file ownership).\n",
87
88
  "skc-session-clawhip-routing.md": "# Clawhip-routed SKC sessions\n\nThis guide documents the visible tmux session pattern used by operator bots such as Clawhip, Hermes, and OpenClaw when repository work must stay observable in a routed channel.\n\nUse this pattern when a human or chatops router needs to watch the session, receive stale-session alerts, and send follow-up prompts into the same visible SKC pane.\n\nFor pure machine control, prefer the Coordinator MCP tools in [`docs/hermes-mcp-bridge.md`](./hermes-mcp-bridge.md). For a single embedded worker process, prefer [`docs/rpc.md`](./rpc.md). This visible-session pattern is the operator-facing fallback/interop lane.\n\n## Contract\n\n1. Create or verify a dedicated git worktree for the issue or PR.\n2. Register a named tmux session with the host router before launching SKC.\n3. Start interactive `skc` inside the worktree.\n4. Wait until the SKC TUI is ready.\n5. Inject the real task prompt separately.\n6. Verify acceptance from actual work evidence, not from a visible pasted prompt.\n\nDo not launch visible routed work in the canonical repo checkout. Use a worktree so branch changes, generated files, tests, and cleanup stay scoped to the task.\n\n## Session naming\n\nUse stable names that include the project and artifact id:\n\n```text\nsayknow-cli-issue-905-ctrl-shift-enter-newline\nsayknow-cli-pr-911-ctrl-shift-enter-review\nclawhip-issue-269-lightweight-zero-receipt\n```\n\nAvoid ambiguous names such as `fix-tui`, `review`, or `issue-905` when multiple repositories route into the same chat surface.\n\n## Portable script shape\n\nThe exact router command is host-owned. A Clawhip-style wrapper usually has three small scripts:\n\n```sh\n# create.sh\n# create/register a routed tmux session and start interactive skc in the worktree\nscripts/skc-session/create.sh <session-name> <worktree-path> [channel-id] [mention]\n\n# prompt.sh\n# inject the real task after the TUI is ready\nscripts/skc-session/prompt.sh <session-name> @/path/to/task.md\n\n# tail.sh\n# inspect bounded pane output before/after prompt delivery\nscripts/skc-session/tail.sh <session-name> [lines]\n```\n\nThis repository includes a portable implementation in `scripts/skc-session/`. It keeps private routing values outside the script body: channel ids and mentions are runtime arguments, the router binary is optional, and credentials are never embedded. Host deployments can still override router behavior with environment variables instead of editing the scripts.\n\n\n## Included helper scripts\n\nThe `scripts/skc-session/` directory contains the public version of the operator helpers:\n\n- `create.sh` validates a dedicated git worktree, starts interactive `skc` in tmux, preserves the pane after exit, prints and writes the session-specific durable state path, writes `metadata.json`, mirrors pane output to `pane.log`, records lifecycle events in `events.log`, bridges the inner `skc` process to a public-safe `runtime-state.json`, writes normal-exit `final.json`, and optionally registers a Clawhip-style `tmux watch`.\n- `prompt.sh` sends a text or `@file` prompt only after the pane looks like a ready SKC TUI; if the tmux session vanished, it refuses injection and prints the durable metadata/log/final/events recovery paths plus the last pane-log excerpt.\n- `tail.sh` captures bounded pane output for readiness and acceptance checks, with durable metadata, pane-log, event-log, and final-status fallback when tmux vanished.\n- `harness-tmux-owner-start.sh` starts the SKC harness control plane with the RuntimeOwner resident inside tmux for dogfood/debug cases that need visible owner liveness.\n\nConfiguration is runtime-only:\n\n```sh\nexport SKC_BIN=/path/to/skc # optional; defaults to command -v skc\nexport SKC_SESSION_FLAGS=\"--model provider/model\" # optional interactive skc flags\nexport SKC_SESSION_ROUTER=clawhip # optional router binary\nexport SKC_SESSION_SKIP_ROUTER=1 # skip router registration\nexport SKC_SESSION_STATE_DIR=/tmp/skc-session-state # optional durable metadata/log root\nexport SKC_SESSION_LOG_SEARCH_ROOT=$HOME/Workspace # optional tail/prompt fallback search root\nexport SKC_SESSION_STALE_MINUTES=60 # router stale window\nexport SKC_SESSION_KEYWORDS=\"/skill:ralplan,Question\"\n```\n\nNo token, channel id, mention, workspace root, or private host path is hard-coded. Pass channel/mention values at invocation time when your router needs them.\n\n## Example flow\n\n```sh\n# 1. Prepare a dedicated worktree.\ngit -C /repo/sayknow-cli fetch origin dev\ngit -C /repo/sayknow-cli worktree add \\\n /repo/worktrees/sayknow-cli-issue-905-ctrl-shift-enter-newline \\\n -b issue-905-ctrl-shift-enter-newline origin/dev\n\n# 2. Start the routed visible session.\n./scripts/skc-session/create.sh \\\n sayknow-cli-issue-905-ctrl-shift-enter-newline \\\n /repo/worktrees/sayknow-cli-issue-905-ctrl-shift-enter-newline \\\n \"$CHANNEL_ID\" \\\n \"$MENTION\"\n\n# 3. Confirm TUI readiness.\n./scripts/skc-session/tail.sh sayknow-cli-issue-905-ctrl-shift-enter-newline 80\n\n# 4. Inject the task prompt.\n./scripts/skc-session/prompt.sh \\\n sayknow-cli-issue-905-ctrl-shift-enter-newline \\\n @/tmp/issue-905-task.md\n\n# 5. Confirm real work started.\n./scripts/skc-session/tail.sh sayknow-cli-issue-905-ctrl-shift-enter-newline 160\n```\n\n## Prompt shape\n\nImplementation prompt:\n\n```text\n/skill:ralplan\n\nskc ultragoal fix issue #905 missed Ctrl+Shift+Enter newline case.\n\nRepo: jaybeyond/Sayknow_CLI\nWorktree: /repo/worktrees/sayknow-cli-issue-905-ctrl-shift-enter-newline\nBranch: issue-905-ctrl-shift-enter-newline\nBase: dev\n\nScope:\n- inspect parser/key matching and packages/tui/src/components/editor.ts\n- add explicit ctrl+shift+enter newline handling\n- add focused tests for the reported terminal sequences\n- run targeted verification\n- commit, push, and open a PR to dev\n\nNon-goals:\n- no unrelated tmux/session/process changes\n- no synchronous filesystem, process, tmux, network, or durable writes in keystroke paths\n```\n\nReview prompt:\n\n```text\n/skill:ralplan\n\nReview PR #911 as a red-team-only merge gate.\nInspect origin/dev...HEAD, changed files, CI, and contract risks.\nLook for blockers, regressions, test gaps, and hidden user-facing drift.\nPost MERGE_READY or REQUEST_CHANGES with evidence. Do not merge.\n```\n\n## Acceptance checks\n\nAfter prompt delivery, require one of these before reporting that the session is working:\n\n- a tool call or file read in the pane,\n- an explicit plan or todo update,\n- a diff or test command,\n- a GitHub comment/review/PR URL,\n- a terminal verdict such as `MERGE_READY` or `REQUEST_CHANGES`.\n\nA prompt being visible in tmux scrollback is not acceptance by itself. If tmux disappears before terminal verdict, inspect the state path printed by `create.sh`: `metadata.json` identifies the worktree/session and links `runtime-state.json`; `runtime-state.json` contains public-safe SKC lifecycle state (`completed` / `errored`, timestamps, cwd/workdir, branch, session file, exit code/signal/error when available) without pane logs, prompts, transcripts, tokens, config, environment dumps, or raw tool output; `pane.log` contains the private mirrored transcript; `events.log` records launch/exit milestones; `final.json` is present when the wrapper observed `skc` exit; and `vanished.json` is present when the external monitor observed the tmux session disappear. Use `tail.sh <session-name> [lines]` to surface these artifacts without a live tmux server.\n\n## Anti-patterns\n\n- Starting `skc -p` for long-running visible repo work.\n- Launching from the canonical repo checkout instead of a task worktree.\n- Running a long SKC/tmux session under a short shell timeout that can SIGKILL the owner process.\n- Treating tmux process existence as proof that the prompt was accepted.\n- Restarting a vanished session without first checking its durable metadata, pane log, event log, and final status.\n- Hard-coding private channel ids, bot mentions, or router tokens into public SKC docs.\n- Using this visible-session pattern when Coordinator MCP turn state is available and sufficient.\n",
88
- "standalone-mcp.md": "# Standalone SKC MCP support\n\nThis page answers the common user question: “Does normal `skc` inherit my Claude Code/Codex MCP servers, or can I configure MCP servers directly for the standalone TUI?”\n\n## Short answer\n\nNormal standalone SKC (`skc`, `skc --tmux`, and print-mode prompts) does **not** inherit MCP servers from Claude Code, Codex, Cursor, Gemini, Windsurf, or other tools as a public startup contract.\n\nStandalone SKC also has a narrow direct-registration command for explicit user-provided server definitions:\n\n```bash\nskc mcp add context7 npx -y @upstash/context7-mcp\nskc mcp add docs --type http --url https://example.test/mcp --header Authorization=\"Bearer $TOKEN\"\nskc mcp list\nskc mcp remove context7\n```\n\n`skc mcp add` writes only the definition supplied on that invocation to SKC's own MCP config (`~/.skc/agent/mcp.json` by default, or `./.skc/mcp.json` with `--project`). It does not read Claude Code, Codex, OpenCode, Cursor, Gemini, Windsurf, or other live configs. `skc mcp list` and `skc mcp remove` print redacted definitions so env/header/auth/OAuth credential values are not exposed in public output.\n\n## What is supported today\n\n| Need | Use | Notes |\n| --- | --- | --- |\n| External bot or multi-session controller wants to drive SKC | [Coordinator MCP](./hermes-mcp-bridge.md) via `skc mcp-serve coordinator` | SKC exposes an **outward** MCP server with SKC coordinator tools. This is not a way to import arbitrary MCP tools into the standalone TUI. |\n| Editor/ACP client owns MCP servers and wants SKC as the agent backend | [ACP mode](./external-control-readiness.md#acp-mode) via `skc --mode acp` or `skc acp` | The ACP client supplies and owns MCP servers. SKC keeps those client-owned MCP tools isolated from standalone on-disk discovery. |\n| Host application already manages MCP servers and policies | [RPC host tools](./rpc.md#host-tool-sub-protocol) via `skc --mode rpc` | Convert the selected MCP capabilities into host-owned RPC tools. The host executes the MCP call and returns `host_tool_result`. |\n| OpenClaw/Hermes-style host wants to map its own MCP/skills into SKC | [OpenClaw / Hermes RPC integration notes](./openclaw-hermes-rpc-integration.md) | Treat MCP as a host implementation detail and expose only policy-approved capabilities as RPC host tools. |\n| Codex / Claude Code want a one-step install to delegate planning/execution to SKC | [Canonical sayknow-cli plugin](./hermes-mcp-bridge.md) under `plugins/` via `skc setup claude` / `skc setup codex` | Installs the Coordinator MCP server plus `skc_delegate_plan/execute/team` commands. Fail-closed: workdir-scoped roots, mutations off until opt-in. Install with `codex plugin marketplace add ./plugins` (verified on Codex CLI 0.139.0) or `/plugin marketplace add ./plugins` for Claude Code. |\n\n## What standalone SKC does not do\n\nStandalone SKC does **not** currently promise any of these behaviors:\n\n- reading Claude Code's global MCP server list and automatically enabling it;\n- reading Codex MCP server config as an inherited runtime contract;\n- merging multiple tools' MCP configs into the normal TUI at startup;\n- making `.mcp.json`, `mcp.json`, `.codex/config.toml`, or other discovered files a stable public standalone-TUI config API;\n- exposing Coordinator MCP tools as ordinary in-session model tools.\n\nThis boundary is intentional: MCP servers often carry credentials, local filesystem reach, browser/session state, approval semantics, and tool names that belong to the host that configured them. Blind inheritance would mix policies between products and make it unclear which process owns credentials, approvals, sandboxing, and lifecycle.\n\n## Recommended workaround for a specific MCP server\n\nIf you need a context engine, internal search server, browser MCP, database MCP, or another custom MCP inside SKC:\n\n1. Keep the MCP server configured in the host that owns its credentials and policy.\n2. Start SKC through RPC (`skc --mode rpc`) from that host.\n3. Register a narrow host-owned tool with `set_host_tools` / `RpcClient#setCustomTools()`.\n4. Have the host tool call the real MCP server and return the result to SKC as `host_tool_result`.\n\nThat shape keeps the MCP server's auth, approvals, filesystem access, and process lifetime with the host while still letting the SKC model request the capability when needed.\n\nFor multi-session orchestration, prefer Coordinator MCP instead. Coordinator MCP lets an external controller start/register sessions, send turns, answer questions, read artifacts, and write durable status reports; it does not import arbitrary MCP servers into a standalone TUI session.\n\n## Related docs\n\n- [Coordinator MCP bridge](./hermes-mcp-bridge.md)\n- [External control surface readiness](./external-control-readiness.md)\n- [RPC Protocol Reference](./rpc.md)\n- [OpenClaw / Hermes RPC integration notes](./openclaw-hermes-rpc-integration.md)\n- [Clawhip-routed SKC sessions](./skc-session-clawhip-routing.md)\n",
89
+ "standalone-mcp.md": "# Standalone SKC MCP support\n\nThis page answers the common user question: “Does normal `skc` inherit my Claude Code/Codex MCP servers, or can I configure MCP servers directly for the standalone TUI?”\n\n## Short answer\n\nNormal standalone SKC (`skc`, `skc --tmux`, and print-mode prompts) does **not** inherit MCP servers from Claude Code, Codex, Cursor, Gemini, Windsurf, or other tools as a public startup contract.\n\nStandalone SKC also has a narrow direct-registration command for explicit user-provided server definitions:\n\n```bash\nskc mcp add context7 npx -y @upstash/context7-mcp\nskc mcp add docs --type http --url https://example.test/mcp --header Authorization=\"Bearer $TOKEN\"\nskc mcp list\nskc mcp remove context7\n```\n\n`skc mcp add` writes only the definition supplied on that invocation to SKC's own MCP config (`~/.skc/agent/mcp.json` by default, or `./.skc/mcp.json` with `--project`). It does not read Claude Code, Codex, OpenCode, Cursor, Gemini, Windsurf, or other live configs. `skc mcp list` and `skc mcp remove` print redacted definitions so env/header/auth/OAuth credential values are not exposed in public output. These registrations are storage-only today: normal standalone `skc`, `skc --tmux`, and print-mode sessions do not load them as runtime tools.\n\n## What is supported today\n\n| Need | Use | Notes |\n| --- | --- | --- |\n| External bot or multi-session controller wants to drive SKC | [Coordinator MCP](./hermes-mcp-bridge.md) via `skc mcp-serve coordinator` | SKC exposes an **outward** MCP server with SKC coordinator tools. This is not a way to import arbitrary MCP tools into the standalone TUI. |\n| Editor/ACP client owns MCP servers and wants SKC as the agent backend | [ACP mode](./external-control-readiness.md#acp-mode) via `skc --mode acp` or `skc acp` | The ACP client supplies and owns MCP servers. SKC keeps those client-owned MCP tools isolated from standalone on-disk discovery. |\n| Host application already manages MCP servers and policies | [RPC host tools](./rpc.md#host-tool-sub-protocol) via `skc --mode rpc` | Convert the selected MCP capabilities into host-owned RPC tools. The host executes the MCP call and returns `host_tool_result`. |\n| OpenClaw/Hermes-style host wants to map its own MCP/skills into SKC | [OpenClaw / Hermes RPC integration notes](./openclaw-hermes-rpc-integration.md) | Treat MCP as a host implementation detail and expose only policy-approved capabilities as RPC host tools. |\n| Codex / Claude Code want a one-step install to delegate planning/execution to SKC | [Canonical sayknow-cli plugin](./hermes-mcp-bridge.md) under `plugins/` via `skc setup claude` / `skc setup codex` | Installs the Coordinator MCP server plus `skc_delegate_plan/execute/team` commands. Fail-closed: workdir-scoped roots, mutations off until opt-in. Install with `codex plugin marketplace add ./plugins` (verified on Codex CLI 0.139.0) or `/plugin marketplace add ./plugins` for Claude Code. |\n\n## What standalone SKC does not do\n\nStandalone SKC does **not** currently promise any of these behaviors:\n\n- reading Claude Code's global MCP server list and automatically enabling it;\n- reading Codex MCP server config as an inherited runtime contract;\n- merging multiple tools' MCP configs into the normal TUI at startup;\n- making `.mcp.json`, `mcp.json`, `.codex/config.toml`, or other discovered files a stable public standalone-TUI config API;\n- exposing Coordinator MCP tools as ordinary in-session model tools.\n\nThis boundary is intentional: MCP servers often carry credentials, local filesystem reach, browser/session state, approval semantics, and tool names that belong to the host that configured them. Blind inheritance would mix policies between products and make it unclear which process owns credentials, approvals, sandboxing, and lifecycle.\n\n## Recommended workaround for a specific MCP server\n\nIf you need a context engine, internal search server, browser MCP, database MCP, or another custom MCP inside SKC:\n\n1. Keep the MCP server configured in the host that owns its credentials and policy.\n2. Start SKC through RPC (`skc --mode rpc`) from that host.\n3. Register a narrow host-owned tool with `set_host_tools` / `RpcClient#setCustomTools()`.\n4. Have the host tool call the real MCP server and return the result to SKC as `host_tool_result`.\n\nThat shape keeps the MCP server's auth, approvals, filesystem access, and process lifetime with the host while still letting the SKC model request the capability when needed.\n\nFor multi-session orchestration, prefer Coordinator MCP instead. Coordinator MCP lets an external controller start/register sessions, send turns, answer questions, read artifacts, and write durable status reports; it does not import arbitrary MCP servers into a standalone TUI session.\n\n## Related docs\n\n- [Coordinator MCP bridge](./hermes-mcp-bridge.md)\n- [External control surface readiness](./external-control-readiness.md)\n- [RPC Protocol Reference](./rpc.md)\n- [OpenClaw / Hermes RPC integration notes](./openclaw-hermes-rpc-integration.md)\n- [Clawhip-routed SKC sessions](./skc-session-clawhip-routing.md)\n",
89
90
  "telegram-onboarding.md": "# Telegram notification onboarding\n\nThis guide documents the current bundled Telegram notification setup path from\nSayknow-CLI source. It is for the managed reference client used by\n`skc notify setup`, not a separate remote-control product.\n\n## What you are setting up\n\nSayknow-CLI notifications are a loopback WebSocket SDK plus a managed Telegram\nreference daemon:\n\n- each SKC session publishes a local notification endpoint under\n `.skc/state/notifications/<sessionId>.json`;\n- the managed Telegram daemon scans those endpoints, connects to them, and sends\n action-needed events to the configured Telegram chat;\n- replies and inline button taps route back to the exact session/action through\n the same notification protocol. When the configured chat supports Telegram\n forum topics, each session is routed through its own topic.\n\nThe setup command stores global notification settings in your SKC agent config\nand later sessions auto-connect when notifications are enabled.\n\n## 1. Create a Telegram bot with BotFather\n\nUse Telegram's official BotFather flow to create a bot and copy its HTTP API\ntoken:\n\n- Official BotFather documentation: <https://core.telegram.org/bots/features#botfather>\n- General Telegram Bot API documentation: <https://core.telegram.org/bots/api>\n\nIn Telegram, open `@BotFather`, run `/newbot`, choose a display name and a unique\nusername ending in `bot`, then copy the token BotFather returns. Treat the token\nlike a password: do not paste it into logs, screenshots, issues, or shell history\nthat other people can read.\n\n## 2. Run the interactive setup wizard\n\nFrom any terminal where `skc` is installed:\n\n```sh\nskc notify setup\n```\n\nCurrent implementation path: `packages/coding-agent/src/cli/notify-cli.ts`.\n\nThe wizard does this:\n\n1. prompts for `Telegram BotFather token:`;\n2. validates the token with Telegram `getMe`;\n3. verifies private-chat Threaded Mode capability via `getMe.has_topics_enabled`\n and, when it is off in an interactive run, prints @BotFather guidance and\n lets you retry or continue unverified;\n4. asks you to message the bot from a private Telegram chat;\n5. polls Telegram `getUpdates` until it sees a private chat message;\n6. writes the paired chat id and enables notifications.\n\nThe setup pairing flow is private-chat only. If setup sees a `group`,\n`supergroup`, or `channel`, it rejects that chat and keeps waiting for a private\nDM. This is intentional for safe local discovery: group chats must not receive\nsession names, action ids, or pending status by accident.\n\nTelegram private-chat topics: the managed daemon's per-session delivery uses\nTelegram forum topics (`createForumTopic` + `message_thread_id`). Telegram now\nsupports forum topics in **private chats** when the bot owner enables **Threaded\nMode** for the bot in @BotFather. SKC cannot enable Threaded Mode through the Bot\nAPI; setup only detects the capability (`getMe.has_topics_enabled`) and guides the\nmanual BotFather toggle. A forum-enabled supergroup is no longer required.\n\nNote: enabling topics in private chats may require an additional Telegram Stars\npurchase fee, per Telegram's Terms of Service for Bot Developers.\n\nIf BotFather's **Bot Settings** menu does not show **Threads Settings** or\n**Threaded Mode**, do not treat that as a setup blocker. Telegram exposes this\ncapability unevenly across clients/accounts/bot states, and SKC cannot force the\nmenu to appear through the Bot API. The safe fallback is to continue setup with a\nprivate DM pairing: choose `skip` in the interactive prompt (or use\n`--token <botToken> --chat-id <chatId>` for non-interactive setup). SKC will save\n`threaded=unverified`/`threaded=unknown`, try topics at runtime when possible,\nand otherwise deliver flat to the paired private chat with outbound notifications\nand inline ask buttons only plus the one-time nudge shown below.\n\nSetup verification is capability verification, not a delivery guarantee: even when\nsetup reports `threaded=verified`, the first runtime `createForumTopic` for the\npaired chat can still fail if Telegram refuses it. When per-session topics are\nunavailable, the daemon does **not** drop notifications — it routes them to the\nnormal (flat) paired chat and posts a one-time nudge: `Flat Telegram private chat\nsupports outbound notifications and inline ask buttons only. Enable Threaded Mode\nin @BotFather > Bot Settings > Threads Settings for free-text replies and session\ncommands.` Because pairing is private-only, flat delivery lands in your own\nprivate DM with the bot.\n\nThe final setup line reports a `threaded=` status:\n\n- `threaded=verified`: the bot has Threaded Mode capability (`has_topics_enabled`\n was true during setup);\n- `threaded=unverified`: Threaded Mode was off and you skipped, or setup ran\n non-interactively; setup is saved, topics are attempted when available, and\n runtime delivery falls back to the paired flat private chat with outbound\n notifications and inline ask buttons only when Telegram refuses topic creation;\n- `threaded=unknown`: the Telegram response did not include `has_topics_enabled`,\n so capability could not be verified.\n\nAfter setup succeeds, it prints a masked token and the paired chat id:\n\n```text\nNotifications enabled. botToken=1234…(len N) chatId=123456789 threaded=verified\n```\n\nThe raw token is never printed by SKC status/setup output after it is stored.\n\n## 3. Non-interactive setup\n\nFor scripts or CI-style local provisioning, pass the bot token and known private\nchat id explicitly. Non-interactive runs cannot prompt for the BotFather toggle,\nso if Threaded Mode is off (or the capability is unknown) setup is still saved\nwith a warning and a `threaded=unverified`/`threaded=unknown` status:\n\n```sh\nskc notify setup --token <botToken> --chat-id <chatId>\n```\n\nOptional redaction can be enabled during setup:\n\n```sh\nskc notify setup --token <botToken> --chat-id <chatId> --redact\n```\n\n`--redact` sets `notifications.redact = true`. Under redaction, idle summaries\nand streamed content are suppressed before remote delivery, but ask questions and\noptions remain readable because they must be answerable remotely.\n\n## 4. Check status without leaking secrets\n\n```sh\nskc notify status\n```\n\nThe status command reads the typed notification settings and prints:\n\n- `enabled`\n- masked `botToken`\n- paired `chatId`\n- `redact`\n\nIt uses the same masking helper as setup (`first 4 chars + … + length`), so it is\nsafe to paste into a support thread if the chat id itself is not sensitive in\nyour environment.\n\n## 5. What setup writes\n\n`skc notify setup` writes these settings through the SKC Settings layer:\n\n- `notifications.enabled = true`\n- `notifications.telegram.botToken = <token>`\n- `notifications.telegram.chatId = <paired chat id>`\n- `notifications.redact = true` only when `--redact` was passed\n\nAt runtime, notifications are considered globally configured only when all of\nthese are present:\n\n- `notifications.enabled`\n- `notifications.telegram.botToken`\n- `notifications.telegram.chatId`\n\nEnvironment/session precedence from `packages/coding-agent/src/notifications/config.ts`:\n\n1. `SKC_NOTIFICATIONS=0` is a hard opt-out.\n2. Local `/notify off` disables only the current session.\n3. `SKC_NOTIFICATIONS=1` or `SKC_NOTIFICATIONS_TOKEN` enables the legacy explicit path.\n4. A complete global setup enables notifications automatically.\n5. Otherwise notifications stay off.\n\n## 6. Start or reuse sessions\n\nAfter setup, start SKC normally:\n\n```sh\nskc --tmux\n```\n\nor use any other supported SKC launch mode. When the notification extension is\nregistered, the session writes its endpoint discovery file and ensures the\nTelegram daemon is running.\n\nThe daemon is a singleton per bot token/chat pair. Telegram allows only one\nactive `getUpdates` long-poll owner for a bot token, so SKC keeps a local daemon\nlock/state file and makes later sessions attach to the fresh owner instead of\nstarting a second poller. This avoids Telegram `409 Conflict` failures.\n\n## 7. Use the Telegram chat\n\nThe managed daemon prefers Telegram forum-topic delivery for per-session routing\nin the paired private chat. When Threaded Mode is available for the bot (verified\nduring setup via `getMe.has_topics_enabled`), the daemon calls\n`createForumTopic`/`editForumTopic` and sends messages with `message_thread_id`\nagainst the paired `notifications.telegram.chatId`. If BotFather does not show\n**Threads Settings**/**Threaded Mode**, or if Telegram refuses topic creation even\nafter setup reported `threaded=verified`, the daemon routes notifications to the\nnormal (flat) paired private chat and posts a one-time nudge to enable Threaded\nMode rather than dropping them.\nFlat private chat is notification-only plus inline ask buttons. It is not a\nfree-text chat surface: replies typed as normal messages and session commands such\nas `/verbose`, `/lean`, `/verbosity`, and `/redact` require Threaded Mode/topic\nrouting.\n\nFlat private-chat fallback preserves outbound notifications and inline-button\nanswers, but it cannot provide a separate Telegram topic per SKC session. Free-\ntext replies and in-topic config commands depend on topic routing, so enable\nThreaded Mode in @BotFather > Bot Settings > Threads Settings when you need\nmulti-session reply separation or session commands from Telegram. Do not\npair a group, supergroup, or channel as a substitute: setup intentionally accepts\nonly a private DM, and hand-edited non-private chat ids remain fail-closed to\navoid leaking session data. If you specifically want group topics, create a\nforum-enabled Telegram group and use a separate/custom notification integration;\nthe bundled `skc notify setup` onboarding path is private-chat only.\n\nThe managed daemon can render:\n\n- session identity headers;\n- context updates;\n- live/finalized assistant output;\n- image attachments;\n- ask prompts with inline buttons;\n- activity/typing indicators;\n- inbound delivery acknowledgements.\n\nReply paths:\n\n- tap an inline button on an ask notification;\n- reply in the session topic with free text when forum-topic routing is\n available;\n- send in-topic config commands:\n - `/verbose`\n - `/lean`\n - `/verbosity <lean|verbose>`\n - `/redact <on|off>`\n- send paired-chat lifecycle commands from the Telegram command menu or by typing:\n - `/session_create path <dir>`\n - `/session_create worktree <repo> <branch>`\n - `/session_create dir <newdir>`\n - `/session_recent [create|resume]`\n - `/session_close <sessionId>`\n - `/session_resume <sessionId|prefix>`\n\nThe removed legacy `/answer <session-tag> <answer>` flow is not the primary UX;\nTelegram topic routing identifies the target session when the configured chat\nsupports it.\n\n## 8. Local `/notify` inside a session\n\nInside a running SKC session:\n\n- `/notify status` reports current session notification status without secrets;\n- `/notify off` disables the current session endpoint and removes its discovery\n record without changing global setup;\n- `/notify on` re-enables the current session when global setup is complete and\n `SKC_NOTIFICATIONS=0` is not forcing opt-out.\n\n## 9. Debug-only manual bridge\n\nThe manual Telegram CLI remains a reference/debug tool:\n\n```sh\nbun run packages/coding-agent/src/notifications/telegram-cli.ts --bot-token \"$BOT_TOKEN\"\n```\n\nIf a fresh managed daemon already owns the same bot token and paired chat, the\nmanual CLI refuses to start by default because a second poller would cause\nTelegram `409 Conflict`. Use `--force` only for deliberate debugging after you\nunderstand which daemon owns polling.\n\n## Troubleshooting\n\n### `Telegram getMe failed`\n\nThe BotFather token is invalid or was revoked. Re-copy the token from BotFather\nor regenerate it in the official BotFather UI.\n\n### Setup times out waiting for a private chat\n\nSend any message directly to the bot from your Telegram user account. Do not add\nit to a group for pairing; groups/supergroups/channels are intentionally rejected\nby the current setup flow.\n\n### Setup succeeds but no Telegram session messages arrive\n\nCheck the `threaded=` status from the last `skc notify setup` run. If it is\n`threaded=unverified` or `threaded=unknown`, first try the current Telegram\nclient's @BotFather flow for this bot. If BotFather's **Bot Settings** menu lacks\n**Threads Settings**/**Threaded Mode**, continue with the saved private-chat\npairing; this is supported. SKC cannot enable Threaded Mode through the Bot API,\nand no paid/Stars option is required just to receive flat private-chat\nnotifications. When `createForumTopic` is refused for the paired chat, the daemon\nfalls back to flat delivery in the paired private chat and posts a one-time nudge\nthat points to @BotFather > Bot Settings > Threads Settings. Flat fallback is\nlimited to outbound notifications and inline ask buttons; free-text replies and\nsession commands require Threaded Mode/topic routing.\n\n### Telegram 409 conflict\n\nOnly one `getUpdates` poller can own a bot token. Stop any old manual bridge or\nexternal bot process using the same token, then let SKC's managed daemon own it.\n\n### A session does not send notifications\n\nCheck, in order:\n\n1. `skc notify status`\n2. `SKC_NOTIFICATIONS` is not set to `0`\n3. the session has not run `/notify off`\n4. the repo has `.skc/state/notifications/<sessionId>.json`\n5. the managed daemon state is fresh under the SKC agent notifications directory\n\nDo not paste endpoint discovery files into public issues; they contain the\nper-session WebSocket token needed by clients.\n",
90
91
  "telegram-remote.md": "# Telegram Remote — control skc sessions from your phone\n\nTelegram Remote is a **tiny, safe operator remote** for Sayknow-CLI (`skc`)\nsessions. It lets you list, observe, start, and stop sessions from a Telegram\nchat — a control button, not a remote shell or cockpit. The real session owner\nstays on your machine (skc/tmux); Telegram only issues bounded, allowlisted\ncommands over the Coordinator MCP.\n\nThe gateway implementation lives in\n[`packages/telegram-remote`](../packages/telegram-remote/README.md); this guide\ncovers how to turn it on and use it.\n\n## What you get\n\nTwo backends, selected by `telegram.backend`:\n\n- **`coordinator`** (default) — multi-session lifecycle + observation. Bot\n commands: `/sessions`, `/observe <id>`, `/start-session <preset> [task]`,\n `/stop <id>`, `/help`.\n- **`rpc`** — attach/detach keyboard for one persistent `skc launch --output rpc`\n session. Bot commands: `/attach`, `/detach`, `/status`, `/abort`, `/help`.\n\nAnything outside this vocabulary is rejected as unknown.\n\n## Quick start (skc settings)\n\n1. **Create a bot.** Message [@BotFather](https://t.me/BotFather) → `/newbot`,\n copy the token (`123456:AA...`).\n2. **Find your Telegram id.** Message [@userinfobot](https://t.me/userinfobot)\n (or read it from your bot's `getUpdates`). You need your numeric user id\n and/or chat id.\n3. **Configure skc.** Open `skc`, go to **Settings → Integrations**, and set:\n - **Telegram Remote** (`telegram.enabled`) → on\n - **Bot Token** (`telegram.botToken`) → the @BotFather token\n - **Allowed User IDs** (`telegram.allowedUserIds`) → your id\n (comma-separated; or **Allowed Chat IDs**). At least one allowlist is\n required — unlisted senders are refused with no hints.\n - **Session Presets** (`telegram.presets`) → JSON array of approved presets\n (see below) if you want `/start-session`.\n\n Settings persist to your skc config; you can also edit them directly in\n `config.yml` under the `telegram.*` keys.\n\n4. **Start the gateway.**\n\n ```sh\n skc telegram start # start with current settings\n skc telegram status # show whether it is configured / running\n skc telegram env # print the SKC_TELEGRAM_REMOTE_* env it would use\n ```\n\n When `telegram.enabled` is on, skc also **auto-starts** the gateway in the\n background (PID-tracked, detached) the next time you launch an interactive\n session, so `skc telegram start` is only needed for a manual/one-off start.\n\n5. **Use it from Telegram.** Send `/help` to your bot, then `/sessions`,\n `/observe <id>`, `/start-session <preset>`, `/stop <id>` (coordinator mode).\n\n### Presets (`/start-session`)\n\nSession creation is **preset-only** — no workdir/command/branch ever comes from\nchat. A preset binds a fixed workdir + session command + an optional task\ntemplate with a single length-capped `{{task}}` slot:\n\n```json\n[\n {\n \"id\": \"proj\",\n \"workdir\": \"/home/you/src/project\",\n \"sessionCommand\": \"skc --worktree\",\n \"taskTemplate\": \"Use /skill:ralplan to plan: {{task}}\",\n \"taskMaxLen\": 2000\n }\n]\n```\n\n`/start-session proj fix the flaky auth test` starts the `proj` preset with the\ntask substituted into the template.\n\n## RPC mode (one persistent session)\n\nSet **Backend** (`telegram.backend`) → `rpc` to attach to a single existing\nowner-only socket exposed by `skc launch --output rpc --listen <socket>`. The\ngateway never spawns, kills, or tears down that session — it is only a Telegram\nattach/detach remote keyboard. RPC mode requires **RPC Socket**\n(`telegram.rpcSocket`) and **State Directory** (`telegram.stateDir`) for\nreconnect/resync. Agent questions and gates render as inline buttons;\nturn-complete delivery sends the final assistant text (HTML-escaped, chunked to\nTelegram's 4096-byte limit).\n\n## Safety properties\n\n- **Default deny.** Only allowlisted Telegram user/chat ids may issue any\n command; unlisted senders get an identical boring refusal.\n- **Preset-only creation.** No raw workdir/command/branch/shell/RPC from chat.\n- **Forced-minimal mutations.** The coordinator runs with the smallest mutation\n set — `sessions` (read + start), plus `reports` only when `/stop` is enabled\n (**Enable /stop**, `telegram.enableStop`). `questions` is never enabled.\n- **Redaction by construction.** Only a typed projection (session id, derived\n name, bounded status/turn enums, branch, timestamps, short sanitized blocker)\n ever leaves the machine. Raw tmux tail, transcripts, tool IO, diffs, file\n contents, env, prompts, and tokens are never transmitted.\n- **`/stop` confirmation.** `/stop <id>` arms; a second `/stop <id> confirm` (or\n the inline **Confirm stop** button) records a graceful coordinator\n `cancelled`. It does not kill a tmux process.\n\n## Rich messaging & push (optional)\n\n- **Rich Messages** (`telegram.enableRich`, default on) — HTML formatting +\n inline **Observe/Stop/Refresh** buttons. Set off for plain text.\n- **Register Bot Menu** (`telegram.registerCommands`, default on) — registers\n the Bot command menu at startup.\n- **Push Notifications** (`telegram.enablePush`) — Follow/Mute subscriptions via\n the coordinator event-watch surface (needs a state dir). Push never widens the\n transmitted-data allowlist.\n\n## Settings ↔ environment\n\nThe `skc telegram` command and autostart translate `telegram.*` settings into\n`SKC_TELEGRAM_REMOTE_*` environment variables consumed by the gateway (see\n`skc telegram env`). You can also run the gateway standalone with those env vars\ndirectly — see [`packages/telegram-remote/README.md`](../packages/telegram-remote/README.md)\nfor the full variable list, `.env.example`, and turnkey **systemd**/**launchd**\nservice examples for always-on deployment.\n\n## Non-goals\n\nTelegram Remote is not a remote RPC cockpit, remote shell, config editor, or\ntranscript viewer. It is a bounded lifecycle + observation button. For richer\ncontrol, use skc directly on the host.\n",
91
92
  "theme.md": "# Theming Reference\n\nThis document describes how theming works in the coding-agent today: schema, loading, runtime behavior, and failure modes.\n\n## What the theme system controls\n\nThe theme system drives:\n\n- foreground/background color tokens used across the TUI\n- markdown styling adapters (`getMarkdownTheme()`)\n- selector/editor/settings list adapters (`getSelectListTheme()`, `getEditorTheme()`, `getSettingsListTheme()`)\n- symbol preset + symbol overrides (`unicode`, `nerd`, `ascii`)\n- syntax highlighting colors used by native highlighter (`@sayknow-cli/natives`)\n- status line segment colors\n\nPrimary implementation: `src/modes/theme/theme.ts`.\n\n## Theme JSON shape\n\nTheme files are JSON objects validated against the runtime schema in `theme.ts` (`ThemeJsonSchema`) and mirrored by `src/modes/theme/theme-schema.json`.\n\nTop-level fields:\n\n- `name` (required)\n- `colors` (required; all color tokens required)\n- `vars` (optional; reusable color variables)\n- `export` (optional; HTML export colors)\n- `symbols` (optional)\n - `preset` (optional: `unicode | nerd | ascii`)\n - `overrides` (optional: key/value overrides for `SymbolKey`)\n\nColor values accept:\n\n- hex string (`\"#RRGGBB\"`)\n- 256-color index (`0..255`)\n- variable reference string (resolved through `vars`)\n- empty string (`\"\"`) meaning terminal default (`\\x1b[39m` fg, `\\x1b[49m` bg)\n\n## Required color tokens (current)\n\nAll tokens below are required in `colors`.\n\n### Core text and borders (11)\n\n`accent`, `border`, `borderAccent`, `borderMuted`, `success`, `error`, `warning`, `muted`, `dim`, `text`, `thinkingText`\n\n### Background blocks (7)\n\n`selectedBg`, `userMessageBg`, `customMessageBg`, `toolPendingBg`, `toolSuccessBg`, `toolErrorBg`, `statusLineBg`\n\n### Message/tool text (5)\n\n`userMessageText`, `customMessageText`, `customMessageLabel`, `toolTitle`, `toolOutput`\n\n### Markdown (10)\n\n`mdHeading`, `mdLink`, `mdLinkUrl`, `mdCode`, `mdCodeBlock`, `mdCodeBlockBorder`, `mdQuote`, `mdQuoteBorder`, `mdHr`, `mdListBullet`\n\n### Tool diff + syntax highlighting (12)\n\n`toolDiffAdded`, `toolDiffRemoved`, `toolDiffContext`,\n`syntaxComment`, `syntaxKeyword`, `syntaxFunction`, `syntaxVariable`, `syntaxString`, `syntaxNumber`, `syntaxType`, `syntaxOperator`, `syntaxPunctuation`\n\n### Mode/thinking borders (8)\n\n`thinkingOff`, `thinkingMinimal`, `thinkingLow`, `thinkingMedium`, `thinkingHigh`, `thinkingXhigh`, `bashMode`, `pythonMode`\n\n### Status line segment colors (14)\n\n`statusLineSep`, `statusLineModel`, `statusLinePath`, `statusLineGitClean`, `statusLineGitDirty`, `statusLineContext`, `statusLineSpend`, `statusLineStaged`, `statusLineDirty`, `statusLineUntracked`, `statusLineOutput`, `statusLineCost`, `statusLineSubagents`\n\n## Optional tokens\n\n### `export` section (optional)\n\nUsed for HTML export theming helpers:\n\n- `export.pageBg`\n- `export.cardBg`\n- `export.infoBg`\n\nIf omitted, export code derives defaults from resolved theme colors.\n\n### `symbols` section (optional)\n\n- `symbols.preset` sets a theme-level default symbol set.\n- `symbols.overrides` can override individual `SymbolKey` values.\n\nRuntime precedence:\n\n1. settings `symbolPreset` override (if set)\n2. theme JSON `symbols.preset`\n3. fallback `\"unicode\"`\n\nInvalid override keys are ignored and logged (`logger.debug`).\n\n## Built-in vs custom theme sources\n\nTheme lookup order (`loadThemeJson`):\n\n1. built-in embedded themes (`red-octopus.json`, `blue-octopus.json`, `claude-code.json`, `codex.json`, and `opencode.json` compiled into `defaultThemes`)\n2. custom theme file: `<customThemesDir>/<name>.json`\n\nCustom themes directory comes from `getCustomThemesDir()`:\n\n- default: `~/.skc/agent/themes`\n- overridden by `SKC_CODING_AGENT_DIR` (`$SKC_CODING_AGENT_DIR/themes`)\n\n`getAvailableThemes()` returns merged built-in + custom names, sorted, with built-ins taking precedence on name collision.\n\n## Loading, validation, and resolution\n\nFor custom theme files:\n\n1. read JSON\n2. parse JSON\n3. validate against `ThemeJsonSchema`\n4. resolve `vars` references recursively\n5. convert resolved values to ANSI by terminal capability mode\n\nValidation behavior:\n\n- missing required color tokens: explicit grouped error message\n- bad token types/values: validation errors with JSON path\n- unknown theme file: `Theme not found: <name>`\n\nVar reference behavior:\n\n- supports nested references\n- throws on missing variable reference\n- throws on circular references\n\n## Terminal color mode behavior\n\nColor mode detection (`detectColorMode`):\n\n- `COLORTERM=truecolor|24bit` => truecolor\n- `WT_SESSION` => truecolor\n- `TERM` in `dumb`, `linux`, or empty => 256color\n- otherwise => truecolor\n\nConversion behavior:\n\n- hex -> `Bun.color(..., \"ansi-16m\" | \"ansi-256\")`\n- numeric -> `38;5` / `48;5` ANSI\n- `\"\"` -> default fg/bg reset\n\n## Runtime switching behavior\n\n### Initial theme (`initTheme`)\n\n`main.ts` initializes theme with settings:\n\n- `symbolPreset`\n- `colorBlindMode`\n- `theme.dark`\n- `theme.light`\n\nAuto theme slot selection uses terminal appearance in this order:\n\n1. terminal-reported OSC 11 background luminance, unless the macOS/Zellij fallback path is active\n2. `COLORFGBG` background index (`< 8` => dark, `>= 8` => light)\n3. macOS appearance fallback only for the known-broken macOS/Zellij OSC 11 path\n4. dark slot fallback\n\nBuilt-in theme note: `blue-octopus` is the default SKC theme for both the dark and light slots, and `red-octopus` is a bundled warm, high-contrast alternate. Both are cephalopod brand themes with separate semantic error/warning/diff-removal tokens and octopus-oriented symbol overrides. Three additional bundled migration themes — `claude-code`, `codex`, and `opencode` — mirror the look of those tools for easy eye-migration. All three are dark-classified and recommended for `theme.dark`, but are selectable in either slot; they keep SKC's default symbol identity (no crab-symbol overrides).\n\nCurrent defaults from settings schema:\n\n- `theme.dark = \"blue-octopus\"`\n- `theme.light = \"blue-octopus\"`\n- `symbolPreset = \"unicode\"`\n- `colorBlindMode = false`\n\n### Explicit switching (`setTheme`)\n\n- loads selected theme\n- updates global `theme` singleton\n- optionally starts watcher\n- triggers `onThemeChange` callback\n\nOn failure:\n\n- falls back to built-in `dark`\n- returns `{ success: false, error }`\n\n### Preview switching (`previewTheme`)\n\n- applies temporary preview theme to global `theme`\n- does **not** change persisted settings by itself\n- returns success/error without fallback replacement\n\nThe settings theme picker is confirm-only; arrow-key browsing does not call `previewTheme`, so the rendered theme and displayed/persisted theme name stay aligned until Enter confirms a new selection.\n\n## Watchers and live reload\n\nWhen watcher is enabled (`setTheme(..., true)` / interactive init):\n\n- watches `<customThemesDir>/<currentTheme>.json` only when that file exists\n- built-ins are effectively not watched; built-in theme lookup also takes precedence over same-name custom files\n- matching file changes schedule a debounced reload; reload errors or temporary file absence keep the last successfully loaded theme\n- the watcher does not perform a delete/rename fallback; it waits for a future successful reload or explicit theme switch\n\nAuto mode also reevaluates dark/light slot mapping from terminal appearance changes, `SIGWINCH`, and the macOS fallback observer when active.\n\n## Color-blind mode behavior\n\n`colorBlindMode` changes only one token at runtime:\n\n- `toolDiffAdded` is HSV-adjusted (green shifted toward blue)\n- adjustment is applied only when resolved value is a hex string\n\nOther tokens are unchanged.\n\n## Where theme settings are persisted\n\nTheme-related settings are persisted by `Settings` to global config YAML:\n\n- path: `<agentDir>/config.yml`\n- default agent dir: `~/.skc/agent`\n- effective default file: `~/.skc/agent/config.yml`\n\nPersisted keys:\n\n- `theme.dark`\n- `theme.light`\n- `symbolPreset`\n- `colorBlindMode`\n\nLegacy migration exists: old flat `theme: \"name\"` is migrated to nested `theme.dark` or `theme.light` based on luminance detection; legacy built-in names `dark`/`light` map to `red-octopus`/`blue-octopus` unless matching custom theme files exist.\n\n## Creating a custom theme (practical)\n\n1. Create file in custom themes dir, e.g. `~/.skc/agent/themes/my-theme.json`.\n2. Include `name`, optional `vars`, and **all required** `colors` tokens.\n3. Optionally include `symbols` and `export`.\n4. Select the theme in Settings (`Display -> Dark theme` or `Display -> Light theme`) depending on which auto slot you want. All bundled themes are selectable: the crustacean defaults `red-octopus` and `blue-octopus`, plus the migration themes `claude-code`, `codex`, and `opencode` (dark-classified, recommended for the dark slot but selectable in either).\n\nMinimal skeleton:\n\n```json\n{\n \"name\": \"my-theme\",\n \"vars\": {\n \"accent\": \"#7aa2f7\",\n \"muted\": 244\n },\n \"colors\": {\n \"accent\": \"accent\",\n \"border\": \"#4c566a\",\n \"borderAccent\": \"accent\",\n \"borderMuted\": \"muted\",\n \"success\": \"#9ece6a\",\n \"error\": \"#f7768e\",\n \"warning\": \"#e0af68\",\n \"muted\": \"muted\",\n \"dim\": 240,\n \"text\": \"\",\n \"thinkingText\": \"muted\",\n\n \"selectedBg\": \"#2a2f45\",\n \"userMessageBg\": \"#1f2335\",\n \"userMessageText\": \"\",\n \"customMessageBg\": \"#24283b\",\n \"customMessageText\": \"\",\n \"customMessageLabel\": \"accent\",\n \"toolPendingBg\": \"#1f2335\",\n \"toolSuccessBg\": \"#1f2d2a\",\n \"toolErrorBg\": \"#2d1f2a\",\n \"toolTitle\": \"\",\n \"toolOutput\": \"muted\",\n\n \"mdHeading\": \"accent\",\n \"mdLink\": \"accent\",\n \"mdLinkUrl\": \"muted\",\n \"mdCode\": \"#c0caf5\",\n \"mdCodeBlock\": \"#c0caf5\",\n \"mdCodeBlockBorder\": \"muted\",\n \"mdQuote\": \"muted\",\n \"mdQuoteBorder\": \"muted\",\n \"mdHr\": \"muted\",\n \"mdListBullet\": \"accent\",\n\n \"toolDiffAdded\": \"#9ece6a\",\n \"toolDiffRemoved\": \"#f7768e\",\n \"toolDiffContext\": \"muted\",\n\n \"syntaxComment\": \"#565f89\",\n \"syntaxKeyword\": \"#bb9af7\",\n \"syntaxFunction\": \"#7aa2f7\",\n \"syntaxVariable\": \"#c0caf5\",\n \"syntaxString\": \"#9ece6a\",\n \"syntaxNumber\": \"#ff9e64\",\n \"syntaxType\": \"#2ac3de\",\n \"syntaxOperator\": \"#89ddff\",\n \"syntaxPunctuation\": \"#9aa5ce\",\n\n \"thinkingOff\": 240,\n \"thinkingMinimal\": 244,\n \"thinkingLow\": \"#7aa2f7\",\n \"thinkingMedium\": \"#2ac3de\",\n \"thinkingHigh\": \"#bb9af7\",\n \"thinkingXhigh\": \"#f7768e\",\n\n \"bashMode\": \"#2ac3de\",\n \"pythonMode\": \"#bb9af7\",\n\n \"statusLineBg\": \"#16161e\",\n \"statusLineSep\": 240,\n \"statusLineModel\": \"#bb9af7\",\n \"statusLinePath\": \"#7aa2f7\",\n \"statusLineGitClean\": \"#9ece6a\",\n \"statusLineGitDirty\": \"#e0af68\",\n \"statusLineContext\": \"#2ac3de\",\n \"statusLineSpend\": \"#7dcfff\",\n \"statusLineStaged\": \"#9ece6a\",\n \"statusLineDirty\": \"#e0af68\",\n \"statusLineUntracked\": \"#f7768e\",\n \"statusLineOutput\": \"#c0caf5\",\n \"statusLineCost\": \"#ff9e64\",\n \"statusLineSubagents\": \"#bb9af7\"\n }\n}\n```\n\n## Testing custom themes\n\nUse this workflow:\n\n1. Start interactive mode (watcher enabled from startup).\n2. Open settings and confirm the custom theme in the dark/light theme picker; arrow-key browsing is intentionally non-mutating.\n3. For custom theme files, edit the JSON while running and confirm auto-reload on save.\n4. Exercise critical surfaces:\n - markdown rendering\n - tool blocks (pending/success/error)\n - diff rendering (added/removed/context)\n - status line readability\n - thinking level border changes\n - bash/python mode border colors\n5. Validate both symbol presets if your theme depends on glyph width/appearance.\n\n## Real constraints and caveats\n\n- All `colors` tokens are required for custom themes.\n- `export` and `symbols` are optional.\n- `$schema` in theme JSON is informational; runtime validation is enforced by a Zod schema in code.\n- `setTheme` failure falls back to `dark`; `previewTheme` failure does not replace current theme.\n- File watcher reload errors or temporary missing files keep the current loaded theme until a successful reload or explicit theme switch.\n",
@@ -8,9 +8,20 @@
8
8
  * - skc://<file>.md - Reads a specific documentation file
9
9
  */
10
10
  import * as path from "node:path";
11
- import { EMBEDDED_DOC_FILENAMES, EMBEDDED_DOCS } from "./docs-index.generated";
12
11
  import type { InternalResource, InternalUrl, ProtocolHandler } from "./types";
13
12
 
13
+ type DocsIndex = {
14
+ EMBEDDED_DOC_FILENAMES: readonly string[];
15
+ EMBEDDED_DOCS: Record<string, string>;
16
+ };
17
+
18
+ let docsIndexPromise: Promise<DocsIndex> | undefined;
19
+
20
+ function loadDocsIndex(): Promise<DocsIndex> {
21
+ if (!docsIndexPromise) docsIndexPromise = import("./docs-index.generated");
22
+ return docsIndexPromise;
23
+ }
24
+
14
25
  /**
15
26
  * Handler for skc:// URLs.
16
27
  *
@@ -34,6 +45,7 @@ export class SkcProtocolHandler implements ProtocolHandler {
34
45
  }
35
46
 
36
47
  async #listDocs(url: InternalUrl): Promise<InternalResource> {
48
+ const { EMBEDDED_DOC_FILENAMES } = await loadDocsIndex();
37
49
  if (EMBEDDED_DOC_FILENAMES.length === 0) {
38
50
  throw new Error("No documentation files found");
39
51
  }
@@ -60,6 +72,7 @@ export class SkcProtocolHandler implements ProtocolHandler {
60
72
  throw new Error("Path traversal (..) is not allowed in skc:// URLs");
61
73
  }
62
74
 
75
+ const { EMBEDDED_DOC_FILENAMES, EMBEDDED_DOCS } = await loadDocsIndex();
63
76
  const content = EMBEDDED_DOCS[normalized];
64
77
  if (content === undefined) {
65
78
  const lookup = normalized.replace(/\.md$/, "");
@@ -152,8 +152,8 @@ type ManagedSessionRecord = {
152
152
  liveMessageProgress: { textEmitted: boolean; thoughtEmitted: boolean } | undefined;
153
153
  toolArgsById: Map<string, unknown>;
154
154
  extensionsConfigured: boolean;
155
- // Installed inside `#scheduleBootstrapUpdates` (post-race-guard); released
156
- // in `#disposeSessionRecord`. Lives independent of any prompt turn.
155
+ // Installed after the bootstrap race guard or eagerly when the client starts a prompt;
156
+ // released in `#disposeSessionRecord`. Lives independent of any prompt turn.
157
157
  lifetimeUnsubscribe: (() => void) | undefined;
158
158
  };
159
159
 
@@ -619,6 +619,7 @@ export class AcpAgent implements Agent {
619
619
  promise: pendingPrompt.promise,
620
620
  };
621
621
 
622
+ this.#ensureLifetimeSubscription(record);
622
623
  record.promptTurn.unsubscribe = record.session.subscribe(event => {
623
624
  void this.#handlePromptEvent(record, event);
624
625
  });
@@ -831,6 +832,7 @@ export class AcpAgent implements Agent {
831
832
  }
832
833
  promptTurn.cancelRequested = true;
833
834
  promptTurn.unsubscribe?.();
835
+ void this.#emitCancelledPromptIdleUpdate(record);
834
836
  const cleanup = this.#runCancelCleanup(record, promptTurn);
835
837
  promptTurn.cleanup = cleanup;
836
838
  this.#finishPrompt(record, {
@@ -1043,8 +1045,8 @@ export class AcpAgent implements Agent {
1043
1045
  async #registerPreparedSession(session: AgentSession, mcpServers: McpServer[]): Promise<ManagedSessionRecord> {
1044
1046
  const record = this.#createManagedSessionRecord(session);
1045
1047
  session.setClientBridge(createAcpClientBridge(this.#connection, session.sessionId, this.#clientCapabilities));
1046
- // `record.lifetimeUnsubscribe` is installed in `#scheduleBootstrapUpdates`
1047
- // so it shares the bootstrap race guard — see that comment for why.
1048
+ // The lifetime subscription normally follows the bootstrap race guard, but
1049
+ // prompt() installs it eagerly once the client has demonstrated session ownership.
1048
1050
  try {
1049
1051
  await this.#configureExtensions(record);
1050
1052
  await this.#configureMcpServers(record, mcpServers);
@@ -1070,7 +1072,38 @@ export class AcpAgent implements Agent {
1070
1072
  };
1071
1073
  }
1072
1074
 
1075
+ #ensureLifetimeSubscription(record: ManagedSessionRecord): void {
1076
+ if (record.lifetimeUnsubscribe) {
1077
+ return;
1078
+ }
1079
+ record.lifetimeUnsubscribe = record.session.subscribe(event => {
1080
+ void this.#handleLifetimeEvent(record, event);
1081
+ });
1082
+ }
1083
+
1073
1084
  async #handleLifetimeEvent(record: ManagedSessionRecord, event: AgentSessionEvent): Promise<void> {
1085
+ if (event.type === "auto_compaction_start" || event.type === "auto_compaction_end") {
1086
+ // Prompt-bound compaction is normally forwarded by #handlePromptEvent. The lifetime
1087
+ // subscription covers idle maintenance and the end event after prompt cancellation.
1088
+ const promptTurn = record.promptTurn;
1089
+ if (
1090
+ isPromptTurnInFlight(promptTurn) &&
1091
+ (!promptTurn.cancelRequested || event.type === "auto_compaction_start")
1092
+ ) {
1093
+ return;
1094
+ }
1095
+ for (const notification of mapAgentWireEventPayloadToAcpSessionUpdates(
1096
+ toAgentWireEventPayload(event),
1097
+ record.session.sessionId,
1098
+ {
1099
+ cwd: record.session.sessionManager.getCwd(),
1100
+ compactionEndPhase: "idle",
1101
+ },
1102
+ )) {
1103
+ await this.#connection.sessionUpdate(notification);
1104
+ }
1105
+ return;
1106
+ }
1074
1107
  if (event.type !== "thinking_level_changed") {
1075
1108
  return;
1076
1109
  }
@@ -1140,6 +1173,7 @@ export class AcpAgent implements Agent {
1140
1173
  getMessageProgress: message => this.#getLiveMessageProgress(record, message),
1141
1174
  getToolArgs: toolCallId => record.toolArgsById.get(toolCallId),
1142
1175
  cwd: record.session.sessionManager.getCwd(),
1176
+ compactionEndPhase: "responding",
1143
1177
  },
1144
1178
  )) {
1145
1179
  await this.#connection.sessionUpdate(notification);
@@ -1551,13 +1585,10 @@ export class AcpAgent implements Agent {
1551
1585
  // enough that the response future has scheduled before our timer fires
1552
1586
  // on stdio-only transports.
1553
1587
  //
1554
- // The session-lifetime subscription is installed inside the same timer
1555
- // so it shares this guard — without it, an extension's `session_start`
1556
- // handler (or any async work it schedules) calling `setThinkingLevel`
1557
- // would push a `config_option_update` for a session id the client
1558
- // hasn't been told about yet. The pre-bootstrap thinking level is
1559
- // reported in the response's `configOptions`, so deferring the
1560
- // notification loses no state.
1588
+ // The session-lifetime subscription normally shares this guard so extension
1589
+ // work cannot notify an unknown session id. prompt() may install it earlier:
1590
+ // receipt of a prompt proves the client already owns the returned session id,
1591
+ // and closes the cancellation window before this timer fires.
1561
1592
  setTimeout(() => {
1562
1593
  if (this.#connection.signal.aborted) {
1563
1594
  return;
@@ -1566,11 +1597,7 @@ export class AcpAgent implements Agent {
1566
1597
  if (!record) {
1567
1598
  return;
1568
1599
  }
1569
- if (!record.lifetimeUnsubscribe) {
1570
- record.lifetimeUnsubscribe = record.session.subscribe(event => {
1571
- void this.#handleLifetimeEvent(record, event);
1572
- });
1573
- }
1600
+ this.#ensureLifetimeSubscription(record);
1574
1601
  void this.#emitBootstrapUpdates(sessionId, record);
1575
1602
  }, ACP_BOOTSTRAP_RACE_GUARD_MS);
1576
1603
  }
@@ -1606,6 +1633,30 @@ export class AcpAgent implements Agent {
1606
1633
  });
1607
1634
  }
1608
1635
 
1636
+ /** Ensure cancellation clears a previously emitted busy/compacting phase even if abort never produces an end event. */
1637
+ async #emitCancelledPromptIdleUpdate(record: ManagedSessionRecord): Promise<void> {
1638
+ if (this.#connection.signal.aborted) {
1639
+ return;
1640
+ }
1641
+ try {
1642
+ await this.#connection.sessionUpdate({
1643
+ sessionId: record.session.sessionId,
1644
+ update: {
1645
+ sessionUpdate: "session_info_update",
1646
+ title: record.session.sessionName,
1647
+ updatedAt: new Date().toISOString(),
1648
+ _meta: {
1649
+ skcPhase: "idle",
1650
+ running: false,
1651
+ skcRunning: false,
1652
+ },
1653
+ },
1654
+ });
1655
+ } catch (error) {
1656
+ logger.warn("Failed to emit cancelled ACP prompt idle update", { error });
1657
+ }
1658
+ }
1659
+
1609
1660
  /**
1610
1661
  * Reload plugin/registry state for an ACP session. Mirrors the interactive
1611
1662
  * `/reload-plugins` and `/move` flows: invalidates the plugin-roots cache,
@@ -1647,6 +1698,11 @@ export class AcpAgent implements Agent {
1647
1698
  sessionUpdate: "session_info_update",
1648
1699
  title: record.session.sessionName,
1649
1700
  updatedAt: new Date().toISOString(),
1701
+ _meta: {
1702
+ skcPhase: "idle",
1703
+ running: false,
1704
+ skcRunning: false,
1705
+ },
1650
1706
  },
1651
1707
  });
1652
1708
  }