@iowarp/clio-coder 0.3.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 (226) hide show
  1. package/CHANGELOG.md +407 -0
  2. package/CODE_OF_CONDUCT.md +21 -0
  3. package/CONTRIBUTING.md +224 -0
  4. package/LICENSE +202 -0
  5. package/NOTICE +9 -0
  6. package/README.md +798 -0
  7. package/SECURITY.md +72 -0
  8. package/assets/clio-coder-logo-128.webp +0 -0
  9. package/damage-control-rules.yaml +419 -0
  10. package/dist/acp-UMLFVA3F.js +92 -0
  11. package/dist/agents-Q4MYPMUW.js +91 -0
  12. package/dist/auth-O6HYIJ6J.js +521 -0
  13. package/dist/chunk-262G75JS.js +35 -0
  14. package/dist/chunk-26BZQOAD.js +1281 -0
  15. package/dist/chunk-2J63S4SF.js +508 -0
  16. package/dist/chunk-3DANZDGR.js +717 -0
  17. package/dist/chunk-4UQA7NCT.js +29 -0
  18. package/dist/chunk-527KG6XR.js +497 -0
  19. package/dist/chunk-5LDRNKX2.js +1063 -0
  20. package/dist/chunk-5N2FG33Q.js +25 -0
  21. package/dist/chunk-67MTHP2E.js +135 -0
  22. package/dist/chunk-6CWDTGUC.js +20 -0
  23. package/dist/chunk-7BHLZB3A.js +2115 -0
  24. package/dist/chunk-7RBKDI66.js +348 -0
  25. package/dist/chunk-AMFR5YA3.js +541 -0
  26. package/dist/chunk-BBUH4VAA.js +1224 -0
  27. package/dist/chunk-BYEU76JP.js +899 -0
  28. package/dist/chunk-CLJ5HLUD.js +458 -0
  29. package/dist/chunk-D5YD55AR.js +116 -0
  30. package/dist/chunk-DXQNI4PC.js +61 -0
  31. package/dist/chunk-E3NYWENM.js +1004 -0
  32. package/dist/chunk-GNGDQYDU.js +34688 -0
  33. package/dist/chunk-GOTUR54M.js +9 -0
  34. package/dist/chunk-HBU5MTAM.js +41 -0
  35. package/dist/chunk-HMYNFFY4.js +28 -0
  36. package/dist/chunk-JPOWPFCU.js +1010 -0
  37. package/dist/chunk-JWHCJDCI.js +1215 -0
  38. package/dist/chunk-KBR4MZZR.js +41 -0
  39. package/dist/chunk-KKKPTZLM.js +93 -0
  40. package/dist/chunk-ME6DNWIU.js +66 -0
  41. package/dist/chunk-NI4DEJMC.js +88 -0
  42. package/dist/chunk-O4EJEDHO.js +659 -0
  43. package/dist/chunk-PIDUD6M2.js +31 -0
  44. package/dist/chunk-PS4PFJQP.js +29459 -0
  45. package/dist/chunk-QV47YRF4.js +48 -0
  46. package/dist/chunk-RQDWMVRB.js +279 -0
  47. package/dist/chunk-TFSSEXL6.js +136 -0
  48. package/dist/chunk-TKHQ4DGZ.js +8290 -0
  49. package/dist/chunk-TPOCL34A.js +2876 -0
  50. package/dist/chunk-UGYAX5YI.js +565 -0
  51. package/dist/chunk-UHTSULZS.js +461 -0
  52. package/dist/chunk-UU3R62TT.js +128 -0
  53. package/dist/chunk-UWIJNAOB.js +3906 -0
  54. package/dist/chunk-VOO7NYPP.js +914 -0
  55. package/dist/chunk-VPAWTYLY.js +117 -0
  56. package/dist/chunk-WD6AJM35.js +1216 -0
  57. package/dist/chunk-X3BR7HWV.js +115 -0
  58. package/dist/chunk-X3NE4WVW.js +120 -0
  59. package/dist/chunk-XNISANGE.js +1395 -0
  60. package/dist/chunk-XV4ZJ6ZM.js +3177 -0
  61. package/dist/cli/index.js +236 -0
  62. package/dist/clio-KIQ5SNDS.js +53 -0
  63. package/dist/components-JVHMUBEB.js +653 -0
  64. package/dist/config-ZFCDBMDC.js +372 -0
  65. package/dist/configure-G4E3A2PG.js +27 -0
  66. package/dist/context-CDXTP2MP.js +293 -0
  67. package/dist/context-E3KIFVXI.js +185 -0
  68. package/dist/context-clear-3F4PLXOS.js +102 -0
  69. package/dist/context-index-Q7YSYTR3.js +106 -0
  70. package/dist/docs-YIETIWZI.js +280 -0
  71. package/dist/doctor-M5HJJZOL.js +61 -0
  72. package/dist/domains/agents/builtins/architect.md +33 -0
  73. package/dist/domains/agents/builtins/coder.md +31 -0
  74. package/dist/domains/agents/builtins/context-bootstrap.md +38 -0
  75. package/dist/domains/agents/builtins/debugger.md +30 -0
  76. package/dist/domains/agents/builtins/documenter.md +31 -0
  77. package/dist/domains/agents/builtins/git-master.md +30 -0
  78. package/dist/domains/agents/builtins/provenance.md +30 -0
  79. package/dist/domains/agents/builtins/researcher.md +71 -0
  80. package/dist/domains/agents/builtins/scout.md +42 -0
  81. package/dist/domains/agents/builtins/tester.md +31 -0
  82. package/dist/domains/agents/builtins/verifier.md +30 -0
  83. package/dist/domains/agents/builtins/wiki-writer.md +41 -0
  84. package/dist/eval-B3KZZESM.js +2674 -0
  85. package/dist/evidence-V67CHM35.js +233 -0
  86. package/dist/evolve-YDZSUQYA.js +518 -0
  87. package/dist/extensions-SRG7XCAH.js +207 -0
  88. package/dist/fleet-CA2CRTVG.js +760 -0
  89. package/dist/fleet-preflight-CLIAX7YR.js +21 -0
  90. package/dist/init-2OZDJE2D.js +227 -0
  91. package/dist/memory-3PIQQAKX.js +207 -0
  92. package/dist/models-DY35XI7Y.js +237 -0
  93. package/dist/paths-5OMXW7Z4.js +57 -0
  94. package/dist/preload-KZVHET2B.js +11 -0
  95. package/dist/reset-PIFYNOS3.js +216 -0
  96. package/dist/run-3VSPP24F.js +735 -0
  97. package/dist/share-D36RQCXM.js +241 -0
  98. package/dist/skills-F2MRLELY.js +445 -0
  99. package/dist/skills-eval-E2ZTW4PL.js +932 -0
  100. package/dist/targets-DZMEZAH4.js +977 -0
  101. package/dist/trace-7NYCUI2J.js +250 -0
  102. package/dist/uninstall-AD3JWHBB.js +322 -0
  103. package/dist/upgrade-WYYBKGDY.js +301 -0
  104. package/dist/usage-ULIDAGFF.js +755 -0
  105. package/dist/version-ROZ6CZKH.js +16 -0
  106. package/dist/wiki-generate-PKFIX6OB.js +377 -0
  107. package/dist/worker/entry.js +1739 -0
  108. package/docs/README.md +93 -0
  109. package/docs/acp.md +120 -0
  110. package/docs/alcf-provider.md +72 -0
  111. package/docs/architecture.md +172 -0
  112. package/docs/artifact-versions.md +54 -0
  113. package/docs/built-in-agents.md +265 -0
  114. package/docs/capacity-and-scheduling.md +97 -0
  115. package/docs/commands-and-modes.md +554 -0
  116. package/docs/config-knobs-audit.md +115 -0
  117. package/docs/configuration-and-targets.md +812 -0
  118. package/docs/context-engine.md +236 -0
  119. package/docs/dispatch-architecture-rationale.md +126 -0
  120. package/docs/documentation-coverage.md +46 -0
  121. package/docs/documentation-guide.md +166 -0
  122. package/docs/environment-variables.md +105 -0
  123. package/docs/eval-runner.md +205 -0
  124. package/docs/evals-internal.md +298 -0
  125. package/docs/evidence-and-memory.md +243 -0
  126. package/docs/evolution.md +143 -0
  127. package/docs/exit-codes-and-output.md +74 -0
  128. package/docs/extensions-and-sharing.md +306 -0
  129. package/docs/fleet-demo-runbook.md +179 -0
  130. package/docs/fleet-dispatch.md +591 -0
  131. package/docs/glossary.md +75 -0
  132. package/docs/html/agents_blueprint.html +936 -0
  133. package/docs/html/alcf_blueprint.html +324 -0
  134. package/docs/html/architecture_blueprint.html +850 -0
  135. package/docs/html/commands_blueprint.html +794 -0
  136. package/docs/html/config_knobs_audit_blueprint.html +178 -0
  137. package/docs/html/configuration_blueprint.html +1080 -0
  138. package/docs/html/context_blueprint.html +603 -0
  139. package/docs/html/documentation_blueprint.html +832 -0
  140. package/docs/html/environment_blueprint.html +404 -0
  141. package/docs/html/eval_blueprint.html +743 -0
  142. package/docs/html/evals_internal_blueprint.html +190 -0
  143. package/docs/html/evolution_blueprint.html +674 -0
  144. package/docs/html/extensions_blueprint.html +2065 -0
  145. package/docs/html/fleet_dispatch_blueprint.html +286 -0
  146. package/docs/html/index.html +919 -0
  147. package/docs/html/lifecycle_blueprint.html +723 -0
  148. package/docs/html/memory_blueprint.html +699 -0
  149. package/docs/html/middleware_blueprint.html +664 -0
  150. package/docs/html/models_blueprint.html +2366 -0
  151. package/docs/html/observability_blueprint.html +683 -0
  152. package/docs/html/provider_adapter_blueprint.html +245 -0
  153. package/docs/html/safety_blueprint.html +1386 -0
  154. package/docs/html/shared.css +571 -0
  155. package/docs/html/shared.js +143 -0
  156. package/docs/html/skills_blueprint.html +671 -0
  157. package/docs/html/soak_blueprint.html +182 -0
  158. package/docs/html/tool_usage_blueprint.html +350 -0
  159. package/docs/html/tools_blueprint.html +2249 -0
  160. package/docs/html/trace_blueprint.html +235 -0
  161. package/docs/html/tui_design_blueprint.html +314 -0
  162. package/docs/html/validation_blueprint.html +961 -0
  163. package/docs/html/worker_dispatch_blueprint.html +231 -0
  164. package/docs/installation-and-lifecycle.md +308 -0
  165. package/docs/middleware-and-components.md +148 -0
  166. package/docs/model-catalog.md +189 -0
  167. package/docs/observability.md +233 -0
  168. package/docs/proactive-memory.md +452 -0
  169. package/docs/prompt-envelope-and-tools.md +142 -0
  170. package/docs/provider-adapter-cookbook.md +148 -0
  171. package/docs/release-cut-checklist.md +138 -0
  172. package/docs/safety-model.md +357 -0
  173. package/docs/scientific-validation.md +105 -0
  174. package/docs/session-lifecycle.md +156 -0
  175. package/docs/skills-marketplace.md +46 -0
  176. package/docs/tool-usage.md +527 -0
  177. package/docs/trace-store.md +132 -0
  178. package/docs/troubleshooting.md +33 -0
  179. package/docs/tui-design.md +239 -0
  180. package/docs/worker-dispatch-mechanics.md +242 -0
  181. package/package.json +132 -0
  182. package/skills/README.md +408 -0
  183. package/skills/git/commit-crafting/SKILL.md +79 -0
  184. package/skills/git/commit-crafting/evals.md +92 -0
  185. package/skills/git/create-pr/SKILL.md +116 -0
  186. package/skills/git/create-pr/evals.md +114 -0
  187. package/skills/git/investigate-issue/SKILL.md +139 -0
  188. package/skills/git/investigate-issue/evals.md +94 -0
  189. package/skills/git/resolve-merge-conflicts/SKILL.md +96 -0
  190. package/skills/git/resolve-merge-conflicts/evals.md +58 -0
  191. package/skills/git/review-changes/SKILL.md +103 -0
  192. package/skills/git/review-changes/evals.md +85 -0
  193. package/skills/git/worktree-create/SKILL.md +92 -0
  194. package/skills/git/worktree-create/evals.md +97 -0
  195. package/skills/git/worktree-create/references/worktree-setup.md +66 -0
  196. package/skills/git/worktree-merge/SKILL.md +95 -0
  197. package/skills/git/worktree-merge/evals.md +114 -0
  198. package/skills/skill-marketplace.json +261 -0
  199. package/skills/workflow/cut-it/SKILL.md +86 -0
  200. package/skills/workflow/cut-it/evals.md +42 -0
  201. package/src/domains/agents/builtins/architect.md +33 -0
  202. package/src/domains/agents/builtins/coder.md +31 -0
  203. package/src/domains/agents/builtins/context-bootstrap.md +38 -0
  204. package/src/domains/agents/builtins/debugger.md +30 -0
  205. package/src/domains/agents/builtins/documenter.md +31 -0
  206. package/src/domains/agents/builtins/git-master.md +30 -0
  207. package/src/domains/agents/builtins/provenance.md +30 -0
  208. package/src/domains/agents/builtins/researcher.md +71 -0
  209. package/src/domains/agents/builtins/scout.md +42 -0
  210. package/src/domains/agents/builtins/tester.md +31 -0
  211. package/src/domains/agents/builtins/verifier.md +30 -0
  212. package/src/domains/agents/builtins/wiki-writer.md +41 -0
  213. package/src/domains/agents/fleets/build-review.md +34 -0
  214. package/src/domains/agents/fleets/build-test.md +35 -0
  215. package/src/domains/agents/fleets/sdlc.md +86 -0
  216. package/src/domains/prompts/fragments/identity/clio-worker.md +11 -0
  217. package/src/domains/prompts/fragments/identity/clio.md +26 -0
  218. package/src/domains/prompts/fragments/operating/contract.md +64 -0
  219. package/src/domains/prompts/fragments/safety/auto-edit.md +14 -0
  220. package/src/domains/prompts/fragments/safety/full-auto.md +14 -0
  221. package/src/domains/prompts/fragments/safety/read-only.md +13 -0
  222. package/src/domains/prompts/fragments/safety/suggest.md +13 -0
  223. package/src/domains/prompts/fragments/wiki/page.md +75 -0
  224. package/src/domains/prompts/fragments/wiki/plan.md +48 -0
  225. package/src/domains/providers/models/cloud-models/alcf.yaml +40 -0
  226. package/src/domains/providers/models/local-models/clio-local-coding-targets.yaml +993 -0
@@ -0,0 +1,1395 @@
1
+ import {
2
+ createDelayedManualCodeInput,
3
+ promptOAuthSelection
4
+ } from "./chunk-KKKPTZLM.js";
5
+ import {
6
+ column,
7
+ terminalColumns,
8
+ truncate,
9
+ twoColumnRow,
10
+ wrapPlain
11
+ } from "./chunk-ME6DNWIU.js";
12
+ import {
13
+ fingerprintNativeRuntime
14
+ } from "./chunk-262G75JS.js";
15
+ import {
16
+ initializeClioHome
17
+ } from "./chunk-TFSSEXL6.js";
18
+ import {
19
+ credentialWriteFailed,
20
+ printPlaintextCredentialWarning
21
+ } from "./chunk-PIDUD6M2.js";
22
+ import {
23
+ printError,
24
+ printOk
25
+ } from "./chunk-67MTHP2E.js";
26
+ import {
27
+ buildProviderSupportEntry,
28
+ configuredTargetsForRuntime,
29
+ credentialsPresent,
30
+ describeRuntimeModels,
31
+ getCatalogModelForRuntime,
32
+ getRuntimeRegistry,
33
+ isOrchestratorEligibleRuntime,
34
+ listKnownModelsForRuntime,
35
+ listProviderSupportEntries,
36
+ probeCapabilitiesForModel,
37
+ registerBuiltinRuntimes,
38
+ supportGroupLabel
39
+ } from "./chunk-TKHQ4DGZ.js";
40
+ import {
41
+ readSettings,
42
+ settingsPath,
43
+ updateSettings
44
+ } from "./chunk-JWHCJDCI.js";
45
+ import {
46
+ openAuthStorage,
47
+ registerClioOAuthProviders,
48
+ resolveAuthTarget,
49
+ resolveRuntimeAuthTarget,
50
+ targetRequiresAuth
51
+ } from "./chunk-5LDRNKX2.js";
52
+
53
+ // src/cli/configure.ts
54
+ import { stdin as input, stdout as output } from "node:process";
55
+ import { createInterface } from "node:readline/promises";
56
+
57
+ // src/cli/configure-layout.ts
58
+ function maxLength(values) {
59
+ return values.reduce((widest, value) => Math.max(widest, value.length), 0);
60
+ }
61
+ var CONFIGURE_CATEGORY_CHOICES = [
62
+ {
63
+ category: "local-app",
64
+ label: "Local app",
65
+ summary: "Ollama or LM Studio (recommended for new users)",
66
+ aliases: ["local"]
67
+ },
68
+ {
69
+ category: "local-http",
70
+ label: "Local HTTP server",
71
+ summary: "llama.cpp / vLLM / SGLang / OpenAI/Anthropic-compatible",
72
+ aliases: ["http"]
73
+ },
74
+ {
75
+ category: "chatgpt",
76
+ label: "ChatGPT plan",
77
+ summary: "Plus or Pro via Codex OAuth",
78
+ aliases: ["codex"]
79
+ },
80
+ {
81
+ category: "cloud-api",
82
+ label: "Cloud API key",
83
+ summary: "Anthropic, OpenAI, OpenRouter, Groq, Google, DeepSeek, Mistral, Bedrock, or any OpenAI/Anthropic-compatible endpoint (e.g. Inception)",
84
+ aliases: ["cloud"]
85
+ },
86
+ {
87
+ category: "all",
88
+ label: "All runtimes",
89
+ summary: "advanced (full list)",
90
+ aliases: ["a"]
91
+ }
92
+ ];
93
+ function formatCategoryMenu(width) {
94
+ const leftWidth = maxLength(CONFIGURE_CATEGORY_CHOICES.map((choice, index) => `${index + 1}. ${choice.label}`)) + 2;
95
+ const lines = [];
96
+ for (const [index, choice] of CONFIGURE_CATEGORY_CHOICES.entries()) {
97
+ lines.push(...twoColumnRow(`${index + 1}. ${choice.label}`, choice.summary, { indent: 2, leftWidth, width }));
98
+ }
99
+ return lines;
100
+ }
101
+ function matchCategoryChoice(answer) {
102
+ const lc = answer.trim().toLowerCase();
103
+ if (lc.length === 0) return null;
104
+ for (const [index, choice] of CONFIGURE_CATEGORY_CHOICES.entries()) {
105
+ if (lc === String(index + 1) || lc === choice.category || choice.aliases.includes(lc)) {
106
+ return choice.category;
107
+ }
108
+ }
109
+ return null;
110
+ }
111
+ function formatRuntimeMenu(items, width) {
112
+ if (items.length === 0) return [];
113
+ const leftWidth = maxLength(items.map((item, index) => `${String(index + 1).padStart(2)}. ${item.runtimeId}`)) + 1;
114
+ const lines = [];
115
+ let lastGroup = null;
116
+ const grouped = new Set(items.map((item) => item.group)).size > 1;
117
+ for (const [index, item] of items.entries()) {
118
+ if (grouped && item.group !== lastGroup) {
119
+ lastGroup = item.group;
120
+ lines.push(` ${item.group}:`);
121
+ }
122
+ lines.push(
123
+ ...twoColumnRow(`${String(index + 1).padStart(2)}. ${item.runtimeId}`, item.summary, {
124
+ indent: 4,
125
+ leftWidth,
126
+ width
127
+ })
128
+ );
129
+ }
130
+ return lines;
131
+ }
132
+ var LIST_INDENT = 2;
133
+ var LIST_GAP = 1;
134
+ var LIST_MIN_MODELS = 16;
135
+ function formatRuntimeList(rows, width) {
136
+ if (rows.length === 0) return [];
137
+ const targetCells = rows.map((row) => `targets=${row.targets}`);
138
+ const idWidth = maxLength(rows.map((row) => row.runtimeId));
139
+ const labelWidth = maxLength(rows.map((row) => row.label));
140
+ const authWidth = maxLength(rows.map((row) => row.auth));
141
+ const targetsWidth = maxLength(targetCells);
142
+ const alignedWidth = LIST_INDENT + idWidth + LIST_GAP + labelWidth + LIST_GAP + authWidth + LIST_GAP + targetsWidth;
143
+ const inline = width >= alignedWidth + LIST_GAP + LIST_MIN_MODELS;
144
+ const pad = " ".repeat(LIST_INDENT);
145
+ const detailPad = " ".repeat(LIST_INDENT + 2);
146
+ const lines = [];
147
+ let lastGroup = null;
148
+ for (const [index, row] of rows.entries()) {
149
+ if (row.group !== lastGroup) {
150
+ if (lastGroup !== null) lines.push("");
151
+ lastGroup = row.group;
152
+ lines.push(`${row.group}:`);
153
+ }
154
+ const targetCell = targetCells[index] ?? "";
155
+ const models = `models=${row.models}`;
156
+ if (inline) {
157
+ const id = column(row.runtimeId, idWidth);
158
+ const label = column(row.label, labelWidth);
159
+ const auth = column(row.auth, authWidth);
160
+ lines.push(truncate(`${pad}${id} ${label} ${auth} ${column(targetCell, targetsWidth)} ${models}`, width));
161
+ continue;
162
+ }
163
+ lines.push(truncate(`${pad}${column(row.runtimeId, idWidth)} ${column(row.auth, authWidth)} ${targetCell}`, width));
164
+ lines.push(truncate(`${detailPad}${row.label} \xB7 ${models}`, width));
165
+ }
166
+ return lines;
167
+ }
168
+
169
+ // src/cli/validate-model.ts
170
+ function validateModelChoice(input2) {
171
+ const { runtimeId, modelId, knownModels, force } = input2;
172
+ if (knownModels.length === 0) return { ok: true };
173
+ if (knownModels.includes(modelId)) return { ok: true };
174
+ if (force) {
175
+ return {
176
+ ok: true,
177
+ warning: `model '${modelId}' not in ${runtimeId} catalog (use without --force to reject)`
178
+ };
179
+ }
180
+ const sample = knownModels.slice(0, 10).join(", ");
181
+ return {
182
+ ok: false,
183
+ reason: `model '${modelId}' not in ${runtimeId} catalog. Known: ${sample}. Use --force to skip validation.`,
184
+ knownModels: knownModels.slice(0, 10)
185
+ };
186
+ }
187
+
188
+ // src/cli/configure.ts
189
+ var HELP = `clio-coder configure
190
+
191
+ Configure model targets for chat and fleet-agent dispatch.
192
+
193
+ Usage:
194
+ clio-coder configure interactive wizard
195
+ clio-coder configure --list list target runtimes (user-facing only)
196
+ clio-coder configure --list --all list every registered runtime including aliases
197
+ clio-coder configure --id <targetId> [flags] --runtime <runtimeId>
198
+
199
+ Non-interactive flags:
200
+ --id <targetId> target id to register (required when non-interactive)
201
+ --runtime <runtimeId> runtime to use when registering non-interactively
202
+ --url <host> target base URL (http(s):// or ws://)
203
+ --model <wireModelId> default model id for this target
204
+ --orchestrator-model <id> model to use when setting chat default
205
+ --background-model <id> model to use for proactive task memory
206
+ --fleet-model <id> model to use when setting fleet default
207
+ (mutually exclusive with --agent-profile)
208
+ --agent-profile <name> save this target as a named fleet profile
209
+ --agent-profile-model <id> model to use for --agent-profile
210
+ --api-key-env <VAR> read API key from this env var at call time
211
+ --api-key <literal> store API key in credentials.yaml
212
+ --force allow a model outside the runtime catalog
213
+ --gateway mark the target as a gateway
214
+ --lifecycle <user-managed|clio-managed>
215
+ resident model lifecycle policy
216
+ --set-orchestrator use this target for chat
217
+ --set-background use this target for proactive task memory
218
+ --set-fleet-default use this target for the fleet default
219
+ --context-window <N> capability override
220
+ --max-tokens <N> output token capability override
221
+ --reasoning <true|false> capability override
222
+ `;
223
+ var DEFAULT_PORTS = {
224
+ llamacpp: 8080,
225
+ "llamacpp-anthropic": 8080,
226
+ "llamacpp-completion": 8080,
227
+ "llamacpp-embed": 8080,
228
+ "llamacpp-rerank": 8080,
229
+ "lmstudio-native": 1234,
230
+ "ollama-native": 11434,
231
+ vllm: 8e3,
232
+ sglang: 3e4,
233
+ "lemonade-anthropic": 8e3,
234
+ lemonade: 8e3,
235
+ "anthropic-compat": 8e3,
236
+ "openai-compat": 8e3
237
+ };
238
+ function parseSetupArgs(argv) {
239
+ const out = {
240
+ positional: [],
241
+ help: false,
242
+ list: false,
243
+ all: false,
244
+ force: false,
245
+ gateway: false,
246
+ setOrchestrator: false,
247
+ setBackground: false,
248
+ setWorkerDefault: false
249
+ };
250
+ for (let i = 0; i < argv.length; i++) {
251
+ const a = argv[i];
252
+ const need = () => {
253
+ const v = argv[i + 1];
254
+ if (v === void 0) throw new Error(`${a} requires a value`);
255
+ i += 1;
256
+ return v;
257
+ };
258
+ switch (a) {
259
+ case "--help":
260
+ case "-h":
261
+ out.help = true;
262
+ break;
263
+ case "--list":
264
+ out.list = true;
265
+ break;
266
+ case "--all":
267
+ out.all = true;
268
+ break;
269
+ case "--remove":
270
+ out.remove = need();
271
+ break;
272
+ case "--rename":
273
+ out.renameOld = need();
274
+ out.renameNew = need();
275
+ break;
276
+ case "--id":
277
+ out.id = need();
278
+ break;
279
+ case "--runtime":
280
+ out.runtime = need();
281
+ break;
282
+ case "--url":
283
+ out.url = need();
284
+ break;
285
+ case "--model":
286
+ out.model = need();
287
+ break;
288
+ case "--orchestrator-model":
289
+ out.orchestratorModel = need();
290
+ break;
291
+ case "--background-model":
292
+ out.backgroundModel = need();
293
+ break;
294
+ case "--fleet-model":
295
+ case "--worker-model":
296
+ out.workerModel = need();
297
+ break;
298
+ case "--agent-profile":
299
+ case "--worker-profile":
300
+ out.workerProfile = need();
301
+ break;
302
+ case "--agent-profile-model":
303
+ case "--worker-profile-model":
304
+ out.workerProfileModel = need();
305
+ break;
306
+ case "--api-key-env":
307
+ out.apiKeyEnv = need();
308
+ break;
309
+ case "--api-key":
310
+ out.apiKey = need();
311
+ break;
312
+ case "--force":
313
+ out.force = true;
314
+ break;
315
+ case "--gateway":
316
+ out.gateway = true;
317
+ break;
318
+ case "--lifecycle": {
319
+ const v = need();
320
+ if (v !== "user-managed" && v !== "clio-managed") {
321
+ throw new Error("--lifecycle must be user-managed or clio-managed");
322
+ }
323
+ out.lifecycle = v;
324
+ break;
325
+ }
326
+ case "--set-orchestrator":
327
+ out.setOrchestrator = true;
328
+ break;
329
+ case "--set-background":
330
+ out.setBackground = true;
331
+ break;
332
+ case "--set-fleet-default":
333
+ case "--set-worker-default":
334
+ out.setWorkerDefault = true;
335
+ break;
336
+ case "--context-window": {
337
+ const n = Number(need());
338
+ if (!Number.isFinite(n) || n <= 0) throw new Error("--context-window must be a positive number");
339
+ out.contextWindow = Math.floor(n);
340
+ break;
341
+ }
342
+ case "--max-tokens": {
343
+ const n = Number(need());
344
+ if (!Number.isFinite(n) || n <= 0) throw new Error("--max-tokens must be a positive number");
345
+ out.maxTokens = Math.floor(n);
346
+ break;
347
+ }
348
+ case "--reasoning": {
349
+ const v = need().toLowerCase();
350
+ if (v !== "true" && v !== "false") throw new Error("--reasoning must be true or false");
351
+ out.reasoning = v === "true";
352
+ break;
353
+ }
354
+ default:
355
+ if (a.startsWith("-")) throw new Error(`unknown flag: ${a}`);
356
+ out.positional.push(a);
357
+ }
358
+ }
359
+ return out;
360
+ }
361
+ function ensureRegistryPopulated() {
362
+ registerClioOAuthProviders();
363
+ const registry = getRuntimeRegistry();
364
+ if (registry.list().length === 0) registerBuiltinRuntimes(registry);
365
+ }
366
+ function trimTrailing(url) {
367
+ return url.endsWith("/") && url.length > 1 ? url.slice(0, -1) : url;
368
+ }
369
+ function normalizeUrl(input2, runtimeId) {
370
+ const trimmed = input2.trim();
371
+ if (trimmed.length === 0) return defaultUrlFor(runtimeId);
372
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed);
373
+ const withScheme = hasScheme ? trimmed : `http://${trimmed}`;
374
+ try {
375
+ const parsed = new URL(withScheme);
376
+ if (!hasScheme && !parsed.port && DEFAULT_PORTS[runtimeId]) {
377
+ parsed.port = String(DEFAULT_PORTS[runtimeId]);
378
+ }
379
+ return trimTrailing(parsed.toString());
380
+ } catch {
381
+ return trimTrailing(withScheme);
382
+ }
383
+ }
384
+ function defaultUrlFor(runtimeId) {
385
+ const port = DEFAULT_PORTS[runtimeId];
386
+ return port ? `http://127.0.0.1:${port}` : "http://127.0.0.1:8080";
387
+ }
388
+ var RUNTIME_LIST_CAPTION = "every registered runtime. run `clio-coder auth list` for the ones clio authenticates itself; the rest authenticate through their own tool (claude-cli, aws-sdk) or need no credential.";
389
+ function printRuntimeList(includeHidden) {
390
+ const settings = readSettings();
391
+ const auth = openAuthStorage();
392
+ const rows = [];
393
+ for (const entry of listProviderSupportEntries(getRuntimeRegistry().list(), { includeHidden })) {
394
+ const runtime = getRuntimeRegistry().get(entry.runtimeId);
395
+ const status = runtime && entry.connectable ? auth.statusForTarget(resolveRuntimeAuthTarget(runtime), { includeFallback: false }) : null;
396
+ const authLabel = runtime?.auth === "oauth" ? status?.available ? "connected" : "login" : runtime?.auth === "api-key" ? status?.available ? "credential" : "needs-key" : runtime?.auth ?? "none";
397
+ rows.push({
398
+ group: supportGroupLabel(entry.group),
399
+ runtimeId: entry.runtimeId,
400
+ label: entry.label,
401
+ auth: authLabel,
402
+ targets: configuredTargetsForRuntime(settings, entry.runtimeId).length,
403
+ models: describeRuntimeModels(entry, 2)
404
+ });
405
+ }
406
+ const width = terminalColumns();
407
+ for (const line of formatRuntimeList(rows, width)) {
408
+ process.stdout.write(`${line}
409
+ `);
410
+ }
411
+ for (const line of wrapPlain(RUNTIME_LIST_CAPTION, width)) {
412
+ process.stdout.write(`${line}
413
+ `);
414
+ }
415
+ }
416
+ function deriveTargetId(runtimeId, existing) {
417
+ const base = runtimeId;
418
+ const taken = new Set(existing.map((e) => e.id));
419
+ if (!taken.has(base)) return base;
420
+ for (let i = 2; i < 1e3; i++) {
421
+ const candidate = `${base}-${i}`;
422
+ if (!taken.has(candidate)) return candidate;
423
+ }
424
+ return `${base}-${Date.now()}`;
425
+ }
426
+ async function buildProbeContext(runtime, target) {
427
+ const probeCtx = {
428
+ credentialsPresent: credentialsPresent(),
429
+ httpTimeoutMs: 5e3
430
+ };
431
+ if (!runtime || !target || !targetRequiresAuth(target, runtime)) return probeCtx;
432
+ try {
433
+ const resolution = await openAuthStorage().resolveForTarget(resolveAuthTarget(target, runtime), {
434
+ includeFallback: false
435
+ });
436
+ if (resolution.apiKey) probeCtx.authToken = resolution.apiKey;
437
+ } catch {
438
+ }
439
+ return probeCtx;
440
+ }
441
+ function runtimeKnownModelsFor(runtimeId) {
442
+ return listKnownModelsForRuntime(runtimeId);
443
+ }
444
+ function catalogContextWindowFor(runtime, modelId) {
445
+ const catalogModel = getCatalogModelForRuntime(runtime.id, modelId);
446
+ if (typeof catalogModel?.contextWindow === "number" && catalogModel.contextWindow > 0) {
447
+ return catalogModel.contextWindow;
448
+ }
449
+ if (runtimeKnownModelsFor(runtime.id).includes(modelId) && runtime.defaultCapabilities.contextWindow > 0) {
450
+ return runtime.defaultCapabilities.contextWindow;
451
+ }
452
+ return null;
453
+ }
454
+ function validateResolvedModel(runtimeId, modelId, force) {
455
+ if (!modelId) return true;
456
+ const validation = validateModelChoice({
457
+ runtimeId,
458
+ modelId,
459
+ knownModels: runtimeKnownModelsFor(runtimeId),
460
+ force
461
+ });
462
+ if (!validation.ok) {
463
+ process.stderr.write(`error: ${validation.reason}
464
+ `);
465
+ return false;
466
+ }
467
+ if (validation.warning) process.stderr.write(`warning: ${validation.warning}
468
+ `);
469
+ return true;
470
+ }
471
+ function validateContextWindowOverride(runtime, modelId, contextWindow, force) {
472
+ if (contextWindow === void 0 || !modelId) return true;
473
+ const catalogMax = catalogContextWindowFor(runtime, modelId);
474
+ if (catalogMax === null || contextWindow <= catalogMax) return true;
475
+ const message = `--context-window ${contextWindow} exceeds catalog max ${catalogMax} for model '${modelId}'`;
476
+ if (!force) {
477
+ process.stderr.write(`error: ${message}. Use --force to override.
478
+ `);
479
+ return false;
480
+ }
481
+ process.stderr.write(`warning: ${message}
482
+ `);
483
+ return true;
484
+ }
485
+ async function runtimeProbe(runtime, target) {
486
+ if (typeof runtime.probe !== "function") return null;
487
+ try {
488
+ return await runtime.probe(target, await buildProbeContext(runtime, target));
489
+ } catch (err) {
490
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
491
+ }
492
+ }
493
+ async function runtimeProbeModels(runtime, target) {
494
+ if (typeof runtime.probeModels !== "function") return [];
495
+ try {
496
+ return await runtime.probeModels(target, await buildProbeContext(runtime, target));
497
+ } catch {
498
+ return [];
499
+ }
500
+ }
501
+ function applyTarget(settings, descriptor) {
502
+ const idx = settings.targets.findIndex((e) => e.id === descriptor.id);
503
+ if (idx >= 0) settings.targets[idx] = descriptor;
504
+ else settings.targets.push(descriptor);
505
+ }
506
+ function setOrchestratorPointer(settings, descriptor, model) {
507
+ const runtime = getRuntimeRegistry().get(descriptor.runtime);
508
+ if (!runtime) {
509
+ throw new Error(
510
+ `cannot use target '${descriptor.id}' as orchestrator target because runtime '${descriptor.runtime}' is not registered`
511
+ );
512
+ }
513
+ if (!isOrchestratorEligibleRuntime(runtime)) {
514
+ throw new Error(
515
+ `cannot use target '${descriptor.id}' as orchestrator target because runtime '${runtime.id}' is not an HTTP/native runtime`
516
+ );
517
+ }
518
+ settings.orchestrator.target = descriptor.id;
519
+ settings.orchestrator.model = model ?? descriptor.defaultModel ?? null;
520
+ }
521
+ function setWorkerDefaultPointer(settings, descriptor, model) {
522
+ settings.workers.default.target = descriptor.id;
523
+ settings.workers.default.model = model ?? descriptor.defaultModel ?? null;
524
+ }
525
+ function setBackgroundPointer(settings, descriptor, model) {
526
+ const runtime = getRuntimeRegistry().get(descriptor.runtime);
527
+ if (!runtime || !isOrchestratorEligibleRuntime(runtime)) {
528
+ throw new Error(
529
+ `cannot use target '${descriptor.id}' as background target because runtime '${descriptor.runtime}' is not an HTTP/native runtime`
530
+ );
531
+ }
532
+ settings.background.target = descriptor.id;
533
+ settings.background.model = model ?? descriptor.defaultModel ?? null;
534
+ }
535
+ function assertOrchestratorReplacementEligible(settings, descriptor) {
536
+ if (settings.orchestrator.target !== descriptor.id && settings.background.target !== descriptor.id) return;
537
+ const role = settings.orchestrator.target === descriptor.id ? "orchestrator" : "background";
538
+ const runtime = getRuntimeRegistry().get(descriptor.runtime);
539
+ if (!runtime) {
540
+ throw new Error(
541
+ `cannot update ${role} target '${descriptor.id}' because runtime '${descriptor.runtime}' is not registered`
542
+ );
543
+ }
544
+ if (!isOrchestratorEligibleRuntime(runtime)) {
545
+ throw new Error(`cannot update ${role} target '${descriptor.id}' to non-HTTP/native runtime '${runtime.id}'`);
546
+ }
547
+ }
548
+ function setWorkerProfilePointer(settings, name, descriptor, model) {
549
+ const trimmed = name.trim();
550
+ if (trimmed.length === 0) throw new Error("fleet profile name must be non-empty");
551
+ settings.workers.profiles[trimmed] = {
552
+ target: descriptor.id,
553
+ model: model ?? descriptor.defaultModel ?? null,
554
+ thinkingLevel: "off"
555
+ };
556
+ }
557
+ function warnUndiscoveredContextWindow(descriptor, probe) {
558
+ if (!probe?.ok) return;
559
+ if (typeof descriptor.capabilities?.contextWindow === "number" && descriptor.capabilities.contextWindow > 0) return;
560
+ const discovered = probeCapabilitiesForModel(
561
+ {
562
+ target: descriptor,
563
+ probeCapabilities: probe.discoveredCapabilities ?? null,
564
+ probeModelCapabilities: probe.modelCapabilities ?? null,
565
+ probeModelId: probe.capabilityModelId ?? null
566
+ },
567
+ descriptor.defaultModel
568
+ );
569
+ if (typeof discovered?.contextWindow === "number" && discovered.contextWindow > 0) return;
570
+ process.stdout.write(
571
+ " warning: the target reported no context window; Clio will use the runtime default as a guess. Set one with --context-window.\n"
572
+ );
573
+ }
574
+ function probeReadings(probe) {
575
+ const readings = [];
576
+ if (probe.models && probe.models.length > 0) readings.push(`${probe.models.length} models`);
577
+ if (probe.serverVersion) readings.push(probe.serverVersion);
578
+ if (probe.discoveredCapabilities && Object.keys(probe.discoveredCapabilities).length > 0) {
579
+ readings.push("capabilities");
580
+ }
581
+ return readings;
582
+ }
583
+ function probeLines(descriptor, probe) {
584
+ const latency = probe.latencyMs !== void 0 ? ` (${probe.latencyMs}ms)` : "";
585
+ if (!probe.ok) {
586
+ const where = descriptor.url ? ` ${descriptor.url}` : "";
587
+ return [
588
+ `probe failed${latency}:${where} ${probe.error ?? "unknown"}`,
589
+ ` check the server is running and reachable, then re-run: clio-coder configure --id ${descriptor.id} --url <url>`
590
+ ];
591
+ }
592
+ const readings = probeReadings(probe);
593
+ if (readings.length > 0) return [`probe ok${latency} ${readings.join(", ")}`];
594
+ return [
595
+ `probe reachable${latency}, but the target answered no model list and no version`,
596
+ " Clio cannot verify the model id or the context window from here and will send both as written.",
597
+ " re-read them once the server serves them with: clio-coder targets --probe"
598
+ ];
599
+ }
600
+ function printSummary(settings, descriptor, probe) {
601
+ process.stdout.write(`
602
+ saved target ${descriptor.id} (runtime=${descriptor.runtime})
603
+ `);
604
+ if (descriptor.url) process.stdout.write(` url ${descriptor.url}
605
+ `);
606
+ if (descriptor.defaultModel) process.stdout.write(` model ${descriptor.defaultModel}
607
+ `);
608
+ if (descriptor.auth?.apiKeyEnvVar) process.stdout.write(` apiKeyEnv ${descriptor.auth.apiKeyEnvVar}
609
+ `);
610
+ if (descriptor.gateway) process.stdout.write(" gateway true\n");
611
+ if (descriptor.lifecycle) process.stdout.write(` lifecycle ${descriptor.lifecycle}
612
+ `);
613
+ if (probe) {
614
+ for (const line of probeLines(descriptor, probe)) process.stdout.write(` ${line}
615
+ `);
616
+ }
617
+ warnUndiscoveredContextWindow(descriptor, probe);
618
+ if (settings.orchestrator.target === descriptor.id) process.stdout.write(" orchestrator target\n");
619
+ if (settings.background.target === descriptor.id) process.stdout.write(" background memory target\n");
620
+ if (settings.workers.default.target === descriptor.id) process.stdout.write(" fleet default\n");
621
+ for (const [name, profile] of Object.entries(settings.workers.profiles)) {
622
+ if (profile.target === descriptor.id) process.stdout.write(` fleet profile ${name}
623
+ `);
624
+ }
625
+ process.stdout.write(`
626
+ settings written to ${settingsPath()}
627
+ `);
628
+ }
629
+ function buildDescriptor(runtime, id, parts) {
630
+ const descriptor = { id, runtime: runtime.id };
631
+ if (parts.url) descriptor.url = parts.url;
632
+ const wireModels = parts.wireModels?.filter((value, index, all) => value.trim().length > 0 && all.indexOf(value) === index) ?? [];
633
+ if (parts.model) descriptor.defaultModel = parts.model;
634
+ else {
635
+ const firstWireModel = wireModels[0];
636
+ if (firstWireModel) descriptor.defaultModel = firstWireModel;
637
+ }
638
+ const auth = {};
639
+ if (parts.apiKeyEnv) auth.apiKeyEnvVar = parts.apiKeyEnv;
640
+ if (parts.apiKeyRef) auth.apiKeyRef = parts.apiKeyRef;
641
+ if (parts.oauthProfile) auth.oauthProfile = parts.oauthProfile;
642
+ if (Object.keys(auth).length > 0) descriptor.auth = auth;
643
+ if (wireModels.length > 0) descriptor.wireModels = wireModels;
644
+ if (parts.gateway) descriptor.gateway = true;
645
+ if (parts.lifecycle) descriptor.lifecycle = parts.lifecycle;
646
+ const caps = {};
647
+ if (parts.contextWindow !== void 0) caps.contextWindow = parts.contextWindow;
648
+ if (parts.maxTokens !== void 0) caps.maxTokens = parts.maxTokens;
649
+ if (parts.reasoning !== void 0) caps.reasoning = parts.reasoning;
650
+ if (Object.keys(caps).length > 0) descriptor.capabilities = caps;
651
+ return descriptor;
652
+ }
653
+ function describeAuthStatus(runtime) {
654
+ const status = openAuthStorage().statusForTarget(resolveRuntimeAuthTarget(runtime), { includeFallback: false });
655
+ if (!status.available) return "none stored";
656
+ if (status.source === "environment") return `environment${status.detail ? ` (${status.detail})` : ""}`;
657
+ if (status.source === "stored-api-key") return "stored api key";
658
+ if (status.source === "stored-oauth") return "stored oauth";
659
+ return status.source;
660
+ }
661
+ async function loginOAuthRuntime(rl, runtime) {
662
+ const auth = openAuthStorage();
663
+ if (runtime.authNotice) process.stdout.write(`note: ${runtime.authNotice}
664
+ `);
665
+ const manualCodeInput = createDelayedManualCodeInput(
666
+ rl,
667
+ "Paste verification code if browser callback does not complete automatically: "
668
+ );
669
+ try {
670
+ await auth.login(runtime.oauthProviderId ?? runtime.id, {
671
+ onAuth: ({ url, instructions }) => {
672
+ process.stdout.write(`
673
+ Open: ${url}
674
+ `);
675
+ if (instructions) process.stdout.write(`${instructions}
676
+ `);
677
+ process.stdout.write("Waiting for the browser callback. A manual code prompt will appear if needed.\n");
678
+ },
679
+ onDeviceCode: ({ verificationUri, userCode }) => {
680
+ process.stdout.write(`
681
+ Open: ${verificationUri}
682
+ `);
683
+ process.stdout.write(`Enter code: ${userCode}
684
+ `);
685
+ },
686
+ onPrompt: async (prompt) => {
687
+ const answer = await rl.question(`${prompt.message}${prompt.allowEmpty ? " " : ": "}`);
688
+ return prompt.allowEmpty ? answer : answer.trim();
689
+ },
690
+ onSelect: (prompt) => promptOAuthSelection(rl, prompt),
691
+ onManualCodeInput: manualCodeInput.onManualCodeInput,
692
+ onProgress: (message) => {
693
+ process.stderr.write(`${message}
694
+ `);
695
+ }
696
+ });
697
+ if (credentialWriteFailed(auth, `credential for ${runtime.id} was not stored`)) return false;
698
+ printOk(`authenticated ${runtime.id}`);
699
+ return true;
700
+ } catch (error) {
701
+ printError(error instanceof Error ? error.message : String(error));
702
+ return false;
703
+ } finally {
704
+ manualCodeInput.cancel();
705
+ }
706
+ }
707
+ async function resolveSupportedWireModels(runtime, target, existing) {
708
+ const known = listKnownModelsForRuntime(runtime.id);
709
+ if (known.length > 0) return known;
710
+ const discovered = runtime.kind === "http" ? await runtimeProbeModels(runtime, target) : [];
711
+ if (discovered.length > 0) return discovered;
712
+ return existing?.wireModels ? [...existing.wireModels] : [];
713
+ }
714
+ function resolveModelChoice(answer, wireModels, defaultValue) {
715
+ if (answer.length === 0) return defaultValue;
716
+ const numeric = Number(answer);
717
+ if (Number.isInteger(numeric) && numeric >= 1 && numeric <= wireModels.length) {
718
+ return wireModels[numeric - 1];
719
+ }
720
+ return answer;
721
+ }
722
+ async function askModelChoice(rl, label, wireModels, defaultValue) {
723
+ const answer = await ask(rl, `${label} (number or id)`, defaultValue ?? "");
724
+ if (answer === null) return null;
725
+ return resolveModelChoice(answer, wireModels, defaultValue) ?? "";
726
+ }
727
+ function refuseCatalogSeededModel(runtime, support) {
728
+ printError(
729
+ `--model is required for ${runtime.id}: its ${support.modelHints.length} model ids come from the pi-ai catalog in name order, which recommends none of them`
730
+ );
731
+ process.stderr.write(
732
+ ` run \`clio-coder configure --runtime ${runtime.id}\` with no other flags to choose from the full list
733
+ `
734
+ );
735
+ }
736
+ async function runNonInteractive(runtime, args) {
737
+ if (!args.id) {
738
+ printError("--id is required when passing flags non-interactively");
739
+ return 2;
740
+ }
741
+ if (args.workerProfileModel !== void 0 && args.workerProfile === void 0) {
742
+ printError("--agent-profile-model requires --agent-profile");
743
+ return 2;
744
+ }
745
+ if (args.workerProfile !== void 0 && args.workerProfile.trim().length === 0) {
746
+ printError("--agent-profile must be non-empty");
747
+ return 2;
748
+ }
749
+ if (args.workerProfile !== void 0 && args.workerModel !== void 0) {
750
+ printError(
751
+ "--fleet-model and --agent-profile conflict; use --agent-profile-model for the profile, or drop --agent-profile to set the fleet default"
752
+ );
753
+ return 2;
754
+ }
755
+ const settings = readSettings();
756
+ const auth = openAuthStorage();
757
+ const support = buildProviderSupportEntry(runtime);
758
+ const existing = settings.targets.find((e) => e.id === args.id);
759
+ if (existing && existing.runtime !== runtime.id) {
760
+ printError(`target ${args.id} already exists with runtime ${existing.runtime}`);
761
+ return 2;
762
+ }
763
+ let url = args.url ? normalizeUrl(args.url, runtime.id) : existing?.url;
764
+ if (!url && support.supportsCustomUrl) {
765
+ url = defaultUrlFor(runtime.id);
766
+ }
767
+ if (url && (runtime.id === "openai-compat" || runtime.id === "anthropic-compat")) {
768
+ const fingerprint = await fingerprintNativeRuntime(url);
769
+ if (fingerprint) {
770
+ process.stdout.write(
771
+ `note: detected ${fingerprint.displayName} at ${url}; consider \`clio-coder targets convert ${args.id} --runtime ${fingerprint.runtimeId}\` for proper resident-model lifecycle
772
+ `
773
+ );
774
+ }
775
+ }
776
+ const authStatus = auth.statusForTarget(resolveRuntimeAuthTarget(runtime), { includeFallback: false });
777
+ const apiKeyEnv = args.apiKeyEnv ?? existing?.auth?.apiKeyEnvVar;
778
+ const apiKeyRef = runtime.auth === "api-key" && (args.apiKey || existing?.auth?.apiKeyRef || authStatus.source === "stored-api-key") ? runtime.id : void 0;
779
+ const oauthProfile = runtime.auth === "oauth" ? existing?.auth?.oauthProfile ?? runtime.oauthProviderId ?? runtime.id : void 0;
780
+ const seed = buildDescriptor(runtime, args.id, {
781
+ ...url !== void 0 ? { url } : {},
782
+ ...args.model !== void 0 ? { model: args.model } : existing?.defaultModel ? { model: existing.defaultModel } : support.defaultModel ? { model: support.defaultModel } : {},
783
+ ...apiKeyEnv !== void 0 ? { apiKeyEnv } : {},
784
+ ...apiKeyRef !== void 0 ? { apiKeyRef } : {},
785
+ ...oauthProfile !== void 0 ? { oauthProfile } : {},
786
+ gateway: args.gateway || existing?.gateway === true,
787
+ ...args.lifecycle !== void 0 ? { lifecycle: args.lifecycle } : existing?.lifecycle !== void 0 ? { lifecycle: existing.lifecycle } : {},
788
+ ...args.contextWindow !== void 0 ? { contextWindow: args.contextWindow } : {},
789
+ ...args.maxTokens !== void 0 ? { maxTokens: args.maxTokens } : {},
790
+ ...args.reasoning !== void 0 ? { reasoning: args.reasoning } : {}
791
+ });
792
+ const wireModels = await resolveSupportedWireModels(runtime, seed, existing);
793
+ const model = args.model ?? existing?.defaultModel ?? support.defaultModel ?? (support.modelSource === "catalog" ? void 0 : wireModels[0]);
794
+ if (model === void 0 && support.modelSource === "catalog") {
795
+ refuseCatalogSeededModel(runtime, support);
796
+ return 2;
797
+ }
798
+ if (!validateResolvedModel(runtime.id, model, args.force)) return 2;
799
+ if (!validateContextWindowOverride(runtime, model, args.contextWindow, args.force)) return 2;
800
+ const descriptor = buildDescriptor(runtime, args.id, {
801
+ ...url !== void 0 ? { url } : {},
802
+ ...model ? { model } : {},
803
+ ...wireModels.length > 0 ? { wireModels } : {},
804
+ ...apiKeyEnv !== void 0 ? { apiKeyEnv } : {},
805
+ ...apiKeyRef !== void 0 ? { apiKeyRef } : {},
806
+ ...oauthProfile !== void 0 ? { oauthProfile } : {},
807
+ gateway: args.gateway || existing?.gateway === true,
808
+ ...args.lifecycle !== void 0 ? { lifecycle: args.lifecycle } : existing?.lifecycle !== void 0 ? { lifecycle: existing.lifecycle } : {},
809
+ ...args.contextWindow !== void 0 ? { contextWindow: args.contextWindow } : {},
810
+ ...args.maxTokens !== void 0 ? { maxTokens: args.maxTokens } : {},
811
+ ...args.reasoning !== void 0 ? { reasoning: args.reasoning } : {}
812
+ });
813
+ const setOrchestrator = args.setOrchestrator || args.orchestratorModel !== void 0;
814
+ const setBackground = args.setBackground || args.backgroundModel !== void 0;
815
+ if ((setOrchestrator || setBackground) && !isOrchestratorEligibleRuntime(runtime)) {
816
+ printError(
817
+ `cannot use target '${descriptor.id}' as a chat or background target because runtime '${runtime.id}' is not an HTTP/native runtime`
818
+ );
819
+ return 1;
820
+ }
821
+ try {
822
+ assertOrchestratorReplacementEligible(settings, descriptor);
823
+ } catch (error) {
824
+ printError(error instanceof Error ? error.message : String(error));
825
+ return 1;
826
+ }
827
+ if (args.apiKey) {
828
+ auth.setApiKey(runtime.id, args.apiKey);
829
+ if (credentialWriteFailed(auth, `credential for ${runtime.id} was not stored; target '${descriptor.id}' not saved`))
830
+ return 1;
831
+ printPlaintextCredentialWarning();
832
+ }
833
+ const setWorkerDefault = args.setWorkerDefault || args.workerProfile === void 0 && args.workerModel !== void 0;
834
+ const applyConfiguration = (target) => {
835
+ applyTarget(target, descriptor);
836
+ if (setOrchestrator)
837
+ setOrchestratorPointer(target, descriptor, args.orchestratorModel ?? descriptor.defaultModel ?? null);
838
+ if (setBackground) setBackgroundPointer(target, descriptor, args.backgroundModel ?? descriptor.defaultModel ?? null);
839
+ if (setWorkerDefault)
840
+ setWorkerDefaultPointer(target, descriptor, args.workerModel ?? descriptor.defaultModel ?? null);
841
+ if (args.workerProfile !== void 0) {
842
+ setWorkerProfilePointer(
843
+ target,
844
+ args.workerProfile,
845
+ descriptor,
846
+ args.workerProfileModel ?? descriptor.defaultModel ?? null
847
+ );
848
+ }
849
+ };
850
+ applyConfiguration(settings);
851
+ updateSettings(applyConfiguration);
852
+ const probe = await runtimeProbe(runtime, descriptor);
853
+ printSummary(settings, descriptor, probe);
854
+ if (runtime.auth === "oauth" && !auth.statusForTarget(resolveRuntimeAuthTarget(runtime), { includeFallback: false }).available) {
855
+ process.stdout.write(
856
+ `note: authenticate ${runtime.id} with \`clio-coder auth login ${runtime.id}\` before using this target
857
+ `
858
+ );
859
+ }
860
+ printOk(`target ${args.id} saved`);
861
+ return 0;
862
+ }
863
+ async function ask(rl, label, defaultValue) {
864
+ const suffix = defaultValue && defaultValue.length > 0 ? ` [${defaultValue}]` : "";
865
+ try {
866
+ const answer = (await rl.question(`${label}${suffix}: `)).trim();
867
+ if (answer.length === 0) return defaultValue ?? "";
868
+ if (answer.toLowerCase() === "q" || answer.toLowerCase() === "quit") return null;
869
+ return answer;
870
+ } catch {
871
+ return null;
872
+ }
873
+ }
874
+ async function askYesNo(rl, label, defaultValue) {
875
+ const marker = defaultValue ? "Y/n" : "y/N";
876
+ for (; ; ) {
877
+ const answer = await ask(rl, `${label} [${marker}]`);
878
+ if (answer === null) return defaultValue;
879
+ if (answer.length === 0) return defaultValue;
880
+ const lc = answer.toLowerCase();
881
+ if (lc === "y" || lc === "yes") return true;
882
+ if (lc === "n" || lc === "no") return false;
883
+ process.stderr.write(`invalid response: ${answer}
884
+ `);
885
+ }
886
+ }
887
+ async function pickRuntime(rl) {
888
+ const registry = getRuntimeRegistry();
889
+ const entries = listProviderSupportEntries(registry.list());
890
+ return pickRuntimeFromEntries(rl, entries, "\nSupported runtimes:");
891
+ }
892
+ async function pickRuntimeFromEntries(rl, entries, heading) {
893
+ const registry = getRuntimeRegistry();
894
+ if (entries.length === 0) {
895
+ process.stderr.write("no runtimes available in this category\n");
896
+ return null;
897
+ }
898
+ process.stdout.write(`${heading}
899
+ `);
900
+ const menu = formatRuntimeMenu(
901
+ entries.map((entry) => ({
902
+ group: supportGroupLabel(entry.group),
903
+ runtimeId: entry.runtimeId,
904
+ summary: entry.summary
905
+ })),
906
+ terminalColumns()
907
+ );
908
+ for (const line of menu) process.stdout.write(`${line}
909
+ `);
910
+ const allowedIds = new Set(entries.map((entry) => entry.runtimeId));
911
+ const defaultRuntimeId = entries.find((entry) => entry.featured)?.runtimeId ?? "";
912
+ for (; ; ) {
913
+ const answer = await ask(rl, "\nSelection (number or runtime id)", defaultRuntimeId);
914
+ if (answer === null) return null;
915
+ if (answer.length === 0) {
916
+ process.stderr.write(`pick a number from 1 to ${entries.length}, or type a runtime id
917
+ `);
918
+ continue;
919
+ }
920
+ const numeric = Number(answer);
921
+ if (Number.isInteger(numeric) && numeric >= 1 && numeric <= entries.length) {
922
+ const picked = entries[numeric - 1];
923
+ if (picked) {
924
+ const runtime = registry.get(picked.runtimeId);
925
+ if (runtime) return runtime;
926
+ }
927
+ }
928
+ if (allowedIds.has(answer)) {
929
+ const match = registry.get(answer);
930
+ if (match) return match;
931
+ }
932
+ process.stderr.write(`unknown runtime id for this category: ${answer}
933
+ `);
934
+ }
935
+ }
936
+ var LOCAL_APP_RUNTIME_IDS = /* @__PURE__ */ new Set(["ollama-native", "lmstudio-native"]);
937
+ var PROTOCOL_COMPAT_RUNTIME_IDS = /* @__PURE__ */ new Set(["openai-compat", "anthropic-compat"]);
938
+ function runtimesForCategory(entries, category) {
939
+ switch (category) {
940
+ case "local-app":
941
+ return entries.filter((entry) => LOCAL_APP_RUNTIME_IDS.has(entry.runtimeId));
942
+ case "local-http":
943
+ return entries.filter((entry) => entry.group === "local-http" && !LOCAL_APP_RUNTIME_IDS.has(entry.runtimeId));
944
+ case "chatgpt":
945
+ return entries.filter((entry) => entry.runtimeId === "openai-codex");
946
+ case "cloud-api": {
947
+ const byLabel = (a, b) => a.label.localeCompare(b.label) || a.runtimeId.localeCompare(b.runtimeId);
948
+ const named = entries.filter((entry) => entry.group === "cloud-api").slice().sort(byLabel);
949
+ const compat = entries.filter((entry) => PROTOCOL_COMPAT_RUNTIME_IDS.has(entry.runtimeId)).map((entry) => ({ ...entry, group: "cloud-api" })).sort(byLabel);
950
+ return [...named, ...compat];
951
+ }
952
+ case "all":
953
+ return entries.slice();
954
+ }
955
+ }
956
+ async function pickCategory(rl) {
957
+ process.stdout.write("\nHow will you connect Clio to a model?\n\n");
958
+ for (const line of formatCategoryMenu(terminalColumns())) process.stdout.write(`${line}
959
+ `);
960
+ for (; ; ) {
961
+ const answer = await ask(rl, "\nSelection", "1");
962
+ if (answer === null) return null;
963
+ if (answer.length === 0) continue;
964
+ const category = matchCategoryChoice(answer);
965
+ if (category) return category;
966
+ process.stderr.write(`invalid choice: ${answer}
967
+ `);
968
+ }
969
+ }
970
+ async function pickRuntimeViaCategory(rl) {
971
+ const registry = getRuntimeRegistry();
972
+ const allEntries = listProviderSupportEntries(registry.list());
973
+ const category = await pickCategory(rl);
974
+ if (category === null) return null;
975
+ if (category === "all") return pickRuntime(rl);
976
+ const filtered = runtimesForCategory(allEntries, category);
977
+ if (filtered.length === 0) {
978
+ process.stderr.write("no runtimes available for that category; falling back to full list\n");
979
+ return pickRuntime(rl);
980
+ }
981
+ if (category === "chatgpt") {
982
+ const only = filtered[0];
983
+ if (only) {
984
+ const runtime = registry.get(only.runtimeId);
985
+ if (runtime) {
986
+ process.stdout.write(`
987
+ Using ${runtime.id} (${only.summary}).
988
+ `);
989
+ return runtime;
990
+ }
991
+ }
992
+ return pickRuntime(rl);
993
+ }
994
+ if (filtered.length === 1) {
995
+ const only = filtered[0];
996
+ if (only) {
997
+ const runtime = registry.get(only.runtimeId);
998
+ if (runtime) {
999
+ process.stdout.write(`
1000
+ Using ${runtime.id} (${only.summary}).
1001
+ `);
1002
+ return runtime;
1003
+ }
1004
+ }
1005
+ }
1006
+ const heading = category === "local-app" ? "\nLocal apps:" : category === "local-http" ? "\nLocal HTTP servers:" : "\nCloud APIs:";
1007
+ return pickRuntimeFromEntries(rl, filtered, heading);
1008
+ }
1009
+ async function maybeSteerToNativeRuntime(rl, currentRuntime, url) {
1010
+ if (currentRuntime.id !== "openai-compat" && currentRuntime.id !== "anthropic-compat") return currentRuntime;
1011
+ const fingerprint = await fingerprintNativeRuntime(url);
1012
+ if (!fingerprint) return currentRuntime;
1013
+ const native = getRuntimeRegistry().get(fingerprint.runtimeId);
1014
+ if (!native) return currentRuntime;
1015
+ process.stdout.write(`
1016
+ Detected ${fingerprint.displayName} at ${url}.
1017
+ `);
1018
+ const switchIt = await askYesNo(rl, `Use ${fingerprint.runtimeId} runtime instead of ${currentRuntime.id}?`, true);
1019
+ if (!switchIt) return currentRuntime;
1020
+ process.stdout.write(`Using ${fingerprint.runtimeId} runtime.
1021
+ `);
1022
+ return native;
1023
+ }
1024
+ async function runInteractive(rl, preselectedRuntime, defaults) {
1025
+ let runtime = preselectedRuntime ?? await pickRuntimeViaCategory(rl);
1026
+ if (!runtime) {
1027
+ printError("configuration cancelled");
1028
+ return 0;
1029
+ }
1030
+ const auth = openAuthStorage();
1031
+ const settings = readSettings();
1032
+ let support = buildProviderSupportEntry(runtime);
1033
+ const initialRuntimeId = runtime.id;
1034
+ const existingForRuntime = configuredTargetsForRuntime(settings, initialRuntimeId);
1035
+ const existing = (defaults.id ? settings.targets.find((entry) => entry.id === defaults.id && entry.runtime === initialRuntimeId) : null) ?? existingForRuntime[0] ?? null;
1036
+ if (existingForRuntime.length > 0) {
1037
+ process.stdout.write(`
1038
+ Existing targets for ${runtime.id}:
1039
+ `);
1040
+ for (const target of existingForRuntime) {
1041
+ process.stdout.write(` - ${target.id}${target.defaultModel ? ` (${target.defaultModel})` : ""}
1042
+ `);
1043
+ }
1044
+ }
1045
+ process.stdout.write(`
1046
+ Selected runtime: ${runtime.id} (${support.summary})
1047
+ `);
1048
+ process.stdout.write(`Credentials: ${describeAuthStatus(runtime)}
1049
+ `);
1050
+ if (support.modelHints.length > 0) {
1051
+ process.stdout.write(`Known models: ${describeRuntimeModels(support, 4)}
1052
+ `);
1053
+ }
1054
+ const suggestedId = defaults.id ?? existing?.id ?? deriveTargetId(runtime.id, settings.targets);
1055
+ const idInput = await ask(rl, "Target id", suggestedId);
1056
+ if (idInput === null || idInput.length === 0) {
1057
+ printError("target id is required");
1058
+ return 2;
1059
+ }
1060
+ const targetId = idInput;
1061
+ let url = existing?.url;
1062
+ if (support.supportsCustomUrl) {
1063
+ const urlDefault = defaults.url ?? existing?.url ?? defaultUrlFor(runtime.id);
1064
+ const urlInput = await ask(
1065
+ rl,
1066
+ support.group === "local-http" ? "Target URL" : "Base URL override (blank for runtime default)",
1067
+ urlDefault
1068
+ );
1069
+ if (urlInput === null) return 0;
1070
+ if (urlInput.length > 0) url = normalizeUrl(urlInput, runtime.id);
1071
+ } else if (defaults.url) {
1072
+ url = normalizeUrl(defaults.url, runtime.id);
1073
+ }
1074
+ if (url) {
1075
+ const steered = await maybeSteerToNativeRuntime(rl, runtime, url);
1076
+ if (steered.id !== runtime.id) {
1077
+ runtime = steered;
1078
+ support = buildProviderSupportEntry(runtime);
1079
+ }
1080
+ }
1081
+ let apiKeyEnv;
1082
+ let apiKeyLiteral;
1083
+ let apiKeyRef = existing?.auth?.apiKeyRef;
1084
+ let oauthProfile = runtime.auth === "oauth" ? existing?.auth?.oauthProfile ?? runtime.oauthProviderId ?? runtime.id : void 0;
1085
+ const authStatus = auth.statusForTarget(resolveRuntimeAuthTarget(runtime), { includeFallback: false });
1086
+ if (runtime.auth === "api-key") {
1087
+ const needsCredential = targetRequiresAuth({ id: targetId, runtime: runtime.id }, runtime);
1088
+ const defaultSource = authStatus.source === "stored-api-key" ? "keep" : authStatus.source === "environment" || existing?.auth?.apiKeyEnvVar || needsCredential ? "env" : "skip";
1089
+ process.stdout.write(
1090
+ "\nCredential source: env reads a key from an environment variable, stored writes one to\ncredentials.yaml, keep leaves the current one alone, skip uses no key at all.\n"
1091
+ );
1092
+ const choice = await ask(rl, "Credential source [env|stored|keep|skip]", defaultSource);
1093
+ if (choice === null) return 0;
1094
+ const normalized = choice.trim().toLowerCase();
1095
+ if (normalized === "stored") {
1096
+ const literal = await ask(rl, "API key literal (stored in credentials.yaml, mode 0600)");
1097
+ if (literal !== null && literal.length > 0) {
1098
+ apiKeyLiteral = literal;
1099
+ apiKeyRef = runtime.id;
1100
+ }
1101
+ } else if (normalized === "env") {
1102
+ const envDefault = defaults.apiKeyEnv ?? existing?.auth?.apiKeyEnvVar ?? runtime.credentialsEnvVar ?? "";
1103
+ const envAnswer = await ask(rl, "Env var name (blank for no key)", envDefault);
1104
+ if (envAnswer === null) return 0;
1105
+ if (envAnswer.length > 0) apiKeyEnv = envAnswer;
1106
+ apiKeyRef = void 0;
1107
+ } else if (normalized === "keep") {
1108
+ apiKeyEnv = existing?.auth?.apiKeyEnvVar ?? (authStatus.source === "environment" ? runtime.credentialsEnvVar : void 0);
1109
+ apiKeyRef = existing?.auth?.apiKeyRef ?? (authStatus.source === "stored-api-key" ? runtime.id : void 0);
1110
+ } else {
1111
+ apiKeyEnv = void 0;
1112
+ apiKeyRef = void 0;
1113
+ }
1114
+ }
1115
+ if (runtime.auth === "oauth") {
1116
+ const connectNow = authStatus.available ? await askYesNo(rl, `Reconnect ${runtime.displayName}?`, false) : await askYesNo(rl, `Connect ${runtime.displayName} now?`, true);
1117
+ if (connectNow) {
1118
+ const connected = await loginOAuthRuntime(rl, runtime);
1119
+ if (!connected) return 1;
1120
+ }
1121
+ oauthProfile = runtime.oauthProviderId ?? runtime.id;
1122
+ }
1123
+ let model = defaults.model;
1124
+ let wireModels = existing?.wireModels ? [...existing.wireModels] : [];
1125
+ const tentative = buildDescriptor(runtime, targetId, {
1126
+ ...url !== void 0 ? { url } : {},
1127
+ ...apiKeyEnv !== void 0 ? { apiKeyEnv } : {},
1128
+ ...apiKeyRef !== void 0 ? { apiKeyRef } : {},
1129
+ ...oauthProfile !== void 0 ? { oauthProfile } : {},
1130
+ gateway: defaults.gateway,
1131
+ ...defaults.lifecycle !== void 0 ? { lifecycle: defaults.lifecycle } : existing?.lifecycle !== void 0 ? { lifecycle: existing.lifecycle } : {},
1132
+ ...defaults.contextWindow !== void 0 ? { contextWindow: defaults.contextWindow } : {},
1133
+ ...defaults.maxTokens !== void 0 ? { maxTokens: defaults.maxTokens } : {},
1134
+ ...defaults.reasoning !== void 0 ? { reasoning: defaults.reasoning } : {}
1135
+ });
1136
+ if (runtime.kind === "http") {
1137
+ wireModels = await resolveSupportedWireModels(runtime, tentative, existing ?? void 0);
1138
+ }
1139
+ const catalogOrdered = support.modelSource === "catalog";
1140
+ model = model ?? existing?.defaultModel ?? support.defaultModel ?? (catalogOrdered ? void 0 : wireModels[0]);
1141
+ if (wireModels.length > 0) {
1142
+ process.stdout.write("\nSelectable models:\n");
1143
+ for (const [index, wireModel] of wireModels.entries()) {
1144
+ process.stdout.write(` ${index + 1}. ${wireModel}${wireModel === model ? " [default]" : ""}
1145
+ `);
1146
+ }
1147
+ if (!model && catalogOrdered) {
1148
+ process.stdout.write(` listed in pi-ai catalog order, which recommends none of them; pick one.
1149
+ `);
1150
+ }
1151
+ for (; ; ) {
1152
+ const pickedModel = await askModelChoice(rl, "Default target model", wireModels, model);
1153
+ if (pickedModel === null) return 0;
1154
+ if (pickedModel.length > 0) model = pickedModel;
1155
+ if (!model) {
1156
+ process.stdout.write(" a model is required: enter a number from the list or a model id.\n");
1157
+ continue;
1158
+ }
1159
+ if (validateResolvedModel(runtime.id, model, defaults.force)) break;
1160
+ }
1161
+ } else {
1162
+ for (; ; ) {
1163
+ if (model && validateResolvedModel(runtime.id, model, defaults.force)) break;
1164
+ const manual = await ask(rl, "Default model id (blank to leave empty)", model ?? "");
1165
+ if (manual === null) return 0;
1166
+ model = manual.length > 0 ? manual : void 0;
1167
+ if (!model) break;
1168
+ }
1169
+ }
1170
+ let contextWindowChoice = defaults.contextWindow;
1171
+ let reasoningChoice = defaults.reasoning;
1172
+ if (PROTOCOL_COMPAT_RUNTIME_IDS.has(runtime.id)) {
1173
+ if (contextWindowChoice === void 0) {
1174
+ const cwDefault = existing?.capabilities?.contextWindow ?? runtime.defaultCapabilities.contextWindow;
1175
+ const cwAnswer = await ask(
1176
+ rl,
1177
+ "Context window in tokens (blank for runtime default)",
1178
+ cwDefault > 0 ? String(cwDefault) : ""
1179
+ );
1180
+ if (cwAnswer === null) return 0;
1181
+ if (cwAnswer.length > 0) {
1182
+ const parsed = Number(cwAnswer);
1183
+ if (Number.isInteger(parsed) && parsed > 0) contextWindowChoice = parsed;
1184
+ else process.stderr.write(`ignoring invalid context window: ${cwAnswer}
1185
+ `);
1186
+ }
1187
+ }
1188
+ if (reasoningChoice === void 0) {
1189
+ const reasoningDefault = existing?.capabilities?.reasoning ?? runtime.defaultCapabilities.reasoning === true;
1190
+ reasoningChoice = await askYesNo(rl, "Does this model support reasoning / thinking?", reasoningDefault);
1191
+ }
1192
+ }
1193
+ if (!validateContextWindowOverride(runtime, model, contextWindowChoice, defaults.force)) return 2;
1194
+ const gatewayDefault = defaults.gateway || existing?.gateway === true;
1195
+ const gatewayAnswer = gatewayDefault ? true : await askYesNo(rl, "Mark as gateway?", false);
1196
+ const descriptor = buildDescriptor(runtime, targetId, {
1197
+ ...url !== void 0 ? { url } : {},
1198
+ ...model !== void 0 ? { model } : {},
1199
+ ...apiKeyEnv !== void 0 ? { apiKeyEnv } : {},
1200
+ ...apiKeyRef !== void 0 ? { apiKeyRef } : {},
1201
+ ...oauthProfile !== void 0 ? { oauthProfile } : {},
1202
+ ...wireModels.length > 0 ? { wireModels } : {},
1203
+ gateway: gatewayAnswer,
1204
+ ...defaults.lifecycle !== void 0 ? { lifecycle: defaults.lifecycle } : existing?.lifecycle !== void 0 ? { lifecycle: existing.lifecycle } : {},
1205
+ ...contextWindowChoice !== void 0 ? { contextWindow: contextWindowChoice } : {},
1206
+ ...defaults.maxTokens !== void 0 ? { maxTokens: defaults.maxTokens } : {},
1207
+ ...reasoningChoice !== void 0 ? { reasoning: reasoningChoice } : {}
1208
+ });
1209
+ try {
1210
+ assertOrchestratorReplacementEligible(settings, descriptor);
1211
+ } catch (error) {
1212
+ printError(error instanceof Error ? error.message : String(error));
1213
+ return 1;
1214
+ }
1215
+ if (apiKeyLiteral) {
1216
+ auth.setApiKey(runtime.id, apiKeyLiteral);
1217
+ if (credentialWriteFailed(auth, `credential for ${runtime.id} was not stored; target '${descriptor.id}' not saved`))
1218
+ return 1;
1219
+ printPlaintextCredentialWarning();
1220
+ }
1221
+ const probe = await runtimeProbe(runtime, descriptor);
1222
+ if (probe) {
1223
+ process.stdout.write("\n");
1224
+ for (const line of probeLines(descriptor, probe)) process.stdout.write(`${line}
1225
+ `);
1226
+ if (!probe.ok) {
1227
+ const keepAnyway = await askYesNo(rl, "save this target anyway, without a reply from it?", true);
1228
+ if (!keepAnyway) {
1229
+ printError("aborted; settings not changed");
1230
+ return 0;
1231
+ }
1232
+ }
1233
+ }
1234
+ const setOrchestrator = !isOrchestratorEligibleRuntime(runtime) ? false : defaults.setOrchestrator ? true : await askYesNo(rl, "use as orchestrator (chat) target?", !settings.orchestrator.target);
1235
+ const setWorkerDefault = defaults.setWorkerDefault ? true : await askYesNo(rl, "use as fleet default?", !settings.workers.default.target);
1236
+ const setBackground = !isOrchestratorEligibleRuntime(runtime) ? false : defaults.setBackground ? true : await askYesNo(rl, "use as background memory target?", false);
1237
+ const orchestratorModel = setOrchestrator ? defaults.orchestratorModel ?? await askModelChoice(
1238
+ rl,
1239
+ "Orchestrator model",
1240
+ wireModels,
1241
+ settings.orchestrator.target === targetId ? settings.orchestrator.model ?? model : model
1242
+ ) : void 0;
1243
+ if (orchestratorModel === null) return 0;
1244
+ const workerModel = setWorkerDefault ? defaults.workerModel ?? await askModelChoice(
1245
+ rl,
1246
+ "Fleet model",
1247
+ wireModels,
1248
+ settings.workers.default.target === targetId ? settings.workers.default.model ?? model : model
1249
+ ) : void 0;
1250
+ if (workerModel === null) return 0;
1251
+ const backgroundModel = setBackground ? defaults.backgroundModel ?? await askModelChoice(
1252
+ rl,
1253
+ "Background memory model",
1254
+ wireModels,
1255
+ settings.background.target === targetId ? settings.background.model ?? model : model
1256
+ ) : void 0;
1257
+ if (backgroundModel === null) return 0;
1258
+ const applyWizardChoice = (target) => {
1259
+ applyTarget(target, descriptor);
1260
+ if (setOrchestrator) setOrchestratorPointer(target, descriptor, orchestratorModel);
1261
+ if (setBackground) setBackgroundPointer(target, descriptor, backgroundModel);
1262
+ if (setWorkerDefault) setWorkerDefaultPointer(target, descriptor, workerModel);
1263
+ };
1264
+ applyWizardChoice(settings);
1265
+ updateSettings(applyWizardChoice);
1266
+ printSummary(settings, descriptor, probe);
1267
+ printOk(`target ${targetId} saved`);
1268
+ return 0;
1269
+ }
1270
+ function runTargetRemove(id) {
1271
+ if (!readSettings().targets.some((e) => e.id === id)) {
1272
+ printError(`no target with id ${id}`);
1273
+ return 1;
1274
+ }
1275
+ updateSettings((settings) => {
1276
+ settings.targets = settings.targets.filter((e) => e.id !== id);
1277
+ if (settings.orchestrator.target === id) {
1278
+ settings.orchestrator.target = null;
1279
+ settings.orchestrator.model = null;
1280
+ }
1281
+ if (settings.background.target === id) {
1282
+ settings.background.target = null;
1283
+ settings.background.model = null;
1284
+ }
1285
+ if (settings.workers.default.target === id) {
1286
+ settings.workers.default.target = null;
1287
+ settings.workers.default.model = null;
1288
+ }
1289
+ for (const [name, profile] of Object.entries(settings.workers.profiles)) {
1290
+ if (profile.target === id) delete settings.workers.profiles[name];
1291
+ }
1292
+ settings.scope = settings.scope.filter((entry) => {
1293
+ const [head] = entry.split("/");
1294
+ return head !== id;
1295
+ });
1296
+ });
1297
+ printOk(`removed target ${id}`);
1298
+ return 0;
1299
+ }
1300
+ function runTargetRename(oldId, newId) {
1301
+ if (oldId === newId) {
1302
+ printError("old and new id are identical");
1303
+ return 2;
1304
+ }
1305
+ const current = readSettings();
1306
+ if (current.targets.some((e) => e.id === newId)) {
1307
+ printError(`target id already exists: ${newId}`);
1308
+ return 2;
1309
+ }
1310
+ if (!current.targets.some((e) => e.id === oldId)) {
1311
+ printError(`no target with id ${oldId}`);
1312
+ return 1;
1313
+ }
1314
+ updateSettings((settings) => {
1315
+ const target = settings.targets.find((e) => e.id === oldId);
1316
+ if (!target) return;
1317
+ target.id = newId;
1318
+ if (settings.orchestrator.target === oldId) settings.orchestrator.target = newId;
1319
+ if (settings.background.target === oldId) settings.background.target = newId;
1320
+ if (settings.workers.default.target === oldId) settings.workers.default.target = newId;
1321
+ for (const profile of Object.values(settings.workers.profiles)) {
1322
+ if (profile.target === oldId) profile.target = newId;
1323
+ }
1324
+ settings.scope = settings.scope.map((entry) => {
1325
+ const [head, ...rest] = entry.split("/");
1326
+ if (head !== oldId) return entry;
1327
+ return rest.length === 0 ? newId : `${newId}/${rest.join("/")}`;
1328
+ });
1329
+ });
1330
+ printOk(`renamed ${oldId} to ${newId}`);
1331
+ return 0;
1332
+ }
1333
+ async function runConfigureCommand(argv) {
1334
+ let args;
1335
+ try {
1336
+ args = parseSetupArgs(argv);
1337
+ } catch (err) {
1338
+ printError(err instanceof Error ? err.message : String(err));
1339
+ process.stdout.write(HELP);
1340
+ return 2;
1341
+ }
1342
+ if (args.help) {
1343
+ process.stdout.write(HELP);
1344
+ return 0;
1345
+ }
1346
+ initializeClioHome();
1347
+ ensureRegistryPopulated();
1348
+ if (args.list) {
1349
+ printRuntimeList(args.all);
1350
+ return 0;
1351
+ }
1352
+ if (args.remove) return runTargetRemove(args.remove);
1353
+ if (args.renameOld && args.renameNew) return runTargetRename(args.renameOld, args.renameNew);
1354
+ if (args.positional.length > 0) {
1355
+ printError(
1356
+ "`clio-coder configure` accepts flags, not positional runtimes. Use `clio-coder auth login <runtime>` first when authentication is needed, then `clio-coder configure --runtime <runtimeId> ...`."
1357
+ );
1358
+ return 2;
1359
+ }
1360
+ const runtimeId = args.runtime;
1361
+ let runtime = null;
1362
+ if (runtimeId) {
1363
+ runtime = getRuntimeRegistry().get(runtimeId);
1364
+ if (!runtime) {
1365
+ printError(`unknown runtime id: ${runtimeId}`);
1366
+ process.stdout.write("run `clio-coder configure --list` to see registered runtimes\n");
1367
+ return 2;
1368
+ }
1369
+ }
1370
+ const hasTargetSetupFlag = args.id !== void 0 || args.url !== void 0 || args.model !== void 0 || args.workerProfile !== void 0 || args.workerProfileModel !== void 0 || args.apiKey !== void 0 || args.apiKeyEnv !== void 0 || args.gateway || args.lifecycle !== void 0 || args.setOrchestrator || args.setWorkerDefault || args.contextWindow !== void 0 || args.maxTokens !== void 0 || args.reasoning !== void 0;
1371
+ const nonInteractive = runtime !== null && hasTargetSetupFlag;
1372
+ if (nonInteractive && runtime) return runNonInteractive(runtime, args);
1373
+ if ((runtimeId !== void 0 || hasTargetSetupFlag) && !input.isTTY) {
1374
+ printError(
1375
+ runtime === null ? "--runtime is required when configuring a target non-interactively" : "--id is required when passing flags non-interactively"
1376
+ );
1377
+ return 2;
1378
+ }
1379
+ const rl = createInterface({ input, output });
1380
+ try {
1381
+ return await runInteractive(rl, runtime, args);
1382
+ } catch (err) {
1383
+ printError(err instanceof Error ? err.message : String(err));
1384
+ return 1;
1385
+ } finally {
1386
+ rl.close();
1387
+ }
1388
+ }
1389
+
1390
+ export {
1391
+ runTargetRemove,
1392
+ runTargetRename,
1393
+ runConfigureCommand
1394
+ };
1395
+ //# sourceMappingURL=chunk-XNISANGE.js.map