@dench.com/cli 3.12.29 → 3.12.31-staging.1469

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/cron.ts CHANGED
@@ -54,6 +54,7 @@ import {
54
54
  CliArgError,
55
55
  getFlag,
56
56
  hasFlag,
57
+ parsePositiveInt,
57
58
  shift as shiftRaw,
58
59
  } from "./lib/cli-args";
59
60
 
@@ -857,10 +858,66 @@ async function runEnable(ctx: CronCliContext, enabled: boolean): Promise<void> {
857
858
  out(ctx, result);
858
859
  }
859
860
 
861
+ const NON_TERMINAL_CRON_RUN_STATUSES = new Set([
862
+ "queued",
863
+ "starting",
864
+ "running",
865
+ "pending",
866
+ "waiting_approval",
867
+ "waiting_message",
868
+ "waiting_child",
869
+ ]);
870
+
871
+ export function isTerminalCronRunStatus(
872
+ status: string | undefined,
873
+ ): status is string {
874
+ return Boolean(status && !NON_TERMINAL_CRON_RUN_STATUSES.has(status));
875
+ }
876
+
877
+ export type CronRunEntry = {
878
+ runId?: string;
879
+ sessionId?: string;
880
+ threadId?: string;
881
+ ts: number;
882
+ runAtMs?: number;
883
+ status?: string;
884
+ summary?: string;
885
+ error?: string;
886
+ };
887
+
888
+ export function findMatchingCronRun(
889
+ entries: readonly CronRunEntry[],
890
+ fired: { runId?: string; threadId?: string | null },
891
+ firedAt: number,
892
+ ): CronRunEntry | undefined {
893
+ if (fired.runId) {
894
+ const byRunId = entries.find((entry) => entry.runId === fired.runId);
895
+ if (byRunId) return byRunId;
896
+ }
897
+ if (fired.threadId) {
898
+ const byThreadId = entries.find(
899
+ (entry) =>
900
+ entry.sessionId === fired.threadId || entry.threadId === fired.threadId,
901
+ );
902
+ if (byThreadId) return byThreadId;
903
+ }
904
+ return entries.find((entry) => {
905
+ if (fired.runId && entry.runId && entry.runId !== fired.runId) {
906
+ return false;
907
+ }
908
+ const entryThreadId = entry.sessionId ?? entry.threadId;
909
+ if (fired.threadId && entryThreadId && entryThreadId !== fired.threadId) {
910
+ return false;
911
+ }
912
+ return entry.ts >= firedAt;
913
+ });
914
+ }
915
+
860
916
  async function runRunNow(ctx: CronCliContext): Promise<void> {
861
917
  const jobId = shift(ctx.args, "job id");
862
918
  const wait = hasFlag(ctx.args, "--wait");
863
919
  const url = `${getApiBase(ctx)}/api/cron/jobs/${encodeURIComponent(jobId)}/run-now`;
920
+ const firedAt = Date.now();
864
921
  const fired = (await postJson(
865
922
  url,
866
923
  apiKeyHeaders(ctx.sessionToken ?? ""),
@@ -881,9 +938,9 @@ async function runRunNow(ctx: CronCliContext): Promise<void> {
881
938
  const runs = (await callQuery(ctx, listCronRunsRef, {
882
939
  jobId,
883
940
  limit: 5,
884
- })) as { entries: Array<{ ts: number; status?: string }> };
885
- const matching = runs.entries.find(() => true);
886
- if (matching && matching.status) {
941
+ })) as { entries: CronRunEntry[] };
942
+ const matching = findMatchingCronRun(runs.entries, fired, firedAt);
943
+ if (matching && isTerminalCronRunStatus(matching.status)) {
887
944
  out(ctx, {
888
945
  ...fired,
889
946
  finalStatus: matching.status,
@@ -898,8 +955,7 @@ async function runRunNow(ctx: CronCliContext): Promise<void> {
898
955
 
899
956
  async function runRuns(ctx: CronCliContext): Promise<void> {
900
957
  const jobId = shift(ctx.args, "job id");
901
- const limitRaw = getFlag(ctx.args, "--limit");
902
- const limit = limitRaw ? parseInt(limitRaw, 10) : 50;
958
+ const limit = parsePositiveInt(getFlag(ctx.args, "--limit"), "--limit") ?? 50;
903
959
  const status = getFlag(ctx.args, "--status");
904
960
  const result = (await callQuery(ctx, listCronRunsRef, { jobId, limit })) as {
905
961
  entries: Array<Record<string, unknown>>;
@@ -913,8 +969,7 @@ async function runRuns(ctx: CronCliContext): Promise<void> {
913
969
  }
914
970
 
915
971
  async function runHistory(ctx: CronCliContext): Promise<void> {
916
- const limitRaw = getFlag(ctx.args, "--limit");
917
- const limit = limitRaw ? parseInt(limitRaw, 10) : 50;
972
+ const limit = parsePositiveInt(getFlag(ctx.args, "--limit"), "--limit") ?? 50;
918
973
  const status = getFlag(ctx.args, "--status");
919
974
  const result = (await callQuery(ctx, listOrgCronRunHistoryRef, {
920
975
  limit,
package/dench.ts CHANGED
@@ -16,6 +16,7 @@ import { fileURLToPath } from "node:url";
16
16
  import { ConvexHttpClient } from "convex/browser";
17
17
  import { makeFunctionReference } from "convex/server";
18
18
  import { agentKindLabel, normalizeAgentKind } from "./agentKind";
19
+ import { decodeInlineTextOrUndefined } from "./fs-daemon-binary";
19
20
  import {
20
21
  apiHostForDenchHost,
21
22
  isLocalHost,
@@ -3492,7 +3493,7 @@ async function uploadConvexFileBytes(
3492
3493
  const hash = sha256HexSync(args.bytes);
3493
3494
  const inlineEligible = args.bytes.byteLength <= 100_000;
3494
3495
  const inlineText = inlineEligible
3495
- ? new TextDecoder("utf-8", { fatal: false }).decode(args.bytes)
3496
+ ? decodeInlineTextOrUndefined(args.bytes, args.path)
3496
3497
  : undefined;
3497
3498
  await runtime.client.mutation(api.functions.files.commitFileUpload, {
3498
3499
  path: args.path,
@@ -4682,9 +4683,22 @@ async function main() {
4682
4683
  return;
4683
4684
  }
4684
4685
 
4686
+ const firstSubcommandToken = (
4687
+ tokens: readonly string[],
4688
+ ): string | undefined => tokens.find((token) => !token.startsWith("-"));
4689
+
4690
+ const removeFirstSubcommandToken = (
4691
+ tokens: readonly string[],
4692
+ token: string,
4693
+ ): string[] => {
4694
+ const idx = tokens.indexOf(token);
4695
+ if (idx === -1) return [...tokens];
4696
+ return [...tokens.slice(0, idx), ...tokens.slice(idx + 1)];
4697
+ };
4698
+
4685
4699
  if (command === "crm") {
4686
4700
  const subArgs = stripRuntimeFlags(args.slice(args.indexOf("crm") + 1));
4687
- const sub = subArgs[0];
4701
+ const sub = firstSubcommandToken(subArgs);
4688
4702
  const { runCrmCommand, isCrmReadHelpRequest } = await import("./crm");
4689
4703
  // Short-circuit help so users don't need a session to read the
4690
4704
  // surface. The crm dispatcher's own help resolves --json + the
@@ -4709,7 +4723,7 @@ async function main() {
4709
4723
  // bearer prefix and resolves the org for both.
4710
4724
  if (runtime.mode === "dev") {
4711
4725
  const gatewayAuth =
4712
- subArgs[0] === "enrich"
4726
+ sub === "enrich"
4713
4727
  ? await resolveGatewayCommandAuth(runtime, "dench crm enrich")
4714
4728
  : undefined;
4715
4729
  await runCrmCommand({
@@ -4729,7 +4743,7 @@ async function main() {
4729
4743
  }
4730
4744
  const authedRuntime = requireAuthenticatedRuntime(runtime, "dench crm");
4731
4745
  const gatewayAuth =
4732
- subArgs[0] === "enrich"
4746
+ sub === "enrich"
4733
4747
  ? await resolveGatewayCommandAuth(authedRuntime, "dench crm enrich")
4734
4748
  : undefined;
4735
4749
  await runCrmCommand({
@@ -4756,7 +4770,7 @@ async function main() {
4756
4770
  // verbs cannot reach (transcript, action items, attendance) and the
4757
4771
  // composite `import`. Same org-scoped auth shape as `dench crm`.
4758
4772
  const subArgs = stripRuntimeFlags(args.slice(args.indexOf("meetings") + 1));
4759
- const sub = subArgs[0];
4773
+ const sub = firstSubcommandToken(subArgs);
4760
4774
  if (!sub || sub === "help" || sub === "--help") {
4761
4775
  const { runMeetingsCommand } = await import("./meetings");
4762
4776
  // biome-ignore lint/suspicious/noExplicitAny: harmless help-only stub
@@ -4796,9 +4810,13 @@ async function main() {
4796
4810
  const { runLeadsCommand, assertLeadsFindArgs, runFindFiltersCommand } =
4797
4811
  await import("./leads");
4798
4812
  const leadArgs = stripRuntimeFlags(args.slice(args.indexOf("leads") + 1));
4813
+ const leadSub = firstSubcommandToken(leadArgs);
4799
4814
  // `filters` prints bundled catalogs — no session or network needed.
4800
- if (leadArgs[0] === "filters") {
4801
- runFindFiltersCommand({ args: leadArgs.slice(1), jsonOutput: json });
4815
+ if (leadSub === "filters") {
4816
+ runFindFiltersCommand({
4817
+ args: removeFirstSubcommandToken(leadArgs, leadSub),
4818
+ jsonOutput: json,
4819
+ });
4802
4820
  return;
4803
4821
  }
4804
4822
  assertLeadsFindArgs(leadArgs);
@@ -4855,7 +4873,7 @@ async function main() {
4855
4873
  // the canonical caller today is the AI agent looking up userIds
4856
4874
  // for `user`-typed CRM cells.
4857
4875
  const subArgs = stripRuntimeFlags(args.slice(args.indexOf("members") + 1));
4858
- const sub = subArgs[0];
4876
+ const sub = firstSubcommandToken(subArgs);
4859
4877
  if (!sub || sub === "help" || sub === "--help") {
4860
4878
  const { runMembersCommand } = await import("./members");
4861
4879
  // biome-ignore lint/suspicious/noExplicitAny: harmless help-only stub
@@ -4891,7 +4909,7 @@ async function main() {
4891
4909
  const subArgs = stripRuntimeFlags(
4892
4910
  args.slice(args.indexOf("notifications") + 1),
4893
4911
  );
4894
- const sub = subArgs[0];
4912
+ const sub = firstSubcommandToken(subArgs);
4895
4913
  const { runNotificationsCommand } = await import("./notifications");
4896
4914
  if (!sub || sub === "help" || sub === "--help") {
4897
4915
  // biome-ignore lint/suspicious/noExplicitAny: harmless help-only stub
@@ -4924,7 +4942,7 @@ async function main() {
4924
4942
  // terminal. Same auth shape as `dench crm`; admin-only work is refused
4925
4943
  // server-side.
4926
4944
  const subArgs = stripRuntimeFlags(args.slice(args.indexOf("settings") + 1));
4927
- const sub = subArgs[0];
4945
+ const sub = firstSubcommandToken(subArgs);
4928
4946
  const { runSettingsCommand } = await import("./settings");
4929
4947
  if (!sub || sub === "help" || sub === "--help") {
4930
4948
  // biome-ignore lint/suspicious/noExplicitAny: harmless help-only stub
@@ -5032,6 +5050,7 @@ async function main() {
5032
5050
 
5033
5051
  if (command === "email") {
5034
5052
  const subArgs = stripRuntimeFlags(args.slice(args.indexOf("email") + 1));
5053
+ const emailSub = firstSubcommandToken(subArgs);
5035
5054
  const { runEmailCommand } = await import("./email");
5036
5055
  const runtime = await getRuntime();
5037
5056
  const authedRuntime = requireAuthenticatedRuntime(runtime, "dench email");
@@ -5040,7 +5059,7 @@ async function main() {
5040
5059
  | undefined;
5041
5060
  try {
5042
5061
  if (
5043
- !["draft", "inbox", "send"].includes(subArgs[0]) &&
5062
+ !(emailSub && ["draft", "inbox", "send"].includes(emailSub)) &&
5044
5063
  !subArgs.some(
5045
5064
  (arg) => arg === "--mailbox" || arg.startsWith("--mailbox="),
5046
5065
  )
@@ -5093,7 +5112,13 @@ async function main() {
5093
5112
  if (command === "apps") {
5094
5113
  const { runAppsCommand } = await import("./apps");
5095
5114
  const subArgs = stripRuntimeFlags(args.slice(args.indexOf("apps") + 1));
5096
- if (!subArgs[0] || subArgs[0] === "help" || subArgs[0] === "--help") {
5115
+ const sub = firstSubcommandToken(subArgs);
5116
+ if (
5117
+ (!sub && !subArgs.includes("--json")) ||
5118
+ sub === "help" ||
5119
+ subArgs.includes("--help") ||
5120
+ subArgs.includes("-h")
5121
+ ) {
5097
5122
  // biome-ignore lint/suspicious/noExplicitAny: help-only stub, no client needed
5098
5123
  await runAppsCommand({ convex: {} as any, args: subArgs });
5099
5124
  return;
@@ -5119,9 +5144,10 @@ async function main() {
5119
5144
  if (command === "mcp") {
5120
5145
  const { runMcpCommand } = await import("./mcp");
5121
5146
  const subArgs = stripRuntimeFlags(args.slice(args.indexOf("mcp") + 1));
5147
+ const sub = firstSubcommandToken(subArgs);
5122
5148
  if (
5123
- !subArgs[0] ||
5124
- subArgs[0] === "help" ||
5149
+ !sub ||
5150
+ sub === "help" ||
5125
5151
  subArgs.includes("--help") ||
5126
5152
  subArgs.includes("-h")
5127
5153
  ) {
@@ -5249,7 +5275,7 @@ async function main() {
5249
5275
 
5250
5276
  if (command === "chat") {
5251
5277
  const subArgs = stripRuntimeFlags(args.slice(args.indexOf("chat") + 1));
5252
- const sub = subArgs[0];
5278
+ const sub = firstSubcommandToken(subArgs);
5253
5279
  if (!sub || sub === "help" || sub === "--help") {
5254
5280
  const { runChatCommand } = await import("./chat");
5255
5281
  // biome-ignore lint/suspicious/noExplicitAny: harmless help-only stub
@@ -5269,14 +5295,14 @@ async function main() {
5269
5295
  runtime,
5270
5296
  `dench chat ${sub}`,
5271
5297
  );
5272
- // Drop the leading subcommand from subArgs — runChatSpawnCommand
5273
- // expects the remaining tokens (prompt + flags).
5298
+ // Drop the matched subcommand token while preserving flags (including
5299
+ // `--json`) placed before or after it.
5274
5300
  await runChatSpawnCommand({
5275
5301
  runtime: {
5276
5302
  host: authedRuntime.host,
5277
5303
  bearerToken: authedRuntime.sessionToken,
5278
5304
  },
5279
- args: subArgs.slice(1),
5305
+ args: removeFirstSubcommandToken(subArgs, sub),
5280
5306
  subcommand: sub,
5281
5307
  });
5282
5308
  return;
@@ -5299,7 +5325,7 @@ async function main() {
5299
5325
 
5300
5326
  if (command === "agent") {
5301
5327
  const subArgs = stripRuntimeFlags(args.slice(args.indexOf("agent") + 1));
5302
- const sub = subArgs[0];
5328
+ const sub = firstSubcommandToken(subArgs);
5303
5329
  if (
5304
5330
  !sub ||
5305
5331
  sub === "help" ||
@@ -5323,7 +5349,7 @@ async function main() {
5323
5349
  );
5324
5350
  await runChatSpawnCommand({
5325
5351
  runtime: { host: runtime.host, bearerToken: runtime.sessionToken },
5326
- args: subArgs.slice(1),
5352
+ args: removeFirstSubcommandToken(subArgs, sub),
5327
5353
  subcommand: sub,
5328
5354
  });
5329
5355
  return;
@@ -5334,7 +5360,7 @@ async function main() {
5334
5360
  // server-side; normalizeCliError explains what to do).
5335
5361
  if (command === "campaign" || command === "campaigns") {
5336
5362
  const subArgs = stripRuntimeFlags(args.slice(args.indexOf(command) + 1));
5337
- const sub = subArgs[0];
5363
+ const sub = firstSubcommandToken(subArgs);
5338
5364
  if (
5339
5365
  !sub ||
5340
5366
  sub === "help" ||
@@ -5370,7 +5396,7 @@ async function main() {
5370
5396
  // top-level command name differs to match the workspace UI rename.
5371
5397
  if (command === "cron" || command === "routine" || command === "routines") {
5372
5398
  const subArgs = stripRuntimeFlags(args.slice(args.indexOf(command) + 1));
5373
- const sub = subArgs[0];
5399
+ const sub = firstSubcommandToken(subArgs);
5374
5400
  // Help is a no-auth path so users can read the surface without a
5375
5401
  // session — mirrors `dench crm help`.
5376
5402
  if (!sub || sub === "help" || sub === "--help") {
@@ -5419,8 +5445,9 @@ async function main() {
5419
5445
  ]);
5420
5446
  if (AGENT_CONFIG_COMMANDS.has(command)) {
5421
5447
  const subArgs = stripRuntimeFlags(args.slice(args.indexOf(command) + 1));
5448
+ const sub = firstSubcommandToken(subArgs);
5422
5449
  if (
5423
- subArgs[0] === "help" ||
5450
+ sub === "help" ||
5424
5451
  subArgs.includes("--help") ||
5425
5452
  subArgs.includes("-h")
5426
5453
  ) {
package/environments.ts CHANGED
@@ -310,6 +310,41 @@ async function restoreState(
310
310
  );
311
311
  }
312
312
 
313
+ async function readStagedEnvironmentResolution(
314
+ resolutionFile: string,
315
+ parsed: { name?: string; revision?: string },
316
+ ): Promise<ResolvedEnvironment> {
317
+ try {
318
+ const info = await lstat(resolutionFile);
319
+ if (info.isSymbolicLink() || !info.isFile()) {
320
+ throw new Error(
321
+ "invalid_environment_resolution: Staged environment payload must be a regular file.",
322
+ );
323
+ }
324
+ const resolved = JSON.parse(
325
+ await readFile(resolutionFile, "utf8"),
326
+ ) as ResolvedEnvironment;
327
+ if (
328
+ !resolved ||
329
+ typeof resolved !== "object" ||
330
+ resolved.name !== parsed.name ||
331
+ (parsed.revision && resolved.revision !== parsed.revision) ||
332
+ !resolved.manifest ||
333
+ typeof resolved.credentialEnv !== "object" ||
334
+ resolved.credentialEnv === null ||
335
+ !Array.isArray(resolved.credentialFiles)
336
+ ) {
337
+ throw new Error(
338
+ "invalid_environment_resolution: Staged environment payload did not match the requested revision.",
339
+ );
340
+ }
341
+ return resolved;
342
+ } finally {
343
+ delete process.env.DENCH_ENVIRONMENT_RESOLUTION_FILE;
344
+ await rm(resolutionFile, { force: true }).catch(() => undefined);
345
+ }
346
+ }
347
+
313
348
  async function executeSavedEnvironment(
314
349
  opts: ClientOptions,
315
350
  parsed: Exclude<ReturnType<typeof validateEnvironmentArgs>, { verb: "help" }>,
@@ -320,12 +355,17 @@ async function executeSavedEnvironment(
320
355
  const stateKey =
321
356
  parsed.stateKey ??
322
357
  (job ? `job:${job}` : `local:${sha256(process.cwd()).slice(0, 32)}`);
323
- const environment = (await opts.convex.action(actionRef("resolve"), {
324
- ...token,
325
- name: parsed.name,
326
- ...(parsed.revision ? { revision: parsed.revision } : {}),
327
- stateKey,
328
- })) as ResolvedEnvironment;
358
+ const stagedResolutionFile =
359
+ process.env.DENCH_ENVIRONMENT_RESOLUTION_FILE?.trim();
360
+ const resolvedFromStagedFile = Boolean(stagedResolutionFile);
361
+ const environment = stagedResolutionFile
362
+ ? await readStagedEnvironmentResolution(stagedResolutionFile, parsed)
363
+ : ((await opts.convex.action(actionRef("resolveForAdmin"), {
364
+ ...token,
365
+ name: parsed.name,
366
+ ...(parsed.revision ? { revision: parsed.revision } : {}),
367
+ stateKey,
368
+ })) as ResolvedEnvironment);
329
369
  const suppliedWorkspace =
330
370
  opts.execution?.workspace ?? process.env.DENCH_ENVIRONMENT_WORKSPACE;
331
371
  const workspace =
@@ -377,12 +417,12 @@ async function executeSavedEnvironment(
377
417
  ? await acquireEnvironmentWorkspaceLock(workspace)
378
418
  : undefined;
379
419
  try {
380
- if (releaseExecution) {
420
+ if (releaseExecution && !resolvedFromStagedFile) {
381
421
  // Another command may have committed state or rotated credentials while
382
422
  // this process waited. Read again under the lock, retaining this revision.
383
423
  Object.assign(
384
424
  environment,
385
- await opts.convex.action(actionRef("resolve"), {
425
+ await opts.convex.action(actionRef("resolveForAdmin"), {
386
426
  ...token,
387
427
  name: environment.name,
388
428
  revision: environment.revision,
@@ -21,6 +21,65 @@
21
21
 
22
22
  const BINARY_PROBE_BYTES = 4096;
23
23
 
24
+ const BINARY_FILE_EXTENSIONS = new Set([
25
+ ".png",
26
+ ".jpg",
27
+ ".jpeg",
28
+ ".gif",
29
+ ".webp",
30
+ ".avif",
31
+ ".ico",
32
+ ".bmp",
33
+ ".tif",
34
+ ".tiff",
35
+ ".pdf",
36
+ ".zip",
37
+ ".gz",
38
+ ".tar",
39
+ ".tgz",
40
+ ".bz2",
41
+ ".xz",
42
+ ".7z",
43
+ ".rar",
44
+ ".woff",
45
+ ".woff2",
46
+ ".ttf",
47
+ ".otf",
48
+ ".eot",
49
+ ".mp3",
50
+ ".mp4",
51
+ ".mov",
52
+ ".avi",
53
+ ".mkv",
54
+ ".webm",
55
+ ".wav",
56
+ ".ogg",
57
+ ".flac",
58
+ ".m4a",
59
+ ".wasm",
60
+ ".exe",
61
+ ".dll",
62
+ ".so",
63
+ ".dylib",
64
+ ".bin",
65
+ ".doc",
66
+ ".docx",
67
+ ".xls",
68
+ ".xlsx",
69
+ ".ppt",
70
+ ".pptx",
71
+ ".sqlite",
72
+ ".db",
73
+ ".parquet",
74
+ ]);
75
+
76
+ export function hasBinaryFileExtension(path: string): boolean {
77
+ const base = path.split(/[\\/]/).pop() ?? "";
78
+ const dot = base.lastIndexOf(".");
79
+ if (dot <= 0) return false;
80
+ return BINARY_FILE_EXTENSIONS.has(base.slice(dot).toLowerCase());
81
+ }
82
+
24
83
  /**
25
84
  * Sniff a buffer for binary content. PNG / PDF / Office / .zip all
26
85
  * contain NUL bytes within the first KB; valid UTF-8 text never does.
@@ -58,7 +117,14 @@ export function detectBinaryBuffer(buffer: Uint8Array): boolean {
58
117
  */
59
118
  export function decodeInlineTextOrUndefined(
60
119
  buffer: Uint8Array,
120
+ path?: string,
61
121
  ): string | undefined {
122
+ if (path && hasBinaryFileExtension(path)) return undefined;
62
123
  if (detectBinaryBuffer(buffer)) return undefined;
63
- return new TextDecoder("utf-8", { fatal: false }).decode(buffer);
124
+ if (buffer.includes(0)) return undefined;
125
+ try {
126
+ return new TextDecoder("utf-8", { fatal: true }).decode(buffer);
127
+ } catch {
128
+ return undefined;
129
+ }
64
130
  }
package/image.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `dench image generate|edit` — gpt-image-2 backed image creation through
2
+ * `dench image generate|edit` — GPT Image (Azure `gpt-image-2.5-flare`) backed image creation through
3
3
  * the Dench Cloud Gateway.
4
4
  *
5
5
  * Mirrors `dench search`: bypasses Convex entirely and talks straight HTTP
@@ -25,9 +25,10 @@
25
25
  * [--output ...] [--no-write] [--json]
26
26
  */
27
27
 
28
+ import { accessSync, constants as fsConstants, statSync } from "node:fs";
28
29
  import { mkdir, readFile, writeFile } from "node:fs/promises";
29
30
  import { dirname, isAbsolute, resolve } from "node:path";
30
- import { getFlag, hasFlag } from "./lib/cli-args";
31
+ import { assertNoUnknownFlags, getFlag, hasFlag } from "./lib/cli-args";
31
32
 
32
33
  type ImageCliContext = {
33
34
  args: string[];
@@ -74,22 +75,35 @@ function requireBearerToken(
74
75
  return bearerToken;
75
76
  }
76
77
 
77
- function resolveDefaultVolumeRoot(): string {
78
+ function isWritableDirectory(path: string): boolean {
79
+ try {
80
+ if (!statSync(path).isDirectory()) return false;
81
+ accessSync(path, fsConstants.W_OK);
82
+ return true;
83
+ } catch {
84
+ return false;
85
+ }
86
+ }
87
+
88
+ export function resolveDefaultVolumeRoot(): string {
78
89
  // Inside a sandbox the volume is mounted at `/workspace` and the
79
90
  // gateway emits paths like `/image-generations/...png`. Outside a
80
91
  // sandbox, write to `./image-generations/...png` so things still
81
92
  // work in dev / CI.
82
- return process.env.DENCH_VOLUME_PATH?.trim() || "/workspace";
93
+ const explicit = process.env.DENCH_VOLUME_PATH?.trim();
94
+ if (explicit) return explicit;
95
+ if (isWritableDirectory("/workspace")) return "/workspace";
96
+ return process.cwd();
83
97
  }
84
98
 
85
- function resolveOutputPath(
99
+ export function resolveOutputPath(
86
100
  explicit: string | undefined,
87
101
  gatewayPath: string,
88
102
  ): string {
89
- const root = resolveDefaultVolumeRoot();
90
103
  if (explicit && explicit.length > 0) {
91
104
  return isAbsolute(explicit) ? explicit : resolve(process.cwd(), explicit);
92
105
  }
106
+ const root = resolveDefaultVolumeRoot();
93
107
  // gatewayPath is `/image-generations/<file>.png` (POSIX, leading slash).
94
108
  return resolve(root, gatewayPath.replace(/^\/+/, ""));
95
109
  }
@@ -280,6 +294,7 @@ async function runGenerateSubcommand(ctx: ImageCliContext): Promise<void> {
280
294
  // Consume optional --print-b64 BEFORE we collapse the remainder into
281
295
  // the prompt, otherwise it would be glued onto the prompt string.
282
296
  const printB64 = hasFlag(ctx.args, "--print-b64");
297
+ assertNoUnknownFlags(ctx.args, "image generate");
283
298
  const promptParts = ctx.args.slice();
284
299
  ctx.args.length = 0;
285
300
  const prompt = promptParts.join(" ").trim();
@@ -329,6 +344,7 @@ async function runEditSubcommand(ctx: ImageCliContext): Promise<void> {
329
344
  inputs.push(input);
330
345
  }
331
346
  const mask = getFlag(ctx.args, "--mask");
347
+ assertNoUnknownFlags(ctx.args, "image edit");
332
348
  const promptParts = ctx.args.slice();
333
349
  ctx.args.length = 0;
334
350
  const prompt = promptParts.join(" ").trim();
package/leads.ts CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  CliArgError,
13
13
  getFlag,
14
14
  hasFlag,
15
+ parsePositiveInt,
15
16
  shift as shiftRaw,
16
17
  } from "./lib/cli-args";
17
18
  import {
@@ -1576,6 +1577,7 @@ export async function runWorkspaceArtifactsCommand(opts: {
1576
1577
  sessionToken?: string;
1577
1578
  }): Promise<boolean> {
1578
1579
  const args = [...opts.args];
1580
+ const jsonOutput = hasFlag(args, "--json") || opts.jsonOutput === true;
1579
1581
  const verb = args[0];
1580
1582
  if (verb !== "list" && verb !== "show" && verb !== "import") {
1581
1583
  return false;
@@ -1584,12 +1586,11 @@ export async function runWorkspaceArtifactsCommand(opts: {
1584
1586
  const ctx: FindCliContext = {
1585
1587
  convex: opts.convex,
1586
1588
  args,
1587
- jsonOutput: hasFlag(args, "--json") || opts.jsonOutput === true,
1589
+ jsonOutput,
1588
1590
  sessionToken: opts.sessionToken,
1589
1591
  };
1590
1592
  if (verb === "list") {
1591
- const limitRaw = getFlag(args, "--limit");
1592
- const limit = limitRaw ? Number(limitRaw) : 25;
1593
+ const limit = parsePositiveInt(getFlag(args, "--limit"), "--limit") ?? 25;
1593
1594
  assertNoUnknownFlags(args, "artifacts list");
1594
1595
  out(ctx, await callQuery(ctx, api.list, { limit }));
1595
1596
  return true;
package/lib/cli-args.ts CHANGED
@@ -156,6 +156,58 @@ export function parseLimit(
156
156
  return { requested, effective, clamped: effective < requested };
157
157
  }
158
158
 
159
+ export function parsePositiveInt(
160
+ raw: string | undefined,
161
+ label: string,
162
+ ): number | undefined {
163
+ if (raw === undefined) return undefined;
164
+ const trimmed = raw.trim();
165
+ if (!/^\d+$/.test(trimmed)) {
166
+ throw new CliArgError(`${label} must be a positive integer, got "${raw}"`);
167
+ }
168
+ const parsed = Number.parseInt(trimmed, 10);
169
+ if (!Number.isSafeInteger(parsed) || parsed < 1) {
170
+ throw new CliArgError(`${label} must be a positive integer, got "${raw}"`);
171
+ }
172
+ return parsed;
173
+ }
174
+
175
+ export function parseNonNegativeNumber(
176
+ raw: string | undefined,
177
+ label: string,
178
+ ): number | undefined {
179
+ if (raw === undefined) return undefined;
180
+ const trimmed = raw.trim();
181
+ if (trimmed.length === 0) {
182
+ throw new CliArgError(
183
+ `${label} must be a non-negative number, got "${raw}"`,
184
+ );
185
+ }
186
+ const parsed = Number(trimmed);
187
+ if (!Number.isFinite(parsed) || parsed < 0) {
188
+ throw new CliArgError(
189
+ `${label} must be a non-negative number, got "${raw}"`,
190
+ );
191
+ }
192
+ return parsed;
193
+ }
194
+
195
+ export function parseFiniteNumber(
196
+ raw: string | undefined,
197
+ label: string,
198
+ ): number | undefined {
199
+ if (raw === undefined) return undefined;
200
+ const trimmed = raw.trim();
201
+ if (trimmed.length === 0) {
202
+ throw new CliArgError(`${label} must be a finite number, got "${raw}"`);
203
+ }
204
+ const parsed = Number(trimmed);
205
+ if (!Number.isFinite(parsed)) {
206
+ throw new CliArgError(`${label} must be a finite number, got "${raw}"`);
207
+ }
208
+ return parsed;
209
+ }
210
+
159
211
  export function assertNoUnknownFlags(
160
212
  args: readonly string[],
161
213
  command: string,