@skaile/workspaces 4.16.3 → 4.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/{asset-feeds-XBSARE5D.js → asset-feeds-MQKQDF3R.js} +4 -4
  3. package/dist/{asset-feeds-XBSARE5D.js.map → asset-feeds-MQKQDF3R.js.map} +1 -1
  4. package/dist/asset-manager/index.js +1 -1
  5. package/dist/bridge/drivers/claude-sdk.js +6 -4
  6. package/dist/bridge/drivers/claude-sdk.js.map +1 -1
  7. package/dist/bridge/drivers/codex.js +3 -2
  8. package/dist/bridge/drivers/codex.js.map +1 -1
  9. package/dist/bridge/drivers/continue.js +3 -3
  10. package/dist/bridge/drivers/echo.js +1 -1
  11. package/dist/bridge/drivers/gemini.js +5 -5
  12. package/dist/bridge/drivers/goose.js +3 -3
  13. package/dist/bridge/drivers/omp.js +3 -2
  14. package/dist/bridge/drivers/omp.js.map +1 -1
  15. package/dist/bridge/drivers/opencode.js +3 -3
  16. package/dist/bridge/drivers/qwen.js +5 -5
  17. package/dist/bridge/index.js +4 -4
  18. package/dist/bridge/src/agent-exec.d.ts +34 -0
  19. package/dist/bridge/src/agent-exec.d.ts.map +1 -0
  20. package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
  21. package/dist/bridge/src/drivers/codex.d.ts.map +1 -1
  22. package/dist/bridge/src/drivers/omp.d.ts.map +1 -1
  23. package/dist/bridge/src/index.d.ts +1 -0
  24. package/dist/bridge/src/index.d.ts.map +1 -1
  25. package/dist/{chunk-76IGAJ47.js → chunk-2AQIFJHK.js} +3 -3
  26. package/dist/{chunk-76IGAJ47.js.map → chunk-2AQIFJHK.js.map} +1 -1
  27. package/dist/{chunk-OWMHVP6Q.js → chunk-3H4HP733.js} +8 -8
  28. package/dist/{chunk-OWMHVP6Q.js.map → chunk-3H4HP733.js.map} +1 -1
  29. package/dist/{chunk-ZCKQQJ7K.js → chunk-3VGQLF3N.js} +2 -2
  30. package/dist/{chunk-ZCKQQJ7K.js.map → chunk-3VGQLF3N.js.map} +1 -1
  31. package/dist/{chunk-4SIMGJIU.js → chunk-3W7AOGPY.js} +19 -4
  32. package/dist/chunk-3W7AOGPY.js.map +1 -0
  33. package/dist/{chunk-GGRHNBUP.js → chunk-4RKCOURU.js} +3 -3
  34. package/dist/{chunk-GGRHNBUP.js.map → chunk-4RKCOURU.js.map} +1 -1
  35. package/dist/{chunk-VIX4AEVZ.js → chunk-6F4TIY7X.js} +4 -4
  36. package/dist/{chunk-VIX4AEVZ.js.map → chunk-6F4TIY7X.js.map} +1 -1
  37. package/dist/{chunk-BWWNJLXJ.js → chunk-7EAJNEQ5.js} +6 -6
  38. package/dist/{chunk-BWWNJLXJ.js.map → chunk-7EAJNEQ5.js.map} +1 -1
  39. package/dist/{chunk-5OAMRXJZ.js → chunk-AAZDYM5D.js} +3 -3
  40. package/dist/{chunk-5OAMRXJZ.js.map → chunk-AAZDYM5D.js.map} +1 -1
  41. package/dist/{chunk-WTUHM2NJ.js → chunk-AOFJ2OKW.js} +2 -2
  42. package/dist/{chunk-WTUHM2NJ.js.map → chunk-AOFJ2OKW.js.map} +1 -1
  43. package/dist/{chunk-3MRCJJSH.js → chunk-C3YE4REG.js} +3 -3
  44. package/dist/{chunk-3MRCJJSH.js.map → chunk-C3YE4REG.js.map} +1 -1
  45. package/dist/{chunk-LPPRZAO5.js → chunk-D5CRFGDL.js} +3 -3
  46. package/dist/{chunk-LPPRZAO5.js.map → chunk-D5CRFGDL.js.map} +1 -1
  47. package/dist/{chunk-B6IDJRRZ.js → chunk-JURHZYOY.js} +3 -3
  48. package/dist/{chunk-B6IDJRRZ.js.map → chunk-JURHZYOY.js.map} +1 -1
  49. package/dist/{chunk-UBDQFZZH.js → chunk-NYDTZ2MK.js} +5 -5
  50. package/dist/{chunk-UBDQFZZH.js.map → chunk-NYDTZ2MK.js.map} +1 -1
  51. package/dist/{chunk-W4AEVRUC.js → chunk-RAHLV6QG.js} +6 -6
  52. package/dist/{chunk-W4AEVRUC.js.map → chunk-RAHLV6QG.js.map} +1 -1
  53. package/dist/{chunk-I66MW6OR.js → chunk-WOE4LPGF.js} +3 -3
  54. package/dist/{chunk-I66MW6OR.js.map → chunk-WOE4LPGF.js.map} +1 -1
  55. package/dist/{chunk-7GCOHM2S.js → chunk-XRTOSEF3.js} +2 -2
  56. package/dist/{chunk-7GCOHM2S.js.map → chunk-XRTOSEF3.js.map} +1 -1
  57. package/dist/{chunk-N5YUCSMA.js → chunk-YXXEHY7D.js} +3 -3
  58. package/dist/{chunk-N5YUCSMA.js.map → chunk-YXXEHY7D.js.map} +1 -1
  59. package/dist/{chunk-SNW3UR3K.js → chunk-Z7KDOGKF.js} +6 -6
  60. package/dist/{chunk-SNW3UR3K.js.map → chunk-Z7KDOGKF.js.map} +1 -1
  61. package/dist/cli/index.js +32 -32
  62. package/dist/connectors/index.js +5 -5
  63. package/dist/{ensure-sources-PTZJZE56.js → ensure-sources-6XKA46PN.js} +4 -4
  64. package/dist/{ensure-sources-PTZJZE56.js.map → ensure-sources-6XKA46PN.js.map} +1 -1
  65. package/dist/factory-assets/connectors/box.js +5 -5
  66. package/dist/factory-assets/connectors/deploy.js +5 -5
  67. package/dist/factory-assets/connectors/devserver.js +5 -5
  68. package/dist/factory-assets/connectors/flow/adapter.js +5 -5
  69. package/dist/factory-assets/connectors/flow/run-flow.js +6 -6
  70. package/dist/factory-assets/connectors/flow.js +5 -5
  71. package/dist/factory-assets/connectors/git.js +5 -5
  72. package/dist/factory-assets/connectors/gmail.js +5 -5
  73. package/dist/factory-assets/connectors/googledrive.js +5 -5
  74. package/dist/factory-assets/connectors/local.js +5 -5
  75. package/dist/factory-assets/connectors/mattermost.js +5 -5
  76. package/dist/factory-assets/connectors/memory.js +5 -5
  77. package/dist/factory-assets/connectors/minio.js +5 -5
  78. package/dist/factory-assets/connectors/postgres.js +5 -5
  79. package/dist/factory-assets/connectors/s3.js +5 -5
  80. package/dist/factory-assets/connectors/sharepoint.js +5 -5
  81. package/dist/factory-assets/connectors/sqlite.js +5 -5
  82. package/dist/factory-assets/connectors/static-server.js +5 -5
  83. package/dist/factory-assets/connectors/tunnel.js +5 -5
  84. package/dist/factory-assets/connectors/webdav.js +5 -5
  85. package/dist/factory-assets/connectors/xstate-store.js +5 -5
  86. package/dist/factory-assets/connectors/xstate.js +5 -5
  87. package/dist/{helpers-TPVJ6XTD.js → helpers-6I4SY2S7.js} +4 -4
  88. package/dist/{helpers-TPVJ6XTD.js.map → helpers-6I4SY2S7.js.map} +1 -1
  89. package/dist/{library-publish-4XE5BQTE.js → library-publish-PPNFBAVH.js} +6 -6
  90. package/dist/{library-publish-4XE5BQTE.js.map → library-publish-PPNFBAVH.js.map} +1 -1
  91. package/dist/{open-library-WFTFVJ67.js → open-library-64LO64NE.js} +5 -5
  92. package/dist/{open-library-WFTFVJ67.js.map → open-library-64LO64NE.js.map} +1 -1
  93. package/dist/{project-FI5A4E7X.js → project-3UFTV7DL.js} +5 -5
  94. package/dist/{project-FI5A4E7X.js.map → project-3UFTV7DL.js.map} +1 -1
  95. package/dist/runner/index.js +8 -8
  96. package/dist/sdk/asset-manager.js +1 -1
  97. package/dist/sdk/bridge.js +4 -4
  98. package/dist/sdk/index.js +8 -8
  99. package/dist/sdk/runner.js +8 -8
  100. package/dist/{setup-EDSTI5LM.js → setup-JGXLTJ57.js} +9 -9
  101. package/dist/{setup-EDSTI5LM.js.map → setup-JGXLTJ57.js.map} +1 -1
  102. package/dist/{source-7VNEUEGO.js → source-NHEYY7WH.js} +6 -6
  103. package/dist/{source-7VNEUEGO.js.map → source-NHEYY7WH.js.map} +1 -1
  104. package/dist/{source-manifest-publish-SQ2SXJEA.js → source-manifest-publish-IJLVR3IL.js} +7 -7
  105. package/dist/{source-manifest-publish-SQ2SXJEA.js.map → source-manifest-publish-IJLVR3IL.js.map} +1 -1
  106. package/dist/tui/index.js +8 -8
  107. package/dist/workspace-plug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iBAAiB,CAAA;AAC3B","file":"setup-EDSTI5LM.js","sourcesContent":["/**\n * skaile setup — interactive AI provider setup wizard.\n *\n * Front-end over `skaile providers add` and `skaile config`: it discovers what\n * is already configured, picks endpoints out of the catalog, writes them to\n * `~/.skaile/providers.yml` with `env:` credential references, and saves the\n * driver plus one namespaced model selector to `skaile.yaml` or\n * `.skaile/settings.json`.\n *\n * It never stores a secret. The registry holds a reference; the value goes to\n * a `.env` file or stays in the operator's shell.\n *\n * @see PROVIDER-CONFIG-PLAN.md §1.6, §2.5\n */\n\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport * as p from \"@clack/prompts\";\nimport {\n type AIProviderPreset,\n getModels,\n listProviderPresets,\n validateApiKey,\n} from \"@skaile/workspaces/bridge\";\nimport {\n loadSettings,\n maskApiKey,\n projectSettingsPath,\n resolveSettings,\n type SkaileSettings,\n saveSettings,\n WorkspaceYamlEditor,\n} from \"@skaile/workspaces/core\";\nimport {\n addProviderEntry,\n credentialEnvVarName,\n loadRegistryView,\n ProviderRegistryWriteError,\n} from \"./commands/providers.ts\";\n\n// ---------------------------------------------------------------------------\n// Catalog\n// ---------------------------------------------------------------------------\n\n/** LLM presets, in catalog order — the wizard never shows voice endpoints. */\nfunction llmPresets(): AIProviderPreset[] {\n return listProviderPresets().filter((preset) => preset.kind === \"llm\");\n}\n\n/** Where the operator gets a key, for the presets that have a console. */\nconst PRESET_KEY_URLS: Record<string, string> = {\n anthropic: \"https://console.anthropic.com/settings/keys\",\n openai: \"https://platform.openai.com/api-keys\",\n google: \"https://aistudio.google.com/apikey\",\n mistral: \"https://console.mistral.ai/api-keys\",\n groq: \"https://console.groq.com/keys\",\n openrouter: \"https://openrouter.ai/settings/keys\",\n deepseek: \"https://platform.deepseek.com/api_keys\",\n xai: \"https://console.x.ai/\",\n together: \"https://api.together.ai/settings/api-keys\",\n fireworks: \"https://fireworks.ai/api-keys\",\n};\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Where a freshly entered secret is written — never `settings.json`. */\nexport type SecretTarget = \"env-project\" | \"env-global\" | \"skip\";\nexport type DefaultsTarget = \"project\" | \"personal\";\n\n/** One endpoint the wizard will make sure exists in the registry. */\nexport interface ProviderChoice {\n /** Catalog preset id; also the registry entry id. */\n id: string;\n /** Env var the entry's `credential.ref` points at. */\n envVar: string;\n /** A secret the operator just typed, if any. */\n secret?: string;\n /** The registry already has this entry with this reference. */\n satisfied: boolean;\n}\n\n/** The wizard's answers, in the order {@link applySetupPlan} writes them. */\nexport interface SetupPlan {\n providers: ProviderChoice[];\n secretTarget: SecretTarget;\n defaultsTarget: DefaultsTarget;\n /** `<providerId>/<modelId>` — what lands in `model:`. */\n modelRef: string;\n driver: string;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction exitOnCancel<T>(value: T): asserts value is Exclude<T, symbol> {\n if (p.isCancel(value)) {\n p.cancel(\"Setup cancelled.\");\n process.exit(0);\n }\n}\n\n/** Load .env files from common locations and parse key=value pairs */\nfunction loadDotenvKeys(): Record<string, string> {\n const locations = [path.join(process.cwd(), \".env\"), path.join(os.homedir(), \".env\")];\n const result: Record<string, string> = {};\n for (const loc of locations) {\n try {\n const content = fs.readFileSync(loc, \"utf-8\");\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eq = trimmed.indexOf(\"=\");\n if (eq === -1) continue;\n const key = trimmed.slice(0, eq).trim();\n let val = trimmed.slice(eq + 1).trim();\n // Strip surrounding quotes\n if (\n (val.startsWith('\"') && val.endsWith('\"')) ||\n (val.startsWith(\"'\") && val.endsWith(\"'\"))\n ) {\n val = val.slice(1, -1);\n }\n result[key] = val;\n }\n } catch {\n // file doesn't exist, skip\n }\n }\n return result;\n}\n\n/** Append key=value entries to a .env file without overwriting existing keys */\nfunction appendEnvFile(filePath: string, entries: Record<string, string>): void {\n let existing = \"\";\n try {\n existing = fs.readFileSync(filePath, \"utf-8\");\n } catch {\n // file doesn't exist yet\n }\n\n const existingKeys = new Set<string>();\n for (const line of existing.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eq = trimmed.indexOf(\"=\");\n if (eq !== -1) existingKeys.add(trimmed.slice(0, eq).trim());\n }\n\n const lines: string[] = [];\n for (const [key, value] of Object.entries(entries)) {\n if (existingKeys.has(key)) {\n p.log.warn(` ${key} already exists in ${filePath} — skipping`);\n continue;\n }\n lines.push(`${key}=${value}`);\n }\n\n if (lines.length === 0) return;\n\n const separator = existing.endsWith(\"\\n\") || existing === \"\" ? \"\" : \"\\n\";\n const content = `${separator + lines.join(\"\\n\")}\\n`;\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.appendFileSync(filePath, content, \"utf-8\");\n}\n\n/** The env var a preset's credential conventionally lives in. */\nfunction presetEnvVar(preset: AIProviderPreset): string {\n return preset.credential.env ?? `${preset.id.toUpperCase().replace(/[^A-Z0-9]/g, \"_\")}_API_KEY`;\n}\n\n/** Entries already in the registry, keyed by id, with their `env:` var name. */\nfunction configuredEntries(projectDir: string): Record<string, string | undefined> {\n const view = loadRegistryView({ projectDir });\n const out: Record<string, string | undefined> = {};\n for (const id of view.merged.order) {\n out[id] = credentialEnvVarName(view.merged.providers[id]);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Wizard steps\n// ---------------------------------------------------------------------------\n\nfunction showCurrentState(\n settings: SkaileSettings,\n configured: Record<string, string | undefined>,\n env: Record<string, string>,\n): void {\n const lines: string[] = [\"Configured providers (~/.skaile/providers.yml):\"];\n const ids = Object.keys(configured);\n if (ids.length === 0) {\n lines.push(\" (none)\");\n } else {\n for (const id of ids) {\n const envVar = configured[id];\n const value = envVar ? env[envVar] : undefined;\n lines.push(\n ` ${id.padEnd(14)} ${envVar ?? \"no credential ref\"}` +\n (value ? ` ${maskApiKey(value)}` : envVar ? \" (not set in this environment)\" : \"\"),\n );\n }\n }\n lines.push(\"\");\n lines.push(\"Current defaults:\");\n lines.push(` Model: ${settings.model ?? \"(not set)\"}`);\n lines.push(` Driver: ${settings.driver ?? \"(not set)\"}`);\n\n p.note(lines.join(\"\\n\"), \"Current configuration\");\n}\n\nasync function selectPresets(\n configured: Record<string, string | undefined>,\n env: Record<string, string>,\n): Promise<AIProviderPreset[]> {\n const presets = llmPresets();\n const result = await p.multiselect({\n message: \"Which providers do you want to configure?\",\n options: presets.map((preset) => ({\n value: preset.id,\n label: preset.label,\n hint: configured[preset.id]\n ? \"configured\"\n : env[presetEnvVar(preset)]\n ? `${presetEnvVar(preset)} is set`\n : undefined,\n })),\n initialValues: presets\n .filter((preset) => configured[preset.id] || env[presetEnvVar(preset)])\n .map((preset) => preset.id),\n required: true,\n });\n exitOnCancel(result);\n const chosen = new Set(result as string[]);\n return presets.filter((preset) => chosen.has(preset.id));\n}\n\n/**\n * Run the optional validation step for a freshly entered key.\n * Returns true if the key should be kept (valid, or user opted to keep anyway),\n * false if it should be discarded.\n */\nasync function confirmKeyAfterValidation(provider: string, key: string): Promise<boolean> {\n const shouldValidate = await p.confirm({ message: \"Validate this key?\", initialValue: true });\n exitOnCancel(shouldValidate);\n if (!shouldValidate) return true;\n\n const s = p.spinner();\n s.start(`Validating ${provider} key...`);\n const result = await validateApiKey(provider, key);\n if (result.ok) {\n s.stop(`${provider} key is valid`);\n return true;\n }\n s.stop(`${provider} validation failed: ${result.error}`);\n const retry = await p.confirm({ message: \"Use this key anyway?\", initialValue: false });\n exitOnCancel(retry);\n return retry;\n}\n\n/**\n * Decide what one provider needs: the env var its credential reference points\n * at, and — only when that variable is not already populated — the secret to\n * put in it.\n */\nasync function collectProvider(\n preset: AIProviderPreset,\n configured: Record<string, string | undefined>,\n env: Record<string, string>,\n): Promise<ProviderChoice> {\n const envVar = configured[preset.id] ?? presetEnvVar(preset);\n const known = env[envVar];\n\n if (preset.credential.kind !== \"api_key_header\" && preset.credential.kind !== \"bearer\") {\n // sigv4 / google_adc / azure_entra / none — nothing to type in.\n p.log.info(`${preset.label}: credential comes from ${preset.credential.kind}, no key needed`);\n return { id: preset.id, envVar, satisfied: !!configured[preset.id] };\n }\n\n if (known) {\n p.log.info(`${preset.label}: ${envVar} is already set (${maskApiKey(known)})`);\n return { id: preset.id, envVar, satisfied: !!configured[preset.id] };\n }\n\n const keyUrl = PRESET_KEY_URLS[preset.id];\n const key = await p.password({\n message: `${preset.label} API key${keyUrl ? ` (get one at ${keyUrl})` : \"\"}, or leave blank to set ${envVar} yourself:`,\n });\n exitOnCancel(key);\n if (!key) return { id: preset.id, envVar, satisfied: !!configured[preset.id] };\n\n const keep = await confirmKeyAfterValidation(preset.id, key as string);\n if (!keep) return { id: preset.id, envVar, satisfied: !!configured[preset.id] };\n return { id: preset.id, envVar, secret: key as string, satisfied: !!configured[preset.id] };\n}\n\nasync function selectSecretTarget(): Promise<SecretTarget> {\n const result = await p.select({\n message: \"Where should the secrets be written? (skaile stores only the variable name)\",\n options: [\n { value: \"env-project\" as const, label: `${process.cwd()}/.env (project-level)` },\n { value: \"env-global\" as const, label: `${os.homedir()}/.env (global)` },\n { value: \"skip\" as const, label: \"Skip — I'll export the variables myself\" },\n ],\n });\n exitOnCancel(result);\n return result as SecretTarget;\n}\n\nasync function selectDefaultProvider(choices: ProviderChoice[], current?: string): Promise<string> {\n if (choices.length === 1) return choices[0].id;\n const initial = choices.find((choice) => current?.startsWith(`${choice.id}/`))?.id;\n const result = await p.select({\n message: \"Which provider should the default model come from?\",\n options: choices.map((choice) => ({ value: choice.id, label: choice.id })),\n initialValue: initial ?? choices[0].id,\n });\n exitOnCancel(result);\n return result as string;\n}\n\n/**\n * Pick the model id for `providerId`, returning the namespaced selector.\n * A live list needs a key; without one the built-in catalog is offered.\n */\nasync function selectModelRef(\n providerId: string,\n current?: string,\n apiKey?: string,\n): Promise<string> {\n const currentModel = current?.startsWith(`${providerId}/`)\n ? current.slice(providerId.length + 1)\n : undefined;\n\n const s = apiKey ? p.spinner() : undefined;\n if (s) s.start(`Fetching models from ${providerId}...`);\n const fetchResult = await getModels(providerId, apiKey);\n if (s) {\n if (fetchResult.source === \"api\") {\n s.stop(`Loaded ${fetchResult.models.length} models from ${providerId}`);\n } else if (fetchResult.error) {\n s.stop(`Could not fetch live models (${fetchResult.error}) — using built-in catalog`);\n } else {\n s.stop(\"Using built-in model catalog\");\n }\n }\n\n const models = fetchResult.models;\n if (models.length === 0) {\n p.log.warn(`No models found for ${providerId} — enter a model id manually`);\n const result = await p.text({ message: \"Model id:\", initialValue: currentModel ?? \"\" });\n exitOnCancel(result);\n return `${providerId}/${result as string}`;\n }\n\n const result = await p.select({\n message: `Default model (${providerId}):`,\n options: models.map((m) => ({ value: m.id, label: `${m.name} (${m.id})` })),\n initialValue:\n currentModel && models.some((m) => m.id === currentModel) ? currentModel : models[0].id,\n });\n exitOnCancel(result);\n return `${providerId}/${result as string}`;\n}\n\nasync function selectDriver(current?: string): Promise<string> {\n const result = await p.select({\n message: \"Default agent driver:\",\n options: [\n { value: \"omp\", label: \"omp (oh-my-pi — multi-provider, recommended)\" },\n { value: \"claude-sdk\", label: \"claude-sdk (Anthropic Agent SDK, Claude only)\" },\n { value: \"codex\", label: \"codex (OpenAI Codex SDK, OpenAI only)\" },\n ],\n initialValue: current ?? \"omp\",\n });\n exitOnCancel(result);\n return result as string;\n}\n\nasync function selectDefaultsTarget(projectDir: string): Promise<DefaultsTarget> {\n if (!fs.existsSync(path.join(projectDir, \"skaile.yaml\"))) return \"personal\";\n\n const result = await p.select({\n message: \"Where should the driver and model selector be saved?\",\n options: [\n {\n value: \"project\" as const,\n label: \"skaile.yaml (project-wide, shared with team)\",\n hint: \"recommended\",\n },\n { value: \"personal\" as const, label: \".skaile/settings.json (personal only, gitignored)\" },\n ],\n initialValue: \"project\" as const,\n });\n exitOnCancel(result);\n return result as DefaultsTarget;\n}\n\n/** Build the human-readable summary shown before applying the plan. */\nfunction buildSummaryLines(plan: SetupPlan, settingsFile: string): string[] {\n const lines: string[] = [\"Providers (~/.skaile/providers.yml):\"];\n for (const choice of plan.providers) {\n lines.push(\n ` ${choice.id.padEnd(14)} credential env:${choice.envVar}` +\n (choice.satisfied ? \" (already configured)\" : \"\"),\n );\n }\n\n const withSecrets = plan.providers.filter((choice) => choice.secret);\n if (withSecrets.length > 0) {\n const targetLabels: Record<SecretTarget, string> = {\n \"env-project\": `${process.cwd()}/.env`,\n \"env-global\": `${os.homedir()}/.env`,\n skip: \"not saved (export them yourself)\",\n };\n lines.push(\"\");\n lines.push(\"Secrets:\");\n for (const choice of withSecrets) {\n lines.push(` ${choice.envVar.padEnd(24)} ${maskApiKey(choice.secret ?? \"\")}`);\n }\n lines.push(` Written to: ${targetLabels[plan.secretTarget]}`);\n }\n\n lines.push(\"\");\n lines.push(\"Defaults:\");\n lines.push(` Model: ${plan.modelRef}`);\n lines.push(` Driver: ${plan.driver}`);\n lines.push(\n ` Saved to: ${plan.defaultsTarget === \"project\" ? \"skaile.yaml (project-wide)\" : settingsFile}`,\n );\n return lines;\n}\n\n/**\n * Create or update each chosen registry entry through the same write path as\n * `skaile providers add`. An entry that already points at the chosen variable\n * is left exactly as it is — the operator may have tuned its base URL or model\n * map, and re-running the wizard must not undo that.\n */\nfunction persistProviders(plan: SetupPlan, projectDir: string): void {\n for (const choice of plan.providers) {\n if (choice.satisfied) {\n p.log.info(`${choice.id}: keeping the existing registry entry`);\n continue;\n }\n try {\n const added = addProviderEntry({\n id: choice.id,\n presetId: choice.id,\n credentialRef: `env:${choice.envVar}`,\n projectDir,\n force: true,\n });\n p.log.success(`${choice.id} → ${added.path}`);\n } catch (error) {\n if (!(error instanceof ProviderRegistryWriteError)) throw error;\n p.log.error(`${choice.id}: ${error.message}`);\n }\n }\n}\n\n/** Write the secrets the operator typed to the chosen `.env` file. */\nfunction persistSecrets(plan: SetupPlan): void {\n const entries: Record<string, string> = {};\n for (const choice of plan.providers) {\n if (choice.secret) entries[choice.envVar] = choice.secret;\n }\n if (Object.keys(entries).length === 0) return;\n\n if (plan.secretTarget === \"skip\") {\n p.log.info(\n `Export these before starting a session: ${Object.keys(entries)\n .map((name) => `${name}=…`)\n .join(\" \")}`,\n );\n return;\n }\n const file =\n plan.secretTarget === \"env-project\"\n ? path.join(process.cwd(), \".env\")\n : path.join(os.homedir(), \".env\");\n appendEnvFile(file, entries);\n p.log.success(`Appended ${Object.keys(entries).length} variable(s) to ${file}`);\n}\n\n/**\n * Apply the plan's defaults: write them to skaile.yaml when saving project-wide,\n * and set/strip the corresponding personal settings fields on `merged` (mutated\n * in place) so they don't shadow project-wide values.\n */\nfunction applyDefaults(plan: SetupPlan, projectDir: string, merged: SkaileSettings): void {\n if (plan.defaultsTarget === \"project\") {\n const yamlPath = path.join(projectDir, \"skaile.yaml\");\n const editor = WorkspaceYamlEditor.load(yamlPath);\n editor.setAgentConfig(\"default\", { model: plan.modelRef, driver: plan.driver });\n editor.save();\n p.log.success(`Saved defaults to ${yamlPath}`);\n delete merged.model;\n delete merged.driver;\n return;\n }\n merged.model = plan.modelRef;\n merged.driver = plan.driver;\n}\n\n/**\n * Everything the wizard writes, once the operator has approved the plan:\n * registry entries, `.env` secrets, and the defaults.\n *\n * Separate from the prompting so the wizard's effect on disk is exercisable\n * without a terminal — and so there is exactly one place that writes.\n */\nexport async function applySetupPlan(plan: SetupPlan, projectDir: string): Promise<void> {\n const settingsFile = projectSettingsPath(projectDir);\n persistProviders(plan, projectDir);\n persistSecrets(plan);\n\n const merged: SkaileSettings = { ...(await loadSettings(settingsFile)) };\n applyDefaults(plan, projectDir, merged);\n await saveSettings(merged, settingsFile);\n p.log.success(`Saved settings to ${settingsFile}`);\n}\n\nasync function reviewAndSave(plan: SetupPlan, projectDir: string): Promise<void> {\n p.note(buildSummaryLines(plan, projectSettingsPath(projectDir)).join(\"\\n\"), \"Summary\");\n\n const confirmed = await p.confirm({ message: \"Apply these settings?\", initialValue: true });\n exitOnCancel(confirmed);\n if (!confirmed) {\n p.cancel(\"Setup cancelled — no changes were made.\");\n process.exit(0);\n }\n\n await applySetupPlan(plan, projectDir);\n}\n\n// ---------------------------------------------------------------------------\n// Main entry\n// ---------------------------------------------------------------------------\n\n/** Check whether Claude Code OAuth credentials exist on disk */\nfunction hasClaudeCodeCredentials(): boolean {\n const credPath = path.join(os.homedir(), \".claude\", \".credentials.json\");\n try {\n const parsed = JSON.parse(fs.readFileSync(credPath, \"utf-8\"));\n return parsed && (parsed.accessToken || parsed.refreshToken || parsed.oauthToken);\n } catch {\n return false;\n }\n}\n\n/** The presets a driver can actually talk to (§2.3 plurality). */\nfunction presetsForDriver(driver: string): AIProviderPreset[] | undefined {\n if (driver === \"claude-sdk\") return llmPresets().filter((preset) => preset.id === \"anthropic\");\n if (driver === \"codex\") return llmPresets().filter((preset) => preset.id === \"openai\");\n return undefined;\n}\n\n/**\n * Interactive provider setup wizard: discovers what the AI provider registry\n * already holds, adds the endpoints the operator picks (credential references\n * only), and writes the driver plus a `<providerId>/<modelId>` selector to\n * `skaile.yaml` or `.skaile/settings.json`.\n *\n * @param _args - Unused positional args (reserved for future use).\n * @param opts - Options including an optional `projectDir` override.\n * @docLink cli/dev-guide#setup\n */\nexport async function cmdSetup(_args: string[], opts: { projectDir?: string }): Promise<void> {\n p.intro(\"skaile setup\");\n\n const projectDir = opts.projectDir ?? process.cwd();\n\n let settings: SkaileSettings;\n try {\n settings = await resolveSettings(projectDir);\n } catch (error) {\n // A pre-registry skaile.yaml cannot be read at all — say so once, with the\n // command that fixes it, instead of walking the operator through a wizard\n // whose result the file would reject.\n p.cancel(error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n\n const env = { ...loadDotenvKeys(), ...process.env } as Record<string, string>;\n const configured = configuredEntries(projectDir);\n showCurrentState(settings, configured, env);\n\n // The driver comes first: it decides which endpoints are even selectable.\n const driver = await selectDriver(settings.driver);\n const forced = presetsForDriver(driver);\n if (forced && driver === \"claude-sdk\" && !env.ANTHROPIC_API_KEY && hasClaudeCodeCredentials()) {\n p.log.info(\"Claude Code subscription detected — the SDK can use that login instead of a key.\");\n }\n const presets = forced ?? (await selectPresets(configured, env));\n\n const providers: ProviderChoice[] = [];\n for (const preset of presets) {\n providers.push(await collectProvider(preset, configured, env));\n }\n\n const secretTarget = providers.some((choice) => choice.secret)\n ? await selectSecretTarget()\n : \"skip\";\n\n const defaultProvider = await selectDefaultProvider(providers, settings.model);\n const chosen = providers.find((choice) => choice.id === defaultProvider);\n const modelRef = await selectModelRef(\n defaultProvider,\n settings.model,\n chosen?.secret ?? (chosen ? env[chosen.envVar] : undefined),\n );\n\n const defaultsTarget = await selectDefaultsTarget(projectDir);\n\n await reviewAndSave({ providers, secretTarget, defaultsTarget, modelRef, driver }, projectDir);\n\n p.outro(\"Setup complete!\");\n}\n"]}
1
+ {"version":3,"sources":["../cli/src/setup.ts"],"names":["result"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAS,UAAA,GAAiC;AACxC,EAAA,OAAO,qBAAoB,CAAE,MAAA,CAAO,CAAC,MAAA,KAAW,MAAA,CAAO,SAAS,KAAK,CAAA;AACvE;AAGA,IAAM,eAAA,GAA0C;AAAA,EAC9C,SAAA,EAAW,6CAAA;AAAA,EACX,MAAA,EAAQ,sCAAA;AAAA,EACR,MAAA,EAAQ,oCAAA;AAAA,EACR,OAAA,EAAS,qCAAA;AAAA,EACT,IAAA,EAAM,+BAAA;AAAA,EACN,UAAA,EAAY,qCAAA;AAAA,EACZ,QAAA,EAAU,wCAAA;AAAA,EACV,GAAA,EAAK,uBAAA;AAAA,EACL,QAAA,EAAU,2CAAA;AAAA,EACV,SAAA,EAAW;AACb,CAAA;AAoCA,SAAS,aAAgB,KAAA,EAA+C;AACtE,EAAA,IAAM,CAAA,CAAA,QAAA,CAAS,KAAK,CAAA,EAAG;AACrB,IAAE,SAAO,kBAAkB,CAAA;AAC3B,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AAC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MAAA,CAAO,OAAO,eAAe,CAAA;AACvE,EAAA,MAAM,WAAW,MAAM,cAAA;AAAA,IACrB,eAAA;AAAA,IACA,QAAA,CAAS,KAAA;AAAA,IACT,QAAQ,MAAA,KAAW,MAAA,GAAS,GAAA,CAAI,MAAA,CAAO,MAAM,CAAA,GAAI,MAAA;AAAA,GACnD;AAEA,EAAA,MAAM,cAAA,GAAiB,MAAM,oBAAA,CAAqB,UAAU,CAAA;AAE5D,EAAA,MAAM,aAAA,CAAc,EAAE,SAAA,EAAW,YAAA,EAAc,gBAAgB,QAAA,EAAU,MAAA,IAAU,UAAU,CAAA;AAE7F,EAAE,QAAM,iBAAiB,CAAA;AAC3B","file":"setup-JGXLTJ57.js","sourcesContent":["/**\n * skaile setup — interactive AI provider setup wizard.\n *\n * Front-end over `skaile providers add` and `skaile config`: it discovers what\n * is already configured, picks endpoints out of the catalog, writes them to\n * `~/.skaile/providers.yml` with `env:` credential references, and saves the\n * driver plus one namespaced model selector to `skaile.yaml` or\n * `.skaile/settings.json`.\n *\n * It never stores a secret. The registry holds a reference; the value goes to\n * a `.env` file or stays in the operator's shell.\n *\n * @see PROVIDER-CONFIG-PLAN.md §1.6, §2.5\n */\n\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport * as p from \"@clack/prompts\";\nimport {\n type AIProviderPreset,\n getModels,\n listProviderPresets,\n validateApiKey,\n} from \"@skaile/workspaces/bridge\";\nimport {\n loadSettings,\n maskApiKey,\n projectSettingsPath,\n resolveSettings,\n type SkaileSettings,\n saveSettings,\n WorkspaceYamlEditor,\n} from \"@skaile/workspaces/core\";\nimport {\n addProviderEntry,\n credentialEnvVarName,\n loadRegistryView,\n ProviderRegistryWriteError,\n} from \"./commands/providers.ts\";\n\n// ---------------------------------------------------------------------------\n// Catalog\n// ---------------------------------------------------------------------------\n\n/** LLM presets, in catalog order — the wizard never shows voice endpoints. */\nfunction llmPresets(): AIProviderPreset[] {\n return listProviderPresets().filter((preset) => preset.kind === \"llm\");\n}\n\n/** Where the operator gets a key, for the presets that have a console. */\nconst PRESET_KEY_URLS: Record<string, string> = {\n anthropic: \"https://console.anthropic.com/settings/keys\",\n openai: \"https://platform.openai.com/api-keys\",\n google: \"https://aistudio.google.com/apikey\",\n mistral: \"https://console.mistral.ai/api-keys\",\n groq: \"https://console.groq.com/keys\",\n openrouter: \"https://openrouter.ai/settings/keys\",\n deepseek: \"https://platform.deepseek.com/api_keys\",\n xai: \"https://console.x.ai/\",\n together: \"https://api.together.ai/settings/api-keys\",\n fireworks: \"https://fireworks.ai/api-keys\",\n};\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Where a freshly entered secret is written — never `settings.json`. */\nexport type SecretTarget = \"env-project\" | \"env-global\" | \"skip\";\nexport type DefaultsTarget = \"project\" | \"personal\";\n\n/** One endpoint the wizard will make sure exists in the registry. */\nexport interface ProviderChoice {\n /** Catalog preset id; also the registry entry id. */\n id: string;\n /** Env var the entry's `credential.ref` points at. */\n envVar: string;\n /** A secret the operator just typed, if any. */\n secret?: string;\n /** The registry already has this entry with this reference. */\n satisfied: boolean;\n}\n\n/** The wizard's answers, in the order {@link applySetupPlan} writes them. */\nexport interface SetupPlan {\n providers: ProviderChoice[];\n secretTarget: SecretTarget;\n defaultsTarget: DefaultsTarget;\n /** `<providerId>/<modelId>` — what lands in `model:`. */\n modelRef: string;\n driver: string;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction exitOnCancel<T>(value: T): asserts value is Exclude<T, symbol> {\n if (p.isCancel(value)) {\n p.cancel(\"Setup cancelled.\");\n process.exit(0);\n }\n}\n\n/** Load .env files from common locations and parse key=value pairs */\nfunction loadDotenvKeys(): Record<string, string> {\n const locations = [path.join(process.cwd(), \".env\"), path.join(os.homedir(), \".env\")];\n const result: Record<string, string> = {};\n for (const loc of locations) {\n try {\n const content = fs.readFileSync(loc, \"utf-8\");\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eq = trimmed.indexOf(\"=\");\n if (eq === -1) continue;\n const key = trimmed.slice(0, eq).trim();\n let val = trimmed.slice(eq + 1).trim();\n // Strip surrounding quotes\n if (\n (val.startsWith('\"') && val.endsWith('\"')) ||\n (val.startsWith(\"'\") && val.endsWith(\"'\"))\n ) {\n val = val.slice(1, -1);\n }\n result[key] = val;\n }\n } catch {\n // file doesn't exist, skip\n }\n }\n return result;\n}\n\n/** Append key=value entries to a .env file without overwriting existing keys */\nfunction appendEnvFile(filePath: string, entries: Record<string, string>): void {\n let existing = \"\";\n try {\n existing = fs.readFileSync(filePath, \"utf-8\");\n } catch {\n // file doesn't exist yet\n }\n\n const existingKeys = new Set<string>();\n for (const line of existing.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eq = trimmed.indexOf(\"=\");\n if (eq !== -1) existingKeys.add(trimmed.slice(0, eq).trim());\n }\n\n const lines: string[] = [];\n for (const [key, value] of Object.entries(entries)) {\n if (existingKeys.has(key)) {\n p.log.warn(` ${key} already exists in ${filePath} — skipping`);\n continue;\n }\n lines.push(`${key}=${value}`);\n }\n\n if (lines.length === 0) return;\n\n const separator = existing.endsWith(\"\\n\") || existing === \"\" ? \"\" : \"\\n\";\n const content = `${separator + lines.join(\"\\n\")}\\n`;\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.appendFileSync(filePath, content, \"utf-8\");\n}\n\n/** The env var a preset's credential conventionally lives in. */\nfunction presetEnvVar(preset: AIProviderPreset): string {\n return preset.credential.env ?? `${preset.id.toUpperCase().replace(/[^A-Z0-9]/g, \"_\")}_API_KEY`;\n}\n\n/** Entries already in the registry, keyed by id, with their `env:` var name. */\nfunction configuredEntries(projectDir: string): Record<string, string | undefined> {\n const view = loadRegistryView({ projectDir });\n const out: Record<string, string | undefined> = {};\n for (const id of view.merged.order) {\n out[id] = credentialEnvVarName(view.merged.providers[id]);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Wizard steps\n// ---------------------------------------------------------------------------\n\nfunction showCurrentState(\n settings: SkaileSettings,\n configured: Record<string, string | undefined>,\n env: Record<string, string>,\n): void {\n const lines: string[] = [\"Configured providers (~/.skaile/providers.yml):\"];\n const ids = Object.keys(configured);\n if (ids.length === 0) {\n lines.push(\" (none)\");\n } else {\n for (const id of ids) {\n const envVar = configured[id];\n const value = envVar ? env[envVar] : undefined;\n lines.push(\n ` ${id.padEnd(14)} ${envVar ?? \"no credential ref\"}` +\n (value ? ` ${maskApiKey(value)}` : envVar ? \" (not set in this environment)\" : \"\"),\n );\n }\n }\n lines.push(\"\");\n lines.push(\"Current defaults:\");\n lines.push(` Model: ${settings.model ?? \"(not set)\"}`);\n lines.push(` Driver: ${settings.driver ?? \"(not set)\"}`);\n\n p.note(lines.join(\"\\n\"), \"Current configuration\");\n}\n\nasync function selectPresets(\n configured: Record<string, string | undefined>,\n env: Record<string, string>,\n): Promise<AIProviderPreset[]> {\n const presets = llmPresets();\n const result = await p.multiselect({\n message: \"Which providers do you want to configure?\",\n options: presets.map((preset) => ({\n value: preset.id,\n label: preset.label,\n hint: configured[preset.id]\n ? \"configured\"\n : env[presetEnvVar(preset)]\n ? `${presetEnvVar(preset)} is set`\n : undefined,\n })),\n initialValues: presets\n .filter((preset) => configured[preset.id] || env[presetEnvVar(preset)])\n .map((preset) => preset.id),\n required: true,\n });\n exitOnCancel(result);\n const chosen = new Set(result as string[]);\n return presets.filter((preset) => chosen.has(preset.id));\n}\n\n/**\n * Run the optional validation step for a freshly entered key.\n * Returns true if the key should be kept (valid, or user opted to keep anyway),\n * false if it should be discarded.\n */\nasync function confirmKeyAfterValidation(provider: string, key: string): Promise<boolean> {\n const shouldValidate = await p.confirm({ message: \"Validate this key?\", initialValue: true });\n exitOnCancel(shouldValidate);\n if (!shouldValidate) return true;\n\n const s = p.spinner();\n s.start(`Validating ${provider} key...`);\n const result = await validateApiKey(provider, key);\n if (result.ok) {\n s.stop(`${provider} key is valid`);\n return true;\n }\n s.stop(`${provider} validation failed: ${result.error}`);\n const retry = await p.confirm({ message: \"Use this key anyway?\", initialValue: false });\n exitOnCancel(retry);\n return retry;\n}\n\n/**\n * Decide what one provider needs: the env var its credential reference points\n * at, and — only when that variable is not already populated — the secret to\n * put in it.\n */\nasync function collectProvider(\n preset: AIProviderPreset,\n configured: Record<string, string | undefined>,\n env: Record<string, string>,\n): Promise<ProviderChoice> {\n const envVar = configured[preset.id] ?? presetEnvVar(preset);\n const known = env[envVar];\n\n if (preset.credential.kind !== \"api_key_header\" && preset.credential.kind !== \"bearer\") {\n // sigv4 / google_adc / azure_entra / none — nothing to type in.\n p.log.info(`${preset.label}: credential comes from ${preset.credential.kind}, no key needed`);\n return { id: preset.id, envVar, satisfied: !!configured[preset.id] };\n }\n\n if (known) {\n p.log.info(`${preset.label}: ${envVar} is already set (${maskApiKey(known)})`);\n return { id: preset.id, envVar, satisfied: !!configured[preset.id] };\n }\n\n const keyUrl = PRESET_KEY_URLS[preset.id];\n const key = await p.password({\n message: `${preset.label} API key${keyUrl ? ` (get one at ${keyUrl})` : \"\"}, or leave blank to set ${envVar} yourself:`,\n });\n exitOnCancel(key);\n if (!key) return { id: preset.id, envVar, satisfied: !!configured[preset.id] };\n\n const keep = await confirmKeyAfterValidation(preset.id, key as string);\n if (!keep) return { id: preset.id, envVar, satisfied: !!configured[preset.id] };\n return { id: preset.id, envVar, secret: key as string, satisfied: !!configured[preset.id] };\n}\n\nasync function selectSecretTarget(): Promise<SecretTarget> {\n const result = await p.select({\n message: \"Where should the secrets be written? (skaile stores only the variable name)\",\n options: [\n { value: \"env-project\" as const, label: `${process.cwd()}/.env (project-level)` },\n { value: \"env-global\" as const, label: `${os.homedir()}/.env (global)` },\n { value: \"skip\" as const, label: \"Skip — I'll export the variables myself\" },\n ],\n });\n exitOnCancel(result);\n return result as SecretTarget;\n}\n\nasync function selectDefaultProvider(choices: ProviderChoice[], current?: string): Promise<string> {\n if (choices.length === 1) return choices[0].id;\n const initial = choices.find((choice) => current?.startsWith(`${choice.id}/`))?.id;\n const result = await p.select({\n message: \"Which provider should the default model come from?\",\n options: choices.map((choice) => ({ value: choice.id, label: choice.id })),\n initialValue: initial ?? choices[0].id,\n });\n exitOnCancel(result);\n return result as string;\n}\n\n/**\n * Pick the model id for `providerId`, returning the namespaced selector.\n * A live list needs a key; without one the built-in catalog is offered.\n */\nasync function selectModelRef(\n providerId: string,\n current?: string,\n apiKey?: string,\n): Promise<string> {\n const currentModel = current?.startsWith(`${providerId}/`)\n ? current.slice(providerId.length + 1)\n : undefined;\n\n const s = apiKey ? p.spinner() : undefined;\n if (s) s.start(`Fetching models from ${providerId}...`);\n const fetchResult = await getModels(providerId, apiKey);\n if (s) {\n if (fetchResult.source === \"api\") {\n s.stop(`Loaded ${fetchResult.models.length} models from ${providerId}`);\n } else if (fetchResult.error) {\n s.stop(`Could not fetch live models (${fetchResult.error}) — using built-in catalog`);\n } else {\n s.stop(\"Using built-in model catalog\");\n }\n }\n\n const models = fetchResult.models;\n if (models.length === 0) {\n p.log.warn(`No models found for ${providerId} — enter a model id manually`);\n const result = await p.text({ message: \"Model id:\", initialValue: currentModel ?? \"\" });\n exitOnCancel(result);\n return `${providerId}/${result as string}`;\n }\n\n const result = await p.select({\n message: `Default model (${providerId}):`,\n options: models.map((m) => ({ value: m.id, label: `${m.name} (${m.id})` })),\n initialValue:\n currentModel && models.some((m) => m.id === currentModel) ? currentModel : models[0].id,\n });\n exitOnCancel(result);\n return `${providerId}/${result as string}`;\n}\n\nasync function selectDriver(current?: string): Promise<string> {\n const result = await p.select({\n message: \"Default agent driver:\",\n options: [\n { value: \"omp\", label: \"omp (oh-my-pi — multi-provider, recommended)\" },\n { value: \"claude-sdk\", label: \"claude-sdk (Anthropic Agent SDK, Claude only)\" },\n { value: \"codex\", label: \"codex (OpenAI Codex SDK, OpenAI only)\" },\n ],\n initialValue: current ?? \"omp\",\n });\n exitOnCancel(result);\n return result as string;\n}\n\nasync function selectDefaultsTarget(projectDir: string): Promise<DefaultsTarget> {\n if (!fs.existsSync(path.join(projectDir, \"skaile.yaml\"))) return \"personal\";\n\n const result = await p.select({\n message: \"Where should the driver and model selector be saved?\",\n options: [\n {\n value: \"project\" as const,\n label: \"skaile.yaml (project-wide, shared with team)\",\n hint: \"recommended\",\n },\n { value: \"personal\" as const, label: \".skaile/settings.json (personal only, gitignored)\" },\n ],\n initialValue: \"project\" as const,\n });\n exitOnCancel(result);\n return result as DefaultsTarget;\n}\n\n/** Build the human-readable summary shown before applying the plan. */\nfunction buildSummaryLines(plan: SetupPlan, settingsFile: string): string[] {\n const lines: string[] = [\"Providers (~/.skaile/providers.yml):\"];\n for (const choice of plan.providers) {\n lines.push(\n ` ${choice.id.padEnd(14)} credential env:${choice.envVar}` +\n (choice.satisfied ? \" (already configured)\" : \"\"),\n );\n }\n\n const withSecrets = plan.providers.filter((choice) => choice.secret);\n if (withSecrets.length > 0) {\n const targetLabels: Record<SecretTarget, string> = {\n \"env-project\": `${process.cwd()}/.env`,\n \"env-global\": `${os.homedir()}/.env`,\n skip: \"not saved (export them yourself)\",\n };\n lines.push(\"\");\n lines.push(\"Secrets:\");\n for (const choice of withSecrets) {\n lines.push(` ${choice.envVar.padEnd(24)} ${maskApiKey(choice.secret ?? \"\")}`);\n }\n lines.push(` Written to: ${targetLabels[plan.secretTarget]}`);\n }\n\n lines.push(\"\");\n lines.push(\"Defaults:\");\n lines.push(` Model: ${plan.modelRef}`);\n lines.push(` Driver: ${plan.driver}`);\n lines.push(\n ` Saved to: ${plan.defaultsTarget === \"project\" ? \"skaile.yaml (project-wide)\" : settingsFile}`,\n );\n return lines;\n}\n\n/**\n * Create or update each chosen registry entry through the same write path as\n * `skaile providers add`. An entry that already points at the chosen variable\n * is left exactly as it is — the operator may have tuned its base URL or model\n * map, and re-running the wizard must not undo that.\n */\nfunction persistProviders(plan: SetupPlan, projectDir: string): void {\n for (const choice of plan.providers) {\n if (choice.satisfied) {\n p.log.info(`${choice.id}: keeping the existing registry entry`);\n continue;\n }\n try {\n const added = addProviderEntry({\n id: choice.id,\n presetId: choice.id,\n credentialRef: `env:${choice.envVar}`,\n projectDir,\n force: true,\n });\n p.log.success(`${choice.id} → ${added.path}`);\n } catch (error) {\n if (!(error instanceof ProviderRegistryWriteError)) throw error;\n p.log.error(`${choice.id}: ${error.message}`);\n }\n }\n}\n\n/** Write the secrets the operator typed to the chosen `.env` file. */\nfunction persistSecrets(plan: SetupPlan): void {\n const entries: Record<string, string> = {};\n for (const choice of plan.providers) {\n if (choice.secret) entries[choice.envVar] = choice.secret;\n }\n if (Object.keys(entries).length === 0) return;\n\n if (plan.secretTarget === \"skip\") {\n p.log.info(\n `Export these before starting a session: ${Object.keys(entries)\n .map((name) => `${name}=…`)\n .join(\" \")}`,\n );\n return;\n }\n const file =\n plan.secretTarget === \"env-project\"\n ? path.join(process.cwd(), \".env\")\n : path.join(os.homedir(), \".env\");\n appendEnvFile(file, entries);\n p.log.success(`Appended ${Object.keys(entries).length} variable(s) to ${file}`);\n}\n\n/**\n * Apply the plan's defaults: write them to skaile.yaml when saving project-wide,\n * and set/strip the corresponding personal settings fields on `merged` (mutated\n * in place) so they don't shadow project-wide values.\n */\nfunction applyDefaults(plan: SetupPlan, projectDir: string, merged: SkaileSettings): void {\n if (plan.defaultsTarget === \"project\") {\n const yamlPath = path.join(projectDir, \"skaile.yaml\");\n const editor = WorkspaceYamlEditor.load(yamlPath);\n editor.setAgentConfig(\"default\", { model: plan.modelRef, driver: plan.driver });\n editor.save();\n p.log.success(`Saved defaults to ${yamlPath}`);\n delete merged.model;\n delete merged.driver;\n return;\n }\n merged.model = plan.modelRef;\n merged.driver = plan.driver;\n}\n\n/**\n * Everything the wizard writes, once the operator has approved the plan:\n * registry entries, `.env` secrets, and the defaults.\n *\n * Separate from the prompting so the wizard's effect on disk is exercisable\n * without a terminal — and so there is exactly one place that writes.\n */\nexport async function applySetupPlan(plan: SetupPlan, projectDir: string): Promise<void> {\n const settingsFile = projectSettingsPath(projectDir);\n persistProviders(plan, projectDir);\n persistSecrets(plan);\n\n const merged: SkaileSettings = { ...(await loadSettings(settingsFile)) };\n applyDefaults(plan, projectDir, merged);\n await saveSettings(merged, settingsFile);\n p.log.success(`Saved settings to ${settingsFile}`);\n}\n\nasync function reviewAndSave(plan: SetupPlan, projectDir: string): Promise<void> {\n p.note(buildSummaryLines(plan, projectSettingsPath(projectDir)).join(\"\\n\"), \"Summary\");\n\n const confirmed = await p.confirm({ message: \"Apply these settings?\", initialValue: true });\n exitOnCancel(confirmed);\n if (!confirmed) {\n p.cancel(\"Setup cancelled — no changes were made.\");\n process.exit(0);\n }\n\n await applySetupPlan(plan, projectDir);\n}\n\n// ---------------------------------------------------------------------------\n// Main entry\n// ---------------------------------------------------------------------------\n\n/** Check whether Claude Code OAuth credentials exist on disk */\nfunction hasClaudeCodeCredentials(): boolean {\n const credPath = path.join(os.homedir(), \".claude\", \".credentials.json\");\n try {\n const parsed = JSON.parse(fs.readFileSync(credPath, \"utf-8\"));\n return parsed && (parsed.accessToken || parsed.refreshToken || parsed.oauthToken);\n } catch {\n return false;\n }\n}\n\n/** The presets a driver can actually talk to (§2.3 plurality). */\nfunction presetsForDriver(driver: string): AIProviderPreset[] | undefined {\n if (driver === \"claude-sdk\") return llmPresets().filter((preset) => preset.id === \"anthropic\");\n if (driver === \"codex\") return llmPresets().filter((preset) => preset.id === \"openai\");\n return undefined;\n}\n\n/**\n * Interactive provider setup wizard: discovers what the AI provider registry\n * already holds, adds the endpoints the operator picks (credential references\n * only), and writes the driver plus a `<providerId>/<modelId>` selector to\n * `skaile.yaml` or `.skaile/settings.json`.\n *\n * @param _args - Unused positional args (reserved for future use).\n * @param opts - Options including an optional `projectDir` override.\n * @docLink cli/dev-guide#setup\n */\nexport async function cmdSetup(_args: string[], opts: { projectDir?: string }): Promise<void> {\n p.intro(\"skaile setup\");\n\n const projectDir = opts.projectDir ?? process.cwd();\n\n let settings: SkaileSettings;\n try {\n settings = await resolveSettings(projectDir);\n } catch (error) {\n // A pre-registry skaile.yaml cannot be read at all — say so once, with the\n // command that fixes it, instead of walking the operator through a wizard\n // whose result the file would reject.\n p.cancel(error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n\n const env = { ...loadDotenvKeys(), ...process.env } as Record<string, string>;\n const configured = configuredEntries(projectDir);\n showCurrentState(settings, configured, env);\n\n // The driver comes first: it decides which endpoints are even selectable.\n const driver = await selectDriver(settings.driver);\n const forced = presetsForDriver(driver);\n if (forced && driver === \"claude-sdk\" && !env.ANTHROPIC_API_KEY && hasClaudeCodeCredentials()) {\n p.log.info(\"Claude Code subscription detected — the SDK can use that login instead of a key.\");\n }\n const presets = forced ?? (await selectPresets(configured, env));\n\n const providers: ProviderChoice[] = [];\n for (const preset of presets) {\n providers.push(await collectProvider(preset, configured, env));\n }\n\n const secretTarget = providers.some((choice) => choice.secret)\n ? await selectSecretTarget()\n : \"skip\";\n\n const defaultProvider = await selectDefaultProvider(providers, settings.model);\n const chosen = providers.find((choice) => choice.id === defaultProvider);\n const modelRef = await selectModelRef(\n defaultProvider,\n settings.model,\n chosen?.secret ?? (chosen ? env[chosen.envVar] : undefined),\n );\n\n const defaultsTarget = await selectDefaultsTarget(projectDir);\n\n await reviewAndSave({ providers, secretTarget, defaultsTarget, modelRef, driver }, projectDir);\n\n p.outro(\"Setup complete!\");\n}\n"]}
@@ -1,11 +1,11 @@
1
- export { autoSyncForSearch, ensureClone, findCacheKeyCollision, indexingHadFailures, legacySourceConfigHint, makeSourceCommand, normalizeSourceUrl, readProjectSources, sourceClonePath, sourceMatchesKey, syncProjectSources } from './chunk-W4AEVRUC.js';
2
- import './chunk-GGRHNBUP.js';
3
- import './chunk-I66MW6OR.js';
1
+ export { autoSyncForSearch, ensureClone, findCacheKeyCollision, indexingHadFailures, legacySourceConfigHint, makeSourceCommand, normalizeSourceUrl, readProjectSources, sourceClonePath, sourceMatchesKey, syncProjectSources } from './chunk-RAHLV6QG.js';
2
+ import './chunk-4RKCOURU.js';
3
+ import './chunk-WOE4LPGF.js';
4
4
  import './chunk-KTCMBEEB.js';
5
5
  import './chunk-ALLCAFHQ.js';
6
6
  import './chunk-V4RGCKYC.js';
7
7
  import './chunk-DHMBE5J7.js';
8
- import './chunk-WTUHM2NJ.js';
8
+ import './chunk-AOFJ2OKW.js';
9
9
  import './chunk-UFWADBG6.js';
10
10
  import './chunk-HGPSZXZP.js';
11
11
  import './chunk-VOEBLPXO.js';
@@ -34,5 +34,5 @@ import './chunk-UQ6LFBPZ.js';
34
34
  import './chunk-DKCFWSVW.js';
35
35
  import './chunk-N7B3LZ7V.js';
36
36
  import './chunk-NSBPE2FW.js';
37
- //# sourceMappingURL=source-7VNEUEGO.js.map
38
- //# sourceMappingURL=source-7VNEUEGO.js.map
37
+ //# sourceMappingURL=source-NHEYY7WH.js.map
38
+ //# sourceMappingURL=source-NHEYY7WH.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"source-7VNEUEGO.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"source-NHEYY7WH.js"}
@@ -1,13 +1,13 @@
1
- import { makeHttpPublisherClient, refFor, publishToStore, bareName } from './chunk-76IGAJ47.js';
1
+ import { makeHttpPublisherClient, refFor, publishToStore, bareName } from './chunk-2AQIFJHK.js';
2
2
  import { isStoreAuthenticated } from './chunk-IJTEDXWQ.js';
3
- import { sourceClonePath, resolveSourceArg } from './chunk-W4AEVRUC.js';
4
- import './chunk-GGRHNBUP.js';
5
- import { logErr, S, logInfo, logOk, logWarn } from './chunk-I66MW6OR.js';
3
+ import { sourceClonePath, resolveSourceArg } from './chunk-RAHLV6QG.js';
4
+ import './chunk-4RKCOURU.js';
5
+ import { logErr, S, logInfo, logOk, logWarn } from './chunk-WOE4LPGF.js';
6
6
  import './chunk-KTCMBEEB.js';
7
7
  import './chunk-ALLCAFHQ.js';
8
8
  import './chunk-V4RGCKYC.js';
9
9
  import './chunk-DHMBE5J7.js';
10
- import './chunk-WTUHM2NJ.js';
10
+ import './chunk-AOFJ2OKW.js';
11
11
  import './chunk-UFWADBG6.js';
12
12
  import './chunk-HGPSZXZP.js';
13
13
  import './chunk-VOEBLPXO.js';
@@ -234,5 +234,5 @@ async function runYank(arg, opts, client) {
234
234
  }
235
235
 
236
236
  export { getSidecarRepo, normalizePublishedManifest, pushSidecarManifest, runPublish, runYank, saveSidecarRepo };
237
- //# sourceMappingURL=source-manifest-publish-SQ2SXJEA.js.map
238
- //# sourceMappingURL=source-manifest-publish-SQ2SXJEA.js.map
237
+ //# sourceMappingURL=source-manifest-publish-IJLVR3IL.js.map
238
+ //# sourceMappingURL=source-manifest-publish-IJLVR3IL.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../cli/src/commands/source-manifest-publish.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,IAAM,yBAAA,GAA4B,sBAAA;AAW3B,SAAS,0BAAA,CACd,UACA,SAAA,EACmB;AACnB,EAAA,MAAM,UAAU,QAAA,CAAS,MAAA,IAAU,EAAC,EAAG,GAAA,CAAI,CAAC,CAAA,KAAM;AAChD,IAAA,MAAM,EAAE,SAAA,EAAW,KAAA,EAAO,GAAG,MAAK,GAAI,CAAA;AACtC,IAAA,OAAO,IAAA;AAAA,EACT,CAAC,CAAA;AACD,EAAA,OAAO,EAAE,GAAG,QAAA,EAAU,SAAA,EAAW,WAAW,MAAA,EAAO;AACrD;AAWA,SAAS,YAAA,GAAuB;AAC9B,EAAA,MAAM,OAAO,OAAA,CAAQ,GAAA,CAAI,eAAe,IAAA,CAAK,OAAA,IAAW,SAAS,CAAA;AACjE,EAAA,OAAO,IAAA,CAAK,MAAM,eAAe,CAAA;AACnC;AAEA,SAAS,YAAA,GAAoC;AAC3C,EAAA,MAAM,OAAO,YAAA,EAAa;AAC1B,EAAA,IAAI,CAAC,UAAA,CAAW,IAAI,CAAA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AAK;AACZ,MAAA,OAAA;AAAA,QACE,CAAA,eAAA,EAAkB,CAAA,CAAE,IAAI,CAAA,CAAA,EAAI,CAAA,CAAE,IAAI,CAAA,EAAA,EAAK,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,OACzF;AAAA,IACF;AAAA,EACF;AAEA,EAAA,KAAA,CAAM,CAAA,OAAA,EAAU,MAAA,CAAO,MAAM,CAAA,UAAA,CAAY,CAAA;AACzC,EAAA,KAAA,MAAW,CAAA,IAAK,MAAA,EAAQ,OAAA,CAAQ,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAC1C","file":"source-manifest-publish-SQ2SXJEA.js","sourcesContent":["/**\n * `skaile source manifest publish` / `yank` — the curator-publish flow. Takes a\n * locally-curated sidecar manifest (over a foreign public GitHub repo) and:\n *\n * 1. Pushes the curated `skaile.manifest.yaml` to the curator's OWN public\n * \"sidecar\" repo (bytes stay in the foreign source; the sidecar holds only\n * the manifest pointing at it).\n * 2. Registers the foreign source + the sidecar (url + pinned commit) with the\n * store, syncs it, and publishes each curated asset.\n *\n * `yank` is the inverse: unpublish each currently-published asset of the source.\n *\n * The store REST surface is reached through the injectable {@link PublisherClient}\n * (default HTTP client); git side-effects go through an injectable `spawn`. Both\n * seams keep the pure helpers + orchestration unit/integration-testable without a\n * live store or a real remote.\n *\n * @docLink cli/commands/source#manifest-publish\n */\n\nimport { spawnSync } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport {\n decodeSkaileManifest,\n encodeSkaileManifest,\n type SkPublishManifest,\n sourceCacheKey,\n} from \"@skaile/workspaces/core\";\nimport { logErr, logInfo, logOk, logWarn, S } from \"../helpers.ts\";\nimport { makeHttpPublisherClient, type PublisherClient } from \"../store-publisher.ts\";\nimport { isStoreAuthenticated } from \"../store-client.ts\";\nimport { bareName, publishToStore, refFor } from \"./publish-core.ts\";\nimport { sourceClonePath } from \"./source.ts\";\nimport { resolveSourceArg } from \"./source-manifest.ts\";\n\n/** The fixed filename a sidecar repo carries at its root. */\nconst SIDECAR_MANIFEST_FILENAME = \"skaile.manifest.yaml\";\n\n/** Injectable spawn contract — the subset of `spawnSync` these helpers use. */\ntype SpawnLike = typeof spawnSync;\n\n/**\n * Return a copy of `manifest` normalized for publication under `namespace`:\n * the top-level `publisher` is set to `namespace` and every per-asset\n * `publisher` override is removed so all assets inherit the top-level one.\n * Pure — the input is not mutated.\n */\nexport function normalizePublishedManifest(\n manifest: SkPublishManifest,\n namespace: string,\n): SkPublishManifest {\n const assets = (manifest.assets ?? []).map((a) => {\n const { publisher: _drop, ...rest } = a;\n return rest;\n });\n return { ...manifest, publisher: namespace, assets };\n}\n\n// ── Sidecar-repo association (~/.skaile/settings.json) ────────────────────────\n\n/**\n * Path to the user settings file — the same `~/.skaile/settings.json` the store\n * client reads tokens from. Resolves the `.skaile` root exactly as `getStoreRoot`\n * does (`SKAILE_HOME` when set — it IS the `.skaile` dir — else `~/.skaile`), so\n * the sidecar association lives beside the store manifests under one convention\n * and tests isolate through the same `SKAILE_HOME` seam.\n */\nfunction settingsFile(): string {\n const root = process.env.SKAILE_HOME ?? join(homedir(), \".skaile\");\n return join(root, \"settings.json\");\n}\n\nfunction readSettings(): Record<string, any> {\n const file = settingsFile();\n if (!existsSync(file)) return {};\n try {\n return JSON.parse(readFileSync(file, \"utf-8\"));\n } catch {\n return {};\n }\n}\n\n/**\n * The sidecar repo URL previously associated with a source `slug`, if any.\n * Reads `settings.sidecarRepos?.[slug]?.repo`.\n */\nexport function getSidecarRepo(slug: string): string | undefined {\n const settings = readSettings();\n return settings.sidecarRepos?.[slug]?.repo;\n}\n\n/**\n * Persist the sidecar repo URL for a source `slug`, preserving every other\n * settings key. Stored as an object (`{ repo }`) so a `path` (or other fields)\n * can be added later without a schema migration.\n */\nexport function saveSidecarRepo(slug: string, repo: string): void {\n const file = settingsFile();\n mkdirSync(dirname(file), { recursive: true });\n const settings = readSettings();\n const sidecarRepos = { ...(settings.sidecarRepos ?? {}) };\n sidecarRepos[slug] = { ...(sidecarRepos[slug] ?? {}), repo };\n settings.sidecarRepos = sidecarRepos;\n writeFileSync(file, JSON.stringify(settings, null, 2), \"utf-8\");\n}\n\n// ── Sidecar push ──────────────────────────────────────────────────────────────\n\n/**\n * Run a git command in `cwd` via the injected spawn, throwing with the captured\n * stderr on failure. Returns trimmed stdout.\n */\nfunction git(spawn: SpawnLike, cwd: string, args: string[]): string {\n const res = spawn(\"git\", [\"-C\", cwd, ...args], { encoding: \"utf-8\" });\n if (res.status !== 0) {\n const stderr = (res.stderr ?? \"\").toString().trim();\n throw new Error(`git ${args.join(\" \")} failed: ${stderr || `exit ${res.status}`}`);\n }\n return (res.stdout ?? \"\").toString().trim();\n}\n\n/**\n * Clone the curator's sidecar repo, write the curated manifest at its root, and\n * commit + push. Returns the pushed commit sha (used to pin the store source).\n *\n * Idempotent re-publish: when the manifest is unchanged `git commit` fails with\n * \"nothing to commit\" — we swallow that and return the current HEAD so a no-op\n * re-run still yields a valid pin. Any push/auth failure surfaces as a thrown\n * Error carrying git's stderr.\n */\nexport function pushSidecarManifest(opts: {\n sidecarRepoUrl: string;\n manifestText: string;\n spawn?: SpawnLike;\n}): { commitSha: string } {\n const spawn = opts.spawn ?? spawnSync;\n // Dedicated dir next to the source clone cache; wipe any stale clone first so\n // a re-publish always starts from a clean shallow checkout of the remote.\n const cloneDir = `${sourceClonePath(sourceCacheKey(opts.sidecarRepoUrl))}-sidecar-push`;\n rmSync(cloneDir, { recursive: true, force: true });\n mkdirSync(dirname(cloneDir), { recursive: true });\n\n // The clone is scratch — always remove it afterwards (success or failure) so a\n // failed push never leaves a stale checkout in the cache dir.\n try {\n const cloneRes = spawn(\"git\", [\"clone\", \"--depth\", \"1\", opts.sidecarRepoUrl, cloneDir], {\n encoding: \"utf-8\",\n });\n if (cloneRes.status !== 0) {\n const stderr = (cloneRes.stderr ?? \"\").toString().trim();\n throw new Error(\n `git clone ${opts.sidecarRepoUrl} failed: ${stderr || `exit ${cloneRes.status}`}`,\n );\n }\n\n writeFileSync(join(cloneDir, SIDECAR_MANIFEST_FILENAME), opts.manifestText, \"utf-8\");\n git(spawn, cloneDir, [\"add\", SIDECAR_MANIFEST_FILENAME]);\n\n // Fixed bot identity via -c so the commit succeeds regardless of the curator's\n // git config (the sidecar push is a machine action, not authored work).\n const commitRes = spawn(\n \"git\",\n [\n \"-C\",\n cloneDir,\n \"-c\",\n \"user.email=publish@skaile.store\",\n \"-c\",\n \"user.name=skaile\",\n \"commit\",\n \"-m\",\n \"chore(sidecar): publish curated manifest\",\n ],\n { encoding: \"utf-8\" },\n );\n if (commitRes.status !== 0) {\n const out = `${commitRes.stdout ?? \"\"}${commitRes.stderr ?? \"\"}`;\n // Nothing changed → idempotent re-publish; keep the existing HEAD.\n if (!/nothing to commit/i.test(out)) {\n throw new Error(`git commit failed: ${out.trim() || `exit ${commitRes.status}`}`);\n }\n } else {\n // `push origin HEAD` (not a bare `push`) so a fresh sidecar repo with an\n // unborn/renamed default branch still gets its branch created on the remote.\n git(spawn, cloneDir, [\"push\", \"origin\", \"HEAD\"]);\n }\n\n return { commitSha: git(spawn, cloneDir, [\"rev-parse\", \"HEAD\"]) };\n } finally {\n rmSync(cloneDir, { recursive: true, force: true });\n }\n}\n\n// ── Orchestration ───────────────────────────────────────────────────────────\n\n/**\n * `source manifest publish <src>` — publish a curated sidecar manifest to the\n * store. See the module header for the full flow. Store calls go through\n * `client` (default HTTP); git side-effects through `spawn` (default\n * `spawnSync`). The auth gate is enforced only for the default HTTP client so\n * injected fakes bypass it.\n */\nexport async function runPublish(\n arg: string,\n opts: {\n projectDir: string;\n as?: string;\n sidecarRepo?: string;\n ref?: string;\n dryRun?: boolean;\n },\n client?: PublisherClient,\n spawn: SpawnLike = spawnSync,\n): Promise<void> {\n const injected = client !== undefined;\n const pub = client ?? makeHttpPublisherClient();\n\n const { url, slug, manifestFile } = resolveSourceArg(arg, opts.projectDir);\n\n if (!existsSync(manifestFile)) {\n logErr(\n `No curated manifest for \"${slug}\" at ${S.dim(manifestFile)} — ` +\n \"run `skaile source manifest init` first.\",\n );\n process.exit(1);\n }\n\n const { manifest, diagnostics } = decodeSkaileManifest(readFileSync(manifestFile, \"utf-8\"));\n if (diagnostics.some((d) => d.severity === \"error\")) {\n for (const d of diagnostics.filter((x) => x.severity === \"error\")) {\n logErr(`${d.code}: ${d.message}`);\n }\n logErr(\n \"The curated manifest has errors — fix them with `skaile source manifest edit` / \" +\n \"`verify` before publishing.\",\n );\n process.exit(1);\n }\n\n // A real publish makes store calls (+ `me()` when `--as` is omitted), so it\n // needs a token. `--dry-run` is an offline preview: never gate it on auth.\n const authed = injected || isStoreAuthenticated();\n if (!opts.dryRun && !authed) {\n logErr(\"Not signed in — run `skaile store login` first.\");\n process.exit(1);\n }\n\n // Namespace: `--as` wins; else the caller's verified identity. Prefer the\n // GitHub handle (`githubLogin`) over the store login (`username`) — for a user\n // whose login differs from their GitHub handle the login namespace may be\n // reserved (matches the CLI's `resolveLibraryPublisher` precedence). In an\n // unauthenticated dry-run we cannot call `me()`, so show a placeholder.\n let namespace: string;\n if (opts.as) namespace = opts.as;\n else if (authed) {\n const me = await pub.me();\n // `||` not `??`: an empty-string githubLogin (partially-connected account) is\n // not a usable namespace — fall back to the login rather than publish under \"\".\n namespace = me.githubLogin || me.username;\n } else namespace = \"<your store username>\";\n\n const normalized = normalizePublishedManifest(manifest, namespace);\n const publishedText = encodeSkaileManifest(normalized);\n\n const wouldBeRefs = (normalized.assets ?? []).map((a) =>\n refFor(a.kind, namespace, a.name, a.version ?? normalized.version),\n );\n\n if (opts.dryRun) {\n const sidecar = opts.sidecarRepo ?? getSidecarRepo(slug) ?? \"<none — pass --sidecar-repo>\";\n logInfo(`Publish plan for ${S.bold(slug)}:`);\n logInfo(` namespace: ${namespace}`);\n logInfo(` sidecar repo: ${sidecar}`);\n logInfo(` source ref: ${opts.ref ?? \"main\"}`);\n logInfo(` would publish ${wouldBeRefs.length} asset(s):`);\n for (const r of wouldBeRefs) logInfo(` ${r}`);\n return;\n }\n\n const sidecarRepoUrl = opts.sidecarRepo ?? getSidecarRepo(slug);\n if (!sidecarRepoUrl) {\n logErr(\n \"No sidecar repo associated with this source. Pass \" +\n `${S.cmd(\"--sidecar-repo https://github.com/<you>/<repo>\")} — it must be a ` +\n \"PUBLIC GitHub repo you own; the curated manifest is committed there and the \" +\n \"store pins to that commit.\",\n );\n process.exit(1);\n }\n if (opts.sidecarRepo) saveSidecarRepo(slug, sidecarRepoUrl);\n\n const { commitSha } = pushSidecarManifest({ sidecarRepoUrl, manifestText: publishedText, spawn });\n logOk(`Pushed curated manifest to ${S.dim(sidecarRepoUrl)} @ ${commitSha.slice(0, 10)}.`);\n\n // The FOREIGN repo's ref to ingest (branch/sha). Defaults to `main`.\n const sourceRef = opts.ref ?? \"main\";\n\n const { published } = await publishToStore({\n sourceUrl: url,\n ref: sourceRef,\n sidecar: { url: sidecarRepoUrl, ref: commitSha },\n manifest: normalized,\n client: pub,\n });\n\n if (published.length > 0) {\n logInfo(`Consumers can now install them with \\`skaile add ${published[0]}\\`.`);\n }\n}\n\n/**\n * `source manifest yank <src>` — unpublish the source's published assets (all,\n * or the single asset matching `opts.asset`'s name). Auth-gated like publish.\n */\nexport async function runYank(\n arg: string,\n opts: { projectDir: string; asset?: string },\n client?: PublisherClient,\n): Promise<void> {\n const injected = client !== undefined;\n const pub = client ?? makeHttpPublisherClient();\n\n const { url, slug } = resolveSourceArg(arg, opts.projectDir);\n\n if (!injected && !isStoreAuthenticated()) {\n logErr(\"Not signed in — run `skaile store login` first.\");\n process.exit(1);\n }\n\n const rows = await pub.sourcesList();\n const source = rows.find((r) => r.url === url);\n if (!source) {\n logErr(`Source \"${slug}\" is not registered in the store — nothing to yank.`);\n process.exit(1);\n }\n\n // Optionally narrow to a single asset by name (accept a bare name or a ref).\n const targetName = opts.asset ? bareName(opts.asset) : undefined;\n const candidates = (await pub.sourceCandidates(source.id)).filter(\n (c) => c.published && (!targetName || c.name === targetName),\n );\n if (candidates.length === 0) {\n logWarn(\"No published assets matched — nothing to yank.\");\n return;\n }\n\n const yanked: string[] = [];\n for (const c of candidates) {\n try {\n await pub.assetUnpublish(c.id);\n yanked.push(`${c.kind}:${c.name}`);\n } catch (err) {\n logWarn(\n `Failed to yank ${c.kind}:${c.name}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n logOk(`Yanked ${yanked.length} asset(s):`);\n for (const r of yanked) logInfo(` ${r}`);\n}\n"]}
1
+ {"version":3,"sources":["../cli/src/commands/source-manifest-publish.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,IAAM,yBAAA,GAA4B,sBAAA;AAW3B,SAAS,0BAAA,CACd,UACA,SAAA,EACmB;AACnB,EAAA,MAAM,UAAU,QAAA,CAAS,MAAA,IAAU,EAAC,EAAG,GAAA,CAAI,CAAC,CAAA,KAAM;AAChD,IAAA,MAAM,EAAE,SAAA,EAAW,KAAA,EAAO,GAAG,MAAK,GAAI,CAAA;AACtC,IAAA,OAAO,IAAA;AAAA,EACT,CAAC,CAAA;AACD,EAAA,OAAO,EAAE,GAAG,QAAA,EAAU,SAAA,EAAW,WAAW,MAAA,EAAO;AACrD;AAWA,SAAS,YAAA,GAAuB;AAC9B,EAAA,MAAM,OAAO,OAAA,CAAQ,GAAA,CAAI,eAAe,IAAA,CAAK,OAAA,IAAW,SAAS,CAAA;AACjE,EAAA,OAAO,IAAA,CAAK,MAAM,eAAe,CAAA;AACnC;AAEA,SAAS,YAAA,GAAoC;AAC3C,EAAA,MAAM,OAAO,YAAA,EAAa;AAC1B,EAAA,IAAI,CAAC,UAAA,CAAW,IAAI,CAAA,SAAU,EAAC;AAC/B,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,KAAA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AAI,CAAA,CAAA,EAAI,CAAA,CAAE,IAAI,CAAA,EAAA,EAAK,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,OACzF;AAAA,IACF;AAAA,EACF;AAEA,EAAA,KAAA,CAAM,CAAA,OAAA,EAAU,MAAA,CAAO,MAAM,CAAA,UAAA,CAAY,CAAA;AACzC,EAAA,KAAA,MAAW,CAAA,IAAK,MAAA,EAAQ,OAAA,CAAQ,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAC1C","file":"source-manifest-publish-IJLVR3IL.js","sourcesContent":["/**\n * `skaile source manifest publish` / `yank` — the curator-publish flow. Takes a\n * locally-curated sidecar manifest (over a foreign public GitHub repo) and:\n *\n * 1. Pushes the curated `skaile.manifest.yaml` to the curator's OWN public\n * \"sidecar\" repo (bytes stay in the foreign source; the sidecar holds only\n * the manifest pointing at it).\n * 2. Registers the foreign source + the sidecar (url + pinned commit) with the\n * store, syncs it, and publishes each curated asset.\n *\n * `yank` is the inverse: unpublish each currently-published asset of the source.\n *\n * The store REST surface is reached through the injectable {@link PublisherClient}\n * (default HTTP client); git side-effects go through an injectable `spawn`. Both\n * seams keep the pure helpers + orchestration unit/integration-testable without a\n * live store or a real remote.\n *\n * @docLink cli/commands/source#manifest-publish\n */\n\nimport { spawnSync } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport {\n decodeSkaileManifest,\n encodeSkaileManifest,\n type SkPublishManifest,\n sourceCacheKey,\n} from \"@skaile/workspaces/core\";\nimport { logErr, logInfo, logOk, logWarn, S } from \"../helpers.ts\";\nimport { makeHttpPublisherClient, type PublisherClient } from \"../store-publisher.ts\";\nimport { isStoreAuthenticated } from \"../store-client.ts\";\nimport { bareName, publishToStore, refFor } from \"./publish-core.ts\";\nimport { sourceClonePath } from \"./source.ts\";\nimport { resolveSourceArg } from \"./source-manifest.ts\";\n\n/** The fixed filename a sidecar repo carries at its root. */\nconst SIDECAR_MANIFEST_FILENAME = \"skaile.manifest.yaml\";\n\n/** Injectable spawn contract — the subset of `spawnSync` these helpers use. */\ntype SpawnLike = typeof spawnSync;\n\n/**\n * Return a copy of `manifest` normalized for publication under `namespace`:\n * the top-level `publisher` is set to `namespace` and every per-asset\n * `publisher` override is removed so all assets inherit the top-level one.\n * Pure — the input is not mutated.\n */\nexport function normalizePublishedManifest(\n manifest: SkPublishManifest,\n namespace: string,\n): SkPublishManifest {\n const assets = (manifest.assets ?? []).map((a) => {\n const { publisher: _drop, ...rest } = a;\n return rest;\n });\n return { ...manifest, publisher: namespace, assets };\n}\n\n// ── Sidecar-repo association (~/.skaile/settings.json) ────────────────────────\n\n/**\n * Path to the user settings file — the same `~/.skaile/settings.json` the store\n * client reads tokens from. Resolves the `.skaile` root exactly as `getStoreRoot`\n * does (`SKAILE_HOME` when set — it IS the `.skaile` dir — else `~/.skaile`), so\n * the sidecar association lives beside the store manifests under one convention\n * and tests isolate through the same `SKAILE_HOME` seam.\n */\nfunction settingsFile(): string {\n const root = process.env.SKAILE_HOME ?? join(homedir(), \".skaile\");\n return join(root, \"settings.json\");\n}\n\nfunction readSettings(): Record<string, any> {\n const file = settingsFile();\n if (!existsSync(file)) return {};\n try {\n return JSON.parse(readFileSync(file, \"utf-8\"));\n } catch {\n return {};\n }\n}\n\n/**\n * The sidecar repo URL previously associated with a source `slug`, if any.\n * Reads `settings.sidecarRepos?.[slug]?.repo`.\n */\nexport function getSidecarRepo(slug: string): string | undefined {\n const settings = readSettings();\n return settings.sidecarRepos?.[slug]?.repo;\n}\n\n/**\n * Persist the sidecar repo URL for a source `slug`, preserving every other\n * settings key. Stored as an object (`{ repo }`) so a `path` (or other fields)\n * can be added later without a schema migration.\n */\nexport function saveSidecarRepo(slug: string, repo: string): void {\n const file = settingsFile();\n mkdirSync(dirname(file), { recursive: true });\n const settings = readSettings();\n const sidecarRepos = { ...(settings.sidecarRepos ?? {}) };\n sidecarRepos[slug] = { ...(sidecarRepos[slug] ?? {}), repo };\n settings.sidecarRepos = sidecarRepos;\n writeFileSync(file, JSON.stringify(settings, null, 2), \"utf-8\");\n}\n\n// ── Sidecar push ──────────────────────────────────────────────────────────────\n\n/**\n * Run a git command in `cwd` via the injected spawn, throwing with the captured\n * stderr on failure. Returns trimmed stdout.\n */\nfunction git(spawn: SpawnLike, cwd: string, args: string[]): string {\n const res = spawn(\"git\", [\"-C\", cwd, ...args], { encoding: \"utf-8\" });\n if (res.status !== 0) {\n const stderr = (res.stderr ?? \"\").toString().trim();\n throw new Error(`git ${args.join(\" \")} failed: ${stderr || `exit ${res.status}`}`);\n }\n return (res.stdout ?? \"\").toString().trim();\n}\n\n/**\n * Clone the curator's sidecar repo, write the curated manifest at its root, and\n * commit + push. Returns the pushed commit sha (used to pin the store source).\n *\n * Idempotent re-publish: when the manifest is unchanged `git commit` fails with\n * \"nothing to commit\" — we swallow that and return the current HEAD so a no-op\n * re-run still yields a valid pin. Any push/auth failure surfaces as a thrown\n * Error carrying git's stderr.\n */\nexport function pushSidecarManifest(opts: {\n sidecarRepoUrl: string;\n manifestText: string;\n spawn?: SpawnLike;\n}): { commitSha: string } {\n const spawn = opts.spawn ?? spawnSync;\n // Dedicated dir next to the source clone cache; wipe any stale clone first so\n // a re-publish always starts from a clean shallow checkout of the remote.\n const cloneDir = `${sourceClonePath(sourceCacheKey(opts.sidecarRepoUrl))}-sidecar-push`;\n rmSync(cloneDir, { recursive: true, force: true });\n mkdirSync(dirname(cloneDir), { recursive: true });\n\n // The clone is scratch — always remove it afterwards (success or failure) so a\n // failed push never leaves a stale checkout in the cache dir.\n try {\n const cloneRes = spawn(\"git\", [\"clone\", \"--depth\", \"1\", opts.sidecarRepoUrl, cloneDir], {\n encoding: \"utf-8\",\n });\n if (cloneRes.status !== 0) {\n const stderr = (cloneRes.stderr ?? \"\").toString().trim();\n throw new Error(\n `git clone ${opts.sidecarRepoUrl} failed: ${stderr || `exit ${cloneRes.status}`}`,\n );\n }\n\n writeFileSync(join(cloneDir, SIDECAR_MANIFEST_FILENAME), opts.manifestText, \"utf-8\");\n git(spawn, cloneDir, [\"add\", SIDECAR_MANIFEST_FILENAME]);\n\n // Fixed bot identity via -c so the commit succeeds regardless of the curator's\n // git config (the sidecar push is a machine action, not authored work).\n const commitRes = spawn(\n \"git\",\n [\n \"-C\",\n cloneDir,\n \"-c\",\n \"user.email=publish@skaile.store\",\n \"-c\",\n \"user.name=skaile\",\n \"commit\",\n \"-m\",\n \"chore(sidecar): publish curated manifest\",\n ],\n { encoding: \"utf-8\" },\n );\n if (commitRes.status !== 0) {\n const out = `${commitRes.stdout ?? \"\"}${commitRes.stderr ?? \"\"}`;\n // Nothing changed → idempotent re-publish; keep the existing HEAD.\n if (!/nothing to commit/i.test(out)) {\n throw new Error(`git commit failed: ${out.trim() || `exit ${commitRes.status}`}`);\n }\n } else {\n // `push origin HEAD` (not a bare `push`) so a fresh sidecar repo with an\n // unborn/renamed default branch still gets its branch created on the remote.\n git(spawn, cloneDir, [\"push\", \"origin\", \"HEAD\"]);\n }\n\n return { commitSha: git(spawn, cloneDir, [\"rev-parse\", \"HEAD\"]) };\n } finally {\n rmSync(cloneDir, { recursive: true, force: true });\n }\n}\n\n// ── Orchestration ───────────────────────────────────────────────────────────\n\n/**\n * `source manifest publish <src>` — publish a curated sidecar manifest to the\n * store. See the module header for the full flow. Store calls go through\n * `client` (default HTTP); git side-effects through `spawn` (default\n * `spawnSync`). The auth gate is enforced only for the default HTTP client so\n * injected fakes bypass it.\n */\nexport async function runPublish(\n arg: string,\n opts: {\n projectDir: string;\n as?: string;\n sidecarRepo?: string;\n ref?: string;\n dryRun?: boolean;\n },\n client?: PublisherClient,\n spawn: SpawnLike = spawnSync,\n): Promise<void> {\n const injected = client !== undefined;\n const pub = client ?? makeHttpPublisherClient();\n\n const { url, slug, manifestFile } = resolveSourceArg(arg, opts.projectDir);\n\n if (!existsSync(manifestFile)) {\n logErr(\n `No curated manifest for \"${slug}\" at ${S.dim(manifestFile)} — ` +\n \"run `skaile source manifest init` first.\",\n );\n process.exit(1);\n }\n\n const { manifest, diagnostics } = decodeSkaileManifest(readFileSync(manifestFile, \"utf-8\"));\n if (diagnostics.some((d) => d.severity === \"error\")) {\n for (const d of diagnostics.filter((x) => x.severity === \"error\")) {\n logErr(`${d.code}: ${d.message}`);\n }\n logErr(\n \"The curated manifest has errors — fix them with `skaile source manifest edit` / \" +\n \"`verify` before publishing.\",\n );\n process.exit(1);\n }\n\n // A real publish makes store calls (+ `me()` when `--as` is omitted), so it\n // needs a token. `--dry-run` is an offline preview: never gate it on auth.\n const authed = injected || isStoreAuthenticated();\n if (!opts.dryRun && !authed) {\n logErr(\"Not signed in — run `skaile store login` first.\");\n process.exit(1);\n }\n\n // Namespace: `--as` wins; else the caller's verified identity. Prefer the\n // GitHub handle (`githubLogin`) over the store login (`username`) — for a user\n // whose login differs from their GitHub handle the login namespace may be\n // reserved (matches the CLI's `resolveLibraryPublisher` precedence). In an\n // unauthenticated dry-run we cannot call `me()`, so show a placeholder.\n let namespace: string;\n if (opts.as) namespace = opts.as;\n else if (authed) {\n const me = await pub.me();\n // `||` not `??`: an empty-string githubLogin (partially-connected account) is\n // not a usable namespace — fall back to the login rather than publish under \"\".\n namespace = me.githubLogin || me.username;\n } else namespace = \"<your store username>\";\n\n const normalized = normalizePublishedManifest(manifest, namespace);\n const publishedText = encodeSkaileManifest(normalized);\n\n const wouldBeRefs = (normalized.assets ?? []).map((a) =>\n refFor(a.kind, namespace, a.name, a.version ?? normalized.version),\n );\n\n if (opts.dryRun) {\n const sidecar = opts.sidecarRepo ?? getSidecarRepo(slug) ?? \"<none — pass --sidecar-repo>\";\n logInfo(`Publish plan for ${S.bold(slug)}:`);\n logInfo(` namespace: ${namespace}`);\n logInfo(` sidecar repo: ${sidecar}`);\n logInfo(` source ref: ${opts.ref ?? \"main\"}`);\n logInfo(` would publish ${wouldBeRefs.length} asset(s):`);\n for (const r of wouldBeRefs) logInfo(` ${r}`);\n return;\n }\n\n const sidecarRepoUrl = opts.sidecarRepo ?? getSidecarRepo(slug);\n if (!sidecarRepoUrl) {\n logErr(\n \"No sidecar repo associated with this source. Pass \" +\n `${S.cmd(\"--sidecar-repo https://github.com/<you>/<repo>\")} — it must be a ` +\n \"PUBLIC GitHub repo you own; the curated manifest is committed there and the \" +\n \"store pins to that commit.\",\n );\n process.exit(1);\n }\n if (opts.sidecarRepo) saveSidecarRepo(slug, sidecarRepoUrl);\n\n const { commitSha } = pushSidecarManifest({ sidecarRepoUrl, manifestText: publishedText, spawn });\n logOk(`Pushed curated manifest to ${S.dim(sidecarRepoUrl)} @ ${commitSha.slice(0, 10)}.`);\n\n // The FOREIGN repo's ref to ingest (branch/sha). Defaults to `main`.\n const sourceRef = opts.ref ?? \"main\";\n\n const { published } = await publishToStore({\n sourceUrl: url,\n ref: sourceRef,\n sidecar: { url: sidecarRepoUrl, ref: commitSha },\n manifest: normalized,\n client: pub,\n });\n\n if (published.length > 0) {\n logInfo(`Consumers can now install them with \\`skaile add ${published[0]}\\`.`);\n }\n}\n\n/**\n * `source manifest yank <src>` — unpublish the source's published assets (all,\n * or the single asset matching `opts.asset`'s name). Auth-gated like publish.\n */\nexport async function runYank(\n arg: string,\n opts: { projectDir: string; asset?: string },\n client?: PublisherClient,\n): Promise<void> {\n const injected = client !== undefined;\n const pub = client ?? makeHttpPublisherClient();\n\n const { url, slug } = resolveSourceArg(arg, opts.projectDir);\n\n if (!injected && !isStoreAuthenticated()) {\n logErr(\"Not signed in — run `skaile store login` first.\");\n process.exit(1);\n }\n\n const rows = await pub.sourcesList();\n const source = rows.find((r) => r.url === url);\n if (!source) {\n logErr(`Source \"${slug}\" is not registered in the store — nothing to yank.`);\n process.exit(1);\n }\n\n // Optionally narrow to a single asset by name (accept a bare name or a ref).\n const targetName = opts.asset ? bareName(opts.asset) : undefined;\n const candidates = (await pub.sourceCandidates(source.id)).filter(\n (c) => c.published && (!targetName || c.name === targetName),\n );\n if (candidates.length === 0) {\n logWarn(\"No published assets matched — nothing to yank.\");\n return;\n }\n\n const yanked: string[] = [];\n for (const c of candidates) {\n try {\n await pub.assetUnpublish(c.id);\n yanked.push(`${c.kind}:${c.name}`);\n } catch (err) {\n logWarn(\n `Failed to yank ${c.kind}:${c.name}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n logOk(`Yanked ${yanked.length} asset(s):`);\n for (const r of yanked) logInfo(` ${r}`);\n}\n"]}
package/dist/tui/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { createAgentSession } from '../chunk-OWMHVP6Q.js';
2
- import '../chunk-7GCOHM2S.js';
1
+ import { createAgentSession } from '../chunk-3H4HP733.js';
2
+ import '../chunk-XRTOSEF3.js';
3
3
  import '../chunk-PQE2MYB6.js';
4
4
  import '../chunk-KU473DRO.js';
5
5
  import '../chunk-P2DLXBZK.js';
@@ -15,21 +15,21 @@ import '../chunk-73ZXUUL6.js';
15
15
  import '../chunk-32NA4TVC.js';
16
16
  import '../chunk-W3UDISS2.js';
17
17
  import '../chunk-PE3A6FFW.js';
18
- import '../chunk-5OAMRXJZ.js';
18
+ import '../chunk-AAZDYM5D.js';
19
19
  import '../chunk-4R6DROGN.js';
20
20
  import '../chunk-T3YUSWVK.js';
21
21
  import '../chunk-Q6NDQ6BH.js';
22
22
  import '../chunk-ZK7DQRB2.js';
23
- import '../chunk-UBDQFZZH.js';
23
+ import '../chunk-NYDTZ2MK.js';
24
24
  import '../chunk-UF4AEO54.js';
25
25
  import { loadConnectorDeclarations } from '../chunk-MC2MF4U5.js';
26
- import '../chunk-LPPRZAO5.js';
27
- import '../chunk-4SIMGJIU.js';
26
+ import '../chunk-D5CRFGDL.js';
27
+ import '../chunk-3W7AOGPY.js';
28
28
  import '../chunk-LOO5CB5M.js';
29
29
  import '../chunk-TOXPRXAK.js';
30
- import '../chunk-B6IDJRRZ.js';
30
+ import '../chunk-JURHZYOY.js';
31
31
  import '../chunk-BGY4KTU6.js';
32
- import '../chunk-ZCKQQJ7K.js';
32
+ import '../chunk-3VGQLF3N.js';
33
33
  import '../chunk-6E6PKKAD.js';
34
34
  import '../chunk-IFGTRL2I.js';
35
35
  import '../chunk-KTCMBEEB.js';
@@ -1,4 +1,4 @@
1
- export { PluginStore, WorkspacePlugin, buildClaudePluginFiles, resolveProjectDir } from '../chunk-7GCOHM2S.js';
1
+ export { PluginStore, WorkspacePlugin, buildClaudePluginFiles, resolveProjectDir } from '../chunk-XRTOSEF3.js';
2
2
  export { err, ok, okJson } from '../chunk-X5YPJV4N.js';
3
3
  import '../chunk-JMKB7IB4.js';
4
4
  import '../chunk-C3CAXQMA.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skaile/workspaces",
3
- "version": "4.16.3",
3
+ "version": "4.17.0",
4
4
  "description": "Skaile workspaces runtime — types, core, bridge, runner, store, connectors, and supporting layers as one publishable package",
5
5
  "type": "module",
6
6
  "packageManager": "bun@1.3.9",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../bridge/src/cloud.ts","../bridge/src/drivers/scrub-transcript.ts","../bridge/src/drivers/resume-probe.ts"],"names":["join"],"mappings":";;;;;;;;;AAuCA,IAAM,iBAAA,GAAoB,CAAC,mBAAA,EAAqB,sBAAA,EAAwB,oBAAoB,CAAA;AAQrF,IAAM,0BAAA,GAA6B;AAQ1C,IAAM,iBAAA,GAA0C;AAAA,EAC9C,mBAAA,EAAqB,IAAA;AAAA,EACrB,aAAA,EAAe,IAAA;AAAA,EACf,WAAA,EAAa;AACf,CAAA;AAcO,SAAS,mBAAmB,KAAA,EAA4C;AAC7E,EAAA,MAAM,UAAW,KAAA,CAA6B,OAAA;AAC9C,EAAA,MAAM,SAAA,GAAY,eAAe,KAAK,CAAA;AACtC,EAAA,IAAI,OAAA,KAAY,yBAAA,IAA6B,SAAA,KAAc,SAAA,EAAW,OAAO,SAAA;AAC7E,EA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GAA0B,GAAA;AAwBzB,SAAS,uBAAuB,GAAA,EAAkD;AACvF,EAAA,OAAO,GAAA,EAAK,qBAAqB,OAAA,CAAQ,GAAA,CAAI,qBAAqBA,IAAAA,CAAK,OAAA,IAAW,SAAS,CAAA;AAC7F;AAgBA,eAAsB,qBAAA,CACpB,WACA,IAAA,EAKyC;AACzC,EAAA,MAAM,SAAA,GAAY,sBAAA,CAAuB,IAAA,EAAM,GAAG,CAAA;AAClD,EAAA,MAAM,SAAA,GAAY,MAAM,SAAA,IAAa,uBAAA;AACrC,EAAA,MAAM,MAAA,GAAS,MAAM,MAAA,IAAU,oBAAA;AAC/B,EAAA,IAAI;AAIF,IAAA,MAAM,WAAW,MAAM,cAAA;AAAA,MACrB,gBAAgB,SAAS,CAAA,CAAA;AAAA,MACzB,MAAM,MAAA,CAAO,SAAA,EAAW,SAAS,CAAA;AAAA,MACjC;AAAA,KACF;AACA,IAAA,OAAO,WAAW,kBAAA,GAAqB,YAAA;AAAA,EACzC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"chunk-4SIMGJIU.js","sourcesContent":["/**\n * AI endpoint transport for the `claude-sdk` driver — the Claude Agent SDK's\n * child-process environment.\n *\n * {@link buildClaudeEndpointEnv} takes an **AI provider registry entry** and\n * is what the driver calls, on every transport. It is plan §2.3's\n * `buildEndpointEnv` for the claude-sdk row (named for the driver because the\n * vars it emits — `CLAUDE_CODE_USE_*`, `ANTHROPIC_*` — are the Claude Agent\n * SDK's own contract, not a portable one).\n *\n * A registry entry says what the deleted `cloud` axis said — Amazon Bedrock,\n * Google Vertex AI, Azure AI Foundry, a generic gateway — with `surface` +\n * `transport` + `base_url` + `credential`, and says it for the direct\n * endpoint too, which the `cloud` axis could not address at all.\n *\n * Cross-repo contract: env key names and semantics here are load-bearing —\n * the platform resolves credential bundles against the same key set.\n */\n\nimport {\n type AIProviderEntry,\n type AIProviderLlmEntry,\n entryTransport,\n normalizeAnthropicBaseUrl,\n resolveEntryBaseUrl,\n} from \"@skaile/workspaces/core/provider-registry\";\n\n/**\n * Env vars scrubbed from the inherited environment before an endpoint env is\n * assembled. Ambient first-party credentials or a stale `CLAUDE_CODE_USE_*`\n * flag must never leak into a session whose entry points elsewhere (the\n * ambient carriers are restored explicitly when the entry has none of its\n * own).\n *\n * Deliberately NOT exhaustive: ambient transport-specific vars (AWS_*,\n * GOOGLE_*, ANTHROPIC_VERTEX_PROJECT_ID, ANTHROPIC_FOUNDRY_*) survive so a\n * standalone CLI inherits its own signing chain; the SDK ignores vars whose\n * transport flag is unset.\n */\nconst SCRUBBED_ENV_KEYS = [\"ANTHROPIC_API_KEY\", \"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_BASE_URL\"];\n\n/**\n * The Anthropic first-party endpoint. An entry that resolves to exactly this\n * host needs no `ANTHROPIC_BASE_URL`: the SDK already points there, and an\n * explicit value would make every default session look like a third-party\n * redirect to Claude Code's own telemetry and auth heuristics.\n */\nexport const ANTHROPIC_DEFAULT_BASE_URL = \"https://api.anthropic.com\";\n\n/**\n * Headers the SDK owns and an entry must not restate through\n * `ANTHROPIC_CUSTOM_HEADERS`: the protocol version it was built against, and\n * the two credential carriers (which are `credential.ref`'s job — a literal\n * secret in `headers` is a validation error anyway).\n */\nconst SDK_OWNED_HEADERS: Record<string, true> = {\n \"anthropic-version\": true,\n authorization: true,\n \"x-api-key\": true,\n};\n\n/**\n * Which of the Claude Agent SDK's four native transports an entry addresses.\n *\n * The SDK has no `transport` field: it switches on a `CLAUDE_CODE_USE_*` flag.\n * Bedrock and Vertex are their own wire surfaces, so they are recognized by\n * `surface` as well as by `transport` — a legacy-derived entry that had no\n * region (and therefore no `params`, and therefore no `transport`) is still a\n * Bedrock session, exactly as it was before the registry existed.\n */\nexport type ClaudeEndpointMode = \"anthropic\" | \"bedrock\" | \"vertex\" | \"foundry\";\n\n/** Classify a registry entry into its {@link ClaudeEndpointMode}. */\nexport function claudeEndpointMode(entry: AIProviderEntry): ClaudeEndpointMode {\n const surface = (entry as AIProviderLlmEntry).surface;\n const transport = entryTransport(entry);\n if (surface === \"bedrock-converse-stream\" || transport === \"bedrock\") return \"bedrock\";\n if (surface === \"google-vertex\" || transport === \"vertex\") return \"vertex\";\n if (transport === \"foundry\") return \"foundry\";\n return \"anthropic\";\n}\n\n/** Arguments for {@link buildClaudeEndpointEnv}. */\nexport interface ClaudeEndpointEnvInput {\n /** The selected registry entry — the whole endpoint definition. */\n entry: AIProviderEntry;\n /**\n * The entry's credential, already resolved from its `credential.ref`\n * (`resolveEntryCredential`). Absent for `kind: none`, for an ambient\n * `sigv4` / `google_adc` / `azure_entra` chain, for `oauth` (whose blob the\n * runner writes to the Claude credentials file, never to the env), and for a\n * reference that did not resolve.\n */\n credential?: string;\n /**\n * The driver's base environment — `process.env` with `undefined` dropped.\n * The endpoint vars are layered **on top** of it, never instead of it, so\n * `PATH`, `HOME` and `SKAILE_SESSION_ID` reach the child.\n */\n baseEnv: Record<string, string>;\n /** `AgentConfig.env` plus any credential material the session carried. */\n configEnv?: Record<string, string>;\n}\n\n/**\n * Assemble the Claude Agent SDK child env for one registry entry (plan §2.3).\n *\n * Pure (no external state read, no input mutated). Starts from `baseEnv`\n * merged with `configEnv`, scrubs the inherited Anthropic credential/routing\n * vars and every `CLAUDE_CODE_USE_*` flag, then writes exactly what the entry\n * describes: at most one transport flag, the endpoint, and the credential in\n * the carrier its `kind` names.\n *\n * Credential kinds (§1.4): `api_key_header` → `ANTHROPIC_API_KEY` (the SDK\n * sends it as `x-api-key`); `bearer` → `ANTHROPIC_AUTH_TOKEN` (sent as\n * `Authorization: Bearer`); `sigv4` / `google_adc` / `azure_entra` emit\n * nothing and let the AWS/Google/Azure chain sign — which is why the scrub\n * deliberately spares ambient `AWS_*` / `GOOGLE_*` values; `oauth` and `none`\n * emit nothing, and the pre-scrub ambient carriers are restored so an OAuth or\n * shell-configured session keeps the auth it had.\n *\n * Never returns `undefined` or empty values; absent settings are omitted.\n */\nexport function buildClaudeEndpointEnv(args: ClaudeEndpointEnvInput): Record<string, string> {\n const { entry, credential, baseEnv, configEnv } = args;\n const env: Record<string, string> = { ...baseEnv, ...(configEnv ?? {}) };\n\n // Captured before the scrub — an entry with no credential material of its\n // own falls back to these, the way the gateway branch always has.\n const ambient = { authToken: env.ANTHROPIC_AUTH_TOKEN, apiKey: env.ANTHROPIC_API_KEY };\n\n for (const key of Object.keys(env)) {\n if (SCRUBBED_ENV_KEYS.includes(key) || key.startsWith(\"CLAUDE_CODE_USE_\")) {\n delete env[key];\n }\n }\n\n const set = (key: string, value: string | undefined) => {\n // Falsy check is deliberate: an empty-string credential/setting is never\n // valid env — dropping it beats shipping a key the SDK treats as set.\n if (value) env[key] = value;\n };\n\n const kind = entry.credential?.kind ?? \"none\";\n const params = (entry as AIProviderLlmEntry).params as Record<string, string> | undefined;\n\n // Static headers ride as ANTHROPIC_CUSTOM_HEADERS (`Name: Value` per line),\n // the only channel the SDK offers. An entry with none leaves an ambient\n // value alone.\n const headers = Object.entries(entry.headers ?? {}).filter(\n ([name]) => !SDK_OWNED_HEADERS[name.toLowerCase()],\n );\n if (headers.length > 0) {\n env.ANTHROPIC_CUSTOM_HEADERS = headers.map(([name, value]) => `${name}: ${value}`).join(\"\\n\");\n }\n\n switch (claudeEndpointMode(entry)) {\n case \"bedrock\": {\n env.CLAUDE_CODE_USE_BEDROCK = \"1\";\n // The AWS credential bundle itself is `configEnv` material (AWS_*), and\n // ambient AWS_* survived the scrub, so a standalone CLI keeps its own.\n set(\"AWS_REGION\", params?.region);\n break;\n }\n case \"vertex\": {\n env.CLAUDE_CODE_USE_VERTEX = \"1\";\n // GOOGLE_APPLICATION_CREDENTIALS is a path the runner materialized; it\n // arrives through `configEnv` or ambient, never from `credential`.\n set(\"ANTHROPIC_VERTEX_PROJECT_ID\", params?.project);\n set(\"CLOUD_ML_REGION\", params?.location);\n break;\n }\n case \"foundry\": {\n env.CLAUDE_CODE_USE_FOUNDRY = \"1\";\n // §1.3: an explicit `base_url` wins over the resource-derived endpoint,\n // and the SDK has a separate var for each form.\n if (entry.base_url) set(\"ANTHROPIC_FOUNDRY_BASE_URL\", entry.base_url);\n else set(\"ANTHROPIC_FOUNDRY_RESOURCE\", params?.resource);\n set(\"ANTHROPIC_FOUNDRY_API_KEY\", credential);\n break;\n }\n case \"anthropic\": {\n const baseUrl = normalizeAnthropicBaseUrl(resolveEntryBaseUrl(entry));\n if (baseUrl && baseUrl.toLowerCase() !== ANTHROPIC_DEFAULT_BASE_URL) {\n env.ANTHROPIC_BASE_URL = baseUrl;\n }\n if (kind === \"bearer\") set(\"ANTHROPIC_AUTH_TOKEN\", credential);\n else if (kind === \"api_key_header\") set(\"ANTHROPIC_API_KEY\", credential);\n if (!credential) {\n // `oauth` / `none` / an unresolved ref: the ambient carriers are the\n // only auth this session has, and the scrub just removed them.\n if (ambient.authToken) env.ANTHROPIC_AUTH_TOKEN = ambient.authToken;\n else set(\"ANTHROPIC_API_KEY\", ambient.apiKey);\n }\n break;\n }\n }\n\n return env;\n}\n","/**\n * Poisoned-transcript repair for the Claude Agent SDK driver.\n *\n * The Anthropic Messages API can permanently reject a conversation once its\n * persisted history contains a malformed content block. Because the bad block\n * lives in the SDK's on-disk JSONL transcript, every replayed turn fails with\n * the same `400 invalid_request_error` and the session is bricked with no\n * in-band recovery.\n *\n * This module repairs the transcript in place, covering three known poison\n * classes:\n *\n * 1. **Image `media_type` mismatch / omission.** An image block whose declared\n * `media_type` does not match — or is missing for — the actual bytes:\n * `... The image was specified using the image/png media type, but the\n * image appears to be a image/jpeg image`. Produced by the Claude Code\n * `Read` tool's format fallback (anthropics/claude-code#55338, #30124,\n * #33179). Repaired by sniffing the base64 magic bytes and correcting\n * `media_type`.\n * 2. **Oversized image.** An image whose decoded payload exceeds the API's\n * 5 MB per-image limit (anthropics/claude-code#34566). Replaced with a\n * text stub — the byte budget cannot be recovered any other way.\n * 3. **`cache_control` on an empty text block.** A text block carrying a\n * `cache_control` marker with empty/whitespace `text`\n * (anthropics/claude-code#59626). The `cache_control` field is stripped.\n *\n * Genuinely unidentifiable image blocks are also replaced with a text stub.\n *\n * Recovering by content scan (rather than parsing the API's `messages.N`\n * index) is deliberate: the index addresses the assembled API request, not a\n * JSONL line, and reproducing the SDK's message-assembly is fragile. A full\n * scan is index-free and repairs every poisoned block in one pass.\n *\n * **Async and line-streaming since #454.** A Claude Code transcript is routinely\n * multi-megabyte (base64 images inline in `tool_result` blocks), and this runs on\n * a failed turn *and before every resume* — inside the single-threaded `skaile\n * serve` loop. The previous `readFileSync` + `writeFileSync` + `renameSync` held\n * the loop for the whole file and materialised it twice over as one string. Both\n * passes now stream line by line off a `createReadStream`, so the loop is yielded\n * between lines and peak memory is one JSONL line rather than the whole file, and\n * every I/O phase is deadline-bounded.\n *\n * Streaming was chosen over a worker thread: the work is I/O-bound rather than\n * CPU-bound (per-line `JSON.parse` on a yielded loop is not what stalls a turn),\n * and a worker would add a structured-clone of the same multi-MB payload plus a\n * thread lifecycle to a path that must never block a turn.\n *\n * @module\n */\n\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport { readdir, rename, stat, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { fsDeadlineMs, tryWithFsDeadline, withFsDeadline } from \"@skaile/workspaces/core\";\n\n/**\n * Minimal logger shape accepted by {@link scrubPoisonedTranscript}. Compatible\n * with the bridge `Logger`, but narrowed so the helper stays unit-testable\n * without a real logger instance.\n *\n * @category Transcript repair\n */\nexport interface ScrubLogger {\n info(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n}\n\n/**\n * Options for {@link scrubPoisonedTranscript}.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptOptions {\n /**\n * Claude Code config directory — the parent of `projects/`. Resolve from\n * `CLAUDE_CONFIG_DIR`, falling back to `~/.claude`.\n */\n configDir: string;\n /** SDK session id whose transcript JSONL should be repaired. */\n sessionId: string;\n /** Optional logger for diagnostics. */\n log?: ScrubLogger;\n}\n\n/**\n * Outcome of a {@link scrubPoisonedTranscript} pass.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptResult {\n /** The located JSONL transcript path, or `null` when not found. */\n filePath: string | null;\n /** Image blocks whose `media_type` was corrected (or filled in) to match the bytes. */\n corrected: number;\n /**\n * Image blocks replaced with a text stub — either unidentifiable bytes or a\n * payload over the API's 5 MB per-image limit.\n */\n stubbed: number;\n /** Empty text blocks from which a rejected `cache_control` marker was stripped. */\n cacheStripped: number;\n /**\n * `true` when the transcript was located, contained at least one poisoned\n * block, and was rewritten. `false` means nothing needed repair (or the\n * file was not found) — the caller should not retry the resume.\n */\n changed: boolean;\n}\n\n/** Text inserted in place of an image block whose format cannot be identified. */\nconst STUB_TEXT = \"[image removed: unprocessable image data]\";\n\n/** Text inserted in place of an image block that exceeds the API size limit. */\nconst STUB_TEXT_OVERSIZED = \"[image removed: image too large]\";\n\n/**\n * The Anthropic Messages API rejects any single image whose decoded payload\n * exceeds 5 MB. An image at or under this is left alone; a larger one is\n * stubbed (its byte budget cannot be recovered).\n */\nconst MAX_IMAGE_BYTES = 5 * 1024 * 1024;\n\n/**\n * Identify an image's media type from the leading bytes of its base64 payload.\n *\n * Recognises the four formats the Anthropic API accepts. Returns `null` when\n * the magic bytes match no known format — the caller treats that as a\n * genuinely corrupt block and stubs it.\n *\n * @param base64 - Base64-encoded image data (only the prefix is inspected).\n * @returns An `image/*` media type, or `null` when unrecognised.\n * @category Transcript repair\n */\nexport function sniffImageMediaType(base64: string): string | null {\n let buf: Buffer;\n try {\n // 32 base64 chars decode to 24 bytes — enough for the WebP check at 12.\n buf = Buffer.from(base64.slice(0, 32), \"base64\");\n } catch {\n return null;\n }\n if (buf.length < 4) {\n return null;\n }\n // JPEG — SOI marker `FF D8`. Third byte varies (and may be corrupt), so a\n // two-byte check is intentional: it still matches malformed JPEGs, which is\n // exactly the poison case the API flags as \"appears to be image/jpeg\".\n if (buf[0] === 0xff && buf[1] === 0xd8) {\n return \"image/jpeg\";\n }\n // PNG — `89 50 4E 47`.\n if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {\n return \"image/png\";\n }\n // GIF — `47 49 46 38` (\"GIF8\").\n if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38) {\n return \"image/gif\";\n }\n // WebP — `RIFF` at 0..3 and `WEBP` at 8..11.\n if (\n buf.length >= 12 &&\n buf[0] === 0x52 &&\n buf[1] === 0x49 &&\n buf[2] === 0x46 &&\n buf[3] === 0x46 &&\n buf[8] === 0x57 &&\n buf[9] === 0x45 &&\n buf[10] === 0x42 &&\n buf[11] === 0x50\n ) {\n return \"image/webp\";\n }\n return null;\n}\n\n/** A base64 image source on a content block (shape is SDK-defined). */\ninterface Base64ImageSource {\n type?: string;\n media_type?: string;\n data?: string;\n}\n\n/** Loosely-typed content block from a transcript message. */\ninterface ContentBlockLike {\n type?: string;\n source?: Base64ImageSource;\n content?: unknown;\n [k: string]: unknown;\n}\n\n/** Mutable counters threaded through one scrub pass. */\ninterface ScrubCounters {\n corrected: number;\n stubbed: number;\n cacheStripped: number;\n}\n\n/** Total repairs recorded in a counter set — used to detect per-line changes. */\nfunction totalChanges(c: ScrubCounters): number {\n return c.corrected + c.stubbed + c.cacheStripped;\n}\n\n/**\n * Repair a single content block. Returns the (possibly replaced) block.\n *\n * - A `tool_result` block recurses into its `content` array.\n * - A text block carrying a `cache_control` marker whose `text` is empty or\n * whitespace has the marker stripped (the API rejects `cache_control` on\n * empty text blocks).\n * - An image block whose decoded payload exceeds the API's 5 MB limit is\n * replaced with a text stub.\n * - An image block whose bytes match no known format is replaced with a text\n * stub (an image cannot simply be dropped — a `tool_result` must keep at\n * least one content entry, and a bare `image` block is replaced 1:1).\n * - An image block whose declared `media_type` mismatches (or is missing for)\n * the sniffed type is corrected in place.\n * - Every other block is returned untouched.\n */\nfunction scrubBlock(block: ContentBlockLike, counters: ScrubCounters): ContentBlockLike {\n if (block.type === \"tool_result\" && Array.isArray(block.content)) {\n return {\n ...block,\n content: (block.content as ContentBlockLike[]).map((inner) => scrubBlock(inner, counters)),\n };\n }\n\n // A `cache_control` marker on a text block whose text is empty or whitespace\n // is rejected by the API (\"cache_control cannot be set for empty text\n // blocks\"). Strip the marker — the empty block itself is harmless.\n if (block.type === \"text\" && block.cache_control != null) {\n const text = typeof block.text === \"string\" ? block.text : \"\";\n if (text.trim() === \"\") {\n counters.cacheStripped++;\n const clone = { ...block };\n delete clone.cache_control;\n return clone;\n }\n }\n\n if (\n block.type === \"image\" &&\n block.source?.type === \"base64\" &&\n typeof block.source.data === \"string\"\n ) {\n const data = block.source.data;\n // The API rejects any image whose decoded payload exceeds 5 MB. The byte\n // budget cannot be salvaged, so the whole block becomes a text stub.\n // base64 encodes 3 bytes per 4 chars, so decoded length ≈ len * 3 / 4.\n if (Math.floor((data.length * 3) / 4) > MAX_IMAGE_BYTES) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT_OVERSIZED };\n }\n const sniffed = sniffImageMediaType(data);\n if (sniffed === null) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT };\n }\n if (sniffed !== block.source.media_type) {\n counters.corrected++;\n return { ...block, source: { ...block.source, media_type: sniffed } };\n }\n }\n\n return block;\n}\n\n/**\n * Locate the JSONL transcript for `sessionId` under `<configDir>/projects/`.\n *\n * Claude Code encodes the project directory into the `projects/` subfolder\n * name; rather than reproduce that encoding, this scans every subfolder for\n * `<sessionId>.jsonl` (the session id is a UUID — globally unique).\n *\n * Async and deadline-bounded since #454. The `existsSync(projectsDir)` probe is\n * gone: `readdir` already fails on a missing directory, so the probe was a\n * second stat on the same path for no information.\n *\n * `timeoutMs` defaults to {@link fsDeadlineMs} so callers that only need the\n * path (the resume probe) can omit it.\n *\n * @category Transcript repair\n */\nexport async function locateTranscriptPath(\n configDir: string,\n sessionId: string,\n timeoutMs: number = fsDeadlineMs(),\n): Promise<string | null> {\n const projectsDir = join(configDir, \"projects\");\n const entries = await tryWithFsDeadline(\n `readdir ${projectsDir}`,\n () => readdir(projectsDir),\n null,\n timeoutMs,\n );\n if (!entries) return null;\n for (const entry of entries) {\n const candidate = join(projectsDir, entry, `${sessionId}.jsonl`);\n const found = await tryWithFsDeadline(\n `stat ${candidate}`,\n async () => (await stat(candidate)).isFile(),\n false,\n timeoutMs,\n );\n if (found) return candidate;\n }\n return null;\n}\n\n/**\n * Yield a file's contents line by line, reproducing `readFileSync(...).split(\"\\n\")`\n * exactly — including the final (possibly empty) segment, so a trailing newline\n * survives a rewrite byte for byte.\n *\n * Splits on `\\n` alone, so a line out of a CRLF transcript arrives with its\n * `\\r` still attached. That carrier byte is part of the line here, and\n * {@link repairLine} re-attaches it to a line it rewrites — the file keeps the\n * terminator style it arrived with. Deliberately not `node:readline`:\n * `crlfDelay` strips the `\\r` outright (rewriting a CRLF transcript to LF) and\n * the interface swallows the trailing-newline distinction, either of which\n * would make the \"clean transcript is left byte-for-byte untouched\" guarantee\n * false. Only one line is held in memory at a time, so a multi-MB transcript\n * never materialises as a single string.\n */\nasync function* streamLines(filePath: string): AsyncGenerator<string> {\n const stream = createReadStream(filePath, { encoding: \"utf8\" });\n let pending = \"\";\n try {\n for await (const chunk of stream) {\n pending += chunk as string;\n let idx = pending.indexOf(\"\\n\");\n while (idx !== -1) {\n yield pending.slice(0, idx);\n pending = pending.slice(idx + 1);\n idx = pending.indexOf(\"\\n\");\n }\n }\n yield pending;\n } finally {\n stream.destroy();\n }\n}\n\n/**\n * Repair one JSONL line, returning the (possibly rewritten) line and mutating\n * `counters`. A non-JSON, blank, or content-less line is returned untouched.\n *\n * The reader splits on `\\n` only, so a line from a CRLF transcript still carries\n * its trailing `\\r`. An untouched line is returned verbatim and keeps it; a\n * rewritten one is rebuilt by `JSON.stringify`, which would drop it — leaving a\n * repaired CRLF transcript with mixed line endings. So the terminator is split\n * off before the parse and re-appended to the rewritten line.\n */\nfunction repairLine(line: string, counters: ScrubCounters): string {\n if (line.trim() === \"\") return line;\n const eol = line.endsWith(\"\\r\") ? \"\\r\" : \"\";\n const body = eol === \"\" ? line : line.slice(0, -1);\n let entry: { message?: { content?: unknown } };\n try {\n entry = JSON.parse(body);\n } catch {\n return line; // Not JSON — leave untouched.\n }\n const content = entry.message?.content;\n if (!Array.isArray(content)) return line;\n const before = totalChanges(counters);\n const scrubbed = (content as ContentBlockLike[]).map((block) => scrubBlock(block, counters));\n if (totalChanges(counters) === before) return line; // Nothing changed on this line.\n return `${JSON.stringify({ ...entry, message: { ...entry.message, content: scrubbed } })}${eol}`;\n}\n\n/**\n * Scan a Claude Code SDK transcript for image content blocks whose declared\n * `media_type` does not match the actual bytes, repair them, and atomically\n * rewrite the file.\n *\n * Safe to call after a turn has failed: the SDK query is dead at that point,\n * and the next resume re-reads the transcript from disk.\n *\n * **Async since #454.** Two streaming passes rather than one whole-file read:\n * pass 1 counts repairs without writing anything, and pass 2 runs only when\n * pass 1 found something. The common case — the preventive scrub of a clean\n * transcript before every resume — is therefore one streaming read and zero\n * writes, and a clean transcript is still left byte-for-byte untouched.\n *\n * @param opts - Config directory, session id, and an optional logger.\n * @returns A {@link ScrubTranscriptResult}. When `changed` is `true` the\n * caller may retry the resume with the same session id.\n * @category Transcript repair\n */\nexport async function scrubPoisonedTranscript(\n opts: ScrubTranscriptOptions,\n): Promise<ScrubTranscriptResult> {\n const { configDir, sessionId, log } = opts;\n const timeoutMs = fsDeadlineMs();\n const result: ScrubTranscriptResult = {\n filePath: null,\n corrected: 0,\n stubbed: 0,\n cacheStripped: 0,\n changed: false,\n };\n\n const filePath = await locateTranscriptPath(configDir, sessionId, timeoutMs);\n if (!filePath) {\n log?.warn(\"scrub-transcript: no transcript found\", { configDir, sessionId });\n return result;\n }\n result.filePath = filePath;\n\n // ── Pass 1: detect. Streams the transcript, counting repairs, writing nothing.\n const counters: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n try {\n await withFsDeadline(\n `scan transcript ${filePath}`,\n async () => {\n for await (const line of streamLines(filePath)) repairLine(line, counters);\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to read transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n return result;\n }\n\n result.corrected = counters.corrected;\n result.stubbed = counters.stubbed;\n result.cacheStripped = counters.cacheStripped;\n\n if (totalChanges(counters) === 0) {\n return result;\n }\n\n // ── Pass 2: rewrite. Atomic: stream a sibling temp file, then rename over the\n // original. Line separators are re-emitted exactly as pass 1 split them, so a\n // trailing newline and any blank lines survive verbatim.\n const tmpPath = `${filePath}.scrub-tmp`;\n try {\n await withFsDeadline(\n `rewrite transcript ${filePath}`,\n async () => {\n const discard: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n await pipeline(\n (async function* () {\n let first = true;\n for await (const line of streamLines(filePath)) {\n yield first ? repairLine(line, discard) : `\\n${repairLine(line, discard)}`;\n first = false;\n }\n })(),\n createWriteStream(tmpPath, { encoding: \"utf8\" }),\n );\n await rename(tmpPath, filePath);\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to rewrite transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n // Never leave a half-written sibling behind — the next scrub would rewrite\n // it anyway, but a stray `.scrub-tmp` in the SDK's projects dir is noise.\n await tryWithFsDeadline(`unlink ${tmpPath}`, () => unlink(tmpPath), undefined, timeoutMs);\n return result;\n }\n\n result.changed = true;\n log?.info(\"scrub-transcript: repaired poisoned transcript\", {\n filePath,\n corrected: result.corrected,\n stubbed: result.stubbed,\n cacheStripped: result.cacheStripped,\n });\n return result;\n}\n","/**\n * Pre-first-turn resume probe for the Claude Agent SDK driver.\n *\n * A tier-1 native resume only hands its session id to the SDK inside the first\n * real turn, so the `jsonl_lost` outcome (\"No conversation found\") is invisible\n * until a turn is consumed. The runner shares the container filesystem with the\n * SDK, so a cheap `stat` of the on-disk JSONL transcript is an authoritative,\n * side-effect-free signal of whether the resume will find its history — no\n * probe query, no spurious model turn.\n *\n * @module\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { withFsDeadline } from \"@skaile/workspaces/core\";\nimport { locateTranscriptPath } from \"./scrub-transcript.js\";\n\n/**\n * Overall wall-clock budget for the probe. Deliberately a small fraction of the\n * platform's `session_init_ack` timeout (`DEFAULT_INIT_ACK_TIMEOUT_MS`, 15s):\n * the probe runs synchronously on the pre-ack path, so a wedged\n * `CLAUDE_CONFIG_DIR` mount must never push the ack past its deadline.\n */\nconst RESUME_PROBE_TIMEOUT_MS = 2_000;\n\n/**\n * Outcome of {@link probeResumeTranscript}: whether the SDK transcript for a\n * requested tier-1 resume exists on disk.\n *\n * @category Resume probe\n */\nexport type ResumeProbeOutcome = \"transcript_found\" | \"jsonl_lost\";\n\n/**\n * Resolve the Claude Code config directory — the parent of `projects/` — from\n * an explicit env map, the process environment, or the `~/.claude` default.\n *\n * The runner's probe and the claude-sdk driver share this one resolver, so they\n * agree as long as they see the same `CLAUDE_CONFIG_DIR`. Today they do:\n * `CLAUDE_CONFIG_DIR` is container-scoped and neither side threads a per-session\n * override through `config.env`, so both fall through to `process.env`. If a\n * future change ever set the driver's `config.env.CLAUDE_CONFIG_DIR` to a\n * divergent path, the reactive `resume_failed { jsonl_lost }` turn remains the\n * safety net.\n *\n * @category Resume probe\n */\nexport function resolveClaudeConfigDir(env?: Record<string, string | undefined>): string {\n return env?.CLAUDE_CONFIG_DIR || process.env.CLAUDE_CONFIG_DIR || join(homedir(), \".claude\");\n}\n\n/**\n * Probe whether the SDK JSONL transcript for `sessionId` exists on disk.\n *\n * Non-null locator result → `transcript_found`; null → `jsonl_lost`;\n * `undefined` → outcome unknown (the probe exceeded its budget or errored). The\n * caller leaves the ack field ABSENT on `undefined` so the reactive\n * `resume_failed { jsonl_lost }` turn stays the safety net — a timed-out probe\n * must never masquerade as a genuine `jsonl_lost` and force a needless downgrade.\n *\n * `opts.timeoutMs` overrides {@link RESUME_PROBE_TIMEOUT_MS}; `opts.locate`\n * overrides the transcript locator (used by tests / alternate stores).\n *\n * @category Resume probe\n */\nexport async function probeResumeTranscript(\n sessionId: string,\n opts?: {\n env?: Record<string, string | undefined>;\n timeoutMs?: number;\n locate?: (configDir: string, sessionId: string) => Promise<string | null>;\n },\n): Promise<ResumeProbeOutcome | undefined> {\n const configDir = resolveClaudeConfigDir(opts?.env);\n const timeoutMs = opts?.timeoutMs ?? RESUME_PROBE_TIMEOUT_MS;\n const locate = opts?.locate ?? locateTranscriptPath;\n try {\n // Bound the whole probe on wall-clock and THROW on expiry: the inner per-op\n // deadline swallows a timeout into a null path (a false `jsonl_lost`), so a\n // wedged mount must yield \"unknown\" here rather than a spurious downgrade.\n const filePath = await withFsDeadline(\n `resume-probe ${sessionId}`,\n () => locate(configDir, sessionId),\n timeoutMs,\n );\n return filePath ? \"transcript_found\" : \"jsonl_lost\";\n } catch {\n return undefined;\n }\n}\n"]}