dsh-tg-bridge 1.24.0 → 1.25.1

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/README.md CHANGED
@@ -16,7 +16,9 @@ a bot that answers, one step at a time.
16
16
  - **Voice**: local faster-whisper, the transcript is shown before the answer.
17
17
  - **Photos**: the turn's own model reads them through `read_image`, text and UI
18
18
  included; no second model is needed (a vision overlay stays opt-in).
19
- - **Project per topic**: `/cd my-app`, and all turns run from that directory.
19
+ - **Project per topic**: `/cd my-app`, and all turns run from that directory — on
20
+ a permission-enabled profile the sandbox is narrowed to it too, so the agent
21
+ cannot write outside the project.
20
22
  - **Goal and checklist per topic**: `/goal`, `/tasks`; both survive restarts and are prepended to every turn.
21
23
  - **Live progress**: one edited message per turn — steps, a timer and the cache hit rate, plus
22
24
  the model's reasoning in a collapsed block you can tap open. A long turn adds a second
@@ -29,6 +31,9 @@ a bot that answers, one step at a time.
29
31
  - **`dsh-tg check`**: diagnostics in one command, no changes to the system.
30
32
  - **Languages**: menus and service messages in `en`, `ru`, `zh`; `/lang` pins the topic language, and without it a new topic takes the language of the message itself (Cyrillic → `ru`, Han characters → `zh`), then the Telegram `language_code`, then `en`.
31
33
  - **"Stop"/"Retry" buttons, tool confirmations**: right in the message, no commands to type.
34
+ - **`/report`**: one command turns "it broke" into a redacted document — version,
35
+ profile, preset, model, directory, the last failure and the log tail, with
36
+ tokens, keys and home paths removed before the file is written.
32
37
 
33
38
  ## Requirements
34
39
 
@@ -113,6 +118,7 @@ Optional provider settings live in `config.json`:
113
118
  | `vision.patch` | opt-in overlay profile for photo turns; default `""` — the turn's own model reads images |
114
119
  | `vision.enabled` | set `true` to run photo turns on `vision.patch` instead of the topic profile |
115
120
  | `fallbackModels` | ordered failover chain; default `[]` — see below |
121
+ | `fallbackEnabled` | `false` switches the whole chain off without editing the list; `/fallback off` sets it |
116
122
  | `maxParallel` | how many topics run at once, 1–8, default `3`; also `/jobs 5` in the chat |
117
123
  | `replayWindowMs` | how old a journaled update may be and still be replayed after a restart; default `600000` (10 min) |
118
124
 
@@ -124,7 +130,8 @@ model refuses:
124
130
  "provider": "router-a",
125
131
  "model": "some-model",
126
132
  "patch": "~/.dsh/tg-bridge/model-a.yml",
127
- "free": false
133
+ "free": false,
134
+ "off": false
128
135
  }
129
136
  ```
130
137
 
@@ -133,7 +140,9 @@ model refuses:
133
140
  keeps every other setting and only the model changes. `provider` is the id the
134
141
  provider is written under in the profile — it decides whose key and host the
135
142
  pre-flight probe asks, so the same model id on two routers stays two attempts.
136
- `free` only adds `(free)` to the switch notice.
143
+ `free` only adds `(free)` to the switch notice. `off` keeps an entry in the list
144
+ but out of the walk; an entry whose `patch` file is missing is skipped the same
145
+ way, and the chat says so instead of counting it.
137
146
 
138
147
  The chain may mix companies: a 503 from one provider says nothing about another,
139
148
  so a busy channel skips its own models and the next company is still tried. Put
@@ -141,6 +150,38 @@ models from different companies next to each other — two arms of one router ar
141
150
  one outage, not two chances — and keep the `:free` models at the end, as the
142
151
  last resort.
143
152
 
153
+ **What starts a switch.** Anything the provider itself says no to: a 400/413/422
154
+ refusal (its own validator rejecting the request), 401/403 (key refused), 402 or
155
+ a quota/balance message (empty account), 404 (that model id is not carried),
156
+ 429 (rate limit), 5xx and `get_channel_failed` / "all providers busy" (the pool
157
+ is down), a dropped connection or DNS/TLS failure, and an empty answer. A refusal
158
+ gets one other route, not the whole chain: it is replayed in full, and if the
159
+ second vendor refuses identically the request — not the route — is what is wrong,
160
+ so the reply says to start a fresh session with `/new`.
161
+
162
+ **What does not start a switch.** The turn time cap, `/stop`, a session or
163
+ directory error, a missing `dsh` binary: no other vendor changes those, and a
164
+ replay would cost a full turn to learn the same thing. They are listed in the
165
+ card so the distinction is visible instead of guessed.
166
+
167
+ ### `/fallback` — the chain from the chat
168
+
169
+ ```
170
+ /fallback the card: chain state, numbered routes, what starts a switch
171
+ /fallback on | off the whole chain (per route: /fallback off 3)
172
+ /fallback use 3 | skip 3 one route back in or out
173
+ /fallback up 3 | down 3 move a route in the order
174
+ /fallback test [3] ask each route (or one) with a 1-token request
175
+ /fallback add <provider>/<model> write an overlay and append the route
176
+ /fallback remove 3 drop a route from the list (its overlay file stays)
177
+ ```
178
+
179
+ Every line has a button on the card: `● n` switches a route, `↑ n` / `↓ n` move
180
+ it, and the card redraws in place after each press. `test` proves the key and the
181
+ channel are alive — not that the provider accepts this conversation, so a route
182
+ can answer `ping` and still refuse a long prompt with a 400. The card says that
183
+ in as many words.
184
+
144
185
  Get your id from [@userinfobot](https://t.me/userinfobot), the token from
145
186
  [@BotFather](https://t.me/BotFather).
146
187
 
@@ -210,7 +251,8 @@ Send the bot:
210
251
  | `/update` | which bridge runs, what npm has, and whether a newer release exists (`/update confirm` installs it) |
211
252
  | `/thoughts [file\|all\|off]` | the last turn's reasoning as a message; `file`/`all` send the full log as a Markdown document, `off` hides the block |
212
253
  | `/help` | commands grouped by category |
213
- | `/cd my-app` | topic bound to the project |
254
+ | `/cd my-app` | topic bound to the project, and the sandbox narrowed to it |
255
+ | `/report` | a redacted bundle (version, profile, preset, model, cwd, last failure, log tail) sent to the owner as a document; in a group, the path only |
214
256
  | `/prices` | what the current model costs, and whose price that is: your provider's, the same model on another gateway, or "no public price" when nobody publishes one |
215
257
 
216
258
  ## Commands
@@ -226,7 +268,7 @@ Profiles: /profile · /profile <name> · /profile new <name> from <template>
226
268
  Sets: /crew · /crew use|off|new|copy|rm · /crew model <v>
227
269
  Extensions: /skills · /plugins · /plugins search <word> · /plugins disable|enable <id> · /soul
228
270
  Updates: /update · /update confirm · /update on|off|check|auto · /subscribe on|off
229
- Diagnostics: /doctor · /logs [errors|N|text]
271
+ Diagnostics: /doctor · /logs [errors|N|text] · /report
230
272
  Service: /app · /restart · /help
231
273
  Settings: /settings — the same switches as buttons, grouped in four tabs
232
274
  Display: /lang · /reasoning on|off · /thoughts
@@ -309,13 +351,18 @@ local path and that path is steered, exactly as an idle turn would hand it over.
309
351
 
310
352
  What each kind of attachment becomes inside a running turn:
311
353
 
312
- | Sent | Inside the turn |
313
- |---|---|
314
- | voice note, audio file, audio sent as a document | transcript, echoed as `🎤 …` before the steer |
315
- | small text file (`.md`, `.json`, `.csv`, `.py`, `.log`, … up to 60 KB) | the content itself between `<file>` markers — no tool call needed |
316
- | PDF, archive, binary, anything bigger | its local path under `~/.dsh/tg-bridge/inbox/` |
317
- | video, video note, animation | its path; the agent can pull frames or sound out with ffmpeg |
318
- | photo | its path plus one honest line; the turn reads it with `read_image`, and says so in one line if it cannot |
354
+ | Sent | Inside the turn | Needs |
355
+ |---|---|---|
356
+ | voice note, audio file, audio sent as a document | transcript, echoed as `🎤 …` before the steer | `faster-whisper` on `PATH`, enabled with `init --voice`; **off by default** |
357
+ | small text file (`.md`, `.json`, `.csv`, `.py`, `.log`, … up to 60 KB) | the content itself between `<file>` markers — no tool call needed | nothing |
358
+ | PDF, archive, binary, anything bigger | its local path under `~/.dsh/tg-bridge/inbox/` | nothing; the agent opens it with its own tools |
359
+ | video, video note, animation | its path; the agent can pull frames or sound out with ffmpeg | ffmpeg, only if frames or audio are needed |
360
+ | photo | its path plus one honest line; the turn reads it with `read_image`, and says so in one line if it cannot | a model that accepts images |
361
+
362
+ Voice is the one row with a hidden prerequisite. Without `faster-whisper`
363
+ installed, a voice note still arrives — as a path the agent cannot read — so the
364
+ bridge says transcription is off instead of pretending it heard something. Run
365
+ `dsh-tg init --voice` after installing the transcriber; nothing else changes.
319
366
 
320
367
  A caption does not turn the attachment into a text-only message: it is folded into the same
321
368
  hand-over, so "why did this fail" plus a `.log` file arrives as one steer.
@@ -431,6 +478,52 @@ profile's first turn. The binding is per topic: `/model` then edits that profile
431
478
  has with the `dsh-plugin` keyword — the desktop app's plugin browser, from the chat. Each result
432
479
  carries a plus button that runs `/plugins add <name>`.
433
480
 
481
+ ### The directory a topic writes in
482
+
483
+ `/cd my-app` does two things, and they are worth separating because they used to
484
+ be one: the turn runs *in* that directory, and the sandbox *stops* at it. The
485
+ second half only works on a profile that has a permission table — the bridge
486
+ writes the row only when one exists, and never invents one for a profile that
487
+ opted out.
488
+
489
+ ```
490
+ /cd my-app bind the topic: run here, and write only here
491
+ /cd ~/Projects/api wide run here, but do not narrow the sandbox
492
+ /cd reset unbind; the topic goes back to config.cwd
493
+ /cd what this topic is bound to, and how
494
+ ```
495
+
496
+ | Sandbox mode | Writes inside the root | Writes outside the root |
497
+ |---|---|---|
498
+ | `read-only` | denied | denied |
499
+ | `workspace-write` | allowed | denied |
500
+ | `danger-full-access` | allowed | allowed |
501
+
502
+ `workspaceRoot` is the boundary, and it holds even when the turn switches its own
503
+ working directory: the refusal follows the configured root, not the directory the
504
+ agent moved to. That is the point — a model that wanders into another project
505
+ gets a refusal instead of a write.
506
+
507
+ Three things this table does **not** say, because measurement disagreed with the
508
+ obvious reading:
509
+
510
+ - the sandbox row alone changes nothing. `mode: read-only` in the
511
+ `sandbox-policy` row plus `defaultPreset: danger-full-access` in the permission
512
+ table still wrote outside the root. The permission table wins; the sandbox row
513
+ is a default for a profile that has no table.
514
+ - `danger-full-access` therefore has to be chosen on purpose, per topic
515
+ (`/permissions danger-full-access`), and it is the only mode that reaches
516
+ outside the root.
517
+ - a preset with `approval: ask` cannot be used from a chat at all: a headless
518
+ turn has no approval channel, so the escalation fails closed and the turn
519
+ errors. `/permissions` lists such a preset with the reason instead of letting
520
+ someone pick a trap.
521
+
522
+ Stock installs are not permission-enabled: `cordis.patch.yml` ships with the
523
+ `tg-bridge` plugin row only, so `/cd` binds the directory and `/permissions`
524
+ edits the profile-wide preset, exactly as before. The per-topic behaviour starts
525
+ the first time a profile gains a permission table.
526
+
434
527
  ### Goals and tasks
435
528
 
436
529
  A topic carries its own goal and checklist, so the aim survives `/new`, a
@@ -464,6 +557,7 @@ no lock race and no lost update.
464
557
  ## Documentation
465
558
 
466
559
  - [docs/TELEGRAM-SETUP.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/TELEGRAM-SETUP.md): BotFather settings, group and bot permissions
560
+ - [docs/SUPPORT.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/SUPPORT.md): what to send with a bug report, what never to send, and the one-line answer for "the bot went silent"
467
561
  - [docs/ROADMAP.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/ROADMAP.md): what comes next
468
562
  - [docs/UX-ANALYSIS.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/UX-ANALYSIS.md): interactive UX review
469
563
  - [docs/COST.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/COST.md): what one turn costs and how to reduce it
package/aset-profile.mjs CHANGED
@@ -16,7 +16,8 @@ import { createHash } from 'node:crypto';
16
16
  import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
17
17
  import { homedir } from 'node:os';
18
18
  import { join } from 'node:path';
19
- import { setAgentPreset, setModel, setPermissionPreset, setSubagents } from './patch-rows.mjs';
19
+ import { setAgentPreset, setModel, setSubagents } from './patch-rows.mjs';
20
+ import { sandboxModeOf, setPermission } from './permission-rows.mjs';
20
21
 
21
22
  const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh');
22
23
  const PROFILES = join(DSH_HOME, 'profiles');
@@ -25,7 +26,7 @@ const PROFILES = join(DSH_HOME, 'profiles');
25
26
  export const DERIVED_PREFIX = 'aset-';
26
27
 
27
28
  /** `aset-` + 10 hex: short enough for a DSH profile name, long enough to collide never. */
28
- export function derivedName(base, set) {
29
+ export function derivedName(base, set, workspace = '') {
29
30
  const material = JSON.stringify([
30
31
  base,
31
32
  set?.name || '',
@@ -33,6 +34,11 @@ export function derivedName(base, set) {
33
34
  set?.effort || '',
34
35
  set?.permissions || '',
35
36
  set?.dshPreset || '',
37
+ // The bound directory belongs in the name: a topic moved with `/cd` must not
38
+ // keep a profile whose workspaceRoot points at the project it left. It is a
39
+ // separate argument, not a set field, because a set is shared between topics
40
+ // and the workspace is not.
41
+ String(workspace || ''),
36
42
  set?.agents || null,
37
43
  set?.toolFilter || null,
38
44
  ]);
@@ -44,14 +50,30 @@ export function derivedName(base, set) {
44
50
  * A field that already matches the base is skipped, so the copy differs from
45
51
  * the base only where the set differs — otherwise every generated profile
46
52
  * would pin today's model forever.
53
+ *
54
+ * The workspace is the exception: a bound topic states its own boundary even
55
+ * when the base happens to name the same directory, because inheriting one is
56
+ * how a later edit to the base quietly widens a topic that never asked.
47
57
  */
48
- export function overlayPatch(basePatch, set, base = {}) {
58
+ export function overlayPatch(basePatch, set, base = {}, workspace = '') {
49
59
  const source = String(basePatch ?? '');
50
60
  let next = source;
51
61
  const model = String(set?.model || '').trim();
52
62
  if (model && model !== base.model) next = setModel(next, model, String(set?.provider || '').trim());
53
63
  const permissions = String(set?.permissions || '').trim();
54
- if (permissions && permissions !== base.permissions) next = setPermissionPreset(next, permissions);
64
+ const bound = String(workspace || '').trim();
65
+ // Both permission rows are written together (see `permission-rows.mjs`): the
66
+ // preset that is chosen and the sandbox mode it stands for. A profile that
67
+ // moves one and not the other describes a policy it does not run.
68
+ const presetId = (permissions && permissions !== base.permissions) ? permissions : '';
69
+ if (presetId || bound) {
70
+ const wanted = presetId || base.permissions || '';
71
+ next = setPermission(next, {
72
+ preset: wanted,
73
+ sandbox: sandboxModeOf(next, wanted),
74
+ workspaceRoot: bound,
75
+ });
76
+ }
55
77
  const preset = String(set?.dshPreset || '').trim();
56
78
  if (preset && preset !== base.preset) next = setAgentPreset(next, preset);
57
79
  if (set?.agents && typeof set.agents === 'object') next = setSubagents(next, set.agents);
@@ -62,16 +84,23 @@ export function overlayPatch(basePatch, set, base = {}) {
62
84
  * Build `<base>`'s copy for `set` and return the profile name to run under.
63
85
  * Returns '' when there is nothing to materialise (the set changes nothing a
64
86
  * profile owns) or when the base profile is missing.
87
+ *
88
+ * `workspace` is the topic's bound directory, if any: it becomes this profile's
89
+ * `workspaceRoot`, which is what makes the host sandbox — not a prompt — the
90
+ * thing that stops a turn at the project's edge.
65
91
  */
66
- export function materialiseProfile(set, base, { profiles = PROFILES } = {}) {
67
- if (!set || !base) return '';
92
+ export function materialiseProfile(set, base, { profiles = PROFILES, workspace = '' } = {}) {
93
+ // A topic may be bound to a directory without being bound to a set: `/cd` is
94
+ // the common case and it still needs a profile of its own, or the boundary is
95
+ // whatever the base says.
96
+ if (!base || (!set && !workspace)) return '';
68
97
  const baseDir = join(profiles, base);
69
98
  const basePatchPath = join(baseDir, 'cordis.patch.yml');
70
99
  if (!existsSync(basePatchPath)) return '';
71
100
  const basePatch = readFileSync(basePatchPath, 'utf8');
72
- const { patch, changed } = overlayPatch(basePatch, set, baseRowOf(basePatch));
101
+ const { patch, changed } = overlayPatch(basePatch, set, baseRowOf(basePatch), workspace);
73
102
  if (!changed) return '';
74
- const name = derivedName(base, set);
103
+ const name = derivedName(base, set, workspace);
75
104
  const dir = join(profiles, name);
76
105
  if (existsSync(join(dir, 'cordis.patch.yml'))) return name;
77
106
  mkdirSync(dir, { recursive: true });
package/callbacks.mjs CHANGED
@@ -3,6 +3,7 @@
3
3
  // update or an approval, and only one handler may claim it.
4
4
  import { AgentsetStore } from './agentsets.mjs';
5
5
  import { CONTROL_COMMANDS, handleControl, reasoningOf } from './control.mjs';
6
+ import { isFallbackPress, pressTarget } from './fallback-card.mjs';
6
7
  import { progressOf, toggleTask } from './goals.mjs';
7
8
  import { handleMessage } from './handle-message.mjs';
8
9
  import { resolveLang, t } from './i18n.mjs';
@@ -14,7 +15,7 @@ import { answerRewindPress, cutSession, isRewindPress } from './rewind-buttons.m
14
15
  import { applyRewind, newestBackup, restoreBackup } from './rewind.mjs';
15
16
  import { runCommandFromButton } from './run-command.mjs';
16
17
  import { commandFor, renderSettingsCard, settingsCurrent } from './settings-card.mjs';
17
- import { config, done, log, saveState, state } from './state.mjs';
18
+ import { config, done, log, saveConfig, saveState, state } from './state.mjs';
18
19
  import { inlineKeyboard, send, sendFile, tg } from './telegram.mjs';
19
20
  import { sessionFile } from './thoughts.mjs';
20
21
  import { activeTurns, killTurn, profileOf } from './turn.mjs';
@@ -152,6 +153,27 @@ export async function handleCallback(query) {
152
153
  return;
153
154
  }
154
155
 
156
+ // A button on the failover card. Every press becomes the verb of `/fallback`,
157
+ // so a tap and a typed line land in the same code — and the command redraws the
158
+ // card, which is why the old keyboard is trimmed only when the press leaves it.
159
+ if (isFallbackPress(data)) {
160
+ const target = pressTarget(data);
161
+ const words = { t: 'toggle', u: 'up', d: 'down', x: 'test', e: 'chain', s: 'show' };
162
+ // `r` is two verbs on one letter: with a number it removes that route, alone
163
+ // it opens the remove list. Anything else is a stale card and does nothing.
164
+ const verb = target && (target.verb === 'r' ? (target.n ? 'remove' : 'menu') : words[target.verb]);
165
+ if (!verb) {
166
+ await answer(t(lang, 'bridge.cb.unknown'));
167
+ return;
168
+ }
169
+ const typed = target.n && verb !== 'menu' ? `/fallback ${verb} ${target.n}` : `/fallback ${verb}`;
170
+ await clearKeyboard();
171
+ await answer(typed);
172
+ log(`fallback press ${typed} for ${key}`);
173
+ await runCommandFromButton(typed, { chatId, threadId, key, lang });
174
+ return;
175
+ }
176
+
155
177
  if (isMenuPress(data)) {
156
178
  // The panel is a set of cards: the hub, then one page per section. Moving
157
179
  // between them edits this message, so browsing costs no new messages. A
@@ -349,6 +371,9 @@ export async function handleCardPress(query, ctx) {
349
371
  config,
350
372
  activeTurns,
351
373
  saveState,
374
+ // `/fallback` writes config.json; without this the press would look applied
375
+ // and vanish on restart, which is the worst of both answers.
376
+ saveConfig,
352
377
  log,
353
378
  send: (text) => {
354
379
  replies.push(String(text ?? ''));
@@ -10,9 +10,9 @@ export const CONTROL_COMMANDS = [
10
10
  'status', 'models', 'model', 'effort', 'profile', 'agents', 'preset', 'permissions', 'plan',
11
11
  'jobs', 'remind', 'sessions', 'resume', 'plugins', 'plugin',
12
12
  'skills', 'soul', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
13
- 'prices', 'help', 'doctor', 'logs', 'lang', 'reasoning', 'goal', 'task', 'tasks',
13
+ 'prices', 'help', 'doctor', 'logs', 'report', 'lang', 'reasoning', 'goal', 'task', 'tasks',
14
14
  'thoughts', 'version', 'update', 'crew', 'agentset', 'subscribe', 'settings',
15
- 'rewind', 'fork', 'branches', 'menu',
15
+ 'rewind', 'fork', 'branches', 'menu', 'fallback',
16
16
  ];
17
17
 
18
18
  /**
@@ -16,6 +16,7 @@
16
16
  "plainText": false,
17
17
  "servers": {},
18
18
  "fallbackModels": [],
19
+ "fallbackEnabled": true,
19
20
  "voice": {
20
21
  "enabled": false,
21
22
  "python": "",
@@ -0,0 +1,69 @@
1
+ // Where `/cd` points, decided without touching a real filesystem.
2
+ //
3
+ // The old resolver tested `existsSync` and stopped there: a path to a FILE was
4
+ // "bound" and every later turn spawned with a file as its working directory,
5
+ // which fails inside the CLI with an error nobody can read. A missing path was
6
+ // reported as "no such directory" using the raw input rather than the path it
7
+ // actually tried.
8
+ //
9
+ // Pure on purpose: `probe` is the only filesystem question, so the table of
10
+ // cases below is a test, not a story about a machine.
11
+ import { isAbsolute, join, normalize, resolve } from 'node:path';
12
+
13
+ /** How a topic path was understood — the reply says which, so nobody guesses. */
14
+ export const CD_KIND = {
15
+ ABSOLUTE: 'absolute',
16
+ HOME: 'home',
17
+ PROJECT: 'project',
18
+ RELATIVE: 'relative',
19
+ };
20
+
21
+ /** `C:\x`, `C:/x`, `\\server\share`, `/x` — anything the platform calls absolute. */
22
+ function looksAbsolute(input) {
23
+ return /^[A-Za-z]:[\\/]/.test(input) || /^\\\\/.test(input) || input.startsWith('/') || isAbsolute(input);
24
+ }
25
+
26
+ /**
27
+ * Turn what a person typed into the directory a turn should run in.
28
+ *
29
+ * Order matters and is the whole point: an absolute path is never re-interpreted
30
+ * as a project name, and a bare word is never treated as a relative path from
31
+ * the bridge's own directory — `my-app` means `<projectsDir>/my-app`, because
32
+ * that is what a person means when they type it.
33
+ *
34
+ * @param {string} input what followed `/cd`
35
+ * @param {object} ctx
36
+ * @param {string} ctx.home the user's home directory
37
+ * @param {string} ctx.projectsDir where bare names are looked up
38
+ * @param {string} ctx.configCwd directory a relative path resolves against
39
+ * @param {(path: string) => 'dir'|'file'|'none'} ctx.probe
40
+ * @returns {{path: string, kind: string} | {error: 'empty'|'none'|'notdir', path: string, kind: string}}
41
+ */
42
+ export function resolveCd(input, { home, projectsDir, configCwd, probe }) {
43
+ const raw = String(input ?? '').trim().replace(/^["']|["']$/g, '').trim();
44
+ if (!raw) return { error: 'empty', path: '', kind: '' };
45
+
46
+ let candidate = raw;
47
+ let kind = CD_KIND.ABSOLUTE;
48
+ if (raw === '~' || raw.startsWith('~/') || raw.startsWith('~\\')) {
49
+ kind = CD_KIND.HOME;
50
+ candidate = join(home, raw.slice(1));
51
+ } else if (looksAbsolute(raw)) {
52
+ kind = CD_KIND.ABSOLUTE;
53
+ } else if (raw.includes('/') || raw.includes('\\')) {
54
+ // A relative path with a separator is a path, not a project name.
55
+ kind = CD_KIND.RELATIVE;
56
+ candidate = resolve(configCwd || home, raw);
57
+ } else {
58
+ kind = CD_KIND.PROJECT;
59
+ candidate = join(projectsDir, raw);
60
+ }
61
+
62
+ const path = normalize(candidate);
63
+ const found = probe(path);
64
+ // A file is not a working directory. Saying "no such directory" about a file
65
+ // that is plainly there is the reply that turned this into a bug report.
66
+ if (found === 'file') return { error: 'notdir', path, kind };
67
+ if (found !== 'dir') return { error: 'none', path, kind };
68
+ return { path, kind };
69
+ }
@@ -11,6 +11,7 @@ import { t, LANGS, normalizeLang } from '../i18n.mjs';
11
11
  import { addTask, clearGoal, doneTask, editTask, finishGoal, goalOf, progressOf, reopenGoal, removeTask, setGoal } from '../goals.mjs';
12
12
  import { lastTurnReasoning, lastTurnReasoningSteps, lastTurnText, reasoningMarkdown, sessionFile, sessionReasoningSteps, sessionStats } from '../thoughts.mjs';
13
13
  import { parseAgentPresets, parseModelSelection, parsePermissionPresets, parseReasoningEfforts, parseSubagentFleet, parseSubagentRows } from '../agents.mjs';
14
+ import { effectivePreset, setPermission } from '../permission-rows.mjs';
14
15
  import { setRowConfig, unsetRowConfig } from '../profile-edit.mjs';
15
16
  import { parseReminder, stampAt, upcoming } from '../reminders.mjs';
16
17
  import { AgentsetStore, emptySet, slugId } from '../agentsets.mjs';
@@ -254,46 +255,74 @@ export async function handleAgentCommands(ctx) {
254
255
  }
255
256
  case '/permissions': {
256
257
  // Sandbox and approval policy decide what a turn may touch. The desktop
257
- // shows them as a preset picker; here they are a profile row, so the
258
- // switch is honest about being profile-wide: every topic on this profile
259
- // changes with it.
260
- const table = parsePermissionPresets(read(patchPath(activeProfile)));
258
+ // shows them as a preset picker; here they are two profile rows, and the
259
+ // *effective* preset is what `defaultPreset` names — not the first row of
260
+ // the table, which happens to agree only because nobody edits by hand.
261
+ //
262
+ // A topic bound to an agent set already runs under a profile of its own
263
+ // (`aset-profile.mjs`), so there the choice belongs to the set: it moves
264
+ // this topic and leaves every other topic where it was. An unbound topic
265
+ // has no such profile, so the write is profile-wide — and says so.
266
+ const boundId = state.agentsets?.[key] || '';
267
+ const boundSet = boundId ? agentset().get(boundId) : null;
268
+ const text = read(patchPath(activeProfile));
269
+ const table = parsePermissionPresets(text);
261
270
  if (!table) {
262
271
  say(t(lang, 'ctrl.perm.none', { name: activeProfile }));
263
272
  return true;
264
273
  }
274
+ const current = effectivePreset(text);
275
+ const currentId = boundSet
276
+ ? String(boundSet.permissions || current?.id || '')
277
+ : current?.from === 'unknown' ? '' : current?.id || '';
265
278
  const wanted = String(arg || '').trim();
266
279
  if (!wanted) {
267
- const lines = [
268
- t(lang, 'ctrl.perm.title', { name: activeProfile }),
269
- table.current
270
- ? t(lang, 'ctrl.perm.current', { name: table.current })
271
- : t(lang, 'ctrl.perm.noCurrent'),
272
- ];
280
+ const lines = [t(lang, 'ctrl.perm.title', { name: activeProfile })];
281
+ if (boundSet) lines.push(t(lang, 'ctrl.perm.topicTitle', { name: boundSet.name || boundSet.id }));
282
+ if (currentId) lines.push(t(lang, 'ctrl.perm.current', { name: currentId }));
283
+ else if (current?.from === 'unknown') lines.push(t(lang, 'ctrl.perm.broken', { name: current.id }));
284
+ else lines.push(t(lang, 'ctrl.perm.noCurrent'));
273
285
  for (const preset of table.presets) {
274
- const mark = preset.id === table.current ? '*' : ' ';
275
- lines.push(` ${mark} ${preset.id}${preset.sandbox ? ` — ${preset.sandbox}, ${preset.approval || '?'}` : ''}`);
286
+ const mark = preset.id === currentId ? '*' : ' ';
287
+ // A chat has no approval channel: `ask` fails closed at spawn, so the
288
+ // preset is listed with the reason instead of looking selectable.
289
+ const note = preset.approval === 'ask' ? t(lang, 'ctrl.perm.needsApproval') : '';
290
+ lines.push(` ${mark} ${preset.id}${preset.sandbox ? ` — ${preset.sandbox}, ${preset.approval || '?'}` : ''}${note}`);
276
291
  }
277
292
  if (table.presets.length === 0) lines.push(t(lang, 'ctrl.perm.noPresets'));
278
- lines.push(t(lang, 'ctrl.perm.hint'));
293
+ lines.push(t(lang, boundSet ? 'ctrl.perm.hintTopic' : 'ctrl.perm.hint'));
279
294
  say(lines.join('\n'));
280
295
  return true;
281
296
  }
282
- if (!table.presets.some((preset) => preset.id === wanted)) {
297
+ const chosen = table.presets.find((preset) => preset.id === wanted);
298
+ if (!chosen) {
283
299
  say(t(lang, 'ctrl.perm.unknown', {
284
300
  name: wanted,
285
301
  list: table.presets.map((preset) => preset.id).join(', '),
286
302
  }));
287
303
  return true;
288
304
  }
289
- if (wanted === table.current) {
305
+ if (chosen.approval === 'ask') {
306
+ say(t(lang, 'ctrl.perm.cannotAsk', { name: wanted }));
307
+ return true;
308
+ }
309
+ if (wanted === currentId) {
290
310
  say(t(lang, 'ctrl.perm.already', { name: wanted }));
291
311
  return true;
292
312
  }
293
- const next = setRowConfig(read(patchPath(activeProfile)), {
294
- pkg: '@deepseek-ai/dsh-permission-presets', path: ['defaultPreset'], value: wanted,
295
- });
296
- if (!next) { say(t(lang, 'ctrl.perm.already', { name: wanted })); return true; }
313
+ if (boundSet) {
314
+ const result = agentset().put({ ...boundSet, permissions: wanted });
315
+ if (!result.ok) {
316
+ say(t(lang, 'ctrl.set.failed', { error: result.error || '?' }));
317
+ return true;
318
+ }
319
+ ctx.saveState();
320
+ say(t(lang, 'ctrl.perm.setTopic', { name: wanted, set: boundSet.name || boundSet.id }));
321
+ return true;
322
+ }
323
+ // One writer for both rows: the preset and the sandbox mode it stands for.
324
+ const next = setPermission(text, { preset: wanted });
325
+ if (!next || next === text) { say(t(lang, 'ctrl.perm.already', { name: wanted })); return true; }
297
326
  writePatch(activeProfile, next);
298
327
  say(t(lang, 'ctrl.perm.set', { name: wanted, profile: activeProfile }));
299
328
  return true;
@@ -19,12 +19,13 @@ import { applyFork, planFork, planRewind } from '../rewind.mjs';
19
19
  import { cutSession, isRewindPress } from '../rewind-buttons.mjs';
20
20
  import { renderRewindCard, renderRewindUsage } from '../rewind-card.mjs';
21
21
  import { MENU_GROUPS, commandForName, renderPanel, replyKeyboard } from '../menu-card.mjs';
22
+ import { chainSummary } from '../fallback-card.mjs';
22
23
  import { explainCommand } from '../help-explain.mjs';
23
24
  import { profileValues, resolveSettings } from '../settings.mjs';
24
25
  import { UPDATE_DEFAULTS, describeUpdate, modeChange, updateState } from '../update-policy.mjs';
25
26
  import { isNewer, pluginInfo, rowLine, searchPlugins } from '../plugin-search.mjs';
26
27
  import { COMMAND_ALIASES, CONTROL_COMMANDS, DOCUMENTED_COMMANDS } from '../commands-registry.mjs';
27
- import { APP, CLI_JS, DSH_CMD, DSH_HOME, EXE, HOME, PROFILES, THOUGHT_DIR } from '../paths.mjs';
28
+ import { APP, CLI_JS, DSH_CMD, DSH_HOME, DIR, EXE, HOME, LOG, PROFILES, THOUGHT_DIR } from '../paths.mjs';
28
29
  import { read, readJson, patchPath, pkgPath, OVERLAY_MARK, modelsOf, modelOf, windowOf, modelIndent, depthOf, modelsReport, setModel, disabledIds, setDisabled, writePatch } from './models.mjs';
29
30
  import { listPids, waitForExit, waitForStart, pluginsOf, bundleRowIds, addBundle, removeBundle, createProfile, dshPlugin } from './plugins.mjs';
30
31
  import { cwdSlug, bareId, stamp, recentSessions, sessionTitle } from './sessions.mjs';
@@ -32,6 +33,8 @@ import { agentsOf, fleetOf, patchRows, skillsOf, AGENTS, PERSONA_HEADING, soulOf
32
33
  import { fmt, AGENTSETS, agentset, agentsetOf, profileRowOf, bindAgentset, agentsetCard, agentsetKeyboard } from './agentsets.mjs';
33
34
  import { taskKeyboard, goalView, taskView, reasoningOf, filterLogLines } from './tasks.mjs';
34
35
  import { updatePolicy, bridgeRoot, copyRelease, installRelease, bridgeVersion, newestModuleMtime, npmLatest, npmLatestAsync } from './release.mjs';
36
+ import { buildReport, tailOf, writeReport } from '../report.mjs';
37
+ import { effectivePreset } from '../permission-rows.mjs';
35
38
 
36
39
  /**
37
40
  * Which bridge is running, which one npm has, and whether this install can
@@ -63,7 +66,7 @@ function versionCard(lang) {
63
66
  }
64
67
 
65
68
  export async function handleBridgeCommands(ctx) {
66
- const { command, arg, send, reply, log, profile, state, key, config, lang: rawLang, saveState } = ctx;
69
+ const { command, arg, send, reply, log, profile, state, key, config, chatId, threadId, lang: rawLang, saveState } = ctx;
67
70
  // The topic's language, then the config default, then English. Never Russian:
68
71
  // a group that has no opinion still must not guess a language.
69
72
  const lang = normalizeLang(rawLang) || normalizeLang(config?.lang) || 'en';
@@ -330,6 +333,50 @@ export async function handleBridgeCommands(ctx) {
330
333
  say(versionCard(lang) + '\n\n' + describeUpdate(updateState({ installed, latest, mode: policy.mode, notified: policy.notified })));
331
334
  return true;
332
335
  }
336
+ case '/report': {
337
+ // A bug report assembled from what the bridge already knows, so "it broke"
338
+ // does not need five follow-up questions. It is redacted before it leaves
339
+ // (`report.mjs`), and it goes to the owner's own id: in a group the answer
340
+ // is the path on this machine, because the log tail is not group material.
341
+ const owner = Number(config.allowedUserIds?.[0]) || 0;
342
+ const toOwner = Boolean(owner) && Number(chatId) === owner && !Number(threadId);
343
+ const patchText = read(patchPath(activeProfile));
344
+ const preset = effectivePreset(patchText)?.id || '';
345
+ // The same renderer the card uses: a report that counted routes a turn
346
+ // would skip is the report that hides the bug it was opened for.
347
+ const entries = Array.isArray(config.fallbackModels) ? config.fallbackModels : [];
348
+ const chain = chainSummary(entries, { t: (k, v) => t(lang, k, v) });
349
+ const failure = state.lastFailure?.[key]?.error || '';
350
+ const text = buildReport({
351
+ version: bridgeVersion(),
352
+ profile: activeProfile,
353
+ preset,
354
+ model: modelOf(activeProfile).model,
355
+ chain,
356
+ cwd: state.cwd?.[key] || config.cwd || '',
357
+ failure,
358
+ log: tailOf(LOG, 120),
359
+ home: HOME,
360
+ ids: [chatId, threadId, ...(config.allowedUserIds || [])],
361
+ note: String(arg || '').trim(),
362
+ });
363
+ const path = writeReport(text, join(DIR, 'reports'));
364
+ if (!path) {
365
+ say(t(lang, 'ctrl.report.failed'));
366
+ return true;
367
+ }
368
+ if (toOwner && ctx.sendFile) {
369
+ try {
370
+ await ctx.sendFile(path, t(lang, 'ctrl.report.caption', { v: bridgeVersion() || '?' }));
371
+ return true;
372
+ } catch (error) {
373
+ say(t(lang, 'ctrl.report.sendFailed', { err: error.message, path }));
374
+ return true;
375
+ }
376
+ }
377
+ say(t(lang, 'ctrl.report.pathOnly', { path }));
378
+ return true;
379
+ }
333
380
  default:
334
381
  return false;
335
382
  }