@zero-gravity/zero-gravity 0.0.0-stage → 0.1.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 (73) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +21 -0
  3. package/README.md +50 -2
  4. package/THIRD-PARTY-NOTICES.md +100 -0
  5. package/dist/adv-context-SLTP32JQ.js +36 -0
  6. package/dist/advanced-EPLZB6DG.js +164 -0
  7. package/dist/agents-JYRQHH7R.js +181 -0
  8. package/dist/chat-AEHVCKXX.js +47 -0
  9. package/dist/chunk-2OH5KHWO.js +112 -0
  10. package/dist/chunk-2ZYSAYMJ.js +108 -0
  11. package/dist/chunk-4BZ4IXTO.js +161 -0
  12. package/dist/chunk-4ITJY25Z.js +144 -0
  13. package/dist/chunk-4JBLZQAQ.js +65 -0
  14. package/dist/chunk-6QLYRU3N.js +28 -0
  15. package/dist/chunk-7TACFVY2.js +57 -0
  16. package/dist/chunk-AY36KJTH.js +3023 -0
  17. package/dist/chunk-BJABQO7S.js +378 -0
  18. package/dist/chunk-C2GFK4JP.js +387 -0
  19. package/dist/chunk-CDC2K2KP.js +47 -0
  20. package/dist/chunk-DKCCXMSE.js +27 -0
  21. package/dist/chunk-FC3UOHOO.js +194 -0
  22. package/dist/chunk-FIASMDLX.js +216 -0
  23. package/dist/chunk-GMVDCQVW.js +88 -0
  24. package/dist/chunk-JQYZX56A.js +231 -0
  25. package/dist/chunk-JU5PGDOD.js +138 -0
  26. package/dist/chunk-JUZP5SXD.js +309 -0
  27. package/dist/chunk-KGA7VWQG.js +70 -0
  28. package/dist/chunk-L7VNR5LM.js +407 -0
  29. package/dist/chunk-LOSXCWHU.js +145 -0
  30. package/dist/chunk-NVC433AX.js +24 -0
  31. package/dist/chunk-QH27MDJM.js +248 -0
  32. package/dist/chunk-QUC5URWQ.js +708 -0
  33. package/dist/chunk-R2CPYTSP.js +31 -0
  34. package/dist/chunk-R5KQACGR.js +2833 -0
  35. package/dist/chunk-R6DONQKN.js +153 -0
  36. package/dist/chunk-RIX4S3J7.js +4747 -0
  37. package/dist/chunk-SZKAZ2VN.js +35 -0
  38. package/dist/chunk-T6DDNE3W.js +1338 -0
  39. package/dist/chunk-U4URD6TU.js +4605 -0
  40. package/dist/chunk-U5UIUB6L.js +51 -0
  41. package/dist/chunk-UMC77TR3.js +79 -0
  42. package/dist/chunk-UQURXFAE.js +80 -0
  43. package/dist/chunk-VBG7T7XY.js +1703 -0
  44. package/dist/chunk-VCCMJIAG.js +326 -0
  45. package/dist/chunk-VS375NYD.js +91 -0
  46. package/dist/chunk-WANZOLI5.js +1073 -0
  47. package/dist/chunk-WUF3TVAE.js +51 -0
  48. package/dist/chunk-XCWLFZSM.js +149 -0
  49. package/dist/chunk-YJEUXO5I.js +76 -0
  50. package/dist/chunk-YR6RCC6Y.js +894 -0
  51. package/dist/chunk-ZQFAX275.js +35 -0
  52. package/dist/config-ELG4FQ3K.js +30 -0
  53. package/dist/config-IEWRCG7R.js +50 -0
  54. package/dist/doctor-ZZC2D3RW.js +357 -0
  55. package/dist/ext-context-RIMZMEPB.js +37 -0
  56. package/dist/index.js +20 -0
  57. package/dist/init-UB3E47KM.js +22 -0
  58. package/dist/integrations-HW4VTLN4.js +183 -0
  59. package/dist/main-RAWWT22W.js +115 -0
  60. package/dist/mcp-SWD4SO35.js +232 -0
  61. package/dist/mcp-context-PM5FY665.js +28 -0
  62. package/dist/memory-QQ54GRCN.js +128 -0
  63. package/dist/memory-session-R6DGT6CS.js +14 -0
  64. package/dist/memory-summary-4P26B2ZY.js +18 -0
  65. package/dist/plugins-VUGTEUNV.js +166 -0
  66. package/dist/providers-O3WOVP5Q.js +417 -0
  67. package/dist/report-DDIZ6BLF.js +28 -0
  68. package/dist/sec-context-VQHW6TOZ.js +15 -0
  69. package/dist/security-SAYW4LU4.js +95 -0
  70. package/dist/sessions-CL6CRNQL.js +160 -0
  71. package/dist/skills-7KDGTTKX.js +126 -0
  72. package/dist/version-6E6A23B3.js +13 -0
  73. package/package.json +70 -4
@@ -0,0 +1,417 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ChatRuntime,
4
+ formatProviderError
5
+ } from "./chunk-VBG7T7XY.js";
6
+ import "./chunk-7TACFVY2.js";
7
+ import {
8
+ createStyle
9
+ } from "./chunk-NVC433AX.js";
10
+ import "./chunk-QUC5URWQ.js";
11
+ import "./chunk-2OH5KHWO.js";
12
+ import "./chunk-R5KQACGR.js";
13
+ import "./chunk-L7VNR5LM.js";
14
+ import "./chunk-LOSXCWHU.js";
15
+ import {
16
+ PROVIDERS,
17
+ UnknownProviderError,
18
+ describeProviderStatus,
19
+ knownModelList,
20
+ requireProvider,
21
+ resolveCredentialStatus,
22
+ shellInstructions
23
+ } from "./chunk-WANZOLI5.js";
24
+ import "./chunk-JUZP5SXD.js";
25
+ import {
26
+ ProviderFailure
27
+ } from "./chunk-4ITJY25Z.js";
28
+ import "./chunk-CDC2K2KP.js";
29
+ import "./chunk-YJEUXO5I.js";
30
+ import {
31
+ validateDisplayName,
32
+ validateEndpoint,
33
+ validateEnvVarName,
34
+ validateModelId
35
+ } from "./chunk-KGA7VWQG.js";
36
+ import {
37
+ isInteractive
38
+ } from "./chunk-DKCCXMSE.js";
39
+ import "./chunk-U5UIUB6L.js";
40
+ import "./chunk-XCWLFZSM.js";
41
+ import "./chunk-JQYZX56A.js";
42
+ import "./chunk-R6DONQKN.js";
43
+ import {
44
+ defaultConfig
45
+ } from "./chunk-QH27MDJM.js";
46
+ import "./chunk-4BZ4IXTO.js";
47
+ import "./chunk-C2GFK4JP.js";
48
+ import "./chunk-R2CPYTSP.js";
49
+ import "./chunk-ZQFAX275.js";
50
+ import {
51
+ ZgError
52
+ } from "./chunk-FC3UOHOO.js";
53
+ import {
54
+ redactSecrets
55
+ } from "./chunk-WUF3TVAE.js";
56
+
57
+ // src/cli/commands/providers.ts
58
+ import readline from "readline";
59
+ var MODEL_SOURCE_TITLE = {
60
+ known: "Known identifiers (static list bundled with zg; NOT verified for your account)",
61
+ live: "Live list from the provider's API",
62
+ local: "Installed locally"
63
+ };
64
+ function toZg(err) {
65
+ if (err instanceof ZgError) throw err;
66
+ if (err instanceof UnknownProviderError) throw new ZgError(err.message);
67
+ if (err instanceof ProviderFailure) throw new ZgError(formatProviderError(err.error));
68
+ throw err;
69
+ }
70
+ function insecureOk(ctx) {
71
+ return ctx.env["ZG_ALLOW_INSECURE_HTTP"] === "1";
72
+ }
73
+ function out(ctx) {
74
+ return (text) => ctx.stdout(redactSecrets(text));
75
+ }
76
+ function providerRows(ctx, config) {
77
+ return PROVIDERS.map((p) => {
78
+ const status = describeProviderStatus(p, config, ctx.env);
79
+ const spec = p.credentialSpec(config);
80
+ return {
81
+ id: p.id,
82
+ name: p.displayName,
83
+ default: config.defaultProvider === p.id,
84
+ readiness: status.readiness,
85
+ detail: status.detail,
86
+ defaultModel: config.defaultProvider === p.id ? config.defaultModel ?? p.defaultModel : p.defaultModel,
87
+ credential: spec.kind === "none" ? "not required" : `${spec.envVars.join(" / ") || "(env var not configured)"}${spec.kind === "optional" ? " (optional)" : ""}`,
88
+ streaming: p.supportsStreaming
89
+ };
90
+ });
91
+ }
92
+ function printProviderTable(ctx, config, json) {
93
+ const rows = providerRows(ctx, config);
94
+ const say = out(ctx);
95
+ if (json) {
96
+ say(JSON.stringify({ defaultProvider: config.defaultProvider, defaultModel: config.defaultModel, providers: rows }, null, 2));
97
+ return;
98
+ }
99
+ const style = createStyle(ctx.platform.terminal, config.theme);
100
+ const idW = Math.max(...rows.map((r) => r.id.length)) + 2;
101
+ say("");
102
+ say(` ${style.bold("Providers")} ${style.dim("(local status only: no network used, no key is read aloud)")}`);
103
+ say("");
104
+ for (const r of rows) {
105
+ const mark = r.default ? style.cyan(style.unicode ? "\u276F" : ">") : " ";
106
+ const state = r.readiness === "ready" ? style.ok("ready") : style.gold(r.readiness.replace(/-/g, " "));
107
+ say(` ${mark} ${style.gold(r.id.padEnd(idW))}${r.name} ${style.dim("-")} ${state}`);
108
+ say(` ${style.dim("model:")} ${r.defaultModel ?? style.dim("choose one")} ${style.dim("key:")} ${r.credential}`);
109
+ if (r.readiness !== "ready") say(` ${style.dim(r.detail)}`);
110
+ }
111
+ say("");
112
+ say(` ${style.dim("Select one with: zg provider use <id> [--model <name>] Details: zg provider status")}`);
113
+ say("");
114
+ }
115
+ function applyProviderChoice(config, rawId, opts, allowInsecureHttp) {
116
+ let desc;
117
+ try {
118
+ desc = requireProvider(rawId);
119
+ } catch (err) {
120
+ return toZg(err);
121
+ }
122
+ const next = { ...config, defaultProvider: desc.id };
123
+ if (opts.model !== void 0) {
124
+ const v = validateModelId(opts.model);
125
+ if (!v.ok) throw new ZgError(`invalid model: ${v.reason}`);
126
+ next.defaultModel = v.value;
127
+ } else if (config.defaultProvider !== desc.id) {
128
+ next.defaultModel = null;
129
+ }
130
+ const isCustom = desc.id === "openai-compatible";
131
+ if (!isCustom && (opts.envVar !== void 0 || opts.name !== void 0 || opts.key === false)) {
132
+ throw new ZgError("--env-var, --name and --no-key apply only to the openai-compatible provider");
133
+ }
134
+ if (desc.id !== "ollama" && !isCustom && opts.endpoint !== void 0) {
135
+ throw new ZgError(`--endpoint applies only to ollama and openai-compatible, not ${desc.id}`, {
136
+ hint: "built-in cloud providers always use their official endpoints, so keys cannot be redirected."
137
+ });
138
+ }
139
+ if (desc.id === "ollama" && opts.endpoint !== void 0) {
140
+ const v = validateEndpoint(opts.endpoint, { allowInsecureHttp });
141
+ if (!v.ok) throw new ZgError(`invalid endpoint: ${v.reason}`);
142
+ next.ollamaEndpoint = v.value;
143
+ }
144
+ if (isCustom) {
145
+ const existing = config.customEndpoint;
146
+ const rawUrl = opts.endpoint ?? existing?.url;
147
+ if (!rawUrl) throw new ZgError("the openai-compatible provider needs --endpoint <url>", { hint: "example: zg provider use openai-compatible --endpoint https://api.example.com/v1 --model my-model --env-var MY_API_KEY" });
148
+ const url = validateEndpoint(rawUrl, { allowInsecureHttp });
149
+ if (!url.ok) throw new ZgError(`invalid endpoint: ${url.reason}`);
150
+ const needsKey = opts.key !== false;
151
+ let envVar = null;
152
+ if (needsKey) {
153
+ const rawEnv = opts.envVar ?? existing?.envVar ?? void 0;
154
+ if (rawEnv === void 0) throw new ZgError("name the environment variable that holds the key with --env-var <NAME>, or pass --no-key if the server needs none");
155
+ if (existing && opts.endpoint !== void 0 && opts.envVar === void 0 && existing.url !== url.value && existing.requiresKey) {
156
+ throw new ZgError(`the endpoint is changing from ${existing.url} to ${url.value}`, {
157
+ hint: `pass --env-var ${rawEnv} to confirm that key may be sent to the new host (or --no-key).`
158
+ });
159
+ }
160
+ const env = validateEnvVarName(rawEnv);
161
+ if (!env.ok) throw new ZgError(`invalid environment variable name: ${env.reason}`);
162
+ envVar = env.value;
163
+ }
164
+ let displayName = existing?.displayName ?? null;
165
+ if (opts.name !== void 0) {
166
+ const n = validateDisplayName(opts.name);
167
+ if (!n.ok) throw new ZgError(`invalid name: ${n.reason}`);
168
+ displayName = n.value;
169
+ }
170
+ if (next.defaultModel === null) throw new ZgError("the openai-compatible provider needs --model <name>");
171
+ next.customEndpoint = { url: url.value, envVar, displayName, requiresKey: needsKey };
172
+ }
173
+ return next;
174
+ }
175
+ async function interactiveSetup(ctx, config) {
176
+ const say = out(ctx);
177
+ const rl = readline.createInterface({ input: ctx.io.input, terminal: false });
178
+ const lines = rl[Symbol.asyncIterator]();
179
+ const ask = async (question) => {
180
+ ctx.io.output.write(question);
181
+ const next = await lines.next();
182
+ if (next.done) throw new ZgError("input ended before the setup finished; nothing was changed");
183
+ ctx.io.output.write("\n");
184
+ return next.value;
185
+ };
186
+ try {
187
+ say("");
188
+ say("Choose a provider:");
189
+ PROVIDERS.forEach((p, i) => say(` ${i + 1}. ${p.displayName} (${p.id})`));
190
+ const pick = (await ask("Number or id (blank to cancel): ")).trim().toLowerCase();
191
+ if (pick === "") {
192
+ say("Cancelled. Nothing was changed.");
193
+ return;
194
+ }
195
+ const byNumber = /^\d+$/.test(pick) ? PROVIDERS[Number(pick) - 1] : void 0;
196
+ const desc = byNumber ?? PROVIDERS.find((p) => p.id === pick);
197
+ if (!desc) throw new ZgError(`unknown provider. Valid providers: ${PROVIDERS.map((p) => p.id).join(", ")}`);
198
+ const opts = {};
199
+ if (desc.id === "openai-compatible") {
200
+ opts.endpoint = (await ask("Endpoint base URL (https://..., or http://localhost...): ")).trim();
201
+ opts.model = (await ask("Model name: ")).trim();
202
+ const envName = (await ask("Name of the environment variable that holds the key (NOT the key; blank if none needed): ")).trim();
203
+ if (envName === "") opts.key = false;
204
+ else opts.envVar = envName;
205
+ const name = (await ask("Display name (optional): ")).trim();
206
+ if (name !== "") opts.name = name;
207
+ } else {
208
+ const hint = desc.defaultModel ? ` [${desc.defaultModel}]` : "";
209
+ const model = (await ask(`Model${hint}${desc.defaultModel ? "" : " (required)"}: `)).trim();
210
+ if (model !== "") opts.model = model;
211
+ else if (!desc.defaultModel) throw new ZgError(`${desc.displayName} needs a model name. For Ollama, run \`ollama list\` to see installed models.`);
212
+ if (desc.id === "ollama") {
213
+ const ep = (await ask("Ollama endpoint [http://localhost:11434]: ")).trim();
214
+ if (ep !== "") opts.endpoint = ep;
215
+ }
216
+ }
217
+ const next = applyProviderChoice(config, desc.id, opts, insecureOk(ctx));
218
+ await ctx.manager.save(next);
219
+ reportSelection(ctx, next);
220
+ } finally {
221
+ rl.close();
222
+ }
223
+ }
224
+ function reportSelection(ctx, config) {
225
+ const say = out(ctx);
226
+ const desc = requireProvider(config.defaultProvider ?? "");
227
+ const status = describeProviderStatus(desc, config, ctx.env);
228
+ say(`Default provider: ${desc.displayName} (${desc.id})`);
229
+ say(`Model: ${config.defaultModel ?? desc.defaultModel ?? "(none: choose one with --model)"}`);
230
+ say(`Status: ${status.readiness === "ready" ? "ready" : status.readiness.replace(/-/g, " ")}. ${status.detail}`);
231
+ say("This is configuration only; nothing was contacted. Check the connection with `zg provider status --check`.");
232
+ const spec = desc.credentialSpec(config);
233
+ if (status.readiness === "missing-credentials" && spec.envVars[0]) {
234
+ say(`Set your key first: run \`zg auth status\` for ${spec.envVars[0]} setup instructions for your shell.`);
235
+ }
236
+ }
237
+ async function showStatus(ctx, id, check) {
238
+ const say = out(ctx);
239
+ const { config } = await ctx.manager.load();
240
+ const chosen = id ?? config.defaultProvider;
241
+ if (!chosen) throw new ZgError("no default provider is configured", { hint: "run `zg provider use <id>` or `zg provider` to choose one." });
242
+ let desc;
243
+ try {
244
+ desc = requireProvider(chosen);
245
+ } catch (err) {
246
+ return toZg(err);
247
+ }
248
+ const probe = id && id !== config.defaultProvider ? { ...config, defaultProvider: desc.id, defaultModel: null } : config;
249
+ const status = describeProviderStatus(desc, probe, ctx.env);
250
+ const spec = desc.credentialSpec(probe);
251
+ say(`Provider: ${desc.displayName} (${desc.id})${config.defaultProvider === desc.id ? " [default]" : ""}`);
252
+ say(`Model: ${status.model ?? "none selected"}`);
253
+ say(`Streaming: ${desc.supportsStreaming ? config.streaming ? "supported, enabled" : "supported, disabled (config: streaming=false)" : "not supported"}`);
254
+ say(`Key source: ${spec.kind === "none" ? "not required" : `${spec.envVars.join(" / ") || "not configured"}${spec.kind === "optional" ? " (optional)" : ""}`}`);
255
+ say(`Key status: ${credentialWords(resolveCredentialStatus(spec, ctx.env))}`);
256
+ say(`Config: ${status.readiness === "ready" ? "ready" : status.readiness.replace(/-/g, " ")}. ${status.detail}`);
257
+ if (!check) {
258
+ say("Connection: not verified (local status only). Add --check to make a real request.");
259
+ return;
260
+ }
261
+ let backend;
262
+ try {
263
+ backend = desc.createBackend({ config: probe, env: ctx.env, fetch: ctx.fetch, model: null });
264
+ } catch (err) {
265
+ say("Connection: NOT verified");
266
+ return toZg(err);
267
+ }
268
+ const result = await backend.validateConnection();
269
+ if (result.state === "failed") {
270
+ say("Connection: FAILED");
271
+ process.exitCode = 1;
272
+ throw new ZgError(result.error ? formatProviderError(result.error) : result.detail);
273
+ }
274
+ say(`Connection: ${result.state === "connected" ? "CONNECTED" : "unverified"}. ${result.detail}${result.latencyMs !== void 0 ? ` (${result.latencyMs} ms)` : ""}`);
275
+ }
276
+ function credentialWords(s) {
277
+ switch (s.state) {
278
+ case "present":
279
+ return `found in ${s.envVar} (value hidden)`;
280
+ case "missing":
281
+ return `NOT SET (${s.envVars.join(" or ") || "no variable configured"})`;
282
+ case "invalid":
283
+ return `${s.envVar} is set but malformed (quotes, spaces or line breaks?)`;
284
+ case "optional-absent":
285
+ return "not set (not needed unless your server requires it)";
286
+ case "not-required":
287
+ return "not required";
288
+ }
289
+ }
290
+ async function listModels(ctx, id, live) {
291
+ const say = out(ctx);
292
+ const { config } = await ctx.manager.load();
293
+ const chosen = id ?? config.defaultProvider;
294
+ const targets = chosen ? [safeProvider(chosen)] : [...PROVIDERS];
295
+ for (const desc of targets) {
296
+ const probe = chosen && chosen !== config.defaultProvider ? { ...config, defaultProvider: desc.id, defaultModel: null } : config;
297
+ const current = probe.defaultProvider === desc.id ? probe.defaultModel ?? desc.defaultModel : desc.defaultModel;
298
+ const wantLive = live || desc.knownModels.length === 0;
299
+ say("");
300
+ if (!wantLive) {
301
+ printModels(say, desc.displayName, current, knownModelList(desc));
302
+ say(` Add --live to ask the API which models your key can use.`);
303
+ continue;
304
+ }
305
+ try {
306
+ const runtime = new ChatRuntime({ config: probe, env: ctx.env, fetch: ctx.fetch });
307
+ const { list } = await runtime.listModels(desc.id);
308
+ printModels(say, desc.displayName, current, list);
309
+ } catch (err) {
310
+ const message = err instanceof ProviderFailure ? formatProviderError(err.error) : err instanceof Error ? err.message : "unknown error";
311
+ say(`${desc.displayName}: could not fetch a live list. ${message}`);
312
+ if (desc.knownModels.length > 0) printModels(say, desc.displayName, current, knownModelList(desc));
313
+ if (chosen) process.exitCode = 1;
314
+ }
315
+ }
316
+ say("");
317
+ }
318
+ function safeProvider(id) {
319
+ try {
320
+ return requireProvider(id);
321
+ } catch (err) {
322
+ return toZg(err);
323
+ }
324
+ }
325
+ function printModels(say, name, current, list) {
326
+ say(`${name}: ${MODEL_SOURCE_TITLE[list.source]}`);
327
+ if (list.models.length === 0) say(" (none)");
328
+ for (const m of list.models) say(` ${m.id === current ? "*" : " "} ${m.id}`);
329
+ say(` ${list.note}`);
330
+ }
331
+ function registerProviders(program, ctx) {
332
+ const say = out(ctx);
333
+ program.command("providers").description("List AI providers and whether each is ready (local status, no network)").option("--json", "print machine-readable JSON").action(async (opts) => {
334
+ const { config } = await ctx.manager.load();
335
+ printProviderTable(ctx, config, opts.json === true);
336
+ });
337
+ const provider = program.command("provider").description("Choose and inspect the AI provider (interactive when run with no subcommand)");
338
+ provider.action(async () => {
339
+ const { config } = await ctx.manager.load();
340
+ if (!isInteractive(ctx.io)) {
341
+ printProviderTable(ctx, config, false);
342
+ say("Not an interactive terminal. Use: zg provider use <id> [--model <name>]");
343
+ return;
344
+ }
345
+ await interactiveSetup(ctx, config);
346
+ });
347
+ provider.command("list").description("List AI providers (same as `zg providers`)").option("--json", "print machine-readable JSON").action(async (opts) => {
348
+ const { config } = await ctx.manager.load();
349
+ printProviderTable(ctx, config, opts.json === true);
350
+ });
351
+ provider.command("status [provider]").description("Show the provider's local configuration and key status").option("--check", "also make a real request to verify the connection").action((id, opts) => showStatus(ctx, id, opts.check === true));
352
+ provider.command("use <provider>").description("Set the default provider (saved in config; no key is stored)").option("--model <name>", "model to use with this provider").option("--endpoint <url>", "ollama or openai-compatible endpoint URL").option("--env-var <NAME>", "openai-compatible: NAME of the environment variable that holds the key").option("--name <text>", "openai-compatible: display name").option("--no-key", "openai-compatible: the server needs no key").action(async (id, opts) => {
353
+ const { config } = await ctx.manager.load();
354
+ const next = applyProviderChoice(config, id, opts, insecureOk(ctx));
355
+ await ctx.manager.save(next);
356
+ reportSelection(ctx, next);
357
+ });
358
+ const models = program.command("models").description("List model identifiers (known / live / local are labelled separately)").argument("[provider]", "provider id (default: your default provider)").option("--live", "ask the provider's API instead of the bundled list");
359
+ models.action((id, opts) => listModels(ctx, id, opts.live === true));
360
+ models.command("list [provider]").description("Same as `zg models`").option("--live", "ask the provider's API instead of the bundled list").action((id, opts) => listModels(ctx, id, opts.live === true));
361
+ const auth = program.command("auth").description("Check API-key setup (keys live in environment variables, never in zg's files)");
362
+ auth.command("status").description("Show which provider keys are set (values are never shown)").action(async () => {
363
+ let config = defaultConfig();
364
+ try {
365
+ config = (await ctx.manager.load()).config;
366
+ } catch {
367
+ }
368
+ say("");
369
+ say("API keys are read from environment variables only. Values are never printed or stored.");
370
+ say("");
371
+ for (const p of PROVIDERS) {
372
+ const spec = p.credentialSpec(config);
373
+ say(` ${p.id.padEnd(18)} ${credentialWords(resolveCredentialStatus(spec, ctx.env))}`);
374
+ }
375
+ const missing = PROVIDERS.map((p) => ({ p, spec: p.credentialSpec(config) })).filter((x) => x.spec.kind === "required" && resolveCredentialStatus(x.spec, ctx.env).state !== "present" && x.spec.envVars[0]);
376
+ if (missing.length > 0) {
377
+ say("");
378
+ say("To set a key (replace <your-key>; run it in your own terminal, not in chat):");
379
+ const first = missing[0].spec.envVars[0];
380
+ for (const block of shellInstructions(first, ctx.platform.os)) {
381
+ say(` ${block.shell}`);
382
+ for (const line of block.set) say(` ${line}`);
383
+ }
384
+ say(` Other variables: ${PROVIDERS.flatMap((p) => p.credentialSpec(config).envVars).filter((v) => v !== first).join(", ")}`);
385
+ }
386
+ say("");
387
+ });
388
+ auth.command("logout [provider]").description("Explain how to remove a key (zg never stores keys, so there is nothing for it to delete)").action(async (id) => {
389
+ let config = defaultConfig();
390
+ try {
391
+ config = (await ctx.manager.load()).config;
392
+ } catch {
393
+ }
394
+ const targets = id ? [safeProvider(id)] : PROVIDERS.filter((p) => p.credentialSpec(config).envVars.length > 0);
395
+ say("");
396
+ say("zg does not store API keys, so there is no stored login to delete, and zg will not edit your shell configuration.");
397
+ say("To log out, remove the variable yourself:");
398
+ for (const p of targets) {
399
+ for (const envVar of p.credentialSpec(config).envVars) {
400
+ say("");
401
+ say(` ${p.displayName}: ${envVar}`);
402
+ for (const block of shellInstructions(envVar, ctx.platform.os)) {
403
+ say(` ${block.shell}`);
404
+ for (const line of block.unset) say(` ${line}`);
405
+ }
406
+ }
407
+ }
408
+ say("");
409
+ say("Then open a new terminal. If you pasted a key anywhere else (shell history, notes), remove it there too.");
410
+ say("To make a key unusable everywhere, revoke it in the provider's dashboard.");
411
+ say("");
412
+ });
413
+ }
414
+ export {
415
+ applyProviderChoice,
416
+ registerProviders
417
+ };
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ auditText,
4
+ doctorChecks,
5
+ grantsText,
6
+ permissionsText,
7
+ policiesText,
8
+ protectedPathsText,
9
+ scanProjectSecrets,
10
+ secretsText,
11
+ statusText
12
+ } from "./chunk-4BZ4IXTO.js";
13
+ import "./chunk-C2GFK4JP.js";
14
+ import "./chunk-R2CPYTSP.js";
15
+ import "./chunk-ZQFAX275.js";
16
+ import "./chunk-FC3UOHOO.js";
17
+ import "./chunk-WUF3TVAE.js";
18
+ export {
19
+ auditText,
20
+ doctorChecks,
21
+ grantsText,
22
+ permissionsText,
23
+ policiesText,
24
+ protectedPathsText,
25
+ scanProjectSecrets,
26
+ secretsText,
27
+ statusText
28
+ };
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ openSecEnv
4
+ } from "./chunk-6QLYRU3N.js";
5
+ import "./chunk-VCCMJIAG.js";
6
+ import "./chunk-JQYZX56A.js";
7
+ import "./chunk-QH27MDJM.js";
8
+ import "./chunk-C2GFK4JP.js";
9
+ import "./chunk-R2CPYTSP.js";
10
+ import "./chunk-ZQFAX275.js";
11
+ import "./chunk-FC3UOHOO.js";
12
+ import "./chunk-WUF3TVAE.js";
13
+ export {
14
+ openSecEnv
15
+ };
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ openSecEnv
4
+ } from "./chunk-6QLYRU3N.js";
5
+ import "./chunk-VCCMJIAG.js";
6
+ import {
7
+ confirm
8
+ } from "./chunk-YR6RCC6Y.js";
9
+ import "./chunk-SZKAZ2VN.js";
10
+ import "./chunk-DKCCXMSE.js";
11
+ import "./chunk-U5UIUB6L.js";
12
+ import "./chunk-XCWLFZSM.js";
13
+ import "./chunk-JQYZX56A.js";
14
+ import "./chunk-QH27MDJM.js";
15
+ import {
16
+ auditText,
17
+ doctorChecks,
18
+ grantsText,
19
+ permissionsText,
20
+ policiesText,
21
+ protectedPathsText,
22
+ secretsText,
23
+ statusText
24
+ } from "./chunk-4BZ4IXTO.js";
25
+ import "./chunk-C2GFK4JP.js";
26
+ import "./chunk-R2CPYTSP.js";
27
+ import "./chunk-ZQFAX275.js";
28
+ import {
29
+ ZgError,
30
+ defaultSecuritySettings
31
+ } from "./chunk-FC3UOHOO.js";
32
+ import {
33
+ redactSecrets
34
+ } from "./chunk-WUF3TVAE.js";
35
+
36
+ // src/cli/commands/security.ts
37
+ function registerSecurity(program, ctx) {
38
+ const say = (t) => ctx.stdout(redactSecrets(t));
39
+ const sec = program.command("security").description("Permissions, approvals, protected files, audit log and secret handling");
40
+ sec.action(async () => say(statusText((await openSecEnv(ctx)).report)));
41
+ sec.command("status").description("Active security mode and effective permissions").action(async () => say(statusText((await openSecEnv(ctx)).report)));
42
+ sec.command("permissions").description("The eight permission levels and what each allows").action(async () => say(permissionsText((await openSecEnv(ctx)).report)));
43
+ sec.command("policies").description("Effective policy (global settings plus the project policy)").action(async () => say(policiesText((await openSecEnv(ctx)).report)));
44
+ sec.command("protected-paths").description("Files and folders zg will not change or read").action(async () => say(protectedPathsText((await openSecEnv(ctx)).report)));
45
+ sec.command("secrets").description("How credentials are handled, and a scan of this project for secrets").action(async () => say(await secretsText((await openSecEnv(ctx)).report)));
46
+ sec.command("grants").description("Remembered approvals (saved ones; session approvals live only inside a chat)").action(async () => {
47
+ const { report } = await openSecEnv(ctx);
48
+ await report.engine.grants.load();
49
+ say(grantsText(report.engine));
50
+ });
51
+ sec.command("revoke <id>").description('Revoke a remembered approval by id, or "all"').action(async (id) => {
52
+ const { report } = await openSecEnv(ctx);
53
+ await report.engine.grants.load();
54
+ const n = await report.engine.grants.revoke(id);
55
+ if (n === 0) throw new ZgError(`No remembered approval "${id}".`, { hint: "See them with: zg security grants" });
56
+ await report.engine.audit.append({ id: `rv-${id}`.slice(0, 40), status: "info", operation: "revoke grant", level: "admin", resource: "config", target: id, component: "cli", actor: "user", rule: "grant", risk: "low", session: report.engine.session });
57
+ say(`Revoked ${n} remembered approval${n === 1 ? "" : "s"}.`);
58
+ });
59
+ sec.command("audit").description("Show the audit log (every refusal, approval and change)").option("--limit <n>", "how many records to show", "30").option("--status <s>", "only denied | approved | allowed | completed | failed | needs-approval | info").option("--export <format>", "print the whole log as json or csv").option("--prune", "remove records older than the retention period").action(async (o) => {
60
+ const { report } = await openSecEnv(ctx);
61
+ const e = report.engine;
62
+ if (o.export) {
63
+ if (o.export !== "json" && o.export !== "csv") throw new ZgError("Choose --export json or --export csv.");
64
+ ctx.stdout((await e.audit.export(o.export)).trimEnd());
65
+ return;
66
+ }
67
+ if (o.prune) {
68
+ const n = await e.audit.prune();
69
+ await e.audit.append({ id: "prune", status: "info", operation: "prune audit log", level: "admin", resource: "config", target: `${n} records`, component: "cli", actor: "user", rule: "retention", risk: "low", session: e.session });
70
+ say(`Removed ${n} record${n === 1 ? "" : "s"} older than ${e.settings.audit.retentionDays} days.`);
71
+ return;
72
+ }
73
+ const limit = Number(o.limit);
74
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1e3) throw new ZgError("--limit must be a whole number from 1 to 1000.");
75
+ say(await auditText(e, { limit, ...o.status ? { status: o.status } : {} }));
76
+ });
77
+ sec.command("doctor").description("Check the security setup on this computer").action(async () => {
78
+ const { report } = await openSecEnv(ctx);
79
+ for (const c of await doctorChecks(report)) say(`${c.status === "ok" ? "[ok] " : c.status === "warn" ? "[warn]" : c.status === "fail" ? "[fail]" : "[info]"} ${c.label}: ${c.detail}${c.hint ? `
80
+ hint: ${c.hint}` : ""}`);
81
+ });
82
+ sec.command("reset").description("Put security settings back to the defaults (balanced mode) and revoke all remembered approvals. The audit log is kept.").option("--yes", "do not ask").action(async (o) => {
83
+ const ok = await confirm(ctx, "Reset security settings to the defaults and revoke all remembered approvals?", o.yes === true);
84
+ if (!ok) return say("Nothing was changed.");
85
+ const { report, config } = await openSecEnv(ctx);
86
+ await ctx.manager.save({ ...config, security: defaultSecuritySettings() });
87
+ await report.engine.grants.load();
88
+ await report.engine.grants.revoke("all");
89
+ await report.engine.audit.append({ id: "reset", status: "info", operation: "reset security settings", level: "admin", resource: "config", target: "security", component: "cli", actor: "user", rule: "reset", risk: "medium", session: report.engine.session });
90
+ say("Security settings are back to the defaults (balanced mode). Remembered approvals were revoked. The audit log was kept.");
91
+ });
92
+ }
93
+ export {
94
+ registerSecurity
95
+ };