@sayknow-cli/coding-agent 0.5.19 → 0.5.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.5.21] - 2026-09-17
6
+
7
+ ### Changed
8
+
9
+ - `skc auth-gateway` (`serve`, `status`, `check`) now falls back to the local SQLite credential store when no broker is configured, matching `discoverAuthStorage()` precedence. A configured broker still wins and never degrades to local credentials. Single-machine users no longer have to run `skc auth-broker serve` alongside the gateway.
10
+ - `skc auth-gateway status --json` reports `source` (`broker`/`local`), `dbPath`, and `credentialCount` in both modes; `ready` now requires a bearer token **and** at least one credential (`reason`: `token_missing`, `no_credentials`, `broker_unavailable`, `local_store_unavailable`).
11
+
12
+ ## [0.5.20] - 2026-09-17
13
+
14
+ ### Fixed
15
+
16
+ - Widen npm post-publish visibility wait from ~6 minutes to ~15 minutes. `coding-agent` tarball CDN lag timed out 0.5.14–0.5.19 before the root `sayknow-cli` package could publish.
17
+
5
18
  ## [0.5.19] - 2026-09-16
6
19
 
7
20
  ### Fixed
@@ -1,3 +1,4 @@
1
+ import { AuthStorage } from "@sayknow-cli/ai";
1
2
  export type AuthGatewayAction = "serve" | "token" | "status" | "check";
2
3
  export interface AuthGatewayCommandArgs {
3
4
  action: AuthGatewayAction;
@@ -14,5 +15,28 @@ export interface AuthGatewayCommandArgs {
14
15
  };
15
16
  }
16
17
  declare const ACTIONS: readonly AuthGatewayAction[];
18
+ /**
19
+ * Credential source the gateway is serving from. `broker` mirrors the previous
20
+ * behaviour; `local` is the single-machine path that makes `skc auth-broker
21
+ * serve` optional.
22
+ */
23
+ export interface GatewayCredentialSource {
24
+ storage: AuthStorage;
25
+ kind: "broker" | "local";
26
+ /** Broker URL in broker mode, `null` in local mode. */
27
+ brokerUrl: string | null;
28
+ /** `<agentDir>/agent.db` in local mode, `null` in broker mode. */
29
+ dbPath: string | null;
30
+ /** `broker <url>` / `local <dbPath>` — also used as the AuthStorage sourceLabel. */
31
+ label: string;
32
+ }
33
+ /**
34
+ * Open the credential store the gateway should serve from.
35
+ *
36
+ * Same precedence as `discoverAuthStorage()` in sdk/session.ts: a configured
37
+ * broker wins, otherwise fall back to the local SQLite store. Callers own the
38
+ * returned `storage` and must `close()` it.
39
+ */
40
+ export declare function openGatewayCredentialSource(): Promise<GatewayCredentialSource>;
17
41
  export declare function runAuthGatewayCommand(cmd: AuthGatewayCommandArgs): Promise<void>;
18
42
  export { ACTIONS as AUTH_GATEWAY_ACTIONS };
@@ -1,5 +1,6 @@
1
1
  /**
2
- * `skc auth-gateway` — run a forward proxy that injects auth from the broker.
2
+ * `skc auth-gateway` — run a forward proxy that injects auth from the broker,
3
+ * or from the local credential store when no broker is configured.
3
4
  */
4
5
  import { Command } from "@sayknow-cli/utils/cli";
5
6
  import { type AuthGatewayAction } from "../cli/auth-gateway-cli";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@sayknow-cli/coding-agent",
4
- "version": "0.5.19",
4
+ "version": "0.5.21",
5
5
  "description": "Sayknow-CLI CLI with read, bash, edit, write tools and session management",
6
6
  "homepage": "https://sayknow-cli.com",
7
7
  "author": "jaybeyond",
@@ -54,12 +54,12 @@
54
54
  "@agentclientprotocol/sdk": "1.3.0",
55
55
  "@babel/parser": "^7.29.3",
56
56
  "@mozilla/readability": "^0.6.0",
57
- "@sayknow-cli/stats": "0.5.19",
58
- "@sayknow-cli/agent-core": "0.5.19",
59
- "@sayknow-cli/ai": "0.5.19",
60
- "@sayknow-cli/natives": "0.5.19",
61
- "@sayknow-cli/tui": "0.5.19",
62
- "@sayknow-cli/utils": "0.5.19",
57
+ "@sayknow-cli/stats": "0.5.21",
58
+ "@sayknow-cli/agent-core": "0.5.21",
59
+ "@sayknow-cli/ai": "0.5.21",
60
+ "@sayknow-cli/natives": "0.5.21",
61
+ "@sayknow-cli/tui": "0.5.21",
62
+ "@sayknow-cli/utils": "0.5.21",
63
63
  "@puppeteer/browsers": "^2.13.0",
64
64
  "@types/turndown": "5.0.6",
65
65
  "@xterm/headless": "^6.0.0",
@@ -2,15 +2,20 @@
2
2
  * `skc auth-gateway` command handlers.
3
3
  *
4
4
  * Boots a forward-proxy server that lets less-trusted clients (the macOS
5
- * usage widget and containerized deployments) make provider API calls without ever
6
- * seeing the access token. The gateway is itself a broker client and
7
- * resolves credentials through the configured broker (via the same
8
- * `SKC_AUTH_BROKER_URL` / `auth.broker.url` precedence used elsewhere).
5
+ * usage widget, local desktop apps and containerized deployments) make provider
6
+ * API calls without ever seeing the access token.
7
+ *
8
+ * Credential source mirrors `discoverAuthStorage()` in sdk/session.ts:
9
+ * - broker configured (`SKC_AUTH_BROKER_URL` / `auth.broker.url`) → the
10
+ * gateway is a broker client and never touches local SQLite.
11
+ * - no broker → the local SQLite store at `<agentDir>/agent.db`, so a
12
+ * single-machine user runs the gateway alone instead of also standing up
13
+ * `skc auth-broker serve`.
9
14
  *
10
15
  * Sub-verbs:
11
- * - `serve [--bind=…]` — boots the gateway against the configured broker.
16
+ * - `serve [--bind=…]` — boots the gateway against the broker or local store.
12
17
  * - `token` / `token --regenerate` — manages the gateway bearer token file.
13
- * - `status` — prints the locally-stored gateway token and bind hint.
18
+ * - `status` — prints the locally-stored gateway token and credential source.
14
19
  */
15
20
  import * as crypto from "node:crypto";
16
21
  import * as fs from "node:fs/promises";
@@ -28,7 +33,7 @@ import {
28
33
  type SnapshotResponse,
29
34
  startAuthGateway,
30
35
  } from "@sayknow-cli/ai";
31
- import { getConfigRootDir, isEnoent, VERSION } from "@sayknow-cli/utils";
36
+ import { getAgentDbPath, getAgentDir, getConfigRootDir, isEnoent, VERSION } from "@sayknow-cli/utils";
32
37
  import chalk from "chalk";
33
38
  import { type AuthBrokerClientConfig, resolveAuthBrokerConfig } from "../session/auth-broker-config";
34
39
 
@@ -128,29 +133,66 @@ async function fetchBrokerSnapshot(client: AuthBrokerClient): Promise<SnapshotRe
128
133
  return result.snapshot;
129
134
  }
130
135
 
131
- async function runServe(flags: AuthGatewayCommandArgs["flags"]): Promise<void> {
136
+ /**
137
+ * Credential source the gateway is serving from. `broker` mirrors the previous
138
+ * behaviour; `local` is the single-machine path that makes `skc auth-broker
139
+ * serve` optional.
140
+ */
141
+ export interface GatewayCredentialSource {
142
+ storage: AuthStorage;
143
+ kind: "broker" | "local";
144
+ /** Broker URL in broker mode, `null` in local mode. */
145
+ brokerUrl: string | null;
146
+ /** `<agentDir>/agent.db` in local mode, `null` in broker mode. */
147
+ dbPath: string | null;
148
+ /** `broker <url>` / `local <dbPath>` — also used as the AuthStorage sourceLabel. */
149
+ label: string;
150
+ }
151
+
152
+ /**
153
+ * Open the credential store the gateway should serve from.
154
+ *
155
+ * Same precedence as `discoverAuthStorage()` in sdk/session.ts: a configured
156
+ * broker wins, otherwise fall back to the local SQLite store. Callers own the
157
+ * returned `storage` and must `close()` it.
158
+ */
159
+ export async function openGatewayCredentialSource(): Promise<GatewayCredentialSource> {
132
160
  const brokerConfig = await resolveAuthBrokerConfig();
133
- if (!brokerConfig) {
134
- throw new Error(
135
- "`skc auth-gateway serve` requires SKC_AUTH_BROKER_URL (or `auth.broker.url`/`auth.broker.token` in config.yml). The gateway is itself a broker client.",
136
- );
161
+ if (brokerConfig) {
162
+ // Refresh + usage both flow through the store's broker hooks automatically —
163
+ // `RemoteAuthCredentialStore.refreshOAuthCredential` and `.fetchUsageReports`.
164
+ // AuthStorage discovers them when no explicit option overrides them, so the
165
+ // gateway only needs to construct the store and pass it in.
166
+ const client = createBrokerClient(brokerConfig);
167
+ const initialSnapshot = await fetchBrokerSnapshot(client);
168
+ const store = new RemoteAuthCredentialStore({ client, initialSnapshot });
169
+ const label = `broker ${brokerConfig.url}`;
170
+ const storage = new AuthStorage(store, { sourceLabel: label });
171
+ try {
172
+ await storage.reload();
173
+ } catch (error) {
174
+ try {
175
+ storage.close();
176
+ } catch {
177
+ // Preserve the initial reload failure.
178
+ }
179
+ throw error;
180
+ }
181
+ return { storage, kind: "broker", brokerUrl: brokerConfig.url, dbPath: null, label };
137
182
  }
183
+ const dbPath = getAgentDbPath(getAgentDir());
184
+ const label = `local ${dbPath}`;
185
+ // `AuthStorage.create` opens the store and reloads it in one step.
186
+ const storage = await AuthStorage.create(dbPath, { sourceLabel: label });
187
+ return { storage, kind: "local", brokerUrl: null, dbPath, label };
188
+ }
189
+
190
+ async function runServe(flags: AuthGatewayCommandArgs["flags"]): Promise<void> {
138
191
  const bind = flags.bind ?? DEFAULT_AUTH_GATEWAY_BIND;
139
192
  const gatewayToken = flags.noAuth ? null : await ensureToken();
140
193
 
141
- // Build a broker-backed AuthStorage — same pattern as discoverAuthStorage()
142
- // in sdk/session.ts. The gateway never touches local SQLite.
143
- const client = createBrokerClient(brokerConfig);
144
- const initialSnapshot = await fetchBrokerSnapshot(client);
145
- const store = new RemoteAuthCredentialStore({ client, initialSnapshot });
146
- // Refresh + usage both flow through the store's broker hooks automatically —
147
- // `RemoteAuthCredentialStore.refreshOAuthCredential` and `.fetchUsageReports`.
148
- // AuthStorage discovers them when no explicit option overrides them, so the
149
- // gateway only needs to construct the store and pass it in.
150
- const storage = new AuthStorage(store, {
151
- sourceLabel: `broker ${brokerConfig.url}`,
152
- });
153
- await storage.reload();
194
+ const source = await openGatewayCredentialSource();
195
+ const storage = source.storage;
154
196
 
155
197
  // Build the model resolver + catalog from pi-ai's bundled metadata, scoped
156
198
  // to providers we hold credentials for. Format handlers ask `resolveModel`
@@ -183,7 +225,11 @@ async function runServe(flags: AuthGatewayCommandArgs["flags"]): Promise<void> {
183
225
  } else {
184
226
  process.stdout.write(`auth: disabled (--no-auth) — any client can call this gateway\n`);
185
227
  }
186
- process.stdout.write(`upstream broker: ${brokerConfig.url}\n`);
228
+ if (source.kind === "broker") {
229
+ process.stdout.write(`upstream broker: ${source.brokerUrl}\n`);
230
+ } else {
231
+ process.stdout.write(`credentials: local ${source.dbPath}\n`);
232
+ }
187
233
 
188
234
  const stopped = Promise.withResolvers<void>();
189
235
  let shutdownStarted = false;
@@ -243,24 +289,35 @@ async function runToken(flags: AuthGatewayCommandArgs["flags"]): Promise<void> {
243
289
 
244
290
  async function runStatus(flags: AuthGatewayCommandArgs["flags"]): Promise<void> {
245
291
  const token = await readToken();
246
- const brokerConfig = await resolveAuthBrokerConfig();
247
292
  const tokenFile = getTokenFilePath();
248
- if (!brokerConfig) {
293
+ const tokenPresent = token !== null;
294
+
295
+ let source: GatewayCredentialSource;
296
+ try {
297
+ source = await openGatewayCredentialSource();
298
+ } catch (error) {
299
+ // Broker unreachable, or the local SQLite store failed to open.
300
+ const message = error instanceof Error ? error.message : String(error);
301
+ const brokerConfig = await resolveAuthBrokerConfig().catch(() => null);
249
302
  const status = {
250
303
  ready: false,
251
- reason: "not_configured",
304
+ reason: brokerConfig ? "broker_unavailable" : "local_store_unavailable",
305
+ source: brokerConfig ? "broker" : "local",
252
306
  tokenFile,
253
- tokenPresent: token !== null,
254
- broker: null,
255
- brokerConfigured: false,
307
+ tokenPresent,
308
+ broker: brokerConfig?.url ?? null,
309
+ brokerConfigured: brokerConfig !== null,
256
310
  brokerAuthenticated: false,
311
+ dbPath: brokerConfig ? null : getAgentDbPath(getAgentDir()),
312
+ error: message,
257
313
  };
258
314
  if (flags.json) {
259
315
  process.stdout.write(`${JSON.stringify(status)}\n`);
260
316
  } else {
261
- process.stdout.write(`${chalk.yellow("No broker configured.")} Set SKC_AUTH_BROKER_URL.\n`);
317
+ const what = brokerConfig ? `upstream broker: ${brokerConfig.url}` : `local store: ${status.dbPath}`;
318
+ process.stdout.write(`${chalk.red("FAILED")} ${what}: ${message}\n`);
262
319
  process.stdout.write(
263
- `token: ${status.tokenPresent ? chalk.green("present") : chalk.red("missing")} at ${status.tokenFile}\n`,
320
+ `token: ${tokenPresent ? chalk.green("present") : chalk.red("missing")} at ${tokenFile}\n`,
264
321
  );
265
322
  }
266
323
  process.exitCode = 1;
@@ -268,56 +325,50 @@ async function runStatus(flags: AuthGatewayCommandArgs["flags"]): Promise<void>
268
325
  }
269
326
 
270
327
  try {
271
- const snapshot = await fetchBrokerSnapshot(createBrokerClient(brokerConfig));
272
- const tokenPresent = token !== null;
328
+ const credentialCount = source.storage.exportSnapshot().credentials.length;
329
+ // Ready means a client can actually get an answer: it needs a bearer
330
+ // token to present, and we need at least one provider credential to serve.
331
+ const ready = tokenPresent && credentialCount > 0;
273
332
  const status = {
274
- ready: tokenPresent,
275
- reason: tokenPresent ? null : "token_missing",
333
+ ready,
334
+ reason: !tokenPresent ? "token_missing" : credentialCount === 0 ? "no_credentials" : null,
335
+ source: source.kind,
276
336
  tokenFile,
277
337
  tokenPresent,
278
- broker: brokerConfig.url,
279
- brokerConfigured: true,
280
- brokerAuthenticated: true,
281
- credentialCount: snapshot.credentials.length,
338
+ broker: source.brokerUrl,
339
+ brokerConfigured: source.kind === "broker",
340
+ brokerAuthenticated: source.kind === "broker",
341
+ dbPath: source.dbPath,
342
+ credentialCount,
282
343
  };
283
344
  if (flags.json) {
284
345
  process.stdout.write(`${JSON.stringify(status)}\n`);
285
346
  } else {
286
- const brokerLine = `upstream broker: ${brokerConfig.url} (${snapshot.credentials.length} credential${
287
- snapshot.credentials.length === 1 ? "" : "s"
288
- })`;
289
- process.stdout.write(`${tokenPresent ? chalk.green("ready") : chalk.yellow("not ready")} ${brokerLine}\n`);
347
+ const plural = credentialCount === 1 ? "" : "s";
348
+ const sourceLine =
349
+ source.kind === "broker"
350
+ ? `upstream broker: ${source.brokerUrl} (${credentialCount} credential${plural})`
351
+ : `local store: ${source.dbPath} (${credentialCount} credential${plural})`;
352
+ process.stdout.write(`${ready ? chalk.green("ready") : chalk.yellow("not ready")} ${sourceLine}\n`);
290
353
  process.stdout.write(
291
- `token: ${tokenPresent ? chalk.green("present") : chalk.red("missing")} at ${status.tokenFile}\n`,
354
+ `token: ${tokenPresent ? chalk.green("present") : chalk.red("missing")} at ${tokenFile}\n`,
292
355
  );
293
356
  if (!tokenPresent) {
294
357
  process.stdout.write(
295
358
  "Run `skc auth-gateway token` or `skc auth-gateway serve` to create a bearer token.\n",
296
359
  );
297
360
  }
361
+ if (credentialCount === 0) {
362
+ process.stdout.write(
363
+ source.kind === "broker"
364
+ ? "The broker holds no credentials. Log in on the broker host.\n"
365
+ : "No local credentials. Run `skc auth-broker login <provider>` (e.g. anthropic).\n",
366
+ );
367
+ }
298
368
  }
299
- if (!tokenPresent) process.exitCode = 1;
300
- } catch (error) {
301
- const message = error instanceof Error ? error.message : String(error);
302
- const status = {
303
- ready: false,
304
- reason: "broker_unavailable",
305
- tokenFile,
306
- tokenPresent: token !== null,
307
- broker: brokerConfig.url,
308
- brokerConfigured: true,
309
- brokerAuthenticated: false,
310
- error: message,
311
- };
312
- if (flags.json) {
313
- process.stdout.write(`${JSON.stringify(status)}\n`);
314
- } else {
315
- process.stdout.write(`${chalk.red("FAILED")} upstream broker: ${brokerConfig.url}: ${message}\n`);
316
- process.stdout.write(
317
- `token: ${status.tokenPresent ? chalk.green("present") : chalk.red("missing")} at ${status.tokenFile}\n`,
318
- );
319
- }
320
- process.exitCode = 1;
369
+ if (!ready) process.exitCode = 1;
370
+ } finally {
371
+ source.storage.close();
321
372
  }
322
373
  }
323
374
 
@@ -343,30 +394,22 @@ export async function runAuthGatewayCommand(cmd: AuthGatewayCommandArgs): Promis
343
394
  }
344
395
 
345
396
  /**
346
- * `skc auth-gateway check` — probe each broker-supplied credential and print
347
- * per-credential auth health. Use this when the gateway is returning 401s and
397
+ * `skc auth-gateway check` — probe each credential the gateway would serve and
398
+ * print per-credential auth health. Use this when the gateway is returning 401s
348
399
  * you need to find which row in a multi-account pool is the bad one. The
349
400
  * aggregate `/v1/usage` endpoint silently drops failed credentials, so a
350
401
  * dedicated diagnostic is the only way to see which credentials failed.
351
402
  */
352
403
  async function runCheck(flags: AuthGatewayCommandArgs["flags"]): Promise<void> {
353
- const brokerConfig = await resolveAuthBrokerConfig();
354
- if (!brokerConfig) {
355
- throw new Error(
356
- "`skc auth-gateway check` requires SKC_AUTH_BROKER_URL (or `auth.broker.url`/`auth.broker.token` in config.yml). It probes the same credentials the gateway would serve.",
357
- );
358
- }
359
-
360
- const client = createBrokerClient(brokerConfig);
361
- const initialSnapshot = await fetchBrokerSnapshot(client);
362
- const store = new RemoteAuthCredentialStore({ client, initialSnapshot });
363
- const storage = new AuthStorage(store, { sourceLabel: `broker ${brokerConfig.url}` });
404
+ const source = await openGatewayCredentialSource();
405
+ const storage = source.storage;
364
406
  try {
365
- await storage.reload();
366
407
  const results = await storage.checkCredentials();
367
408
 
368
409
  if (flags.json) {
369
- process.stdout.write(`${JSON.stringify({ broker: brokerConfig.url, credentials: results }, null, 2)}\n`);
410
+ process.stdout.write(
411
+ `${JSON.stringify({ source: source.kind, broker: source.brokerUrl, dbPath: source.dbPath, credentials: results }, null, 2)}\n`,
412
+ );
370
413
  } else {
371
414
  const grouped = new Map<string, typeof results>();
372
415
  for (const row of results) {
@@ -375,7 +418,7 @@ async function runCheck(flags: AuthGatewayCommandArgs["flags"]): Promise<void> {
375
418
  grouped.set(row.provider, list);
376
419
  }
377
420
  const providers = [...grouped.keys()].sort();
378
- process.stdout.write(`broker: ${brokerConfig.url}\n`);
421
+ process.stdout.write(`${source.label}\n`);
379
422
  for (const provider of providers) {
380
423
  const rows = grouped.get(provider) ?? [];
381
424
  process.stdout.write(`\n${chalk.bold(provider)} (${rows.length})\n`);
@@ -1,5 +1,6 @@
1
1
  /**
2
- * `skc auth-gateway` — run a forward proxy that injects auth from the broker.
2
+ * `skc auth-gateway` — run a forward proxy that injects auth from the broker,
3
+ * or from the local credential store when no broker is configured.
3
4
  */
4
5
  import { Args, Command, Flags, renderCommandHelp } from "@sayknow-cli/utils/cli";
5
6
  import {
@@ -11,7 +12,8 @@ import {
11
12
  import { initTheme } from "../modes/theme/theme";
12
13
 
13
14
  export default class AuthGateway extends Command {
14
- static description = "Run an auth-gateway forward proxy backed by the configured broker";
15
+ static description =
16
+ "Run an auth-gateway forward proxy backed by the configured broker, or local credentials when no broker is set";
15
17
 
16
18
  static args = {
17
19
  action: Args.string({
@@ -32,13 +34,13 @@ export default class AuthGateway extends Command {
32
34
  };
33
35
 
34
36
  static examples = [
35
- "# Boot the gateway against the configured broker\n skc auth-gateway serve",
37
+ "# Boot the gateway (broker when configured, else local credentials)\n skc auth-gateway serve",
36
38
  "# Boot on a non-default port\n skc auth-gateway serve --bind=127.0.0.1:4000",
37
39
  "# Print the gateway bearer token (creates one on first run)\n skc auth-gateway token",
38
40
  "# Rotate the gateway bearer token\n skc auth-gateway token --regenerate",
39
41
  "# Run on loopback without any bearer (anyone on this host can call)\n skc auth-gateway serve --no-auth",
40
- "# Show local gateway + broker config status\n skc auth-gateway status",
41
- "# Probe each broker credential to see which one is producing 401s\n skc auth-gateway check",
42
+ "# Show gateway token + credential source status\n skc auth-gateway status",
43
+ "# Probe each credential to see which one is producing 401s\n skc auth-gateway check",
42
44
  "# Same, machine-readable for scripts\n skc auth-gateway check --json",
43
45
  ];
44
46
 
@@ -12,7 +12,7 @@ export const EMBEDDED_DOCS: Readonly<Record<string, string>> = {
12
12
  "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",
13
13
  "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",
14
14
  "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",
15
- "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 │ │ - 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, 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/session.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",
15
+ "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 resolved access token, and forwards the bytes to the real provider. Clients (containerised skc, local desktop apps, llm-git, the macOS usage widget, …) never see the access token. Credentials come from the broker when one is configured, otherwise from the local SQLite store — so the gateway also runs standalone on a single machine.\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 │ │ - 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, 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]\nskc auth-gateway check [--json]\n```\n\n- `serve` resolves credentials with the same precedence as the interactive client (`discoverAuthStorage()`): when `SKC_AUTH_BROKER_URL` (or `auth.broker.url` in `config.yml`) is set the gateway is a broker client — it calls `AuthBrokerClient.fetchSnapshot()`, wraps it in `RemoteAuthCredentialStore`, and never touches local SQLite. With no broker configured it serves from the local store at `<agent-dir>/agent.db`, so a single-machine user runs the gateway alone instead of also standing up `skc auth-broker serve`. 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- `status` prints the credential source (`source: \"broker\" | \"local\"`), `credentialCount`, and the bearer-token state. `ready` is true only when a bearer token exists **and** at least one credential is available; otherwise `reason` is `token_missing`, `no_credentials`, `broker_unavailable`, or `local_store_unavailable` and the exit code is `1`.\n- `check` probes every credential the gateway would serve — broker-supplied or local — and reports per-credential auth health.\n- `token` mirrors the broker’s equivalent.\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/session.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 (or `skc auth-gateway`) should resolve credentials through a broker. Unset means the local SQLite store is used. |\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 a broker client whenever a broker is configured, and falls back to the same local store the interactive client uses when one is not.\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",
16
16
  "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, ACP, 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): 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 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| ACP tool call (agent tooling) | `BashTool.execute` | Usually no UI -> non-PTY | Structured protocol 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\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/internal-urls/artifact-protocol.ts`](../packages/coding-agent/src/internal-urls/artifact-protocol.ts) — `artifact://<id>` resolution.\n",
17
17
  "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/session.ts`](../packages/coding-agent/src/sdk/session.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",
18
18
  "bot-integration.md": "# External controller integration guide\n\nThis guide is for authors of bots and orchestrators that want to drive Sayknow-CLI (`skc`) without scraping terminal scrollback. Hermes, OpenClaw, GitHub bots, chatops bots, and custom schedulers are examples of external controllers; none of them need bespoke SKC behavior if they can speak the Coordinator MCP tools or the SDK WebSocket lifecycle below.\n\nSKC is an external runner. Your controller owns queueing, identity, policy, and credentials; SKC owns the coding-agent session, workflows, tools, artifacts, and evidence inside the selected repository or worktree.\n\n## Integration surfaces\n\nUse the smallest surface that fits your bot:\n\n| Surface | Best for | Command | Stability notes |\n| --- | --- | --- | --- |\n| Coordinator MCP | Any external controller that can discover SDK-backed sessions, send turns, answer questions, and read artifacts. | `skc mcp-serve coordinator` | Preferred orchestration surface. `skc mcp-serve hermes` is a compatibility alias, not a separate contract. |\n| Setup adapter | Rendering a portable MCP config and operator instructions for a controller profile. | `skc setup hermes --root /path/to/repo` | Compatibility-oriented config renderer; does not call an LLM or validate provider credentials. |\n| SDK WebSocket | A controller that drives one live session directly: state queries, events, actions, and workflow-gate replies. | Connect to the session's loopback SDK endpoint (see [`docs/sdk.md`](./sdk.md)) | The canonical machine interface. `--mode rpc`, `--mode rpc-ui`, and `--mode bridge` have been removed. |\n| Daemon session CLI | Scripted control/queries against a live session with JSON output. | `skc daemon session list\\|control\\|query\\|global` | A pure SDK client; honors the same protocol and dispositions. |\n\n## Recommended architecture\n\n```text\nexternal controller / bot\n ├─ chooses repo/worktree and task policy\n ├─ starts MCP server: skc mcp-serve coordinator\n ├─ discovers or starts one SDK-backed SKC session\n ├─ sends one bounded turn at a time\n ├─ answers structured questions explicitly\n ├─ marks turn completion/failure with report_status\n └─ reads artifacts/reports from allowlisted roots\n```\n\nDo not infer completion from terminal output. Treat SDK-backed durable turn state as authoritative. Tmux identifiers, when present, are advisory process metadata only.\n\n## Coordinator MCP setup\n\nRender a non-mutating config preview:\n\n```sh\nskc setup hermes --root /path/to/repo --profile my-bot --repo my-repo\n```\n\nInstall into a Hermes-compatible profile only when the target path is intentional:\n\n```sh\nskc setup hermes \\\n --root /path/to/repo \\\n --profile my-bot \\\n --repo my-repo \\\n --mutation sessions,questions,reports \\\n --profile-dir /path/to/hermes/profile \\\n --install\n```\n\nRun provider-independent contract smokes before trying a live model:\n\n```sh\nskc setup hermes --root /path/to/repo --smoke --json\nskc mcp-serve coordinator --check --json\n```\n\n`skc mcp-serve coordinator --check --json` (and the `hermes` compatibility alias) is a discovery-only, non-mutating catalog check. Its successful JSON payload retains `ok`, `server`, `readOnly`, and `tools`, and adds `catalog: { \"ready\": true, \"reason\": null }` plus `broker`. `broker.discovery_status` is `ready`, `unavailable`, or `error`; its reason is one of `absent_or_invalid`, `unsupported_state_version`, `discovery_access_denied`, or `discovery_read_failed` (or `null` when ready). `broker.operational_ready` is always `null`: this check observes canonical broker discovery but does not connect, ensure/bootstrap, write, repair, or delete. It reports `bootstrap_supported: true` and `bootstrap_attempted: false`, and never exposes broker paths, authority, endpoint, process, token, or raw error details. The human output remains the server/tools summary. SDK check behavior is separate and unchanged.\n\nThe generated config uses these environment variables:\n\n| Variable | Purpose |\n| --- | --- |\n| `SKC_COORDINATOR_MCP_WORKDIR_ROOTS` | Required allowlist for workdirs and artifact paths. |\n| `SKC_COORDINATOR_MCP_MUTATIONS` | Startup opt-in for mutation classes: `sessions`, `questions`, `reports`, or `all`. |\n| `SKC_COORDINATOR_MCP_SESSION_COMMAND` | Command used to start real SKC sessions, defaulting to `skc --worktree` in generated setup. |\n| `SKC_COORDINATOR_MCP_PROFILE` | Optional profile namespace so one bot cannot enumerate another profile's state. |\n| `SKC_COORDINATOR_MCP_REPO` | Optional repo namespace so one repo cannot enumerate another repo's state. |\n| `SKC_COORDINATOR_MCP_STATE_ROOT` | Optional coordination state root; defaults under `.skc/state/coordinator-mcp`. |\n| `SKC_COORDINATOR_MCP_ARTIFACT_BYTE_CAP` | Maximum bytes returned by artifact reads. |\n\nMutating calls require both startup opt-in, per-call `allow_mutation: true`, and the required caller-provided `idempotency_key`. Missing any one fails closed.\n\n## Generic smoke strategy\n\nUse three different smoke levels so CI does not depend on one operator's model, API key, or desktop:\n\n| Smoke | Required for CI | What it proves | Example |\n| --- | --- | --- | --- |\n| Contract smoke | Yes | MCP server metadata, tool discovery, exported tool names, input schemas, read-only default, and mutation-gate failures. No provider credentials required. | `skc mcp-serve coordinator --check --json` and focused tests around `tools/list` plus mutation denial. |\n| Dry-run lifecycle smoke | Yes when changed behavior affects lifecycle state | A generic controller can discover a mocked SDK session, send a turn, observe active-turn protection, report terminal status, and read the completed turn without a real LLM. | `bun test packages/coding-agent/test/coordinator-mcp-server.test.ts` uses mocked SDK services and temporary state roots. |\n| Optional live smoke | No | One operator's local provider/model/profile setup can run end-to-end in their chosen repo. Failure diagnoses that setup; it must not fail CI or PR validation. | Start `skc mcp-serve coordinator` with local env, dispatch a tiny task, then report/read evidence. |\n\nA public bot integration change should at least preserve the contract smoke and local-leak docs test. Live smokes are diagnostics, not mandatory gates.\n\n## MCP tool contract\n\nRead-only tools:\n\n- `skc_coordinator_list_sessions`\n- `skc_coordinator_read_status`\n- `skc_coordinator_read_tail`\n- `skc_coordinator_read_turn`\n- `skc_coordinator_await_turn`\n- `skc_coordinator_list_questions`\n- `skc_coordinator_list_artifacts`\n- `skc_coordinator_read_artifact`\n- `skc_coordinator_read_coordination_status`\n- `skc_coordinator_watch_events`\n\nMutating tools:\n\n- `skc_coordinator_start_session`\n- `skc_coordinator_register_session`\n- `skc_coordinator_send_prompt`\n- `skc_coordinator_submit_question_answer`\n- `skc_coordinator_report_status`\n- `skc_coordinator_stop_session`\n\n`skc_coordinator_stop_session` closes a coordinator delegate-created (ephemeral) session through canonical SDK broker lifecycle control, then removes its coordinator metadata only after the broker reports success. It refuses sessions with an active turn. User-registered sessions require both `force: true` and the `SKC_COORDINATOR_MCP_FORCE_STOP` capability; the same SDK lifecycle path reaps abandoned ephemeral delegate sessions after the configured idle TTL.\n\nHigh-level delegation tools:\n\n- `skc_delegate_plan`\n- `skc_delegate_execute`\n- `skc_delegate_team`\n\nThe `skc_delegate_*` tools package common SKC workflows for hosts that want to delegate an entire planning, execution, or team turn without manually composing `start_session` and `send_prompt`. They use the same coordinator mutation gates and workdir allowlists as the lower-level session tools.\n\n### Start a managed SKC session\n\nCall `skc_coordinator_start_session` with a canonical workdir inside `SKC_COORDINATOR_MCP_WORKDIR_ROOTS`:\n\n```json\n{\n \"cwd\": \"/path/to/repo\",\n \"prompt\": \"Optional first bounded task prompt\",\n \"idempotency_key\": \"start-skc-demo-1\",\n \"allow_mutation\": true\n}\n```\n\nThe returned payload includes `session.session_id`, `session_state`, and, when a prompt is provided, `turn_id`, `active_turn_id`, `status`, `delivery`, `queued`, and `delivered`. The top-level `status`, `queued`, and `delivered` exactly mirror the nested durable turn; `active_turn_id` is the current active turn.\n\n### Register an SDK-discoverable session\n\nRegister an already-running SKC session only after its endpoint is discoverable from the selected workdir:\n\n```json\n{\n \"session_id\": \"visible-skc-1\",\n \"cwd\": \"/path/to/repo\",\n \"idempotency_key\": \"register-visible-skc-1\",\n \"allow_mutation\": true\n}\n```\n\n`skc_coordinator_register_session` validates the session id and workdir allowlist, then verifies SDK endpoint discovery before writing coordinator state. Optional `tmux_session` and `tmux_target` fields are advisory process metadata only.\n\n### Send work as turns\n\nSend one bounded task prompt and persist the returned `turn_id`:\n\n```json\n{\n \"session_id\": \"skc-demo\",\n \"prompt\": \"Use /skill:ralplan to build a plan for ...\",\n \"idempotency_key\": \"send-skc-demo-1\",\n \"allow_mutation\": true\n}\n```\n\nA session may have one active turn by default. A second prompt returns `active_turn_exists` unless the bot passes:\n\n- `queue: true` to enqueue a durable follow-up turn, or\n- `force: true` to supersede the previous active turn and audit the supersession.\n\n### Wait or watch for completion\n\nUse `skc_coordinator_read_turn` for polling or `skc_coordinator_await_turn` for bounded waiting:\n\n```json\n{\n \"session_id\": \"skc-demo\",\n \"turn_id\": \"turn-00000000-0000-0000-0000-000000000000\",\n \"timeout_ms\": 30000,\n \"poll_interval_ms\": 1000,\n \"lines\": 80\n}\n```\n\nTerminal turn statuses are `completed`, `failed`, `cancelled`, and `superseded`. Non-terminal statuses include `queued`, `delivering`, `active`, `waiting_for_answer`, and `completing`.\n\nWhen the work is done, your bot must call `skc_coordinator_report_status` with the turn id. This writes the final response/error, evidence paths, and coordinator report that later reads consume:\n\n```json\n{\n \"session_id\": \"skc-demo\",\n \"turn_id\": \"turn-00000000-0000-0000-0000-000000000000\",\n \"status\": \"completed\",\n \"summary\": \"Implemented the requested fix and ran focused tests.\",\n \"evidence_paths\": [\"/path/to/repo/test-output.txt\"],\n \"idempotency_key\": \"report-skc-demo-1\",\n \"allow_mutation\": true\n}\n```\n\nUse `status: \"failed\"` plus `blocker` for provider failures, unrecoverable tool failures, missing credentials, policy denial, or task blockers.\nUse `status: \"cancelled\"` when the coordinator policy intentionally stops tracking an active turn, for example after an operator abort or a bot-side shutdown decision. This records the turn as terminal in coordinator state; it does not kill or control any tmux process. To supersede one active turn with replacement work, send the replacement prompt with `force: true` and preserve the superseded turn id in your audit trail.\n\n### Forward finish/stop lifecycle notifications\n\nDiscord, Hermes, Clawhip, and similar external notifiers should be opt-in and should forward only the public lifecycle surface. Use one of these supported paths:\n\n- Coordinator controllers: watch or poll turn state with `skc_coordinator_watch_events`, `skc_coordinator_await_turn`, or `skc_coordinator_read_turn`, then notify from the terminal turn status your controller records with `skc_coordinator_report_status`.\n- In-process extensions or hooks: subscribe to the public lifecycle events `turn_end` and `agent_end` from the shared hook/extension event contract.\n\nRecommended notification mapping:\n\n| Notification intent | Public surface | Safe meaning |\n| --- | --- | --- |\n| Turn finished | `turn_end` or terminal coordinator turn status `completed` | One LLM turn produced its final assistant message. |\n| Agent stopped / finished | `agent_end` | The agent loop ended for the submitted prompt. |\n| Waiting for user | Coordinator turn status `waiting_for_answer` | The agent is blocked on a structured question. |\n| Failed or blocked | Coordinator status `failed` with a public `blocker` summary | The controller recorded a terminal failure. |\n| Cancelled / superseded | Coordinator status `cancelled` or `superseded` | The controller intentionally stopped tracking or replaced the turn. |\n\nDo not forward raw prompts, transcripts, tool outputs, hidden instructions, private configs, host paths, channel ids, webhook URLs, or tokens. If your notifier needs a human-readable sentence, create a caller-supplied sanitized summary and keep provider/tool details out of the payload.\n\nExample public-safe extension event payloads:\n\n```json\n{ \"type\": \"turn_end\", \"turnIndex\": 2, \"summary\": \"Turn finished; review the local SKC session for details.\" }\n```\n\n```json\n{ \"type\": \"agent_end\", \"summary\": \"Agent loop ended; no raw transcript is included.\" }\n```\n\nExample opt-in forwarding policy:\n\n```json\n{\n \"enabled\": true,\n \"events\": [\"turn_end\", \"agent_end\"],\n \"destination\": \"external-notifier-profile\",\n \"redaction\": \"metadata-only\"\n}\n```\n\nSKC does not currently expose a structured stop-reason field on `agent_end`; integrators that need `waiting_for_answer`, `failed`, `cancelled`, or `superseded` should prefer the Coordinator MCP turn status because it is explicit, terminal-state oriented, and safe to relay after controller-side redaction.\n\n### Answer structured questions\n\nPull questions for one required session; every call reconciles durable pending `workflow.gates.list` rows before returning a bounded `questions`, `diagnostics`, and `reconciliation` snapshot. Filter `status: \"pending\"`; legacy `status: \"open\"` remains a compatibility alias for pending. A session can return multiple questions, so handle every pending row independently. The public rows include only the safe question shape and a per-pending-row `answer_binding`; they never expose private gate payloads or gate values.\n\n```json\n{ \"session_id\": \"skc-demo\", \"status\": \"pending\" }\n```\n\nSubmit the exact identifiers and binding from one pending row. `answer` uses public option ids (`opt_0`, etc.), or the advertised `other`/`clarify` form:\n\n```json\n{\n \"session_id\": \"skc-demo\",\n \"turn_id\": \"turn-00000000-0000-0000-0000-000000000000\",\n \"question_id\": \"question-1\",\n \"answer_binding\": \"<binding returned by list_questions>\",\n \"answer\": { \"selected\": [\"opt_0\"] },\n \"idempotency_key\": \"answer-skc-demo-1\",\n \"allow_mutation\": true\n}\n```\n\n`skc_coordinator_submit_question_answer` requires `session_id`, `turn_id`, `question_id`, `answer_binding`, `answer`, `idempotency_key`, and `allow_mutation: true`; it resolves through `workflow.gate_answer`, never generic `ask.answer`. It revalidates against a complete fresh snapshot after restart and before resolution. Incomplete reconciliation returns `terminal_uncertain`; stale, terminal, absent, or ownership-mismatched rows are not answerable. Retry only an identical request with the same idempotency key: it replays the accepted result; reusing that key with conflicting arguments returns `idempotency_conflict`. Always answer the advertised shape; do not synthesize destructive approvals unless bot policy permits them.\n\nThis Coordinator MCP pull loop is separate from #2549/#2551 and unattended plain-CLI behavior; those paths do not gain coordinator gate access.\n\n### Read artifacts and reports\n\nUse `skc_coordinator_list_artifacts` to inspect safe roots and `skc_coordinator_read_artifact` to read a bounded artifact:\n\n```json\n{ \"path\": \"/path/to/repo/.skc/ultragoal/ledger.jsonl\" }\n```\n\nArtifact paths are canonicalized, symlink escapes are rejected, and output is byte-capped. Use `skc_coordinator_read_coordination_status` for status reports written through `skc_coordinator_report_status`.\n\n## SDK WebSocket integration\n\nUse the SDK when your bot owns a single live session rather than an MCP coordinator. Each running session exposes a loopback WebSocket endpoint discovered via `.skc/state/sdk/<sessionId>.json`; the wire protocol (state queries, control operations, event subscription and replay, workflow-gate replies, reverse host-tool leases) is documented in [`docs/sdk.md`](./sdk.md).\n\nKey SDK workflow-gate facts:\n- The discovery file carries the endpoint URL and per-session token; a wrong\n token is rejected at the WebSocket handshake. `server_hello` marks a\n connection ready, and `skc daemon session control|query|global` uses the same\n protocol for shell scripts.\n\n- `action_needed.id` is an opaque, transient presentation ID. It is the only\n generic `reply.id` authority. Do not equate it with a durable workflow gate.\n- A durable workflow-gate presentation optionally includes additive SDK v3 `workflowGateId`. It correlates to Q12's durable `gate_id` only within `(sessionId, workflowGateId)` on the current authenticated endpoint; it never authorizes generic reply.\n- `workflow.gate_answer` and `workflow.plan_approve` use the durable `gate_id`. `expectedSessionId` omission remains accepted and audited for the entire SDK v3 line so deployed v3 clients continue to work, but new clients must send it. Mandatory enforcement or removal may occur no earlier than SDK v4 and only after at least one full published deprecation release/window with deployed-client notice. A supplied session mismatch is rejected before resolution.\n- One session has one active answerable presentation. Additional Q12 gates stay queued while Q12 exposes durable pending records and additive SDK v3 diagnostics. A same-server reconnect replays the active action ID; a process restart quarantines old records and a rebuilt workflow remints fresh gate and presentation IDs.\n- A native generic reply claim wins a direct-control race once acquired; a direct control wins only by atomically retiring the exact unclaimed active presentation. Terminal, stale, and reissued action IDs never regain authority. Do not use text, option/order, durable-ID, or history heuristics, and fail closed rather than guess when identity is unsafe or ambiguous. Do not persist private route/claim/receipt/epoch/generation state.\n- Rust/N-API compatibility is additive: legacy `ActionNeeded`, `register_ask`,\n and `registerAsk` stay uncorrelated; explicit workflow reader/registration\n APIs preserve correlation without exposing private arbitration state.\n- The `@sayknow-cli/coding-agent` runtime and `@sayknow-cli/natives` native addon ship from the same source release at exact matching package versions; the native loader version sentinel enforces the pair. Mixed native/runtime versions are unsupported and cannot claim SDK compatibility.\n\nThe prior documented invariant `action_needed.id == gate_id` is incorrect for\nv3 and must not be implemented by controllers. See [`docs/sdk.md`](./sdk.md)\nfor exact wire examples, Q12 tags/lifecycle diagnostics, and control payloads.\n\n`--mode rpc`, `--mode rpc-ui`, and `--mode bridge` have been removed along with their JSONL/HTTPS protocols and the former Python RPC client. There are no compatibility shims; migrate controllers to the SDK endpoint or Coordinator MCP.\n\n## Error handling playbook\n\n| Situation | Bot behavior |\n| --- | --- |\n| `coordinator_mutation_class_disabled:*` | Re-render setup with the required mutation class, or keep the bot in read-only mode. |\n| `coordinator_mutation_call_not_allowed:*` | Add `allow_mutation: true` only after policy approval for that specific call. |\n| `unknown_session` | Re-list sessions; start a new managed session or register a session after its SDK endpoint is discoverable. |\n| `active_turn_exists` | Poll the active turn, send with `queue: true`, or use `force: true` only when supersession is intentional. |\n| `timeout` from `await_turn` | Treat as non-terminal. Poll again or inspect `read_status`; do not mark failure solely from a bounded wait timeout. |\n| Coordinator cancellation | Use `skc_coordinator_report_status` with `status: \"cancelled\"` for an intentionally stopped turn, or send replacement work with `force: true` when supersession is policy-approved. This is coordinator state, not process control. |\n| Stale session state | Check `read_status.session_state` and SDK endpoint discovery. Register a new discoverable session or report the turn failed with a recoverable blocker. |\n| Provider/auth failure | Capture the model/provider error in `report_status` with `status: \"failed\"`; do not retry forever without a policy budget. |\n| Artifact denied | Keep the artifact inside allowlisted roots and avoid symlink escapes. |\n| Malformed or invalid question answer | Re-read the question/gate schema and submit a value matching the advertised shape. |\n| Bot shutdown | Persist `session_id` and active `turn_id`; on restart use `read_turn` and `read_status` before sending more work. |\n\n## Controller examples\n\nGeneric MCP controller config:\n\n```json\n{\n \"mcp_servers\": {\n \"skc_coordinator\": {\n \"command\": \"skc\",\n \"args\": [\"mcp-serve\", \"coordinator\"],\n \"env\": {\n \"SKC_COORDINATOR_MCP_WORKDIR_ROOTS\": \"/home/bot/src/project:/home/bot/src/worktrees\",\n \"SKC_COORDINATOR_MCP_MUTATIONS\": \"sessions,questions,reports\",\n \"SKC_COORDINATOR_MCP_PROFILE\": \"controller-prod\",\n \"SKC_COORDINATOR_MCP_REPO\": \"project\",\n \"SKC_COORDINATOR_MCP_SESSION_COMMAND\": \"skc --worktree\"\n },\n \"enabled\": true\n }\n }\n}\n```\n\nExample controller loop:\n\n```text\n1. Start `skc mcp-serve coordinator` with repo/worktree roots allowlisted.\n2. Call `skc_coordinator_start_session` for a SKC-managed worktree session.\n3. Send `/skill:deep-interview`, `/skill:ralplan`, or an approved `skc ultragoal ...` task as one turn.\n4. Await the turn; answer `skc_coordinator_list_questions` entries using bot policy.\n5. Report terminal status with evidence paths.\n6. Read artifacts/reports for the user-facing bot response.\n```\n\nHermes and OpenClaw can use the same MCP tool contract. Their names here are examples of controller products, not privileged integration modes.\n\n## Security and credential boundaries\n\n- Do not put provider API keys, GitHub tokens, or bot secrets in prompts.\n- Prefer host tools, host URI schemes, or bot-side sidecars for credentialed external writes.\n- Keep `SKC_COORDINATOR_MCP_WORKDIR_ROOTS` narrow; do not allow `/`, `/home`, or broad parent directories.\n- Use namespaces for multi-tenant bots.\n- Keep mutation classes minimal: read-only for dashboards, `sessions` for work dispatch, `questions` for answering questions, and `reports` for final state.\n- Treat `.skc/` as local runtime state and evidence. Do not expose it wholesale to untrusted users.\n\n## Related references\n\n- [`docs/hermes-mcp-bridge.md`](./hermes-mcp-bridge.md) — coordinator MCP details and setup adapter behavior.\n- [`docs/sdk.md`](./sdk.md) — SDK wire protocol, event frames, workflow gates, host tools, and host URI schemes.\n- [`docs/external-control-readiness.md`](./external-control-readiness.md) — readiness classification of the supported external-control surfaces.\n",