@odla-ai/cli 0.7.1 → 0.9.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.
package/dist/bin.cjs CHANGED
@@ -27,11 +27,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
27
  var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
28
28
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
29
29
 
30
- // src/cli.ts
31
- var import_security2 = require("@odla-ai/security");
32
-
33
30
  // src/admin-ai.ts
34
- var import_node_process4 = __toESM(require("process"), 1);
31
+ var import_node_process5 = __toESM(require("process"), 1);
35
32
 
36
33
  // src/token.ts
37
34
  var import_db = require("@odla-ai/db");
@@ -261,9 +258,32 @@ function platformAudience(value) {
261
258
  return url.origin;
262
259
  }
263
260
 
261
+ // src/secret-input.ts
262
+ var import_node_process3 = __toESM(require("process"), 1);
263
+ var MAX_BYTES = 64 * 1024;
264
+ async function secretInputValue(options, kind = "credential") {
265
+ if (options.fromEnv && options.stdin) throw new Error("choose exactly one of --from-env or --stdin");
266
+ let value;
267
+ if (options.fromEnv) value = import_node_process3.default.env[options.fromEnv];
268
+ else if (options.stdin) value = await (options.readStdin ?? (() => readSecretStream(kind)))();
269
+ else throw new Error(`${kind} input required: use --from-env <NAME> or --stdin; values are never accepted as arguments`);
270
+ value = value?.replace(/[\r\n]+$/, "");
271
+ if (!value) throw new Error(options.fromEnv ? `environment variable ${options.fromEnv} is empty or unset` : `stdin ${kind} is empty`);
272
+ if (new TextEncoder().encode(value).byteLength > MAX_BYTES) throw new Error(`${kind} exceeds 64 KiB`);
273
+ return value;
274
+ }
275
+ async function readSecretStream(kind, stream = import_node_process3.default.stdin) {
276
+ let value = "";
277
+ for await (const chunk of stream) {
278
+ value += String(chunk);
279
+ if (value.length > MAX_BYTES) throw new Error(`${kind} exceeds 64 KiB`);
280
+ }
281
+ return value;
282
+ }
283
+
264
284
  // src/admin-ai-auth.ts
265
285
  var import_node_fs2 = require("fs");
266
- var import_node_process3 = __toESM(require("process"), 1);
286
+ var import_node_process4 = __toESM(require("process"), 1);
267
287
  var import_db2 = require("@odla-ai/db");
268
288
  async function getScopedPlatformToken(options) {
269
289
  return resolveAdminPlatformToken(options);
@@ -271,7 +291,7 @@ async function getScopedPlatformToken(options) {
271
291
  async function resolveAdminPlatformToken(options) {
272
292
  const audience = platformAudience(options.platform);
273
293
  if (options.token) return options.token;
274
- const fromEnv = import_node_process3.default.env.ODLA_ADMIN_TOKEN;
294
+ const fromEnv = import_node_process4.default.env.ODLA_ADMIN_TOKEN;
275
295
  if (fromEnv) return audienceBoundEnvToken(fromEnv, audience);
276
296
  return scopedToken(
277
297
  audience,
@@ -283,7 +303,7 @@ async function resolveAdminPlatformToken(options) {
283
303
  }
284
304
  function audienceBoundEnvToken(token, platform) {
285
305
  const audience = platformAudience(platform);
286
- const declared = import_node_process3.default.env.ODLA_ADMIN_TOKEN_AUDIENCE;
306
+ const declared = import_node_process4.default.env.ODLA_ADMIN_TOKEN_AUDIENCE;
287
307
  if (declared) {
288
308
  if (platformAudience(declared) !== audience) throw new Error("ODLA_ADMIN_TOKEN_AUDIENCE does not match the configured platform");
289
309
  } else if (audience !== "https://odla.ai") {
@@ -293,7 +313,7 @@ function audienceBoundEnvToken(token, platform) {
293
313
  }
294
314
  async function scopedToken(platform, scope, options, doFetch, out) {
295
315
  const audience = platformAudience(platform);
296
- const tokenFile = options.tokenFile ?? `${import_node_process3.default.cwd()}/.odla/admin-token.local.json`;
316
+ const tokenFile = options.tokenFile ?? `${import_node_process4.default.cwd()}/.odla/admin-token.local.json`;
297
317
  const cache = readJsonFile(tokenFile);
298
318
  const cached = cache?.platform === audience ? cache.tokens?.[scope] : void 0;
299
319
  if (cached?.token && (cached.expiresAt ?? 0) > Date.now() + 6e4) {
@@ -308,13 +328,13 @@ async function scopedToken(platform, scope, options, doFetch, out) {
308
328
  onCode: async ({ userCode, expiresIn }) => {
309
329
  const approvalUrl = handshakeUrl(audience, userCode);
310
330
  out.log(`Approve scoped request ${userCode} at ${approvalUrl} within ${Math.floor(expiresIn / 60)}m.`);
311
- const shouldOpen = options.open === true || options.open !== false && !import_node_process3.default.env.CI && Boolean(import_node_process3.default.stdin.isTTY && import_node_process3.default.stdout.isTTY);
331
+ const shouldOpen = options.open === true || options.open !== false && !import_node_process4.default.env.CI && Boolean(import_node_process4.default.stdin.isTTY && import_node_process4.default.stdout.isTTY);
312
332
  if (shouldOpen) await (options.openApprovalUrl ?? openUrl)(approvalUrl).catch(() => void 0);
313
333
  }
314
334
  });
315
335
  const tokens = cache?.platform === audience ? { ...cache.tokens ?? {} } : {};
316
336
  tokens[scope] = { token, expiresAt };
317
- if ((0, import_node_fs2.existsSync)(`${import_node_process3.default.cwd()}/.git`)) ensureGitignore(import_node_process3.default.cwd(), [tokenFile]);
337
+ if ((0, import_node_fs2.existsSync)(`${import_node_process4.default.cwd()}/.git`)) ensureGitignore(import_node_process4.default.cwd(), [tokenFile]);
318
338
  writePrivateJson(tokenFile, { platform: audience, tokens });
319
339
  out.log(`auth: cached ${scope} grant (${tokenFile}; mode 0600)`);
320
340
  return token;
@@ -475,7 +495,7 @@ function isRecord2(value) {
475
495
 
476
496
  // src/admin-ai.ts
477
497
  async function adminAi(options) {
478
- const platform = platformAudience(options.platform ?? import_node_process4.default.env.ODLA_PLATFORM ?? "https://odla.ai");
498
+ const platform = platformAudience(options.platform ?? import_node_process5.default.env.ODLA_PLATFORM ?? "https://odla.ai");
479
499
  const doFetch = options.fetch ?? fetch;
480
500
  const out = options.stdout ?? console;
481
501
  const usageQuery = options.action === "usage" ? adminAiUsageQuery(options) : void 0;
@@ -514,7 +534,7 @@ async function adminAi(options) {
514
534
  }
515
535
  if (options.action === "credential-set") {
516
536
  const provider = requireProvider(options.credentialProvider);
517
- const value = await credentialValue(options);
537
+ const value = await secretInputValue(options);
518
538
  const res2 = await doFetch(`${platform}/registry/platform/ai-credentials/${encodeURIComponent(provider)}`, {
519
539
  method: "PUT",
520
540
  headers,
@@ -624,25 +644,6 @@ function requireProvider(value) {
624
644
  }
625
645
  return value;
626
646
  }
627
- async function credentialValue(options) {
628
- if (options.fromEnv && options.stdin) throw new Error("choose exactly one of --from-env or --stdin");
629
- let value;
630
- if (options.fromEnv) value = import_node_process4.default.env[options.fromEnv];
631
- else if (options.stdin) value = await (options.readStdin ?? readStdin)();
632
- else throw new Error("credential input required: use --from-env <NAME> or --stdin; values are never accepted as arguments");
633
- value = value?.replace(/[\r\n]+$/, "");
634
- if (!value) throw new Error(options.fromEnv ? `environment variable ${options.fromEnv} is empty or unset` : "stdin credential is empty");
635
- if (new TextEncoder().encode(value).byteLength > 64 * 1024) throw new Error("credential exceeds 64 KiB");
636
- return value;
637
- }
638
- async function readStdin() {
639
- let value = "";
640
- for await (const chunk of import_node_process4.default.stdin) {
641
- value += String(chunk);
642
- if (value.length > 64 * 1024) throw new Error("credential exceeds 64 KiB");
643
- }
644
- return value;
645
- }
646
647
  function policyArray(body) {
647
648
  if (isRecord3(body) && Array.isArray(body.policies)) return body.policies.filter(isRecord3);
648
649
  if (isRecord3(body) && isRecord3(body.policies)) return Object.values(body.policies).filter(isRecord3);
@@ -747,15 +748,76 @@ function addOption(options, name, value) {
747
748
  else options[name] = [String(current), String(value)];
748
749
  }
749
750
 
751
+ // src/admin-command.ts
752
+ async function adminCommand(parsed) {
753
+ const area = parsed.positionals[1];
754
+ const action = parsed.positionals[2];
755
+ const credentialSet = action === "credential" && parsed.positionals[3] === "set";
756
+ const credentials = action === "credentials";
757
+ const models = action === "models";
758
+ const usage = action === "usage";
759
+ const audit = action === "audit";
760
+ if (area !== "ai" || action !== "show" && action !== "set" && !credentialSet && !credentials && !models && !usage && !audit) {
761
+ throw new Error('unknown admin command. Try "odla-ai admin ai show".');
762
+ }
763
+ assertArgs(parsed, [
764
+ "platform",
765
+ "json",
766
+ "open",
767
+ "provider",
768
+ "model",
769
+ "enabled",
770
+ "max-input-bytes",
771
+ "max-output-tokens",
772
+ "max-calls-per-run",
773
+ "from-env",
774
+ "stdin",
775
+ "discovery-provider",
776
+ "discovery-model",
777
+ "validation-provider",
778
+ "validation-model",
779
+ "app-id",
780
+ "env",
781
+ "run-id",
782
+ "limit"
783
+ ], credentialSet ? 5 : action === "set" ? 4 : 3);
784
+ await adminAi({
785
+ action: credentialSet ? "credential-set" : credentials ? "credentials" : models ? "models" : usage ? "usage" : audit ? "audit" : action,
786
+ purpose: action === "set" ? parsed.positionals[3] : void 0,
787
+ provider: stringOpt(parsed.options.provider),
788
+ model: stringOpt(parsed.options.model),
789
+ enabled: boolOpt(parsed.options.enabled),
790
+ maxInputBytes: numberOpt(parsed.options["max-input-bytes"], "--max-input-bytes"),
791
+ maxOutputTokens: numberOpt(parsed.options["max-output-tokens"], "--max-output-tokens"),
792
+ maxCallsPerRun: numberOpt(parsed.options["max-calls-per-run"], "--max-calls-per-run"),
793
+ platform: stringOpt(parsed.options.platform),
794
+ json: parsed.options.json === true,
795
+ open: parsed.options.open === false ? false : parsed.options.open === true ? true : void 0,
796
+ credentialProvider: credentialSet ? parsed.positionals[4] : void 0,
797
+ fromEnv: stringOpt(parsed.options["from-env"]),
798
+ stdin: parsed.options.stdin === true,
799
+ discoveryProvider: stringOpt(parsed.options["discovery-provider"]),
800
+ discoveryModel: stringOpt(parsed.options["discovery-model"]),
801
+ validationProvider: stringOpt(parsed.options["validation-provider"]),
802
+ validationModel: stringOpt(parsed.options["validation-model"]),
803
+ appId: stringOpt(parsed.options["app-id"]),
804
+ env: stringOpt(parsed.options.env),
805
+ runId: stringOpt(parsed.options["run-id"]),
806
+ limit: numberOpt(parsed.options.limit, "--limit")
807
+ });
808
+ }
809
+
750
810
  // src/capabilities.ts
751
811
  var CAPABILITIES = {
752
812
  cli: [
753
813
  "register the app and enable configured services per environment",
754
814
  "issue, persist, and explicitly rotate configured service credentials",
755
815
  "write local Worker values and push deployed Worker secrets through Wrangler stdin",
816
+ "store tenant-vault secrets (including the Clerk webhook secret and reserved Clerk secret key) write-only from stdin or an env var",
756
817
  "push db schema/rules and configure platform AI, auth, and deployment links",
757
818
  "validate config offline and smoke-test a provisioned db environment",
758
819
  "run app-attributed hosted security discovery and independent validation without provider keys",
820
+ "connect/revoke source-read-only GitHub sources and drive commit-pinned hosted security jobs without PATs or provider keys",
759
821
  "let admins manage system AI policy and credentials, inspect attributed usage, and read immutable admin changes through separate short-lived capability-only approvals"
760
822
  ],
761
823
  agent: [
@@ -768,12 +830,14 @@ var CAPABILITIES = {
768
830
  "consent to production changes with --yes",
769
831
  "request destructive credential rotation explicitly",
770
832
  "review application semantics, security findings, releases, and merges",
771
- "approve redacted-source disclosure before hosted security reasoning"
833
+ "approve redacted-source disclosure before hosted security reasoning",
834
+ "approve GitHub App repository access separately from redacted-snippet disclosure"
772
835
  ],
773
836
  studio: [
774
837
  "view telemetry and environment state",
775
838
  "perform manual credential recovery when the CLI's local shown-once copy is unavailable",
776
- "configure system AI purposes and view app/environment/run-attributed usage"
839
+ "configure system AI purposes and view app/environment/run-attributed usage",
840
+ "connect/revoke GitHub security sources and inspect ref-to-SHA jobs, routes, retention, coverage, and normalized reports"
777
841
  ]
778
842
  };
779
843
  function printCapabilities(json = false, out = console) {
@@ -1170,14 +1234,107 @@ async function doctor(options) {
1170
1234
  }
1171
1235
  }
1172
1236
 
1173
- // src/init.ts
1237
+ // src/help.ts
1174
1238
  var import_node_fs6 = require("fs");
1239
+ function cliVersion() {
1240
+ const pkg = JSON.parse((0, import_node_fs6.readFileSync)(new URL("../package.json", importMetaUrl), "utf8"));
1241
+ return pkg.version ?? "unknown";
1242
+ }
1243
+ function printHelp() {
1244
+ console.log(`odla-ai
1245
+
1246
+ Usage:
1247
+ odla-ai setup [--dir <project>] [--agent <name>] [--global] [--force]
1248
+ odla-ai init --app-id <id> --name <name> [--services db,ai,o11y] [--env dev --env prod]
1249
+ odla-ai doctor [--config odla.config.mjs]
1250
+ odla-ai capabilities [--json]
1251
+ odla-ai admin ai show [--platform https://odla.ai] [--json]
1252
+ odla-ai admin ai models [--provider <id>] [--json]
1253
+ odla-ai admin ai set <purpose> [--provider <id>] [--model <id>] [--enabled|--no-enabled]
1254
+ odla-ai admin ai set security --discovery-provider <id> --discovery-model <id>
1255
+ --validation-provider <id> --validation-model <id> [--enabled|--no-enabled]
1256
+ odla-ai admin ai credentials [--json]
1257
+ odla-ai admin ai credential set <provider> (--from-env <NAME>|--stdin)
1258
+ odla-ai admin ai usage [--app-id <id>] [--env <env>] [--run-id <id>] [--limit <1-500>] [--json]
1259
+ odla-ai admin ai audit [--limit <1-200>] [--json]
1260
+ odla-ai security github connect [--repo owner/name] [--env dev] [--no-open]
1261
+ odla-ai security github disconnect --source <id> [--env dev] [--yes]
1262
+ odla-ai security plan [--env dev] [--json]
1263
+ odla-ai security sources [--env dev] [--json]
1264
+ odla-ai security run --source <id> --plan-digest <sha256:...> --ack-redacted-source [--ref <branch|tag|sha>] [--env dev] [--no-follow]
1265
+ odla-ai security status <job-id> [--follow] [--json]
1266
+ odla-ai security report <job-id> [--json]
1267
+ odla-ai security run [target] --ack-redacted-source [--env dev] [--profile odla] [--fail-on high]
1268
+ odla-ai security run [target] --self --ack-redacted-source
1269
+ odla-ai provision [--config odla.config.mjs] [--dry-run] [--push-secrets] [--rotate-o11y-token] [--write-dev-vars[=path]] [--yes]
1270
+ odla-ai smoke [--config odla.config.mjs] [--env dev]
1271
+ odla-ai skill install [--dir <project>] [--agent <name>] [--global] [--force]
1272
+ odla-ai secrets push --env <env> [--config odla.config.mjs] [--dry-run] [--yes]
1273
+ odla-ai secrets set <name> --env <env> (--from-env <NAME>|--stdin) [--config odla.config.mjs] [--yes]
1274
+ odla-ai secrets set-clerk-key --env <env> (--from-env <NAME>|--stdin) [--config odla.config.mjs] [--yes]
1275
+ odla-ai version
1276
+
1277
+ Commands:
1278
+ setup Install offline odla runbooks for common coding-agent harnesses.
1279
+ init Create a generic odla.config.mjs plus starter schema/rules files.
1280
+ doctor Validate and summarize the project config without network calls.
1281
+ capabilities Show what the CLI automates vs agent edits and human checkpoints.
1282
+ admin Manage platform-funded AI routing/credentials/usage with narrow device grants.
1283
+ security Connect GitHub sources and run commit-pinned hosted reviews, or scan a local snapshot.
1284
+ provision Register services, configure them, persist credentials, optionally push secrets.
1285
+ smoke Verify local credentials, public-config, live schema, and db aggregate.
1286
+ skill Same installer; --agent accepts all, claude, codex, cursor,
1287
+ copilot, gemini, or agents (repeatable or comma-separated).
1288
+ secrets Push configured db/o11y secrets into the Worker via wrangler
1289
+ stdin; set stores a tenant-vault secret and set-clerk-key the
1290
+ reserved Clerk secret key, write-only from stdin or an env var.
1291
+ version Print the CLI version.
1292
+
1293
+ Safety:
1294
+ New projects target dev only. Add prod explicitly to odla.config.mjs and pass
1295
+ --yes to provision it; use --dry-run first to inspect the resolved plan.
1296
+ Provision caches the approved developer token and service credentials under
1297
+ .odla/ with mode 0600, and init adds those paths to .gitignore. Secret push
1298
+ preflights Wrangler before any shown-once issuance or destructive rotation.
1299
+ Provision opens the approval page automatically in interactive terminals;
1300
+ use --open to force browser launch or --no-open to suppress it.
1301
+ GitHub security uses source-read-only access plus optional metadata-only Checks write: the CLI never asks
1302
+ for a PAT or provider key. GitHub read access is separate from the explicit
1303
+ --ack-redacted-source consent and the exact --plan-digest printed by security
1304
+ plan are required before bounded snippets reach System AI.
1305
+ Run security plan first to inspect the admin-selected providers, models,
1306
+ per-route bounds, credential readiness, retention, no-execution boundary,
1307
+ and digest that binds consent to that exact plan.
1308
+ `);
1309
+ }
1310
+
1311
+ // src/harness-options.ts
1312
+ function harnessList(parsed) {
1313
+ const selected = [
1314
+ ...harnessOption(parsed.options.agent, "--agent"),
1315
+ ...harnessOption(parsed.options.harness, "--harness")
1316
+ ];
1317
+ return selected.length ? selected : ["all"];
1318
+ }
1319
+ function harnessOption(value, flag) {
1320
+ if (value === void 0) return [];
1321
+ if (typeof value === "boolean") throw new Error(`${flag} requires a harness name`);
1322
+ const raw = Array.isArray(value) ? value : [value];
1323
+ const parts = raw.flatMap((item) => item.split(","));
1324
+ if (parts.some((item) => !item.trim())) {
1325
+ throw new Error(`${flag} requires a harness name`);
1326
+ }
1327
+ return parts.map((item) => item.trim());
1328
+ }
1329
+
1330
+ // src/init.ts
1331
+ var import_node_fs7 = require("fs");
1175
1332
  var import_node_path5 = require("path");
1176
1333
  function initProject(options) {
1177
1334
  const out = options.stdout ?? console;
1178
1335
  const rootDir = (0, import_node_path5.resolve)(options.rootDir ?? process.cwd());
1179
1336
  const configPath = (0, import_node_path5.resolve)(rootDir, options.configPath ?? "odla.config.mjs");
1180
- if ((0, import_node_fs6.existsSync)(configPath) && !options.force) {
1337
+ if ((0, import_node_fs7.existsSync)(configPath) && !options.force) {
1181
1338
  throw new Error(`${configPath} already exists. Pass --force to overwrite.`);
1182
1339
  }
1183
1340
  if (!/^[a-z0-9][a-z0-9-]*$/.test(options.appId)) {
@@ -1186,10 +1343,10 @@ function initProject(options) {
1186
1343
  const envs = options.envs?.length ? options.envs : ["dev"];
1187
1344
  const services = options.services?.length ? options.services : ["db", "ai"];
1188
1345
  const aiProvider = options.aiProvider ?? "anthropic";
1189
- (0, import_node_fs6.mkdirSync)((0, import_node_path5.dirname)(configPath), { recursive: true });
1190
- (0, import_node_fs6.mkdirSync)((0, import_node_path5.resolve)(rootDir, "src/odla"), { recursive: true });
1191
- (0, import_node_fs6.mkdirSync)((0, import_node_path5.resolve)(rootDir, ".odla"), { recursive: true });
1192
- (0, import_node_fs6.writeFileSync)(configPath, configTemplate({ appId: options.appId, name: options.name, envs, services, aiProvider }));
1346
+ (0, import_node_fs7.mkdirSync)((0, import_node_path5.dirname)(configPath), { recursive: true });
1347
+ (0, import_node_fs7.mkdirSync)((0, import_node_path5.resolve)(rootDir, "src/odla"), { recursive: true });
1348
+ (0, import_node_fs7.mkdirSync)((0, import_node_path5.resolve)(rootDir, ".odla"), { recursive: true });
1349
+ (0, import_node_fs7.writeFileSync)(configPath, configTemplate({ appId: options.appId, name: options.name, envs, services, aiProvider }));
1193
1350
  writeIfMissing((0, import_node_path5.resolve)(rootDir, "src/odla/schema.mjs"), schemaTemplate());
1194
1351
  writeIfMissing((0, import_node_path5.resolve)(rootDir, "src/odla/rules.mjs"), rulesTemplate());
1195
1352
  ensureGitignore(rootDir);
@@ -1198,8 +1355,8 @@ function initProject(options) {
1198
1355
  out.log("updated .gitignore for local odla credentials");
1199
1356
  }
1200
1357
  function writeIfMissing(path, text) {
1201
- if ((0, import_node_fs6.existsSync)(path)) return;
1202
- (0, import_node_fs6.writeFileSync)(path, text);
1358
+ if ((0, import_node_fs7.existsSync)(path)) return;
1359
+ (0, import_node_fs7.writeFileSync)(path, text);
1203
1360
  }
1204
1361
  function configTemplate(input) {
1205
1362
  return `export default {
@@ -1288,7 +1445,7 @@ function relativeDisplay(path, rootDir) {
1288
1445
  // src/provision.ts
1289
1446
  var import_apps2 = require("@odla-ai/apps");
1290
1447
  var import_ai = require("@odla-ai/ai");
1291
- var import_node_process5 = __toESM(require("process"), 1);
1448
+ var import_node_process6 = __toESM(require("process"), 1);
1292
1449
 
1293
1450
  // src/provision-credentials.ts
1294
1451
  var import_apps = require("@odla-ai/apps");
@@ -1592,7 +1749,7 @@ ${env}: credentials are already saved; retry "odla-ai secrets push --env ${env}$
1592
1749
  out.log(`${env}: rules pushed (${Object.keys(rules).length} namespaces)`);
1593
1750
  }
1594
1751
  if (cfg.services.includes("ai") && cfg.ai?.provider && cfg.ai.keyEnv) {
1595
- const key = import_node_process5.default.env[cfg.ai.keyEnv];
1752
+ const key = import_node_process6.default.env[cfg.ai.keyEnv];
1596
1753
  if (key) {
1597
1754
  const secretName = cfg.ai.secretName ?? defaultSecretName(cfg.ai.provider);
1598
1755
  await (0, import_ai.putSecret)({ endpoint: cfg.dbEndpoint, token, fetch: doFetch }, tenantId, secretName, key);
@@ -1652,6 +1809,219 @@ async function safeText2(res) {
1652
1809
  }
1653
1810
  }
1654
1811
 
1812
+ // src/secrets-set.ts
1813
+ var import_ai2 = require("@odla-ai/ai");
1814
+ var import_apps3 = require("@odla-ai/apps");
1815
+ var PROD_ENV_NAMES2 = /* @__PURE__ */ new Set(["prod", "production"]);
1816
+ async function secretsSet(options) {
1817
+ const name = (options.name ?? "").trim();
1818
+ if (!name) throw new Error('secret name is required, e.g. "odla-ai secrets set clerk_webhook_secret --env dev --stdin"');
1819
+ if (name.startsWith("$")) {
1820
+ throw new Error('"$"-prefixed vault names are platform-reserved; for the Clerk secret key use "odla-ai secrets set-clerk-key"');
1821
+ }
1822
+ const { cfg, tenantId, value, doFetch, out } = await resolveVaultWrite(options);
1823
+ const token = await getDeveloperToken(cfg, options, doFetch, out);
1824
+ try {
1825
+ await (0, import_ai2.putSecret)({ endpoint: cfg.dbEndpoint, token, fetch: doFetch }, tenantId, name, value);
1826
+ } catch (err) {
1827
+ throw new Error(scrubValue(err instanceof Error ? err.message : String(err), value));
1828
+ }
1829
+ out.log(`${name} stored in the ${tenantId} vault (write-only; the value was never echoed and cannot be read back here)`);
1830
+ }
1831
+ async function secretsSetClerkKey(options) {
1832
+ const { cfg, tenantId, value, doFetch, out } = await resolveVaultWrite(options);
1833
+ if (!value.startsWith("sk_")) throw new Error("the Clerk secret key must start with sk_ (sk_test_\u2026 or sk_live_\u2026)");
1834
+ if (value.startsWith("sk_test_") && PROD_ENV_NAMES2.has(options.env)) {
1835
+ throw new Error(`refusing to store an sk_test_ Clerk key for "${options.env}" \u2014 use the production instance's sk_live_ key`);
1836
+ }
1837
+ if (value.startsWith("sk_live_") && !PROD_ENV_NAMES2.has(options.env) && !options.yes) {
1838
+ throw new Error(`refusing to store an sk_live_ Clerk key for "${options.env}" without --yes (live users would sync into a non-prod tenant)`);
1839
+ }
1840
+ const token = await getDeveloperToken(cfg, options, doFetch, out);
1841
+ const res = await doFetch(`${cfg.dbEndpoint}/admin/apps/${encodeURIComponent(tenantId)}/clerk-secret`, {
1842
+ method: "POST",
1843
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
1844
+ body: JSON.stringify({ value })
1845
+ });
1846
+ if (!res.ok) {
1847
+ const text = scrubValue((await res.text().catch(() => "")).slice(0, 300), value);
1848
+ throw new Error(`store Clerk secret key failed (${res.status}): ${text || "request failed"}`);
1849
+ }
1850
+ out.log(`Clerk secret key stored for ${tenantId} ($clerk_secret, reserved + write-only; the value was never echoed)`);
1851
+ }
1852
+ function scrubValue(text, value) {
1853
+ return redactSecrets(text).split(value).join("[value redacted]");
1854
+ }
1855
+ async function resolveVaultWrite(options) {
1856
+ const out = options.stdout ?? console;
1857
+ const doFetch = options.fetch ?? fetch;
1858
+ const cfg = await loadProjectConfig(options.configPath);
1859
+ if (!cfg.envs.includes(options.env)) {
1860
+ throw new Error(`env "${options.env}" is not in config envs (${cfg.envs.join(", ")})`);
1861
+ }
1862
+ if (PROD_ENV_NAMES2.has(options.env) && !options.yes) {
1863
+ throw new Error(`refusing to store a secret for "${options.env}" without --yes`);
1864
+ }
1865
+ const value = await secretInputValue(options, "secret");
1866
+ return { cfg, tenantId: (0, import_apps3.tenantIdFor)(cfg.app.id, options.env), value, doFetch, out };
1867
+ }
1868
+
1869
+ // src/security-command-context.ts
1870
+ var import_promises = require("readline/promises");
1871
+ async function hostedSecurityContext(parsed, dependencies) {
1872
+ const configPath = stringOpt(parsed.options.config) ?? "odla.config.mjs";
1873
+ const cfg = await loadProjectConfig(configPath);
1874
+ const env = stringOpt(parsed.options.env) ?? (cfg.envs.includes("dev") ? "dev" : cfg.envs[0]);
1875
+ if (!env || !cfg.envs.includes(env)) {
1876
+ throw new Error(`env "${env ?? ""}" is not declared in ${configPath}`);
1877
+ }
1878
+ const platform = platformAudience(stringOpt(parsed.options.platform) ?? cfg.platformUrl);
1879
+ if (platformAudience(cfg.platformUrl) !== platform) {
1880
+ throw new Error("--platform cannot reuse a project developer token from another platform; update odla.config.mjs and authenticate there");
1881
+ }
1882
+ const doFetch = dependencies.fetch ?? fetch;
1883
+ const stdout = dependencies.stdout ?? console;
1884
+ const open = parsed.options.open === false ? false : parsed.options.open === true ? true : void 0;
1885
+ const token = await getDeveloperToken(
1886
+ cfg,
1887
+ { configPath, open, openApprovalUrl: dependencies.openUrl },
1888
+ doFetch,
1889
+ stdout
1890
+ );
1891
+ return { platform, token, appId: cfg.app.id, env, fetch: doFetch, stdout };
1892
+ }
1893
+ async function interactiveConfirmation(message, dependencies) {
1894
+ if (dependencies.confirm) return dependencies.confirm(message);
1895
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return false;
1896
+ const prompt = (0, import_promises.createInterface)({ input: process.stdin, output: process.stdout });
1897
+ try {
1898
+ const answer = await prompt.question(`${message} [y/N] `);
1899
+ return /^y(?:es)?$/i.test(answer.trim());
1900
+ } finally {
1901
+ prompt.close();
1902
+ }
1903
+ }
1904
+ function requiredSecurityPositional(parsed, index, label) {
1905
+ const value = parsed.positionals[index];
1906
+ if (!value) throw new Error(`${label} is required`);
1907
+ return value;
1908
+ }
1909
+ function securityProfile(value) {
1910
+ if (value === void 0) return void 0;
1911
+ if (value === "odla" || value === "cloudflare-app" || value === "generic") return value;
1912
+ throw new Error("--profile must be odla, cloudflare-app, or generic");
1913
+ }
1914
+
1915
+ // src/security-command-output.ts
1916
+ function printHostedSecurityPlan(out, plan, appId) {
1917
+ out.log(`Hosted security plan for ${appId}/${plan.env}: ${plan.ready ? "ready" : "not ready"}`);
1918
+ out.log(` plan digest: ${plan.planDigest}`);
1919
+ out.log(` consent/report/redaction: ${plan.consentContract} \xB7 ${plan.reportProjection} \xB7 ${plan.redactionContract}`);
1920
+ out.log(` prompt bundle: ${plan.promptBundle}`);
1921
+ printHostedSecurityPlanRoute(out, "discovery", plan.routes.discovery);
1922
+ printHostedSecurityPlanRoute(out, "validation", plan.routes.validation);
1923
+ out.log(` independent validation: ${plan.independent ? "yes" : "no"}`);
1924
+ out.log(" source disclosure: bounded best-effort credential-pattern-redacted snippets may be sent through odla.ai to the selected providers");
1925
+ out.log(` retained report: model-derived prose and repository-relative paths for up to ${plan.reportRetentionDays} days; treat it as sensitive`);
1926
+ out.log(" target execution: disabled");
1927
+ out.log(` to approve this exact plan, run security run --source <id> --plan-digest ${plan.planDigest} --ack-redacted-source`);
1928
+ }
1929
+ function printHostedSecurityIntent(out, intent) {
1930
+ out.log(`Hosted security execution intent for ${intent.appId}/${intent.env}:`);
1931
+ out.log(` execution digest: ${intent.executionDigest}`);
1932
+ out.log(` contract: ${intent.executionContract}`);
1933
+ out.log(` source: ${intent.repository} (${intent.sourceId})`);
1934
+ out.log(` ref: ${intent.requestedRef ?? `default branch (${intent.defaultBranch})`}`);
1935
+ out.log(` profile: ${intent.profile}`);
1936
+ out.log(` disclosure: ${intent.sourceDisclosure} \xB7 plan ${intent.planDigest}`);
1937
+ }
1938
+ function assertHostedSecurityPlanReady(plan) {
1939
+ const reasons = [];
1940
+ for (const [label, route] of Object.entries(plan.routes)) {
1941
+ if (!route.enabled) reasons.push(`${label} is disabled`);
1942
+ if (!route.credentialReady) reasons.push(`${label} provider credential is unavailable`);
1943
+ }
1944
+ if (!plan.independent) reasons.push("discovery and validation are not independently routed");
1945
+ if (plan.ready && reasons.length === 0) return;
1946
+ if (!plan.ready && reasons.length === 0) reasons.push("the platform marked the plan unavailable");
1947
+ throw new Error(`hosted security is not ready${reasons.length ? `: ${reasons.join("; ")}` : ""}. Ask a platform admin to update System AI security policy or credentials`);
1948
+ }
1949
+ function printHostedJob(out, job, platform, appId) {
1950
+ out.log(`security job ${job.jobId}: ${job.status}`);
1951
+ out.log(` source: ${job.repository} ${job.requestedRef ?? "default"} -> ${job.commitSha ?? "resolving"}`);
1952
+ if (job.routes) {
1953
+ out.log(` discovery: ${routeLabel(job.routes.discovery)}`);
1954
+ out.log(` validation: ${routeLabel(job.routes.validation)}`);
1955
+ } else {
1956
+ out.log(" routes: platform System AI policy (assigned when analysis starts)");
1957
+ }
1958
+ out.log(` disclosure: ${job.sourceDisclosure} snippets \xB7 metadata retained up to ${job.retentionDays} days`);
1959
+ out.log(` consent: plan ${job.planDigest} \xB7 execution ${job.executionDigest} (${job.executionContract})`);
1960
+ if (job.coverageStatus || job.coverage) printHostedCoverage(out, job);
1961
+ if (job.counts) {
1962
+ out.log(` findings: confirmed=${job.counts.confirmed} needs_reproduction=${job.counts.needsReproduction} candidates=${job.counts.candidates}`);
1963
+ }
1964
+ if (job.errorCode) out.log(` failure: ${job.errorCode}`);
1965
+ const url = new URL("/studio", platform);
1966
+ url.searchParams.set("app", appId);
1967
+ url.searchParams.set("env", job.env);
1968
+ url.searchParams.set("tab", "security");
1969
+ url.searchParams.set("job", job.jobId);
1970
+ out.log(` Studio: ${url.toString()}`);
1971
+ }
1972
+ function printHostedReport(out, report) {
1973
+ out.log(`security report ${report.jobId}: ${report.repository}@${report.revision}`);
1974
+ out.log(` coverage: ${report.coverageStatus} cells=${report.metrics.coverageCells} shallow=${report.metrics.shallowCells} blocked=${report.metrics.blockedCells} unscheduled=${report.metrics.unscheduledCells} budget_exhausted=${report.metrics.budgetExhaustedCells}`);
1975
+ out.log(` findings: confirmed=${report.metrics.confirmed} needs_reproduction=${report.metrics.needsReproduction} candidates=${report.metrics.candidates} rejected=${report.metrics.rejected}`);
1976
+ out.log(` discovery: ${report.provenance.discovery?.provider ?? "unknown"}/${report.provenance.discovery?.model ?? "unknown"}`);
1977
+ out.log(` validation: ${report.provenance.validation?.provider ?? "unknown"}/${report.provenance.validation?.model ?? "unknown"} independent=${String(report.provenance.independentValidation)}`);
1978
+ for (const finding of report.findings) {
1979
+ const location = finding.locations[0];
1980
+ out.log(` [${finding.severity}] ${finding.title}${location ? ` (${location.path}:${location.line})` : ""} \xB7 ${finding.disposition}`);
1981
+ }
1982
+ for (const limitation of report.limitations) out.log(` limitation: ${limitation}`);
1983
+ }
1984
+ function enforceHostedReportGate(report, parsed, out, emitSuccess) {
1985
+ const failOn = hostedSeverity(stringOpt(parsed.options["fail-on"]) ?? "high", "--fail-on");
1986
+ const candidateValue = parsed.options["fail-on-candidates"];
1987
+ const failOnCandidates = candidateValue === false ? void 0 : hostedSeverity(stringOpt(candidateValue) ?? "critical", "--fail-on-candidates");
1988
+ const atOrAbove = (severity, threshold) => HOSTED_SEVERITIES.indexOf(severity) >= HOSTED_SEVERITIES.indexOf(threshold);
1989
+ const confirmed = report.findings.filter((finding) => finding.disposition === "confirmed" && atOrAbove(finding.severity, failOn));
1990
+ const leads = failOnCandidates ? report.findings.filter((finding) => finding.disposition !== "confirmed" && atOrAbove(finding.severity, failOnCandidates)) : [];
1991
+ const incomplete = report.coverageStatus !== "complete" && parsed.options["allow-incomplete"] !== true;
1992
+ if (confirmed.length || leads.length || incomplete) {
1993
+ throw new Error(`hosted security gate failed: ${confirmed.length} confirmed >= ${failOn}; ${leads.length} leads >= ${failOnCandidates ?? "disabled"}${incomplete ? `; coverage ${report.coverageStatus}` : ""}`);
1994
+ }
1995
+ if (emitSuccess) {
1996
+ out.log(`security gate passed: 0 confirmed >= ${failOn}; 0 leads >= ${failOnCandidates ?? "disabled"}; coverage ${report.coverageStatus}. This is not proof that the application is secure.`);
1997
+ }
1998
+ }
1999
+ function printHostedSecurityPlanRoute(out, label, route) {
2000
+ const readiness = route.enabled && route.credentialReady ? "ready" : [
2001
+ route.enabled ? void 0 : "disabled",
2002
+ route.credentialReady ? void 0 : "credential unavailable"
2003
+ ].filter(Boolean).join(", ");
2004
+ out.log(` ${label}: ${route.provider}/${route.model} \xB7 policy v${route.policyVersion} \xB7 ${readiness}`);
2005
+ out.log(` bounds: ${route.maxCallsPerRun} calls/run \xB7 ${route.maxInputBytes} input bytes/call \xB7 ${route.maxOutputTokens} output tokens/call`);
2006
+ }
2007
+ function printHostedCoverage(out, job) {
2008
+ const coverage = job.coverage;
2009
+ out.log(` coverage: ${job.coverageStatus ?? "pending"}${coverage?.completeCells !== void 0 ? ` ${coverage.completeCells}/${coverage.totalCells ?? "?"}` : ""}${coverage?.shallowCells ? ` shallow=${coverage.shallowCells}` : ""}${coverage?.blockedCells ? ` blocked=${coverage.blockedCells}` : ""}${coverage?.unscheduledCells ? ` unscheduled=${coverage.unscheduledCells}` : ""}${coverage?.budgetExhaustedCells ? ` budget_exhausted=${coverage.budgetExhaustedCells}` : ""}`);
2010
+ }
2011
+ function routeLabel(route) {
2012
+ return `${route.provider}/${route.model}${route.policyVersion ? ` policy v${route.policyVersion}` : ""}`;
2013
+ }
2014
+ var HOSTED_SEVERITIES = ["informational", "low", "medium", "high", "critical"];
2015
+ function hostedSeverity(value, flag) {
2016
+ if (HOSTED_SEVERITIES.includes(value)) {
2017
+ return value;
2018
+ }
2019
+ throw new Error(`${flag} must be informational, low, medium, high, or critical`);
2020
+ }
2021
+
2022
+ // src/security-run-command.ts
2023
+ var import_security2 = require("@odla-ai/security");
2024
+
1655
2025
  // src/security.ts
1656
2026
  var import_node_path6 = require("path");
1657
2027
  var import_security = require("@odla-ai/security");
@@ -1756,60 +2126,646 @@ function formatBudget(usage) {
1756
2126
  return usage ? `${usage.usedCalls}/${usage.maxCalls} skipped=${usage.skippedCalls}` : "caller-managed";
1757
2127
  }
1758
2128
 
1759
- // src/help.ts
1760
- var import_node_fs7 = require("fs");
1761
- function cliVersion() {
1762
- const pkg = JSON.parse((0, import_node_fs7.readFileSync)(new URL("../package.json", importMetaUrl), "utf8"));
1763
- return pkg.version ?? "unknown";
2129
+ // src/security-hosted-github.ts
2130
+ var import_node_child_process4 = require("child_process");
2131
+ var import_node_util = require("util");
2132
+
2133
+ // src/security-hosted-request.ts
2134
+ async function requestHostedSecurityJson(options, path, init, action) {
2135
+ const platform = platformAudience(options.platform);
2136
+ const token = hostedSecurityCredential(options.token);
2137
+ const requestInit = {
2138
+ ...init,
2139
+ redirect: "error",
2140
+ credentials: "omit",
2141
+ cache: "no-store",
2142
+ signal: options.signal,
2143
+ headers: {
2144
+ authorization: `Bearer ${token}`,
2145
+ "content-type": "application/json",
2146
+ ...init.headers
2147
+ }
2148
+ };
2149
+ const response = await (options.fetch ?? fetch)(new URL(path, platform), requestInit);
2150
+ const body = await response.json().catch(() => ({}));
2151
+ if (!response.ok) {
2152
+ const code = optionalHostedText(body.error?.code, "error code", 128);
2153
+ const message = optionalHostedText(body.error?.message, "error message", 300);
2154
+ throw new Error(`${action} failed (${response.status})${code ? ` ${code}` : ""}${message ? `: ${message}` : ""}`);
2155
+ }
2156
+ return body;
2157
+ }
2158
+ function hostedIdentifier(value, name) {
2159
+ const result = optionalHostedText(value, name, 180);
2160
+ if (!result || !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(result)) {
2161
+ throw new Error(`${name} is invalid`);
2162
+ }
2163
+ return result;
2164
+ }
2165
+ function positivePolicyVersion(value, name) {
2166
+ if (!Number.isSafeInteger(value) || value < 1) {
2167
+ throw new Error(`${name} is invalid`);
2168
+ }
2169
+ return value;
2170
+ }
2171
+ function optionalHostedText(value, name, maxLength) {
2172
+ if (value === void 0 || value === null || value === "") return void 0;
2173
+ if (typeof value !== "string" || value.length > maxLength || /[\u0000-\u001f\u007f]/.test(value)) {
2174
+ throw new Error(`${name} is invalid`);
2175
+ }
2176
+ return value;
2177
+ }
2178
+ function githubRepositoryName(value) {
2179
+ if (typeof value !== "string" || value.length > 201) {
2180
+ throw new Error("repository must be owner/name");
2181
+ }
2182
+ const parts = value.split("/");
2183
+ const owner = parts[0] ?? "";
2184
+ const name = (parts[1] ?? "").replace(/\.git$/i, "");
2185
+ if (parts.length !== 2 || !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,98}[A-Za-z0-9])?$/.test(owner) || !/^[A-Za-z0-9_.-]{1,100}$/.test(name) || name === "." || name === "..") {
2186
+ throw new Error("repository must be owner/name");
2187
+ }
2188
+ return `${owner}/${name}`;
2189
+ }
2190
+ function trustedGitHubInstallUrl(value) {
2191
+ let url;
2192
+ try {
2193
+ url = new URL(value);
2194
+ } catch {
2195
+ throw new Error("odla.ai returned an invalid GitHub installation URL");
2196
+ }
2197
+ if (url.protocol !== "https:" || url.hostname !== "github.com" || url.username || url.password) {
2198
+ throw new Error("odla.ai returned an untrusted GitHub installation URL");
2199
+ }
2200
+ return url.toString();
2201
+ }
2202
+ function hostedPollInterval(value = 2e3) {
2203
+ if (!Number.isSafeInteger(value) || value < 100 || value > 3e4) {
2204
+ throw new Error("poll interval must be 100-30000ms");
2205
+ }
2206
+ return value;
2207
+ }
2208
+ function hostedPollTimeout(value = 10 * 6e4) {
2209
+ if (!Number.isSafeInteger(value) || value < 1e3 || value > 60 * 6e4) {
2210
+ throw new Error("poll timeout must be 1000-3600000ms");
2211
+ }
2212
+ return value;
2213
+ }
2214
+ async function waitForHostedPoll(milliseconds, signal) {
2215
+ if (signal?.aborted) throw signal.reason ?? new DOMException("aborted", "AbortError");
2216
+ await new Promise((resolve7, reject) => {
2217
+ const timer = setTimeout(resolve7, milliseconds);
2218
+ signal?.addEventListener("abort", () => {
2219
+ clearTimeout(timer);
2220
+ reject(signal.reason ?? new DOMException("aborted", "AbortError"));
2221
+ }, { once: true });
2222
+ });
2223
+ }
2224
+ function isValidHostedSecurityPlan(value, env) {
2225
+ if (!value || value.env !== env || !/^sha256:[a-f0-9]{64}$/.test(value.planDigest) || value.consentContract !== "odla.hosted-security-consent.v1" || value.reportProjection !== "odla.hosted-security-report.v1" || value.redactionContract !== "odla.best-effort-credential-pattern-redaction.v1" || typeof value.promptBundle !== "string" || value.promptBundle.length < 1 || value.promptBundle.length > 100 || typeof value.ready !== "boolean" || typeof value.independent !== "boolean" || value.sourceDisclosure !== "redacted" || value.targetExecution !== false || !Number.isSafeInteger(value.reportRetentionDays) || value.reportRetentionDays < 1) return false;
2226
+ const validRoute = (route, purpose) => !!route && route.purpose === purpose && typeof route.enabled === "boolean" && typeof route.credentialReady === "boolean" && typeof route.provider === "string" && route.provider.length > 0 && route.provider.length <= 100 && typeof route.model === "string" && route.model.length > 0 && route.model.length <= 200 && Number.isSafeInteger(route.policyVersion) && route.policyVersion >= 1 && Number.isSafeInteger(route.maxCallsPerRun) && route.maxCallsPerRun >= 1 && Number.isSafeInteger(route.maxInputBytes) && route.maxInputBytes >= 1 && Number.isSafeInteger(route.maxOutputTokens) && route.maxOutputTokens >= 1;
2227
+ return validRoute(value.routes?.discovery, "security.discovery") && validRoute(value.routes?.validation, "security.validation");
2228
+ }
2229
+ function hostedSecurityCredential(value) {
2230
+ if (typeof value !== "string" || value.length < 8 || value.length > 8192 || /\s|[\u0000-\u001f\u007f]/.test(value)) {
2231
+ throw new Error("Hosted security requires an injected odla developer token");
2232
+ }
2233
+ return value;
1764
2234
  }
1765
- function printHelp() {
1766
- console.log(`odla-ai
1767
2235
 
1768
- Usage:
1769
- odla-ai setup [--dir <project>] [--agent <name>] [--global] [--force]
1770
- odla-ai init --app-id <id> --name <name> [--services db,ai,o11y] [--env dev --env prod]
1771
- odla-ai doctor [--config odla.config.mjs]
1772
- odla-ai capabilities [--json]
1773
- odla-ai admin ai show [--platform https://odla.ai] [--json]
1774
- odla-ai admin ai models [--provider <id>] [--json]
1775
- odla-ai admin ai set <purpose> [--provider <id>] [--model <id>] [--enabled|--no-enabled]
1776
- odla-ai admin ai set security --discovery-provider <id> --discovery-model <id>
1777
- --validation-provider <id> --validation-model <id> [--enabled|--no-enabled]
1778
- odla-ai admin ai credentials [--json]
1779
- odla-ai admin ai credential set <provider> (--from-env <NAME>|--stdin)
1780
- odla-ai admin ai usage [--app-id <id>] [--env <env>] [--run-id <id>] [--limit <1-500>] [--json]
1781
- odla-ai admin ai audit [--limit <1-200>] [--json]
1782
- odla-ai security run [target] --ack-redacted-source [--env dev] [--profile odla] [--fail-on high]
1783
- odla-ai security run [target] --self --ack-redacted-source
1784
- odla-ai provision [--config odla.config.mjs] [--dry-run] [--push-secrets] [--rotate-o11y-token] [--write-dev-vars[=path]] [--yes]
1785
- odla-ai smoke [--config odla.config.mjs] [--env dev]
1786
- odla-ai skill install [--dir <project>] [--agent <name>] [--global] [--force]
1787
- odla-ai secrets push --env <env> [--config odla.config.mjs] [--dry-run] [--yes]
1788
- odla-ai version
2236
+ // src/security-hosted-github.ts
2237
+ async function connectGitHubSecuritySource(options) {
2238
+ const out = options.stdout ?? console;
2239
+ const repository = githubRepositoryName(options.repository);
2240
+ const attempt = await requestHostedSecurityJson(
2241
+ options,
2242
+ "/registry/github/connect",
2243
+ {
2244
+ method: "POST",
2245
+ body: JSON.stringify({
2246
+ appId: hostedIdentifier(options.appId, "appId"),
2247
+ env: hostedIdentifier(options.env, "env"),
2248
+ repository
2249
+ })
2250
+ },
2251
+ "start GitHub connection"
2252
+ );
2253
+ const serverExpiry = Date.parse(attempt?.expiresAt ?? "");
2254
+ if (!attempt?.attemptId || !attempt.installUrl || !Number.isFinite(serverExpiry)) {
2255
+ throw new Error("odla.ai returned an invalid GitHub connection attempt");
2256
+ }
2257
+ const installUrl = trustedGitHubInstallUrl(attempt.installUrl);
2258
+ out.log(`GitHub approval: ${installUrl}`);
2259
+ if (options.open !== false) {
2260
+ await (options.openInstallUrl ?? openUrl)(installUrl);
2261
+ out.log("github: opened installation approval in your browser");
2262
+ }
2263
+ const interval = hostedPollInterval(options.pollIntervalMs);
2264
+ const now = options.now ?? Date.now;
2265
+ const deadline = Math.min(serverExpiry, now() + hostedPollTimeout(options.pollTimeoutMs));
2266
+ const wait = options.wait ?? waitForHostedPoll;
2267
+ while (true) {
2268
+ const state = await requestHostedSecurityJson(
2269
+ options,
2270
+ `/registry/github/connect/${encodeURIComponent(attempt.attemptId)}`,
2271
+ {},
2272
+ "check GitHub connection"
2273
+ );
2274
+ if (state.status !== "pending") {
2275
+ if (state.status === "connected") return state;
2276
+ throw new Error(`GitHub connection ${state.status}${state.failureCode ? `: ${state.failureCode}` : ""}`);
2277
+ }
2278
+ if (now() >= deadline) throw new Error("GitHub connection approval timed out");
2279
+ await wait(Math.min(interval, Math.max(0, deadline - now())), options.signal);
2280
+ }
2281
+ }
2282
+ async function listGitHubSecuritySources(options) {
2283
+ const appId = hostedIdentifier(options.appId, "appId");
2284
+ const env = hostedIdentifier(options.env, "env");
2285
+ const body = await requestHostedSecurityJson(
2286
+ options,
2287
+ `/registry/apps/${encodeURIComponent(appId)}/github/sources?env=${encodeURIComponent(env)}`,
2288
+ {},
2289
+ "list GitHub security sources"
2290
+ );
2291
+ return Array.isArray(body.sources) ? body.sources : [];
2292
+ }
2293
+ async function disconnectGitHubSecuritySource(options) {
2294
+ const appId = hostedIdentifier(options.appId, "appId");
2295
+ const sourceId = hostedIdentifier(options.sourceId, "sourceId");
2296
+ await requestHostedSecurityJson(
2297
+ options,
2298
+ `/registry/apps/${encodeURIComponent(appId)}/github/sources/${encodeURIComponent(sourceId)}`,
2299
+ { method: "DELETE" },
2300
+ "disconnect GitHub security source"
2301
+ );
2302
+ }
2303
+ function repositoryFromGitRemote(remoteInput) {
2304
+ const remote = remoteInput.trim();
2305
+ const scp = /^git@github\.com:([^/\s]+)\/([^/\s]+?)\/?$/.exec(remote);
2306
+ if (scp) return githubRepositoryName(`${scp[1]}/${scp[2].replace(/\.git$/, "")}`);
2307
+ let url;
2308
+ try {
2309
+ url = new URL(remote);
2310
+ } catch {
2311
+ throw new Error("origin must be a github.com HTTPS or SSH repository URL");
2312
+ }
2313
+ if (url.hostname !== "github.com" || url.protocol !== "https:" && url.protocol !== "ssh:") {
2314
+ throw new Error("origin must be a github.com HTTPS or SSH repository URL");
2315
+ }
2316
+ if (url.password || url.protocol === "https:" && url.username || url.search || url.hash) {
2317
+ throw new Error("credential-bearing GitHub origin URLs are not accepted");
2318
+ }
2319
+ const parts = url.pathname.replace(/^\/+|\/+$/g, "").split("/");
2320
+ if (parts.length !== 2) {
2321
+ throw new Error("origin must identify one GitHub owner/name repository");
2322
+ }
2323
+ return githubRepositoryName(`${parts[0]}/${parts[1].replace(/\.git$/, "")}`);
2324
+ }
2325
+ async function inferGitHubRepository(cwd = process.cwd(), readOrigin = defaultReadOrigin) {
2326
+ let remote;
2327
+ try {
2328
+ remote = await readOrigin(cwd);
2329
+ } catch {
2330
+ throw new Error("Could not read git origin; pass --repo owner/name");
2331
+ }
2332
+ return repositoryFromGitRemote(remote);
2333
+ }
2334
+ async function defaultReadOrigin(cwd) {
2335
+ const result = await (0, import_node_util.promisify)(import_node_child_process4.execFile)(
2336
+ "git",
2337
+ ["remote", "get-url", "origin"],
2338
+ { cwd, encoding: "utf8" }
2339
+ );
2340
+ return result.stdout;
2341
+ }
1789
2342
 
1790
- Commands:
1791
- setup Install offline odla runbooks for common coding-agent harnesses.
1792
- init Create a generic odla.config.mjs plus starter schema/rules files.
1793
- doctor Validate and summarize the project config without network calls.
1794
- capabilities Show what the CLI automates vs agent edits and human checkpoints.
1795
- admin Manage platform-funded AI routing/credentials/usage with narrow device grants.
1796
- security Run hosted discovery + independent validation with app/run attribution.
1797
- provision Register services, configure them, persist credentials, optionally push secrets.
1798
- smoke Verify local credentials, public-config, live schema, and db aggregate.
1799
- skill Same installer; --agent accepts all, claude, codex, cursor,
1800
- copilot, gemini, or agents (repeatable or comma-separated).
1801
- secrets Push configured db/o11y secrets into the Worker via wrangler stdin.
1802
- version Print the CLI version.
2343
+ // src/security-hosted-intent.ts
2344
+ async function getHostedSecurityIntent(options) {
2345
+ const appId = hostedIdentifier(options.appId, "appId");
2346
+ const env = hostedIdentifier(options.env, "env");
2347
+ const sourceId = hostedIdentifier(options.sourceId, "sourceId");
2348
+ const ref = optionalHostedText(options.ref, "ref", 255);
2349
+ const query = new URLSearchParams({ env, sourceId });
2350
+ if (ref) query.set("ref", ref);
2351
+ if (options.profile) query.set("profile", options.profile);
2352
+ const response = await requestHostedSecurityJson(
2353
+ options,
2354
+ `/registry/apps/${encodeURIComponent(appId)}/security/intent?${query.toString()}`,
2355
+ {},
2356
+ "read hosted security execution intent"
2357
+ );
2358
+ if (!isValidHostedSecurityPlan(response.plan, env) || !isValidIntent(response.intent, { appId, env, sourceId })) {
2359
+ throw new Error("odla.ai returned an invalid hosted security execution intent");
2360
+ }
2361
+ if (response.intent.planDigest !== response.plan.planDigest) {
2362
+ throw new Error("odla.ai returned a hosted security intent for a different processing plan");
2363
+ }
2364
+ return response;
2365
+ }
2366
+ function isValidIntent(value, expected) {
2367
+ return !!value && value.executionContract === "odla.hosted-security-execution-consent.v1" && /^sha256:[a-f0-9]{64}$/.test(value.executionDigest) && /^sha256:[a-f0-9]{64}$/.test(value.planDigest) && value.appId === expected.appId && value.env === expected.env && value.sourceId === expected.sourceId && typeof value.repository === "string" && value.repository.length > 2 && value.repository.length <= 201 && typeof value.defaultBranch === "string" && value.defaultBranch.length > 0 && value.defaultBranch.length <= 255 && typeof value.requestedRef === "string" && value.requestedRef.length > 0 && value.requestedRef.length <= 255 && !/[\u0000-\u001f\u007f]/.test(value.requestedRef) && ["odla", "cloudflare-app", "generic"].includes(value.profile) && value.sourceDisclosure === "redacted";
2368
+ }
1803
2369
 
1804
- Safety:
1805
- New projects target dev only. Add prod explicitly to odla.config.mjs and pass
1806
- --yes to provision it; use --dry-run first to inspect the resolved plan.
1807
- Provision caches the approved developer token and service credentials under
1808
- .odla/ with mode 0600, and init adds those paths to .gitignore. Secret push
1809
- preflights Wrangler before any shown-once issuance or destructive rotation.
1810
- Provision opens the approval page automatically in interactive terminals;
1811
- use --open to force browser launch or --no-open to suppress it.
1812
- `);
2370
+ // src/security-hosted-jobs.ts
2371
+ async function getHostedSecurityPlan(options) {
2372
+ const appId = hostedIdentifier(options.appId, "appId");
2373
+ const env = hostedIdentifier(options.env, "env");
2374
+ const plan = await requestHostedSecurityJson(
2375
+ options,
2376
+ `/registry/apps/${encodeURIComponent(appId)}/security/plan?env=${encodeURIComponent(env)}`,
2377
+ {},
2378
+ "read hosted security disclosure plan"
2379
+ );
2380
+ if (!isValidHostedSecurityPlan(plan, env)) {
2381
+ throw new Error("odla.ai returned an invalid hosted security disclosure plan");
2382
+ }
2383
+ return plan;
2384
+ }
2385
+ async function startHostedSecurityJob(options) {
2386
+ if (options.sourceDisclosureAck !== "redacted") {
2387
+ throw new Error("Hosted GitHub security requires sourceDisclosureAck=redacted; repository access alone is not disclosure consent");
2388
+ }
2389
+ const appId = hostedIdentifier(options.appId, "appId");
2390
+ const env = hostedIdentifier(options.env, "env");
2391
+ const sourceId = hostedIdentifier(options.sourceId, "sourceId");
2392
+ const ref = optionalHostedText(options.ref, "ref", 255);
2393
+ const expectedPlanDigest = securityPlanDigest(options.expectedPlanDigest);
2394
+ const expectedExecutionDigest = securityExecutionDigest(options.expectedExecutionDigest);
2395
+ const expectedPolicyVersions = {
2396
+ discovery: positivePolicyVersion(
2397
+ options.expectedPolicyVersions?.discovery,
2398
+ "expected discovery policy version"
2399
+ ),
2400
+ validation: positivePolicyVersion(
2401
+ options.expectedPolicyVersions?.validation,
2402
+ "expected validation policy version"
2403
+ )
2404
+ };
2405
+ let body;
2406
+ try {
2407
+ body = await requestHostedSecurityJson(
2408
+ options,
2409
+ `/registry/apps/${encodeURIComponent(appId)}/security/jobs`,
2410
+ {
2411
+ method: "POST",
2412
+ body: JSON.stringify({
2413
+ env,
2414
+ sourceId,
2415
+ ...ref ? { ref } : {},
2416
+ ...options.profile ? { profile: options.profile } : {},
2417
+ ...options.clientRequestId ? { clientRequestId: hostedIdentifier(options.clientRequestId, "clientRequestId") } : {},
2418
+ sourceDisclosure: "redacted",
2419
+ expectedPlanDigest,
2420
+ expectedExecutionDigest,
2421
+ expectedPolicyVersions
2422
+ })
2423
+ },
2424
+ "start hosted security job"
2425
+ );
2426
+ } catch (error) {
2427
+ const message = error instanceof Error ? error.message : String(error);
2428
+ if (/\b(?:plan_conflict|policy_conflict|intent_conflict|security_ai_not_ready)\b/.test(message)) {
2429
+ throw new Error("Hosted security plan or execution intent changed or became unavailable after review; fetch a fresh intent and explicitly acknowledge its digest before enqueueing again", { cause: error });
2430
+ }
2431
+ throw error;
2432
+ }
2433
+ if (!body.job?.jobId) {
2434
+ throw new Error("odla.ai returned an invalid hosted security job");
2435
+ }
2436
+ return body.job;
2437
+ }
2438
+ async function getHostedSecurityJob(options) {
2439
+ const body = await requestHostedSecurityJson(
2440
+ options,
2441
+ hostedJobPath(options.appId, options.jobId),
2442
+ {},
2443
+ "read hosted security job"
2444
+ );
2445
+ if (!body.job?.jobId) throw new Error("odla.ai returned an invalid hosted security job");
2446
+ return body.job;
2447
+ }
2448
+ async function followHostedSecurityJob(options) {
2449
+ const interval = hostedPollInterval(options.pollIntervalMs);
2450
+ const now = options.now ?? Date.now;
2451
+ const deadline = now() + hostedPollTimeout(options.pollTimeoutMs ?? 60 * 6e4);
2452
+ const wait = options.wait ?? waitForHostedPoll;
2453
+ let prior = "";
2454
+ while (true) {
2455
+ const job = await getHostedSecurityJob(options);
2456
+ const fingerprint = `${job.status}:${job.updatedAt}`;
2457
+ if (fingerprint !== prior) options.onUpdate?.(Object.freeze({ ...job }));
2458
+ prior = fingerprint;
2459
+ if (isTerminalHostedSecurityStatus(job.status)) return job;
2460
+ if (now() >= deadline) {
2461
+ throw new Error(`Hosted security job ${job.jobId} did not finish before the polling deadline`);
2462
+ }
2463
+ await wait(Math.min(interval, Math.max(0, deadline - now())), options.signal);
2464
+ }
2465
+ }
2466
+ async function getHostedSecurityReport(options) {
2467
+ return requestHostedSecurityJson(
2468
+ options,
2469
+ `${hostedJobPath(options.appId, options.jobId)}/report`,
2470
+ {},
2471
+ "read hosted security report"
2472
+ );
2473
+ }
2474
+ function isTerminalHostedSecurityStatus(status) {
2475
+ return status === "completed" || status === "failed" || status === "cancelled";
2476
+ }
2477
+ function hostedJobPath(appIdInput, jobIdInput) {
2478
+ const appId = hostedIdentifier(appIdInput, "appId");
2479
+ const jobId = hostedIdentifier(jobIdInput, "jobId");
2480
+ return `/registry/apps/${encodeURIComponent(appId)}/security/jobs/${encodeURIComponent(jobId)}`;
2481
+ }
2482
+ function securityPlanDigest(value) {
2483
+ if (!/^sha256:[a-f0-9]{64}$/.test(value)) {
2484
+ throw new Error("expected plan digest must be a sha256 digest from security plan");
2485
+ }
2486
+ return value;
2487
+ }
2488
+ function securityExecutionDigest(value) {
2489
+ if (!/^sha256:[a-f0-9]{64}$/.test(value)) {
2490
+ throw new Error("expected execution digest must be a sha256 digest from security intent");
2491
+ }
2492
+ return value;
2493
+ }
2494
+
2495
+ // src/security-run-command.ts
2496
+ async function runSourceSecurityCommand(parsed, dependencies, sourceId) {
2497
+ assertArgs(parsed, [
2498
+ "config",
2499
+ "env",
2500
+ "profile",
2501
+ "platform",
2502
+ "source",
2503
+ "ref",
2504
+ "follow",
2505
+ "open",
2506
+ "json",
2507
+ "ack-redacted-source",
2508
+ "plan-digest",
2509
+ "fail-on",
2510
+ "fail-on-candidates",
2511
+ "allow-incomplete"
2512
+ ], 2);
2513
+ const follow = parsed.options.follow !== false;
2514
+ if (!follow && (parsed.options["fail-on"] !== void 0 || parsed.options["fail-on-candidates"] !== void 0 || parsed.options["allow-incomplete"] !== void 0)) {
2515
+ throw new Error("hosted security gate options require following the job; remove --no-follow");
2516
+ }
2517
+ const acknowledgedDigest = requiredString(parsed.options["plan-digest"], "--plan-digest");
2518
+ const context = await hostedSecurityContext(parsed, dependencies);
2519
+ const plan = await getHostedSecurityPlan(context);
2520
+ if (parsed.options.json !== true) printHostedSecurityPlan(context.stdout, plan, context.appId);
2521
+ assertHostedSecurityPlanReady(plan);
2522
+ if (acknowledgedDigest !== plan.planDigest) {
2523
+ throw new Error(`--plan-digest does not match the current hosted security plan (${plan.planDigest}); review and explicitly acknowledge the current digest`);
2524
+ }
2525
+ const requestedRef = stringOpt(parsed.options.ref);
2526
+ const requestedProfile = securityProfile(stringOpt(parsed.options.profile));
2527
+ const preview = await getHostedSecurityIntent({
2528
+ ...context,
2529
+ sourceId,
2530
+ ref: requestedRef,
2531
+ profile: requestedProfile
2532
+ });
2533
+ if (parsed.options.json !== true) printHostedSecurityIntent(context.stdout, preview.intent);
2534
+ if (preview.plan.planDigest !== plan.planDigest || preview.intent.planDigest !== plan.planDigest) {
2535
+ throw new Error(`hosted security plan changed while previewing execution (${preview.plan.planDigest}); review and explicitly acknowledge the current plan digest`);
2536
+ }
2537
+ const job = await startHostedSecurityJob({
2538
+ ...context,
2539
+ sourceId,
2540
+ ref: requestedRef,
2541
+ profile: requestedProfile,
2542
+ clientRequestId: crypto.randomUUID(),
2543
+ sourceDisclosureAck: parsed.options["ack-redacted-source"] === true ? "redacted" : void 0,
2544
+ expectedPlanDigest: plan.planDigest,
2545
+ expectedExecutionDigest: preview.intent.executionDigest,
2546
+ expectedPolicyVersions: {
2547
+ discovery: plan.routes.discovery.policyVersion,
2548
+ validation: plan.routes.validation.policyVersion
2549
+ }
2550
+ });
2551
+ const result = follow ? await followHostedSecurityJob({
2552
+ ...context,
2553
+ jobId: job.jobId,
2554
+ wait: dependencies.pollWait,
2555
+ onUpdate: parsed.options.json === true ? void 0 : (value) => printHostedJob(context.stdout, value, context.platform, context.appId)
2556
+ }) : job;
2557
+ if (!follow) {
2558
+ if (parsed.options.json === true) {
2559
+ context.stdout.log(JSON.stringify({ plan, intent: preview.intent, job: result }, null, 2));
2560
+ } else {
2561
+ printHostedJob(context.stdout, result, context.platform, context.appId);
2562
+ }
2563
+ return;
2564
+ }
2565
+ if (result.status !== "completed") {
2566
+ if (parsed.options.json === true) {
2567
+ context.stdout.log(JSON.stringify({ plan, intent: preview.intent, job: result }, null, 2));
2568
+ }
2569
+ throw new Error(`hosted security job ${result.jobId} ended ${result.status}${result.errorCode ? `: ${result.errorCode}` : ""}`);
2570
+ }
2571
+ const report = await getHostedSecurityReport({ ...context, jobId: result.jobId });
2572
+ if (parsed.options.json === true) {
2573
+ context.stdout.log(JSON.stringify({ plan, intent: preview.intent, job: result, report }, null, 2));
2574
+ } else {
2575
+ printHostedReport(context.stdout, report);
2576
+ }
2577
+ enforceHostedReportGate(report, parsed, context.stdout, parsed.options.json !== true);
2578
+ }
2579
+ async function runLocalSecurityCommand(parsed, dependencies) {
2580
+ if (parsed.options.source === true) {
2581
+ throw new Error("--source requires a source id; run security sources first");
2582
+ }
2583
+ assertArgs(parsed, [
2584
+ "config",
2585
+ "env",
2586
+ "out",
2587
+ "profile",
2588
+ "max-hunt-tasks",
2589
+ "run-id",
2590
+ "platform",
2591
+ "self",
2592
+ "ack-redacted-source",
2593
+ "open",
2594
+ "fail-on",
2595
+ "fail-on-candidates",
2596
+ "allow-incomplete"
2597
+ ], 3);
2598
+ const configPath = stringOpt(parsed.options.config) ?? "odla.config.mjs";
2599
+ const selfAudit = parsed.options.self === true;
2600
+ const open = parsed.options.open === false ? false : parsed.options.open === true ? true : void 0;
2601
+ const platform = stringOpt(parsed.options.platform);
2602
+ const doFetch = dependencies.fetch ?? fetch;
2603
+ const out = dependencies.stdout ?? console;
2604
+ const result = await runHostedSecurity({
2605
+ configPath,
2606
+ selfAudit,
2607
+ target: parsed.positionals[2],
2608
+ out: stringOpt(parsed.options.out),
2609
+ env: stringOpt(parsed.options.env),
2610
+ profile: securityProfile(stringOpt(parsed.options.profile)),
2611
+ maxHuntTasks: numberOpt(parsed.options["max-hunt-tasks"], "--max-hunt-tasks"),
2612
+ runId: stringOpt(parsed.options["run-id"]),
2613
+ platform,
2614
+ sourceDisclosureAck: parsed.options["ack-redacted-source"] === true ? "redacted" : void 0,
2615
+ fetch: doFetch,
2616
+ stdout: out,
2617
+ getToken: async (request) => {
2618
+ if (request.scope === "platform:security:self") {
2619
+ return getScopedPlatformToken({
2620
+ platform: request.platform,
2621
+ scope: request.scope,
2622
+ open,
2623
+ fetch: doFetch,
2624
+ stdout: out,
2625
+ openApprovalUrl: dependencies.openUrl
2626
+ });
2627
+ }
2628
+ const cfg = await loadProjectConfig(configPath);
2629
+ if (platformAudience(cfg.platformUrl) !== platformAudience(request.platform)) {
2630
+ throw new Error("--platform cannot reuse a project developer token from another platform; update odla.config.mjs and authenticate there");
2631
+ }
2632
+ return getDeveloperToken(
2633
+ cfg,
2634
+ { configPath, open, openApprovalUrl: dependencies.openUrl },
2635
+ doFetch,
2636
+ out
2637
+ );
2638
+ }
2639
+ });
2640
+ enforceLocalGate(result.report, parsed);
2641
+ }
2642
+ function enforceLocalGate(report, parsed) {
2643
+ const failOn = severityOpt(stringOpt(parsed.options["fail-on"]) ?? "high", "--fail-on");
2644
+ const candidateValue = parsed.options["fail-on-candidates"];
2645
+ const failOnCandidates = candidateValue === false ? void 0 : severityOpt(stringOpt(candidateValue) ?? "critical", "--fail-on-candidates");
2646
+ const confirmed = (0, import_security2.findingsAtOrAbove)(report, failOn);
2647
+ const leads = failOnCandidates ? (0, import_security2.findingsAtOrAbove)(report, failOnCandidates, true).filter((finding) => finding.disposition !== "confirmed") : [];
2648
+ const incomplete = report.coverageStatus === "incomplete" && parsed.options["allow-incomplete"] !== true;
2649
+ if (confirmed.length || leads.length || incomplete) {
2650
+ throw new Error(`hosted security gate failed: ${confirmed.length} confirmed >= ${failOn}; ${leads.length} leads >= ${failOnCandidates ?? "disabled"}${incomplete ? "; coverage incomplete" : ""}`);
2651
+ }
2652
+ }
2653
+ function severityOpt(value, flag) {
2654
+ if (["informational", "low", "medium", "high", "critical"].includes(value)) {
2655
+ return value;
2656
+ }
2657
+ throw new Error(`${flag} must be informational, low, medium, high, or critical`);
2658
+ }
2659
+
2660
+ // src/security-command.ts
2661
+ async function securityCommand(parsed, dependencies) {
2662
+ const sub = parsed.positionals[1];
2663
+ if (sub === "github") {
2664
+ await githubSecurityCommand(parsed, dependencies);
2665
+ return;
2666
+ }
2667
+ if (sub === "plan") {
2668
+ assertArgs(parsed, ["config", "env", "platform", "open", "json"], 2);
2669
+ const context = await hostedSecurityContext(parsed, dependencies);
2670
+ const plan = await getHostedSecurityPlan(context);
2671
+ if (parsed.options.json === true) context.stdout.log(JSON.stringify(plan, null, 2));
2672
+ else printHostedSecurityPlan(context.stdout, plan, context.appId);
2673
+ return;
2674
+ }
2675
+ if (sub === "sources") {
2676
+ await listSecuritySources(parsed, dependencies);
2677
+ return;
2678
+ }
2679
+ if (sub === "status") {
2680
+ await securityStatus(parsed, dependencies);
2681
+ return;
2682
+ }
2683
+ if (sub === "report") {
2684
+ assertArgs(parsed, ["config", "env", "platform", "open", "json"], 3);
2685
+ const jobId = requiredSecurityPositional(parsed, 2, "job id");
2686
+ const context = await hostedSecurityContext(parsed, dependencies);
2687
+ const report = await getHostedSecurityReport({ ...context, jobId });
2688
+ if (parsed.options.json === true) context.stdout.log(JSON.stringify(report, null, 2));
2689
+ else printHostedReport(context.stdout, report);
2690
+ return;
2691
+ }
2692
+ if (sub !== "run") {
2693
+ throw new Error('unknown security command. Try "odla-ai security plan", "security sources", or "security run".');
2694
+ }
2695
+ const sourceId = stringOpt(parsed.options.source);
2696
+ if (sourceId) await runSourceSecurityCommand(parsed, dependencies, sourceId);
2697
+ else await runLocalSecurityCommand(parsed, dependencies);
2698
+ }
2699
+ async function githubSecurityCommand(parsed, dependencies) {
2700
+ const action = parsed.positionals[2];
2701
+ if (action === "disconnect") {
2702
+ assertArgs(parsed, ["config", "env", "platform", "source", "open", "yes"], 3);
2703
+ const context2 = await hostedSecurityContext(parsed, dependencies);
2704
+ const sourceId = requiredString(parsed.options.source, "--source");
2705
+ const confirmed = parsed.options.yes === true || await interactiveConfirmation(
2706
+ `Disconnect GitHub security source ${sourceId} from ${context2.appId}/${context2.env}?`,
2707
+ dependencies
2708
+ );
2709
+ if (!confirmed) {
2710
+ throw new Error("GitHub source disconnect cancelled; pass --yes in a non-interactive shell");
2711
+ }
2712
+ await disconnectGitHubSecuritySource({ ...context2, sourceId });
2713
+ context2.stdout.log(`github: disconnected ${sourceId} from ${context2.appId}/${context2.env}`);
2714
+ return;
2715
+ }
2716
+ if (action !== "connect") {
2717
+ throw new Error('unknown security github command. Try "odla-ai security github connect".');
2718
+ }
2719
+ assertArgs(parsed, ["config", "env", "platform", "repo", "open"], 3);
2720
+ const context = await hostedSecurityContext(parsed, dependencies);
2721
+ const repository = stringOpt(parsed.options.repo) ?? await inferGitHubRepository(process.cwd(), dependencies.readGitOrigin);
2722
+ const connection = await connectGitHubSecuritySource({
2723
+ ...context,
2724
+ repository,
2725
+ open: parsed.options.open !== false,
2726
+ openInstallUrl: dependencies.openUrl ?? openUrl,
2727
+ wait: dependencies.pollWait,
2728
+ stdout: context.stdout
2729
+ });
2730
+ context.stdout.log(`github: connected ${connection.repository ?? repository} (${connection.sourceId ?? "source pending"})`);
2731
+ context.stdout.log("github: odla.ai stores the installation; no PAT or GitHub token is written locally");
2732
+ }
2733
+ async function listSecuritySources(parsed, dependencies) {
2734
+ assertArgs(parsed, ["config", "env", "platform", "open", "json"], 2);
2735
+ const context = await hostedSecurityContext(parsed, dependencies);
2736
+ const [plan, sources] = await Promise.all([
2737
+ getHostedSecurityPlan(context),
2738
+ listGitHubSecuritySources(context)
2739
+ ]);
2740
+ if (parsed.options.json === true) {
2741
+ context.stdout.log(JSON.stringify({ plan, sources }, null, 2));
2742
+ return;
2743
+ }
2744
+ printHostedSecurityPlan(context.stdout, plan, context.appId);
2745
+ if (!sources.length) {
2746
+ context.stdout.log(`No GitHub security sources connected for ${context.appId}/${context.env}.`);
2747
+ return;
2748
+ }
2749
+ context.stdout.log(`GitHub security sources for ${context.appId}/${context.env}
2750
+ source repository default ref status`);
2751
+ for (const source of sources) {
2752
+ context.stdout.log(`${source.sourceId} ${source.repository} ${source.defaultBranch} ${source.status}`);
2753
+ }
2754
+ }
2755
+ async function securityStatus(parsed, dependencies) {
2756
+ assertArgs(parsed, ["config", "env", "platform", "open", "json", "follow"], 3);
2757
+ const jobId = requiredSecurityPositional(parsed, 2, "job id");
2758
+ const context = await hostedSecurityContext(parsed, dependencies);
2759
+ const job = parsed.options.follow === true ? await followHostedSecurityJob({
2760
+ ...context,
2761
+ jobId,
2762
+ wait: dependencies.pollWait,
2763
+ onUpdate: parsed.options.json === true ? void 0 : (value) => printHostedJob(context.stdout, value, context.platform, context.appId)
2764
+ }) : await getHostedSecurityJob({ ...context, jobId });
2765
+ if (parsed.options.json === true) context.stdout.log(JSON.stringify(job, null, 2));
2766
+ else if (parsed.options.follow !== true) {
2767
+ printHostedJob(context.stdout, job, context.platform, context.appId);
2768
+ }
1813
2769
  }
1814
2770
 
1815
2771
  // src/skill.ts
@@ -2147,7 +3103,7 @@ async function safeText3(res) {
2147
3103
  }
2148
3104
 
2149
3105
  // src/cli.ts
2150
- async function runCli(argv = process.argv.slice(2)) {
3106
+ async function runCli(argv = process.argv.slice(2), dependencies = {}) {
2151
3107
  const parsed = parseArgv(argv);
2152
3108
  const command = parsed.positionals[0] ?? "help";
2153
3109
  if (command === "version" || command === "-v" || parsed.options.version === true) {
@@ -2161,7 +3117,15 @@ async function runCli(argv = process.argv.slice(2)) {
2161
3117
  return;
2162
3118
  }
2163
3119
  if (command === "init") {
2164
- assertArgs(parsed, ["app-id", "name", "config", "env", "services", "ai-provider", "force"], 1);
3120
+ assertArgs(parsed, [
3121
+ "app-id",
3122
+ "name",
3123
+ "config",
3124
+ "env",
3125
+ "services",
3126
+ "ai-provider",
3127
+ "force"
3128
+ ], 1);
2165
3129
  initProject({
2166
3130
  appId: requiredString(parsed.options["app-id"], "--app-id"),
2167
3131
  name: requiredString(parsed.options.name, "--name"),
@@ -2184,149 +3148,15 @@ async function runCli(argv = process.argv.slice(2)) {
2184
3148
  return;
2185
3149
  }
2186
3150
  if (command === "admin") {
2187
- const area = parsed.positionals[1];
2188
- const action = parsed.positionals[2];
2189
- const credentialSet = action === "credential" && parsed.positionals[3] === "set";
2190
- const credentials = action === "credentials";
2191
- const models = action === "models";
2192
- const usage = action === "usage";
2193
- const audit = action === "audit";
2194
- if (area !== "ai" || action !== "show" && action !== "set" && !credentialSet && !credentials && !models && !usage && !audit) {
2195
- throw new Error('unknown admin command. Try "odla-ai admin ai show".');
2196
- }
2197
- assertArgs(parsed, [
2198
- "platform",
2199
- "json",
2200
- "open",
2201
- "provider",
2202
- "model",
2203
- "enabled",
2204
- "max-input-bytes",
2205
- "max-output-tokens",
2206
- "max-calls-per-run",
2207
- "from-env",
2208
- "stdin",
2209
- "discovery-provider",
2210
- "discovery-model",
2211
- "validation-provider",
2212
- "validation-model",
2213
- "app-id",
2214
- "env",
2215
- "run-id",
2216
- "limit"
2217
- ], credentialSet ? 5 : action === "set" ? 4 : 3);
2218
- await adminAi({
2219
- action: credentialSet ? "credential-set" : credentials ? "credentials" : models ? "models" : usage ? "usage" : audit ? "audit" : action,
2220
- purpose: action === "set" ? parsed.positionals[3] : void 0,
2221
- provider: stringOpt(parsed.options.provider),
2222
- model: stringOpt(parsed.options.model),
2223
- enabled: boolOpt(parsed.options.enabled),
2224
- maxInputBytes: numberOpt(parsed.options["max-input-bytes"], "--max-input-bytes"),
2225
- maxOutputTokens: numberOpt(parsed.options["max-output-tokens"], "--max-output-tokens"),
2226
- maxCallsPerRun: numberOpt(parsed.options["max-calls-per-run"], "--max-calls-per-run"),
2227
- platform: stringOpt(parsed.options.platform),
2228
- json: parsed.options.json === true,
2229
- open: parsed.options.open === false ? false : parsed.options.open === true ? true : void 0,
2230
- credentialProvider: credentialSet ? parsed.positionals[4] : void 0,
2231
- fromEnv: stringOpt(parsed.options["from-env"]),
2232
- stdin: parsed.options.stdin === true,
2233
- discoveryProvider: stringOpt(parsed.options["discovery-provider"]),
2234
- discoveryModel: stringOpt(parsed.options["discovery-model"]),
2235
- validationProvider: stringOpt(parsed.options["validation-provider"]),
2236
- validationModel: stringOpt(parsed.options["validation-model"]),
2237
- appId: stringOpt(parsed.options["app-id"]),
2238
- env: stringOpt(parsed.options.env),
2239
- runId: stringOpt(parsed.options["run-id"]),
2240
- limit: numberOpt(parsed.options.limit, "--limit")
2241
- });
3151
+ await adminCommand(parsed);
2242
3152
  return;
2243
3153
  }
2244
3154
  if (command === "security") {
2245
- const sub = parsed.positionals[1];
2246
- if (sub !== "run") throw new Error('unknown security command. Try "odla-ai security run".');
2247
- assertArgs(parsed, [
2248
- "config",
2249
- "env",
2250
- "out",
2251
- "profile",
2252
- "max-hunt-tasks",
2253
- "run-id",
2254
- "platform",
2255
- "self",
2256
- "ack-redacted-source",
2257
- "open",
2258
- "fail-on",
2259
- "fail-on-candidates",
2260
- "allow-incomplete"
2261
- ], 3);
2262
- const configPath = stringOpt(parsed.options.config) ?? "odla.config.mjs";
2263
- const selfAudit = parsed.options.self === true;
2264
- const open = parsed.options.open === false ? false : parsed.options.open === true ? true : void 0;
2265
- const platform = stringOpt(parsed.options.platform);
2266
- const result = await runHostedSecurity({
2267
- configPath,
2268
- selfAudit,
2269
- target: parsed.positionals[2],
2270
- out: stringOpt(parsed.options.out),
2271
- env: stringOpt(parsed.options.env),
2272
- profile: securityProfile(stringOpt(parsed.options.profile)),
2273
- maxHuntTasks: numberOpt(parsed.options["max-hunt-tasks"], "--max-hunt-tasks"),
2274
- runId: stringOpt(parsed.options["run-id"]),
2275
- platform,
2276
- sourceDisclosureAck: parsed.options["ack-redacted-source"] === true ? "redacted" : void 0,
2277
- getToken: async (request) => {
2278
- if (request.scope === "platform:security:self") {
2279
- return getScopedPlatformToken({ platform: request.platform, scope: request.scope, open });
2280
- }
2281
- const cfg = await loadProjectConfig(configPath);
2282
- if (platformAudience(cfg.platformUrl) !== platformAudience(request.platform)) {
2283
- throw new Error("--platform cannot reuse a project developer token from another platform; update odla.config.mjs and authenticate there");
2284
- }
2285
- return getDeveloperToken(cfg, { configPath, open }, fetch, console);
2286
- }
2287
- });
2288
- const failOn = severityOpt(stringOpt(parsed.options["fail-on"]) ?? "high", "--fail-on");
2289
- const candidateValue = parsed.options["fail-on-candidates"];
2290
- const failOnCandidates = candidateValue === false ? void 0 : severityOpt(stringOpt(candidateValue) ?? "critical", "--fail-on-candidates");
2291
- const confirmed = (0, import_security2.findingsAtOrAbove)(result.report, failOn);
2292
- const leads = failOnCandidates ? (0, import_security2.findingsAtOrAbove)(result.report, failOnCandidates, true).filter((finding) => finding.disposition !== "confirmed") : [];
2293
- const incomplete = result.report.coverageStatus === "incomplete" && parsed.options["allow-incomplete"] !== true;
2294
- if (confirmed.length || leads.length || incomplete) {
2295
- throw new Error(`hosted security gate failed: ${confirmed.length} confirmed >= ${failOn}; ${leads.length} leads >= ${failOnCandidates ?? "disabled"}${incomplete ? "; coverage incomplete" : ""}`);
2296
- }
3155
+ await securityCommand(parsed, dependencies);
2297
3156
  return;
2298
3157
  }
2299
3158
  if (command === "provision") {
2300
- assertArgs(
2301
- parsed,
2302
- [
2303
- "config",
2304
- "dry-run",
2305
- "rotate-keys",
2306
- "rotate-o11y-token",
2307
- "push-secrets",
2308
- "write-credentials",
2309
- "write-dev-vars",
2310
- "token",
2311
- "open",
2312
- "yes"
2313
- ],
2314
- 1
2315
- );
2316
- const writeDevVars2 = parsed.options["write-dev-vars"];
2317
- const opts = {
2318
- configPath: stringOpt(parsed.options.config) ?? "odla.config.mjs",
2319
- dryRun: parsed.options["dry-run"] === true,
2320
- rotateKeys: parsed.options["rotate-keys"] === true,
2321
- rotateO11yToken: parsed.options["rotate-o11y-token"] === true,
2322
- pushSecrets: parsed.options["push-secrets"] === true,
2323
- writeCredentials: parsed.options["write-credentials"] !== false,
2324
- writeDevVars: typeof writeDevVars2 === "string" ? writeDevVars2 : writeDevVars2 === true,
2325
- token: stringOpt(parsed.options.token),
2326
- open: parsed.options.open === false ? false : parsed.options.open === true ? true : void 0,
2327
- yes: parsed.options.yes === true
2328
- };
2329
- await provision(opts);
3159
+ await provisionCommand(parsed);
2330
3160
  return;
2331
3161
  }
2332
3162
  if (command === "smoke") {
@@ -2352,7 +3182,9 @@ async function runCli(argv = process.argv.slice(2)) {
2352
3182
  }
2353
3183
  if (command === "skill") {
2354
3184
  const sub = parsed.positionals[1];
2355
- if (sub !== "install") throw new Error(`unknown skill subcommand "${sub ?? ""}". Try "odla-ai skill install".`);
3185
+ if (sub !== "install") {
3186
+ throw new Error(`unknown skill subcommand "${sub ?? ""}". Try "odla-ai skill install".`);
3187
+ }
2356
3188
  assertArgs(parsed, ["dir", "global", "force", "agent", "harness"], 2);
2357
3189
  installSkill({
2358
3190
  dir: stringOpt(parsed.options.dir),
@@ -2364,7 +3196,27 @@ async function runCli(argv = process.argv.slice(2)) {
2364
3196
  }
2365
3197
  if (command === "secrets") {
2366
3198
  const sub = parsed.positionals[1];
2367
- if (sub !== "push") throw new Error(`unknown secrets subcommand "${sub ?? ""}". Try "odla-ai secrets push --env dev".`);
3199
+ if (sub === "set" || sub === "set-clerk-key") {
3200
+ assertArgs(parsed, ["config", "env", "from-env", "stdin", "token", "yes"], sub === "set" ? 3 : 2);
3201
+ const options = {
3202
+ configPath: stringOpt(parsed.options.config) ?? "odla.config.mjs",
3203
+ name: parsed.positionals[2],
3204
+ env: requiredString(parsed.options.env, "--env"),
3205
+ fromEnv: stringOpt(parsed.options["from-env"]),
3206
+ stdin: parsed.options.stdin === true,
3207
+ token: stringOpt(parsed.options.token),
3208
+ yes: parsed.options.yes === true,
3209
+ fetch: dependencies.fetch,
3210
+ stdout: dependencies.stdout
3211
+ };
3212
+ await (sub === "set" ? secretsSet(options) : secretsSetClerkKey(options));
3213
+ return;
3214
+ }
3215
+ if (sub !== "push") {
3216
+ throw new Error(
3217
+ `unknown secrets subcommand "${sub ?? ""}". Try "odla-ai secrets push --env dev", "odla-ai secrets set <name> --env dev --stdin", or "odla-ai secrets set-clerk-key --env dev --stdin".`
3218
+ );
3219
+ }
2368
3220
  assertArgs(parsed, ["config", "env", "dry-run", "yes"], 2);
2369
3221
  await secretsPush({
2370
3222
  configPath: stringOpt(parsed.options.config) ?? "odla.config.mjs",
@@ -2376,29 +3228,33 @@ async function runCli(argv = process.argv.slice(2)) {
2376
3228
  }
2377
3229
  throw new Error(`unknown command "${command}". Run "odla-ai help".`);
2378
3230
  }
2379
- function securityProfile(value) {
2380
- if (value === void 0) return void 0;
2381
- if (value === "odla" || value === "cloudflare-app" || value === "generic") return value;
2382
- throw new Error("--profile must be odla, cloudflare-app, or generic");
2383
- }
2384
- function severityOpt(value, flag) {
2385
- if (["informational", "low", "medium", "high", "critical"].includes(value)) return value;
2386
- throw new Error(`${flag} must be informational, low, medium, high, or critical`);
2387
- }
2388
- function harnessList(parsed) {
2389
- const selected = [
2390
- ...harnessOption(parsed.options.agent, "--agent"),
2391
- ...harnessOption(parsed.options.harness, "--harness")
2392
- ];
2393
- return selected.length ? selected : ["all"];
2394
- }
2395
- function harnessOption(value, flag) {
2396
- if (value === void 0) return [];
2397
- if (typeof value === "boolean") throw new Error(`${flag} requires a harness name`);
2398
- const raw = Array.isArray(value) ? value : [value];
2399
- const parts = raw.flatMap((item) => item.split(","));
2400
- if (parts.some((item) => !item.trim())) throw new Error(`${flag} requires a harness name`);
2401
- return parts.map((item) => item.trim());
3231
+ async function provisionCommand(parsed) {
3232
+ assertArgs(parsed, [
3233
+ "config",
3234
+ "dry-run",
3235
+ "rotate-keys",
3236
+ "rotate-o11y-token",
3237
+ "push-secrets",
3238
+ "write-credentials",
3239
+ "write-dev-vars",
3240
+ "token",
3241
+ "open",
3242
+ "yes"
3243
+ ], 1);
3244
+ const writeDevVars2 = parsed.options["write-dev-vars"];
3245
+ const options = {
3246
+ configPath: stringOpt(parsed.options.config) ?? "odla.config.mjs",
3247
+ dryRun: parsed.options["dry-run"] === true,
3248
+ rotateKeys: parsed.options["rotate-keys"] === true,
3249
+ rotateO11yToken: parsed.options["rotate-o11y-token"] === true,
3250
+ pushSecrets: parsed.options["push-secrets"] === true,
3251
+ writeCredentials: parsed.options["write-credentials"] !== false,
3252
+ writeDevVars: typeof writeDevVars2 === "string" ? writeDevVars2 : writeDevVars2 === true,
3253
+ token: stringOpt(parsed.options.token),
3254
+ open: parsed.options.open === false ? false : parsed.options.open === true ? true : void 0,
3255
+ yes: parsed.options.yes === true
3256
+ };
3257
+ await provision(options);
2402
3258
  }
2403
3259
 
2404
3260
  // src/bin.ts