@dench.com/cli 3.12.29 → 3.12.30-staging.1461

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/ads.ts CHANGED
@@ -906,7 +906,7 @@ function installClaude(): string {
906
906
  }
907
907
  settings.statusLine = {
908
908
  type: "command",
909
- command: `${nodeBin()} ${RENDER_SCRIPT}`,
909
+ command: buildClaudeStatusLineCommand(),
910
910
  padding: 0,
911
911
  };
912
912
  // Also show the sponsored line as the "thinking" spinner verb (CC 2.1.143+
@@ -949,12 +949,39 @@ function refreshClaudeSpinnerVerb(): void {
949
949
  atomicWrite(CLAUDE_SETTINGS, `${JSON.stringify(settings, null, 2)}\n`);
950
950
  }
951
951
 
952
+ type ShellKind = "bash" | "zsh" | "fish";
953
+
954
+ export function quoteForShell(value: string, kind: ShellKind = "bash"): string {
955
+ if (value.length === 0) return "''";
956
+ if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(value)) return value;
957
+ if (kind === "fish") {
958
+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
959
+ }
960
+ return `'${value.replace(/'/g, `'\\''`)}'`;
961
+ }
962
+
952
963
  // Absolute path to the interpreter running this CLI. Hooks run in environments
953
964
  // where the interactive-shell PATH (nvm/fnm shims, bun) may be absent, so a
954
965
  // bare `node` silently fails. process.execPath is always resolvable.
955
- function nodeBin(): string {
956
- const p = process.execPath;
957
- return p.includes(" ") ? `"${p}"` : p;
966
+ function nodeBin(
967
+ kind: ShellKind = "bash",
968
+ execPath: string = process.execPath,
969
+ ): string {
970
+ return quoteForShell(execPath, kind);
971
+ }
972
+
973
+ export function buildClaudeStatusLineCommand(
974
+ execPath: string = process.execPath,
975
+ renderScriptPath: string = RENDER_SCRIPT,
976
+ ): string {
977
+ return `${nodeBin("bash", execPath)} ${quoteForShell(renderScriptPath, "bash")}`;
978
+ }
979
+
980
+ export function buildCodexHookCommand(
981
+ execPath: string = process.execPath,
982
+ codexHookScriptPath: string = CODEX_HOOK_CMD,
983
+ ): string {
984
+ return `${nodeBin("bash", execPath)} ${quoteForShell(codexHookScriptPath, "bash")}`;
958
985
  }
959
986
 
960
987
  function uninstallClaude(): string {
@@ -1010,7 +1037,7 @@ function codexHookEntry(): CodexHookEntry {
1010
1037
  hooks: [
1011
1038
  {
1012
1039
  type: "command",
1013
- command: `${nodeBin()} ${CODEX_HOOK_CMD}`,
1040
+ command: buildCodexHookCommand(),
1014
1041
  statusMessage: "dench ads",
1015
1042
  },
1016
1043
  ],
@@ -1018,7 +1045,15 @@ function codexHookEntry(): CodexHookEntry {
1018
1045
  }
1019
1046
 
1020
1047
  function isDenchCodexEntry(entry: CodexHookEntry): boolean {
1021
- return entry.hooks?.some((h) => h.command?.includes(CODEX_HOOK_CMD)) ?? false;
1048
+ const quoted = quoteForShell(CODEX_HOOK_CMD, "bash");
1049
+ return (
1050
+ entry.hooks?.some((h) =>
1051
+ Boolean(
1052
+ h.command &&
1053
+ (h.command.includes(CODEX_HOOK_CMD) || h.command.includes(quoted)),
1054
+ ),
1055
+ ) ?? false
1056
+ );
1022
1057
  }
1023
1058
 
1024
1059
  function stripDenchCodexEntries(file: CodexHooksFile): void {
@@ -1116,8 +1151,6 @@ function uninstallCodex(): string {
1116
1151
  // install — generic shell hook (works in any terminal)
1117
1152
  // ---------------------------------------------------------------------------
1118
1153
 
1119
- type ShellKind = "bash" | "zsh" | "fish";
1120
-
1121
1154
  function shellHookTarget(): { kind: ShellKind; rc: string } | null {
1122
1155
  const shell = process.env.SHELL ?? "";
1123
1156
  if (shell.includes("bash"))
@@ -1140,8 +1173,10 @@ function shellRcPaths(): string[] {
1140
1173
  return [...new Set(paths.filter((path): path is string => Boolean(path)))];
1141
1174
  }
1142
1175
 
1143
- function shellSnippet(
1176
+ export function shellSnippet(
1144
1177
  kind: ShellKind = shellHookTarget()?.kind ?? "bash",
1178
+ execPath: string = process.execPath,
1179
+ renderScriptPath: string = RENDER_SCRIPT,
1145
1180
  ): string {
1146
1181
  if (kind === "fish") {
1147
1182
  return `${SHELL_MARK_START}
@@ -1149,7 +1184,7 @@ function shellSnippet(
1149
1184
  # every prompt) — shows in any terminal (Codex, Cursor, plain shell, …).
1150
1185
  # Remove this block to disable.
1151
1186
  if status is-interactive
1152
- set -l _dench_line (${nodeBin()} ${RENDER_SCRIPT} 2>/dev/null | string collect)
1187
+ set -l _dench_line (${nodeBin("fish", execPath)} ${quoteForShell(renderScriptPath, "fish")} 2>/dev/null | string collect)
1153
1188
  test -n "$_dench_line"; and printf '%s\\n' "$_dench_line"
1154
1189
  end
1155
1190
  ${SHELL_MARK_END}`;
@@ -1160,7 +1195,7 @@ ${SHELL_MARK_END}`;
1160
1195
  # Remove this block to disable.
1161
1196
  case "$-" in
1162
1197
  *i*)
1163
- _dench_line="$(${nodeBin()} ${RENDER_SCRIPT} 2>/dev/null)"
1198
+ _dench_line="$(${nodeBin("bash", execPath)} ${quoteForShell(renderScriptPath, "bash")} 2>/dev/null)"
1164
1199
  [ -n "$_dench_line" ] && printf '%s\\n' "$_dench_line"
1165
1200
  unset _dench_line
1166
1201
  ;;
@@ -1652,7 +1687,11 @@ function claudeInstalled(): boolean {
1652
1687
  // user state worth (re)backing up vs. our own prior install.
1653
1688
  function claudeInstalledFrom(settings: Record<string, unknown>): boolean {
1654
1689
  const sl = settings.statusLine as { command?: string } | undefined;
1655
- return Boolean(sl?.command?.includes(RENDER_SCRIPT));
1690
+ const quoted = quoteForShell(RENDER_SCRIPT, "bash");
1691
+ return Boolean(
1692
+ sl?.command &&
1693
+ (sl.command.includes(RENDER_SCRIPT) || sl.command.includes(quoted)),
1694
+ );
1656
1695
  }
1657
1696
 
1658
1697
  function codexInstalled(): boolean {
@@ -1975,7 +2014,23 @@ async function runWithdrawCommand(opts: {
1975
2014
  clearPendingPayout(responseIdempotencyKey);
1976
2015
  }
1977
2016
  if (opts.json) {
1978
- console.log(JSON.stringify({ ...data, idempotencyKey }, null, 2));
2017
+ const failed = res.status !== 202 && (!res.ok || !data.ok);
2018
+ console.log(
2019
+ JSON.stringify(
2020
+ {
2021
+ ...data,
2022
+ ...(failed
2023
+ ? { ok: false, error: data.error || "Payout failed." }
2024
+ : {}),
2025
+ idempotencyKey: responseIdempotencyKey,
2026
+ },
2027
+ null,
2028
+ 2,
2029
+ ),
2030
+ );
2031
+ if (failed) {
2032
+ process.exitCode = 1;
2033
+ }
1979
2034
  return;
1980
2035
  }
1981
2036
  if (res.status === 202) {
@@ -2101,8 +2156,35 @@ export async function runAdsCommand(opts: {
2101
2156
  await refresh(authToken);
2102
2157
  }
2103
2158
  const fresh = loadAd() ?? loadAd({ allowExpired: true });
2104
- if (!fresh) return; // genuinely nothing to show; stay silent
2105
- process.stdout.write(`${await renderBox(fresh)}\n`);
2159
+ if (!fresh) {
2160
+ if (json) {
2161
+ console.log(JSON.stringify({ ok: true, ad: null }, null, 2));
2162
+ }
2163
+ return; // genuinely nothing to show; stay silent in human mode
2164
+ }
2165
+ if (json) {
2166
+ console.log(
2167
+ JSON.stringify(
2168
+ {
2169
+ ok: true,
2170
+ ad: {
2171
+ id: fresh.id,
2172
+ label: fresh.label,
2173
+ ...(fresh.url ? { url: fresh.url } : {}),
2174
+ ...(fresh.icon ? { icon: fresh.icon } : {}),
2175
+ ...(fresh.iconUrl ? { iconUrl: fresh.iconUrl } : {}),
2176
+ ...(fresh.expiresAt !== undefined
2177
+ ? { expiresAt: fresh.expiresAt }
2178
+ : {}),
2179
+ },
2180
+ },
2181
+ null,
2182
+ 2,
2183
+ ),
2184
+ );
2185
+ } else {
2186
+ process.stdout.write(`${await renderBox(fresh)}\n`);
2187
+ }
2106
2188
  countImpression(fresh);
2107
2189
  const endpoint = adEndpoint();
2108
2190
  if (endpoint) await flushImpressions(endpoint, authToken, fresh);
package/agent-config.ts CHANGED
@@ -25,8 +25,14 @@
25
25
  * stdin path is also supported via `--stdin`, useful in scripts.
26
26
  */
27
27
 
28
- import { execSync } from "node:child_process";
29
- import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
28
+ import { spawnSync } from "node:child_process";
29
+ import {
30
+ chmodSync,
31
+ mkdtempSync,
32
+ readFileSync,
33
+ rmSync,
34
+ writeFileSync,
35
+ } from "node:fs";
30
36
  import { tmpdir } from "node:os";
31
37
  import { join } from "node:path";
32
38
  import type { ConvexHttpClient } from "convex/browser";
@@ -126,18 +132,101 @@ async function readContentFromStdin(): Promise<string> {
126
132
  });
127
133
  }
128
134
 
129
- function openEditor(initial: string, suffix: string): string {
135
+ export function parseEditorCommand(editor: string): string[] {
136
+ const tokens: string[] = [];
137
+ let current = "";
138
+ let quote: "'" | '"' | null = null;
139
+ let hasToken = false;
140
+
141
+ for (let i = 0; i < editor.length; i += 1) {
142
+ const ch = editor[i];
143
+ if (quote === "'") {
144
+ if (ch === "'") {
145
+ quote = null;
146
+ } else {
147
+ current += ch;
148
+ }
149
+ continue;
150
+ }
151
+ if (quote === '"') {
152
+ if (ch === '"') {
153
+ quote = null;
154
+ } else if (ch === "\\" && i + 1 < editor.length) {
155
+ const next = editor[i + 1];
156
+ if (next === '"' || next === "\\" || next === "$" || next === "`") {
157
+ current += next;
158
+ i += 1;
159
+ } else {
160
+ current += ch;
161
+ }
162
+ } else {
163
+ current += ch;
164
+ }
165
+ continue;
166
+ }
167
+ if (/\s/.test(ch)) {
168
+ if (hasToken) {
169
+ tokens.push(current);
170
+ current = "";
171
+ hasToken = false;
172
+ }
173
+ continue;
174
+ }
175
+ if (ch === "'" || ch === '"') {
176
+ quote = ch;
177
+ hasToken = true;
178
+ continue;
179
+ }
180
+ if (ch === "\\" && i + 1 < editor.length) {
181
+ current += editor[i + 1];
182
+ hasToken = true;
183
+ i += 1;
184
+ continue;
185
+ }
186
+ current += ch;
187
+ hasToken = true;
188
+ }
189
+
190
+ if (quote !== null) {
191
+ throw new AgentConfigCliError(`Unclosed quote in EDITOR: ${editor}`);
192
+ }
193
+ if (hasToken) {
194
+ tokens.push(current);
195
+ }
196
+ if (tokens.length === 0) {
197
+ throw new AgentConfigCliError("EDITOR is empty");
198
+ }
199
+ return tokens;
200
+ }
201
+
202
+ export function openEditor(initial: string, suffix: string): string {
130
203
  const editor = process.env.EDITOR?.trim() || "vi";
131
- const dir = join(tmpdir(), "dench-agent-cli");
132
- mkdirSync(dir, { recursive: true });
133
- const file = join(dir, `${Date.now()}-${suffix}.md`);
134
- writeFileSync(file, initial, "utf8");
204
+ const [cmd, ...editorArgs] = parseEditorCommand(editor);
205
+ const dir = mkdtempSync(join(tmpdir(), "dench-agent-cli-"));
206
+ chmodSync(dir, 0o700);
207
+ const safeSuffix = suffix.replace(/[^a-zA-Z0-9._-]/g, "_") || "edit";
208
+ const file = join(dir, `${safeSuffix}.md`);
209
+ writeFileSync(file, initial, { encoding: "utf8", mode: 0o600 });
210
+ chmodSync(file, 0o600);
135
211
  try {
136
- execSync(`${editor} ${file}`, { stdio: "inherit" });
212
+ const result = spawnSync(cmd, [...editorArgs, file], {
213
+ stdio: "inherit",
214
+ shell: false,
215
+ });
216
+ if (result.error) {
217
+ throw new AgentConfigCliError(
218
+ `Failed to launch editor "${cmd}": ${result.error.message}`,
219
+ );
220
+ }
221
+ if (result.status !== 0) {
222
+ throw new AgentConfigCliError(
223
+ `Editor "${cmd}" exited with status ${result.status ?? "unknown"}`,
224
+ );
225
+ }
137
226
  return readFileSync(file, "utf8");
138
227
  } finally {
139
228
  try {
140
- unlinkSync(file);
229
+ rmSync(dir, { recursive: true, force: true });
141
230
  } catch {
142
231
  // best-effort cleanup
143
232
  }
package/apps.ts CHANGED
@@ -17,6 +17,11 @@ import {
17
17
  formatValidation,
18
18
  validateApp,
19
19
  } from "./lib/apps-validate";
20
+ import {
21
+ getFlag,
22
+ parseNonNegativeNumber,
23
+ parsePositiveInt,
24
+ } from "./lib/cli-args";
20
25
  import { closestMatch } from "./lib/levenshtein";
21
26
 
22
27
  const api = {
@@ -94,6 +99,13 @@ function withAuth(ctx: Ctx, args: Record<string, unknown>) {
94
99
  } as never;
95
100
  }
96
101
 
102
+ function withFilesAuth(ctx: Ctx, args: Record<string, unknown>) {
103
+ return {
104
+ ...args,
105
+ ...(ctx.sessionToken ? { apiKey: ctx.sessionToken } : {}),
106
+ } as never;
107
+ }
108
+
97
109
  function appsHelp(): void {
98
110
  console.log(appsHelpText());
99
111
  }
@@ -167,7 +179,7 @@ async function loadAppFolder(
167
179
  const walk = async (dir: string) => {
168
180
  const entries = (await ctx.convex.query(
169
181
  api.listTree,
170
- withAuth(ctx, { prefix: dir }),
182
+ withFilesAuth(ctx, { prefix: dir }),
171
183
  )) as Array<{ path: string; isDir: boolean }>;
172
184
  for (const entry of entries) {
173
185
  if (entry.isDir) {
@@ -178,7 +190,7 @@ async function loadAppFolder(
178
190
  if (rel !== ".dench.yaml" && !TEXT_FILE.test(rel)) continue;
179
191
  const content = (await ctx.convex.query(
180
192
  api.getFileContent,
181
- withAuth(ctx, { path: entry.path }),
193
+ withFilesAuth(ctx, { path: entry.path }),
182
194
  )) as { content?: string | null } | null;
183
195
  if (typeof content?.content === "string") {
184
196
  rows.push({ path: rel, content: content.content });
@@ -261,8 +273,11 @@ async function runWebhooks(ctx: Ctx) {
261
273
  return;
262
274
  }
263
275
  case "poll": {
264
- const since = takeFlag(ctx.args, "--since");
265
- const limit = takeFlag(ctx.args, "--limit");
276
+ const since = parseNonNegativeNumber(
277
+ getFlag(ctx.args, "--since"),
278
+ "--since",
279
+ );
280
+ const limit = parsePositiveInt(getFlag(ctx.args, "--limit"), "--limit");
266
281
  const slug = shift(ctx.args, "app slug");
267
282
  const hookName = shift(ctx.args, "hook name");
268
283
  out(
@@ -272,8 +287,8 @@ async function runWebhooks(ctx: Ctx) {
272
287
  withAuth(ctx, {
273
288
  slug,
274
289
  hookName,
275
- ...(since ? { since: Number(since) } : {}),
276
- ...(limit ? { limit: Number(limit) } : {}),
290
+ ...(since !== undefined ? { since } : {}),
291
+ ...(limit !== undefined ? { limit } : {}),
277
292
  }),
278
293
  ),
279
294
  );
package/browser.ts CHANGED
@@ -138,16 +138,24 @@ function consumeFlag(args: string[], name: string): boolean {
138
138
  return true;
139
139
  }
140
140
 
141
- function parseNumberFlag(args: string[], name: string): number | undefined {
142
- const raw = consumeFlagValue(args, name);
143
- if (raw === undefined) return undefined;
144
- const value = Number(raw);
141
+ function parseFiniteCoordinate(raw: string, label: string): number {
142
+ const trimmed = raw.trim();
143
+ if (trimmed.length === 0) {
144
+ throw new BrowserCliError(`Invalid ${label} value: ${raw}`);
145
+ }
146
+ const value = Number(trimmed);
145
147
  if (!Number.isFinite(value)) {
146
- throw new BrowserCliError(`Invalid ${name} value: ${raw}`);
148
+ throw new BrowserCliError(`Invalid ${label} value: ${raw}`);
147
149
  }
148
150
  return value;
149
151
  }
150
152
 
153
+ function parseNumberFlag(args: string[], name: string): number | undefined {
154
+ const raw = consumeFlagValue(args, name);
155
+ if (raw === undefined) return undefined;
156
+ return parseFiniteCoordinate(raw, name);
157
+ }
158
+
151
159
  function statePath(): string {
152
160
  return (
153
161
  process.env.DENCH_BROWSER_STATE_PATH?.trim() ||
@@ -676,8 +684,10 @@ function parseActionAndBody(ctx: BrowserCliContext): {
676
684
  }
677
685
 
678
686
  if (action === "clickAt") {
679
- const positionalX = ctx.args[0] !== undefined ? Number(ctx.args[0]) : x;
680
- const positionalY = ctx.args[1] !== undefined ? Number(ctx.args[1]) : y;
687
+ const positionalX =
688
+ ctx.args[0] !== undefined ? parseFiniteCoordinate(ctx.args[0], "x") : x;
689
+ const positionalY =
690
+ ctx.args[1] !== undefined ? parseFiniteCoordinate(ctx.args[1], "y") : y;
681
691
  return {
682
692
  body: { action, threadId, x: positionalX, y: positionalY },
683
693
  outputPath,
@@ -772,6 +782,9 @@ export async function runBrowserCommand(opts: {
772
782
  await rememberThreadId(opts.runtime, response.threadId.trim());
773
783
  }
774
784
  const screenshotPath = await maybeWriteScreenshot(response, outputPath);
785
+ if (response.ok === false) {
786
+ process.exitCode = 1;
787
+ }
775
788
  if (ctx.jsonOutput) {
776
789
  output(ctx, screenshotPath ? { ...response, screenshotPath } : response);
777
790
  return;
package/chat-spawn.ts CHANGED
@@ -145,6 +145,7 @@ async function followStream(args: {
145
145
  bearerToken: string;
146
146
  runId?: string;
147
147
  threadId?: string;
148
+ jsonOutput?: boolean;
148
149
  }): Promise<void> {
149
150
  const baseUrl = args.runId
150
151
  ? buildStreamUrlByRunId(args.host, args.runId)
@@ -156,6 +157,7 @@ async function followStream(args: {
156
157
  "followStream requires either { runId } or { threadId }",
157
158
  );
158
159
  }
160
+ const jsonOutput = args.jsonOutput === true;
159
161
  // Tool calls in flight, keyed by toolCallId, so we can render
160
162
  // a single line per call ("→ tool_name … done") instead of
161
163
  // dumping every chunk verbatim.
@@ -167,6 +169,10 @@ async function followStream(args: {
167
169
  let consecutiveEmptyActiveResponses = 0;
168
170
 
169
171
  const flushText = () => {
172
+ if (jsonOutput) {
173
+ textBuffer = "";
174
+ return;
175
+ }
170
176
  if (textBuffer) {
171
177
  process.stdout.write(textBuffer);
172
178
  textBuffer = "";
@@ -175,7 +181,9 @@ async function followStream(args: {
175
181
 
176
182
  const closeInFlightToolLines = (suffix: string) => {
177
183
  if (inFlightTools.size === 0) return false;
178
- process.stdout.write(suffix);
184
+ if (!jsonOutput) {
185
+ process.stdout.write(suffix);
186
+ }
179
187
  inFlightTools.clear();
180
188
  return true;
181
189
  };
@@ -265,6 +273,13 @@ async function followStream(args: {
265
273
  output?: unknown;
266
274
  errorText?: unknown;
267
275
  };
276
+ if (jsonOutput) {
277
+ process.stdout.write(`${JSON.stringify(parsed)}\n`);
278
+ if (c.type === "finish") {
279
+ gotFinish = true;
280
+ }
281
+ return;
282
+ }
268
283
  switch (c.type) {
269
284
  case "text-delta":
270
285
  case "reasoning-delta": {
@@ -422,9 +437,16 @@ async function runChatNew(ctx: ChatSpawnContext): Promise<void> {
422
437
  threadUrl?: string;
423
438
  streamUrl?: string;
424
439
  } | null;
425
- out(ctx, payload);
440
+ const willFollow = Boolean(
441
+ follow && (payload?.threadId || payload?.workflowRunId),
442
+ );
443
+ if (ctx.jsonOutput && willFollow) {
444
+ console.log(JSON.stringify(payload));
445
+ } else {
446
+ out(ctx, payload);
447
+ }
426
448
 
427
- if (follow && (payload?.threadId || payload?.workflowRunId)) {
449
+ if (willFollow && payload) {
428
450
  if (!ctx.jsonOutput) console.error("\n--- following stream ---");
429
451
  await followStream({
430
452
  host: ctx.runtime.host,
@@ -432,6 +454,7 @@ async function runChatNew(ctx: ChatSpawnContext): Promise<void> {
432
454
  ...(payload.threadId
433
455
  ? { threadId: payload.threadId }
434
456
  : { runId: payload.workflowRunId }),
457
+ jsonOutput: ctx.jsonOutput,
435
458
  });
436
459
  }
437
460
  }
@@ -440,6 +463,7 @@ async function runChatSend(ctx: ChatSpawnContext): Promise<void> {
440
463
  const yolo = consumeFlag(ctx.args, "--yolo");
441
464
  const follow = consumeFlag(ctx.args, "--follow");
442
465
  const model = consumeFlagValue(ctx.args, "--model");
466
+ assertNoUnknownFlags(ctx.args, "chat send");
443
467
 
444
468
  // First positional = threadId, the rest joined = prompt.
445
469
  const positionals = ctx.args.filter((arg) => !arg.startsWith("--"));
@@ -481,9 +505,16 @@ async function runChatSend(ctx: ChatSpawnContext): Promise<void> {
481
505
  threadUrl?: string;
482
506
  streamUrl?: string;
483
507
  } | null;
484
- out(ctx, payload);
508
+ const willFollow = Boolean(
509
+ follow && (payload?.threadId || payload?.workflowRunId),
510
+ );
511
+ if (ctx.jsonOutput && willFollow) {
512
+ console.log(JSON.stringify(payload));
513
+ } else {
514
+ out(ctx, payload);
515
+ }
485
516
 
486
- if (follow && (payload?.threadId || payload?.workflowRunId)) {
517
+ if (willFollow && payload) {
487
518
  if (!ctx.jsonOutput) console.error("\n--- following stream ---");
488
519
  await followStream({
489
520
  host: ctx.runtime.host,
@@ -491,6 +522,7 @@ async function runChatSend(ctx: ChatSpawnContext): Promise<void> {
491
522
  ...(payload.threadId
492
523
  ? { threadId: payload.threadId }
493
524
  : { runId: payload.workflowRunId }),
525
+ jsonOutput: ctx.jsonOutput,
494
526
  });
495
527
  }
496
528
  }
@@ -509,6 +541,7 @@ async function runChatSend(ctx: ChatSpawnContext): Promise<void> {
509
541
  * hits Ctrl-C.
510
542
  */
511
543
  async function runChatFollow(ctx: ChatSpawnContext): Promise<void> {
544
+ assertNoUnknownFlags(ctx.args, "chat follow");
512
545
  const positionals = ctx.args.filter((arg) => !arg.startsWith("--"));
513
546
  const threadId = positionals.shift();
514
547
  if (!threadId) {
@@ -521,6 +554,7 @@ async function runChatFollow(ctx: ChatSpawnContext): Promise<void> {
521
554
  host: ctx.runtime.host,
522
555
  bearerToken: ctx.runtime.bearerToken,
523
556
  threadId,
557
+ jsonOutput: ctx.jsonOutput,
524
558
  });
525
559
  }
526
560
 
package/chat.ts CHANGED
@@ -28,6 +28,7 @@
28
28
  import type { ConvexHttpClient } from "convex/browser";
29
29
  import { makeFunctionReference } from "convex/server";
30
30
  import {
31
+ assertNoUnknownFlags,
31
32
  CliArgError,
32
33
  getFlag,
33
34
  hasFlag,
@@ -216,6 +217,7 @@ async function runChatListCommand(ctx: ChatCliContext): Promise<void> {
216
217
  const limit = parseLimit(getFlag(ctx.args, "--limit"));
217
218
  const includeArchived = hasFlag(ctx.args, "--include-archived");
218
219
  const includeAutomated = hasFlag(ctx.args, "--include-automated");
220
+ assertNoUnknownFlags(ctx.args, "chat list");
219
221
  out(
220
222
  ctx,
221
223
  await callQuery(ctx, api.listPastChats, {
@@ -231,6 +233,7 @@ async function runChatSearchCommand(ctx: ChatCliContext): Promise<void> {
231
233
  const includeCurrent = hasFlag(ctx.args, "--include-current");
232
234
  const includeAutomated = hasFlag(ctx.args, "--include-automated");
233
235
  const limit = parseLimit(getFlag(ctx.args, "--limit"));
236
+ assertNoUnknownFlags(ctx.args, "chat search");
234
237
  const queryParts: string[] = [];
235
238
  while (ctx.args.length > 0) {
236
239
  const next = ctx.args.shift();
@@ -243,6 +246,7 @@ async function runChatSearchCommand(ctx: ChatCliContext): Promise<void> {
243
246
  'Usage: dench chat search "<query>" [--limit N] [--include-current] [--include-automated]',
244
247
  );
245
248
  }
249
+ const currentThreadId = process.env.DENCH_THREAD_ID?.trim() || undefined;
246
250
  out(
247
251
  ctx,
248
252
  await ctx.convex.action(api.searchPastChats, {
@@ -250,17 +254,17 @@ async function runChatSearchCommand(ctx: ChatCliContext): Promise<void> {
250
254
  query,
251
255
  limit,
252
256
  includeAutomated,
253
- // The server defaults excludeThreadId to undefined; the agent path
254
- // sets it explicitly. CLI users are not "in" a thread, so we pass
255
- // undefined unless --include-current is intentionally set (no-op).
256
- ...(includeCurrent ? {} : {}),
257
+ ...(!includeCurrent && currentThreadId
258
+ ? { excludeThreadId: currentThreadId }
259
+ : {}),
257
260
  }),
258
261
  );
259
262
  }
260
263
 
261
264
  async function runChatReadCommand(ctx: ChatCliContext): Promise<void> {
262
- const threadId = shift(ctx.args, "thread id");
263
265
  const limit = parseLimit(getFlag(ctx.args, "--limit"));
266
+ assertNoUnknownFlags(ctx.args, "chat read");
267
+ const threadId = shift(ctx.args, "thread id");
264
268
  out(
265
269
  ctx,
266
270
  await callQuery(ctx, api.readPastChat, {
@@ -465,23 +469,9 @@ async function runChatDeleteCommand(ctx: ChatCliContext): Promise<void> {
465
469
  * summary excerpt for each row.
466
470
  */
467
471
  async function runChatTreeCommand(ctx: ChatCliContext): Promise<void> {
468
- // Strip flag values from positionals so e.g. `tree --limit 30` doesn't
469
- // misinterpret "30" as the rootThreadId. We treat "--key value" as a
470
- // pair iff value doesn't itself start with "--".
471
- const positionals: string[] = [];
472
- for (let i = 0; i < ctx.args.length; i++) {
473
- const arg = ctx.args[i];
474
- if (arg.startsWith("--")) {
475
- const next = ctx.args[i + 1];
476
- if (next !== undefined && !next.startsWith("--")) {
477
- i += 1; // skip the flag value
478
- }
479
- continue;
480
- }
481
- positionals.push(arg);
482
- }
483
- const rootThreadId = positionals[0]?.trim() || undefined;
484
472
  const limit = parseLimit(getFlag(ctx.args, "--limit")) ?? 200;
473
+ assertNoUnknownFlags(ctx.args, "chat tree");
474
+ const rootThreadId = ctx.args[0]?.trim() || undefined;
485
475
 
486
476
  const flat = (await callQuery(ctx, api.listPastChats, {
487
477
  limit,
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
  ) {
@@ -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,
package/members.ts CHANGED
@@ -36,7 +36,13 @@ import { readFile } from "node:fs/promises";
36
36
  import { extname } from "node:path";
37
37
  import type { ConvexHttpClient } from "convex/browser";
38
38
  import { makeFunctionReference } from "convex/server";
39
- import { CliArgError, getFlag, hasFlag, shift } from "./lib/cli-args";
39
+ import {
40
+ CliArgError,
41
+ getFlag,
42
+ hasFlag,
43
+ parsePositiveInt,
44
+ shift,
45
+ } from "./lib/cli-args";
40
46
 
41
47
  class MembersCliError extends Error {}
42
48
 
@@ -253,11 +259,7 @@ async function runMemberActivity(ctx: MembersCliContext): Promise<void> {
253
259
  const rawLimit = getFlag(ctx.args, "--limit");
254
260
  const rawKinds = getFlag(ctx.args, "--kinds");
255
261
  assertNoFlags(ctx, "dench members activity");
256
- const limit =
257
- rawLimit === undefined ? undefined : Number.parseInt(rawLimit, 10);
258
- if (limit !== undefined && (!Number.isFinite(limit) || limit < 1)) {
259
- throw new MembersCliError("--limit must be a positive integer");
260
- }
262
+ const limit = parsePositiveInt(rawLimit, "--limit");
261
263
  const kinds = rawKinds
262
264
  ?.split(",")
263
265
  .map((kind) => kind.trim())
@@ -284,6 +286,7 @@ async function runMemberTasks(ctx: MembersCliContext): Promise<void> {
284
286
  const paged = hasFlag(ctx.args, "--page") || cursor !== undefined;
285
287
  const done = hasFlag(ctx.args, "--done");
286
288
  assertNoFlags(ctx, "dench members tasks");
289
+ const limit = parsePositiveInt(rawLimit, "--limit");
287
290
  const userId = await resolveMemberId(ctx, target);
288
291
  const todayStart = new Date();
289
292
  todayStart.setHours(0, 0, 0, 0);
@@ -303,11 +306,11 @@ async function runMemberTasks(ctx: MembersCliContext): Promise<void> {
303
306
  done,
304
307
  paginationOpts: {
305
308
  cursor: cursor ?? null,
306
- numItems: Number.parseInt(rawLimit ?? "25", 10),
309
+ numItems: limit ?? 25,
307
310
  },
308
311
  }
309
- : rawLimit
310
- ? { limit: Number.parseInt(rawLimit, 10) }
312
+ : limit !== undefined
313
+ ? { limit }
311
314
  : {}),
312
315
  },
313
316
  ),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dench.com/cli",
3
- "version": "3.12.29",
3
+ "version": "3.12.30-staging.1461",
4
4
  "description": "Dench agent workspace CLI.",
5
5
  "type": "module",
6
6
  "bin": {
package/search.ts CHANGED
@@ -478,6 +478,7 @@ async function runContentsSubcommand(ctx: SearchCliContext): Promise<void> {
478
478
  getFlag(ctx.args, "--max-chars"),
479
479
  );
480
480
  const summary = getFlag(ctx.args, "--summary");
481
+ assertNoUnknownFlags(ctx.args, "search contents");
481
482
  const urls = ctx.args.slice();
482
483
  ctx.args.length = 0;
483
484
  if (urls.length === 0) {
@@ -501,6 +502,7 @@ async function runContentsSubcommand(ctx: SearchCliContext): Promise<void> {
501
502
  }
502
503
 
503
504
  async function runAnswerSubcommand(ctx: SearchCliContext): Promise<void> {
505
+ assertNoUnknownFlags(ctx.args, "search answer");
504
506
  const queryParts = ctx.args.slice();
505
507
  ctx.args.length = 0;
506
508
  const query = queryParts.join(" ").trim();
package/web.ts CHANGED
@@ -358,7 +358,13 @@ export async function runWebCommand(ctx: WebCliContext): Promise<void> {
358
358
  await runWebSubcommand(ctx);
359
359
  } catch (error) {
360
360
  if (error instanceof WebCliError) {
361
- console.error(error.message);
361
+ if (ctx.jsonOutput) {
362
+ console.error(
363
+ JSON.stringify({ ok: false, error: error.message }, null, 2),
364
+ );
365
+ } else {
366
+ console.error(error.message);
367
+ }
362
368
  process.exitCode = 1;
363
369
  return;
364
370
  }