@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/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,