@thready-web/dsh-bot-plugin 0.1.0-beta.2 → 0.1.0-beta.4

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
@@ -9,7 +9,7 @@ Cordis plugin for the DSH bot. `@thready-web/dsh-bot` is the launcher that start
9
9
  | `@thready-web/dsh-bot-plugin/router` | Hash routing for the official web client |
10
10
  | `@thready-web/dsh-bot-plugin/cli` | Admin commands. The `dsh-bot` binary calls this. |
11
11
 
12
- Prompts, tool descriptions, and API messages are English. A stored persona may still start with a legacy CJK name label. New persona text uses `Name:`, `Style:`, and `Task:`. The workbench defaults to English. The language control switches the whole UI through the message catalog in `ui/src/i18n.ts`.
12
+ Prompts, tool descriptions, and API messages are English. A stored persona may still start with a legacy CJK name label. New persona text uses `Name:`, `Style:`, and `Task:`. The workbench defaults to English. The language control switches the whole UI through the message catalog in `ui/src/i18n/`.
13
13
 
14
14
  ```bash
15
15
  npm install
@@ -37,6 +37,114 @@ In `cordis.patch.yml` every new entry must be wrapped in `- insert:`:
37
37
 
38
38
  Start the host with `dsh --profile <name> --host 127.0.0.1 --port <port> --no-open` after the patch lists these entries. The official client is `/`. The workbench is `/dsh-bot/`. From the `dsh-plugins` repository, `npx dsh-bot` writes that patch and starts the process.
39
39
 
40
+ ## Main-session budget
41
+
42
+ A bot main session may do the work itself (bash, write, ...) or hand it to a worker with `foundations_dispatch`. The host keeps a runaway guard on each main turn:
43
+
44
+ | Field | Default | Meaning |
45
+ | --- | --- | --- |
46
+ | `chatMaxSteps` / `chatWallMs` | 80 / 30 min | Cap for every main turn |
47
+ | `mainMaxSteps` / `mainWallMs` | 80 / 30 min | Cap after a dispatch or a host tool. It can only tighten the chat cap; with the defaults it changes nothing. Set it lower to push long work onto workers. |
48
+
49
+ - The step cap is checked in `agent/pre-step`: the next step is refused and the turn ends `blocked`. A step that already ended is never cancelled, so a turn whose last step answered the user ends `completed`.
50
+ - The wall cap stops a still-running step with `agent.cancel({ kind: 'hook', reason: 'main-budget:wall' })`. Host cancels never use `{ kind: 'user' }` (worker caps use `worker-budget:*`, ticket cancels `ticket-cancel`).
51
+ - Each trip is written to stderr (`session-foundations: main budget main-budget:steps session=… turn=… steps=…`) and posts one `[foundations:budget]` next-turn message. The model then tells the user the turn was cut off and may dispatch the rest to a worker. Set `budgetNotice: false` to skip the message.
52
+
53
+ Override in the patch (`config.work`) or with the `DSH_BOT_WORK_BUDGET` environment variable (the launcher's `--work-budget`). Config wins over the environment. Both accept `steps` / `wall` shorthands and duration strings:
54
+
55
+ ```yaml
56
+ - insert:
57
+ - id: session-foundations
58
+ name: "@thready-web/dsh-bot-plugin"
59
+ config:
60
+ work: { steps: 120, wall: 45m }
61
+ ```
62
+
63
+ ```bash
64
+ DSH_BOT_WORK_BUDGET='steps=120,wall=45m,mainMaxSteps=10'
65
+ ```
66
+
67
+ ## Worker slots and queue
68
+
69
+ Each bot may run more than one worker at a time. These four fields are formal budget keys, not source-only constants. They reach the scheduler through the same path as the main-session caps: plugin `config.work`, then `DSH_BOT_WORK_BUDGET` (the launcher `--work-budget`), then the defaults below.
70
+
71
+ | Field | Default | Max | Meaning |
72
+ | --- | --- | --- | --- |
73
+ | `perBot` / `global` | 2 / 4 | 64 | Running slots: `enqueued`, `started`, or a reserved start. A ticket in `needs_user` does not occupy a slot unless a resume has already reserved one. |
74
+ | `perBotQueue` / `globalQueue` | 8 / 16 | 256 | Accepted tickets waiting for a slot. When both the slot cap and the matching queue cap are full, `foundations_dispatch` returns `BUDGET` and inserts no row. |
75
+
76
+ `perBot` and `perBotQueue` must be positive integers. Values that are missing, zero, negative, non-integer, infinite, or unknown are ignored and the default is kept — a typo never raises a cap to infinity. Values above the max are clamped to the max and logged. If `perBot` is greater than `global`, the effective running cap for one bot is `min(perBot, global)`. The same rule applies to the queue caps. The configured numbers are kept as written; only admission uses the effective minimum, and startup logs it.
77
+
78
+ Limits are read when the work runtime is created (process start or plugin load). They are not hot-reloaded into a process that is already running. After a restart with a lower cap, workers that are already running are not cancelled; later `foundations_dispatch` and queue promotion use the new caps.
79
+
80
+ When a running ticket completes, fails, is cancelled, or parks in `needs_user`, the oldest waiting ticket that still fits the caps starts automatically (global FIFO by `created_at`, then insertion order). First-phase scheduling is not a weighted fair share across bots.
81
+
82
+ Parked `needs_user` tickets still count toward the combined unfinished cap (`slots + queue`), so they cannot grow without bound or block every new dispatch by filling running slots. Idempotent dispatch of the same owner and key replays the existing ticket.
83
+
84
+ Workers share the owner's workspace. There is no filesystem isolation; briefings should state file boundaries, or dependent work should stay serial.
85
+
86
+ Workers use the `foundations-files` preset: official file tools plus official `@deepseek-ai/dsh-tool-bash` and `@deepseek-ai/dsh-tool-jobs`. The host sandbox stays `workspace-write` with the existing approval policy. This does not mount the web preset, add writable roots, or switch the sandbox to `danger-full-access`. A reserved start that does not create a worker within `min(ticket wallMs, 10m)` fails with `reserve-wall` and frees the slot; a late `createChild` is cancelled instead of attached.
87
+
88
+ Runnable examples (any one of these is enough; `config.work` wins over the environment):
89
+
90
+ ```yaml
91
+ # DSH patch, under the session-foundations plugin
92
+ - insert:
93
+ - id: session-foundations
94
+ name: "@thready-web/dsh-bot-plugin"
95
+ config:
96
+ work:
97
+ perBot: 3
98
+ global: 6
99
+ perBotQueue: 8
100
+ globalQueue: 16
101
+ ```
102
+
103
+ ```bash
104
+ # Environment the plugin reads directly
105
+ DSH_BOT_WORK_BUDGET='perBot=3,global=6,perBotQueue=8,globalQueue=16'
106
+
107
+ # Same text through the launcher (also accepts JSON)
108
+ dsh-bot start --work-budget perBot=3,global=6,perBotQueue=8,globalQueue=16
109
+ dsh-bot start --work-budget '{"perBot":1,"global":4}'
110
+ ```
111
+
112
+ `perBot` and `global` are already on the published launcher `--work-budget` allowlist. `perBotQueue` and `globalQueue` need a launcher that includes those keys; until then set the queue caps in `config.work` or `DSH_BOT_WORK_BUDGET` when starting `dsh` without the launcher flag.
113
+
114
+ ## Worker budget waiting
115
+
116
+ A granted worker token/runtime cap pauses admission at the official asynchronous `agent/pre-step` waterfall. The listener waits on an abortable promise; it does not cancel the turn, refuse it as failed, spawn a replacement or invoke a model. A request/tool batch already admitted can finish (and overshoot a quota); no subsequent model request or tool batch is admitted until a sufficient explicit `foundations_grant`.
117
+
118
+ The ticket retains its attempt, fencing token and child session. `budget_json.quota` durably records cumulative committed `usage.totalTokens`, deduplication sequence, active elapsed time, and requested/waiting phase. Active time includes finishing in-flight work until the safe boundary; suspended-boundary waiting time is excluded. Waiting is exempt from lease/enqueue expiry and has no hard-wall failure timer. It retains a worker slot to preserve capacity accounting; the main bot is not in this worker gate or slot pool and can always grant, deny or cancel. Explicit cancellation releases the slot normally.
119
+
120
+ A grant adds amounts, never resets usage, and must exceed both current token usage and active time. An insufficient grant leaves the gate closed without another noisy extension event; its response includes usage, required totals, minimum additional amounts and administrative headroom. Host token/active-wall ceilings are never increased: an unextendable worker stays paused with `host-ceiling` diagnostics until an explicit decision/cancellation. This is not automatic host approval or unlimited renewal.
121
+
122
+ Budget requests are urgent next-turn inbox notices, bypassing stale notice/user/delivery admission barriers without steering or interrupting the main turn. Admission is single-flight per owner and rechecks grant/cancellation races before persisting a notice. Ordinary progress retains its existing admission policy. The workbench labels suspended workers “Waiting for budget”.
123
+
124
+ A process restart cannot preserve an in-memory DSH turn: the durable wait survives and reconciliation alone does not dispatch a model or recreate a child. In the resident host, a sufficient explicit grant durably queues one continuation input into the existing child session, preserving the ticket/attempt/fence and reporting `continuation: same-session-new-turn`, not falsely claiming seamless same-turn resumption. Only this detached continuation advances the input/briefing generation, fencing old disposed turn-end replay from new results. A runtime without this host capability reports `awaiting-host-turn` and keeps expiry protection until a real host boundary; mere restoration never wakes a model. Restoring a ticket never revives a previously failed/cancelled ticket. No automatic workspace recovery is performed.
125
+
126
+ ## Session working directory
127
+
128
+ Workbench sessions start in `THREADY_SESSION_CWD` when set, otherwise in `<DSH_HOME>/workspace` (created on first use), never in `DSH_HOME` itself, which holds the owner token and profiles.
129
+
130
+ Generated raster previews can be embedded at `/dsh-bot/<project>/preview/<image>` or `/dsh-bot/<project>/artifacts/<image>`. These are deliberate artifact directories under that configured workspace, not a general file server or a per-session sharing boundary: authenticated workbench users can view their images. Only JPEG, PNG, GIF and WebP with matching signatures are served, with private/no-store caching. Dotfiles, traversal, symlink escapes, other workspace locations and active HTML/SVG are rejected. With no configured workspace this fallback is disabled. Relative Markdown image paths resolve under `/dsh-bot/`; existing absolute URLs remain unchanged.
131
+
132
+ Markdown images use bounded, aspect-preserving thumbnails. Click to open a viewport-fit dialog, then choose Original size to scroll through screenshot details. Escape, the close button or the backdrop dismisses it, restoring focus and body scrolling. Linked images expose their link separately from the preview control. Preview and unavailable-state labels follow the English/Chinese UI catalog.
133
+
134
+ A failed thumbnail or viewer image is removed and replaced with a neutral unavailable message and an explicit Retry image button; status/interaction polling does not retry it. Markdown renderer identities stay stable when file callbacks or streaming state change. Failure memory belongs to the current mounted session view (up to 128 URLs, each at most 4096 characters), not global state or browser storage; mounted images also retain local failure state. Session navigation/reload clears it. A cache-evicted image can be attempted again if later remounted. Nothing restores deleted workspace files or retains artifact copies.
135
+
136
+ Actions folds keep their initial view until the user toggles them. Streaming updates, new actions, live-to-durable event replacement and completion do not automatically open or close an existing fold. Text and question boundaries still separate action groups in transcript order.
137
+
138
+ ## Interaction synchronization
139
+
140
+ The workbench opts into `/dsh-bot/api/interactions?compact=1&sessionId=...`: official questions, tool approvals, authorization prompts/notices and active authorization flow keys, without enumerating providers. Requests without `compact=1` and `/api/authorization` keep their full catalog responses for older clients.
141
+
142
+ The existing authenticated `/api/live` SSE transport emits `interactions` only when the compact snapshot changes. Native services do not all expose reliable change events, so this is hybrid synchronization: an independent in-process one-second snapshot sampler (no provider listing), not pure native push. Desk RPC stalls do not block interaction delivery. Snapshot failures signal REST fallback without disconnecting the desk stream.
143
+
144
+ A visible connected view reconciles once on entry and every 60 seconds. Unsupported/disconnected streams use bounded 2–15-second backoff; pending questions, open tool approvals or authorization flows keep the fallback at 1.5 seconds. Requests are single-flight with a 10-second abort deadline; newer SSE state wins over late REST results. Session switches discard stale results. Hidden views pause reconciliation and close SSE; resume reconciles immediately and reconnects. These rules do not stop unrelated resource/status updates.
145
+
146
+ The authorization drawer loads the provider directory only on demand, with a per-App single-flight 30-second cache, no browser storage or cross-App cache. Local authorization lifecycle changes and mutations invalidate it. An open drawer revalidates every 30 seconds and on background resume: native provider registration has no complete event hook, so these changes are eventually reconciled rather than falsely treated as push-complete. Dynamic prompts/notices remain on the compact channel even when the drawer is closed.
147
+
40
148
  DSH loads `dist/`. Rebuild after changing `src/`. Until `npm --prefix ui run build` has run, `/dsh-bot/` is 404.
41
149
 
42
150
  Host integration needs Node `>= 24.9` and `DSH_BIN`:
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Official tool-permission answerer for the desk UI.
3
+ *
4
+ * `approval/request` is a distinct waterfall from user-questions. This
5
+ * listener is prepended so typtert `$events` cannot intercept first. The
6
+ * workbench claims every request it can show; anything it cannot identify
7
+ * fails closed as `unavailable`. There is no always-allow on this card.
8
+ */
9
+ import { toolError } from "./errors.js";
10
+ const answerers = new Map();
11
+ export function publishApprovalAnswerer(dataDir, answerer) {
12
+ if (answerer)
13
+ answerers.set(dataDir, answerer);
14
+ else
15
+ answerers.delete(dataDir);
16
+ }
17
+ export function approvalAnswererFor(dataDir) {
18
+ return answerers.get(dataDir) ?? null;
19
+ }
20
+ export function approvalSessionIdOf(agent) {
21
+ if (!agent || typeof agent !== 'object')
22
+ return '';
23
+ if (typeof agent.session === 'string' && agent.session !== '')
24
+ return agent.session;
25
+ if (typeof agent.id === 'string' && agent.id !== '')
26
+ return agent.id;
27
+ return '';
28
+ }
29
+ function textOf(value) {
30
+ return typeof value === 'string' ? value : '';
31
+ }
32
+ function displayReasonOf(value) {
33
+ if (!value || typeof value !== 'object')
34
+ return undefined;
35
+ const en = textOf(value.en);
36
+ if (en === '')
37
+ return undefined;
38
+ const display = { en };
39
+ for (const [locale, message] of Object.entries(value)) {
40
+ if (typeof message === 'string' && message !== '')
41
+ display[locale] = message;
42
+ }
43
+ return display;
44
+ }
45
+ export function createApprovalAnswerer() {
46
+ const pending = new Set();
47
+ const settled = [];
48
+ let nextId = 1;
49
+ function detach(entry) {
50
+ if (!pending.has(entry))
51
+ return false;
52
+ pending.delete(entry);
53
+ if (entry.onAbort && entry.request.signal) {
54
+ entry.request.signal.removeEventListener('abort', entry.onAbort);
55
+ }
56
+ return true;
57
+ }
58
+ function remember(entry, outcome) {
59
+ settled.unshift({
60
+ requestId: entry.requestId,
61
+ sessionId: entry.sessionId,
62
+ toolName: entry.toolName,
63
+ callId: entry.callId,
64
+ reason: textOf(entry.request.reason),
65
+ displayReason: displayReasonOf(entry.request.displayReason),
66
+ state: outcome,
67
+ });
68
+ if (settled.length > 50)
69
+ settled.length = 50;
70
+ }
71
+ async function handle(request, _next) {
72
+ const sessionId = approvalSessionIdOf(request.agent);
73
+ const toolName = textOf(request.toolName);
74
+ if (sessionId === '' || toolName === '')
75
+ return 'unavailable';
76
+ return new Promise(resolve => {
77
+ const callId = textOf(request.callId);
78
+ const entry = {
79
+ requestId: `approval-${nextId++}`,
80
+ request,
81
+ sessionId,
82
+ toolName,
83
+ callId: callId === '' ? undefined : callId,
84
+ resolve,
85
+ };
86
+ const onAbort = () => {
87
+ if (!detach(entry))
88
+ return;
89
+ remember(entry, 'cancelled');
90
+ resolve('cancelled');
91
+ };
92
+ entry.onAbort = onAbort;
93
+ pending.add(entry);
94
+ if (request.signal?.aborted) {
95
+ onAbort();
96
+ return;
97
+ }
98
+ request.signal?.addEventListener('abort', onAbort, { once: true });
99
+ });
100
+ }
101
+ function submit(input) {
102
+ if (typeof input.sessionId !== 'string' || input.sessionId === '') {
103
+ return toolError('VALIDATION', 'sessionId is required.');
104
+ }
105
+ if (typeof input.requestId !== 'string' || input.requestId === '') {
106
+ return toolError('VALIDATION', 'requestId is required.');
107
+ }
108
+ if (input.outcome !== 'allowed-once' && input.outcome !== 'rejected') {
109
+ return toolError('VALIDATION', 'Tool approval only accepts allow-once or reject.');
110
+ }
111
+ const matches = [...pending].filter(entry => entry.sessionId === input.sessionId && entry.requestId === input.requestId);
112
+ if (matches.length > 1)
113
+ return toolError('CONFLICT', 'Multiple open approvals match this request.');
114
+ const entry = matches[0];
115
+ if (!entry)
116
+ return toolError('NOT_FOUND', 'No open tool-approval request matches this session.');
117
+ if (!detach(entry))
118
+ return toolError('CONFLICT', 'This approval was already answered.');
119
+ remember(entry, input.outcome);
120
+ entry.resolve(input.outcome);
121
+ return { ok: true, path: 'approval', outcome: input.outcome, requestId: entry.requestId };
122
+ }
123
+ function snapshot(sessionId) {
124
+ const open = [...pending]
125
+ .filter(entry => !sessionId || entry.sessionId === sessionId)
126
+ .map(entry => ({
127
+ requestId: entry.requestId,
128
+ sessionId: entry.sessionId,
129
+ toolName: entry.toolName,
130
+ callId: entry.callId,
131
+ reason: textOf(entry.request.reason),
132
+ displayReason: displayReasonOf(entry.request.displayReason),
133
+ state: 'open',
134
+ }));
135
+ const done = settled.filter(entry => !sessionId || entry.sessionId === sessionId);
136
+ return [...open, ...done];
137
+ }
138
+ function listen(ctx) {
139
+ const dispose = ctx.on?.('approval/request', handle, true);
140
+ return () => {
141
+ if (typeof dispose === 'function')
142
+ dispose();
143
+ for (const entry of [...pending]) {
144
+ if (!detach(entry))
145
+ continue;
146
+ remember(entry, 'unavailable');
147
+ entry.resolve('unavailable');
148
+ }
149
+ };
150
+ }
151
+ return {
152
+ listen,
153
+ handle,
154
+ submit,
155
+ snapshot,
156
+ pendingCount() {
157
+ return pending.size;
158
+ },
159
+ };
160
+ }
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Official `ctx.authorization` surface for the desk settings UI.
3
+ *
4
+ * Authorization is config-time, never part of the transcript or model
5
+ * context. The desk supplies the official interaction: notices, prompts,
6
+ * and cancel. Secret prompts are answered with the exact submitted value;
7
+ * the UI must not use a password input.
8
+ */
9
+ import { toolError } from "./errors.js";
10
+ class DeclinedError extends Error {
11
+ code = 'DECLINED';
12
+ constructor(message = 'The authorization prompt was declined.') {
13
+ super(message);
14
+ this.name = 'AuthorizationDeclinedError';
15
+ }
16
+ }
17
+ const controllers = new Map();
18
+ export function publishAuthorization(dataDir, controller) {
19
+ if (controller)
20
+ controllers.set(dataDir, controller);
21
+ else
22
+ controllers.delete(dataDir);
23
+ }
24
+ export function authorizationFor(dataDir) {
25
+ return controllers.get(dataDir) ?? null;
26
+ }
27
+ export function createAuthorizationController() {
28
+ const prompts = new Map();
29
+ const notices = [];
30
+ let host = null;
31
+ let nextId = 1;
32
+ let catalogRevision = 0;
33
+ const active = new Map();
34
+ function service() {
35
+ return host?.get?.('authorization');
36
+ }
37
+ function declined(message) {
38
+ const ctor = service()?.constructor?.AuthorizationDeclinedError;
39
+ if (typeof ctor === 'function') {
40
+ try {
41
+ return new ctor(message);
42
+ }
43
+ catch {
44
+ /* fall through */
45
+ }
46
+ }
47
+ const AuthorizationDeclinedError = service()?.AuthorizationDeclinedError;
48
+ if (typeof AuthorizationDeclinedError === 'function') {
49
+ try {
50
+ return new AuthorizationDeclinedError(message);
51
+ }
52
+ catch {
53
+ /* fall through */
54
+ }
55
+ }
56
+ return new DeclinedError(message);
57
+ }
58
+ function list() {
59
+ const entries = service()?.list?.();
60
+ if (!Array.isArray(entries))
61
+ return [];
62
+ return entries.flatMap(entry => {
63
+ if (!entry || typeof entry !== 'object')
64
+ return [];
65
+ const row = entry;
66
+ const methods = Array.isArray(row.methods)
67
+ ? row.methods.flatMap(method => {
68
+ if (!method || typeof method !== 'object')
69
+ return [];
70
+ const item = method;
71
+ if (typeof item.id !== 'string' || item.id === '')
72
+ return [];
73
+ return [
74
+ {
75
+ id: item.id,
76
+ label: typeof item.label === 'string' && item.label !== '' ? item.label : item.id,
77
+ },
78
+ ];
79
+ })
80
+ : [];
81
+ return [
82
+ {
83
+ key: row.key,
84
+ label: typeof row.label === 'string' ? row.label : '',
85
+ methods,
86
+ inFlight: row.inFlight === true,
87
+ },
88
+ ];
89
+ });
90
+ }
91
+ function snapshot(options = {}) {
92
+ return {
93
+ available: Boolean(service()),
94
+ ...(options.catalog === false ? { catalogRevision, inFlight: [...active.values()] } : { entries: list() }),
95
+ notices: [...notices],
96
+ prompts: [...prompts.values()].map(entry => entry.prompt),
97
+ };
98
+ }
99
+ async function begin(input) {
100
+ const auth = service();
101
+ if (!auth || typeof auth.begin !== 'function') {
102
+ return toolError('UNAVAILABLE', 'Official authorization is not composed on this host.');
103
+ }
104
+ if (input.key == null)
105
+ return toolError('VALIDATION', 'A credential key is required.');
106
+ const activeKey = Symbol();
107
+ active.set(activeKey, input.key);
108
+ catalogRevision++;
109
+ try {
110
+ const outcome = await auth.begin({
111
+ key: input.key,
112
+ method: typeof input.method === 'string' && input.method !== '' ? input.method : undefined,
113
+ interaction: {
114
+ notify(notice) {
115
+ const view = {
116
+ key: input.key,
117
+ message: typeof notice?.message === 'string' ? notice.message : '',
118
+ };
119
+ if (typeof notice?.url === 'string' && notice.url !== '')
120
+ view.url = notice.url;
121
+ if (typeof notice?.code === 'string' && notice.code !== '')
122
+ view.code = notice.code;
123
+ notices.push(view);
124
+ if (notices.length > 20)
125
+ notices.shift();
126
+ },
127
+ prompt(prompt) {
128
+ return new Promise((resolve, reject) => {
129
+ const kind = prompt?.kind === 'secret' || prompt?.kind === 'select' ? prompt.kind : 'text';
130
+ const view = {
131
+ promptId: `auth-${nextId++}`,
132
+ key: input.key,
133
+ kind,
134
+ message: typeof prompt?.message === 'string' ? prompt.message : '',
135
+ };
136
+ if (typeof prompt?.placeholder === 'string' && prompt.placeholder !== '') {
137
+ view.placeholder = prompt.placeholder;
138
+ }
139
+ if (kind === 'select' && Array.isArray(prompt?.options)) {
140
+ view.options = prompt.options.flatMap(option => {
141
+ if (!option || typeof option !== 'object')
142
+ return [];
143
+ const row = option;
144
+ if (typeof row.id !== 'string' || row.id === '')
145
+ return [];
146
+ const item = {
147
+ id: row.id,
148
+ label: typeof row.label === 'string' && row.label !== '' ? row.label : row.id,
149
+ };
150
+ if (typeof row.description === 'string' && row.description !== '')
151
+ item.description = row.description;
152
+ return [item];
153
+ });
154
+ }
155
+ prompts.set(view.promptId, { promptId: view.promptId, key: input.key, prompt: view, resolve, reject });
156
+ });
157
+ },
158
+ },
159
+ });
160
+ return { ok: true, outcome };
161
+ }
162
+ catch (error) {
163
+ const code = error && typeof error === 'object' && 'code' in error && typeof error.code === 'string'
164
+ ? error.code
165
+ : 'UNAVAILABLE';
166
+ const message = error instanceof Error ? error.message : 'Authorization could not be started.';
167
+ if (code === 'DECLINED')
168
+ return { ok: true, outcome: { status: 'cancelled' } };
169
+ return toolError(code === 'NO_FLOW' || code === 'UNKNOWN_METHOD' || code === 'ALREADY_IN_FLIGHT' ? code : 'UNAVAILABLE', message);
170
+ }
171
+ finally {
172
+ active.delete(activeKey);
173
+ catalogRevision++;
174
+ }
175
+ }
176
+ function answer(input) {
177
+ if (typeof input.promptId !== 'string' || input.promptId === '') {
178
+ return toolError('VALIDATION', 'promptId is required.');
179
+ }
180
+ const entry = prompts.get(input.promptId);
181
+ if (!entry)
182
+ return toolError('NOT_FOUND', 'No open authorization prompt matches this request.');
183
+ prompts.delete(input.promptId);
184
+ if (input.declined) {
185
+ entry.reject(declined());
186
+ return { ok: true, path: 'declined' };
187
+ }
188
+ if (typeof input.value !== 'string')
189
+ return toolError('VALIDATION', 'A prompt answer is required.');
190
+ entry.resolve(input.value);
191
+ return { ok: true, path: 'answered' };
192
+ }
193
+ function cancel(input) {
194
+ const auth = service();
195
+ if (!auth || typeof auth.cancel !== 'function') {
196
+ return toolError('UNAVAILABLE', 'Official authorization is not composed on this host.');
197
+ }
198
+ if (input.key == null)
199
+ return toolError('VALIDATION', 'A credential key is required.');
200
+ for (const [id, entry] of [...prompts]) {
201
+ if (entry.key === input.key || JSON.stringify(entry.key) === JSON.stringify(input.key)) {
202
+ prompts.delete(id);
203
+ entry.reject(declined());
204
+ }
205
+ }
206
+ catalogRevision++;
207
+ auth.cancel(input.key);
208
+ return { ok: true, path: 'cancelled' };
209
+ }
210
+ function bind(ctx) {
211
+ host = ctx;
212
+ catalogRevision++;
213
+ return () => {
214
+ if (host === ctx)
215
+ host = null;
216
+ catalogRevision++;
217
+ active.clear();
218
+ for (const entry of [...prompts.values()]) {
219
+ prompts.delete(entry.promptId);
220
+ entry.reject(declined());
221
+ }
222
+ };
223
+ }
224
+ return { bind, list, snapshot, begin, answer, cancel };
225
+ }
package/dist/context.js CHANGED
@@ -14,7 +14,15 @@ export const CHAT = [
14
14
  'You are talking with the user. Finish this turn in the first person.',
15
15
  'The latest user message is the current intent. If the previous sentence stopped halfway, answer the new one directly. Do not finish the old sentence.',
16
16
  'When the user did not ask you to look something up, edit files, dispatch work, or contact another bot, do not call tools and do not mention steps or system state.',
17
- 'When the work will take a while, say in one sentence that it is going to the background, then call foundations_dispatch. Do not finish that long job in the main session.',
17
+ 'Default: hand every non-trivial task to a worker with foundations_dispatch. The main session plans, estimates budget, waits for ticket notices, reviews results, and replies to the user.',
18
+ 'Direct execution is allowed only for a short reply that needs no tools; a tiny read-only check (one or two reads) needed to write a briefing or answer a simple question; or when the user clearly asked you to do the work yourself in this session. Do not run a multi-step shell, edit, or write chain in the main session without one of those exceptions.',
19
+ "Prefer foundations_dispatch over bash, write, edit, and any official subagent tool for this bot's work. Official subagent is not the ticket worker.",
20
+ 'If an unfinished ticket can take the new work, call foundations_redirect and reuse that worker. Independent tasks may run in parallel up to the host slot cap. Dependent steps stay serial on the same ticket. Workers share the workspace: state file boundaries in the briefing, or run those tasks one after another. There is no filesystem isolation between workers.',
21
+ 'Workers usually have file tools (read, write, edit, working_directory) and foundations_report. They often do not have bash or other command tools. Assign work the worker can actually do. If a worker reports it is blocked because it has no command tools, do not dispatch that same command-only task to another worker with the same tools, and do not silently finish the job in the main session; tell the user the blockage.',
22
+ 'foundations_dispatch may return status=accepted (received, and possibly waiting for a slot), status=enqueued (placed on the execution queue, not started), or a BUDGET error when both the slot cap and the queue cap are full. accepted or enqueued is not completion and not started. Say in one sentence that the work is in the background, then end the turn. Do not sleep, poll, or keep calling tools while waiting.',
23
+ "A ticket notice is not something the user said. On progress or artifact notices, do not take over the work and do not poll. On a question, answer or call foundations_supply. On a budget-extension notice, call foundations_grant (or deny). On a successful result, call foundations_publish, then write the user-visible reply. Do not treat a later failed status after a published result as if the worker never delivered. Do not invent a final answer or accept the work on the user's behalf before a result. Do not call foundations_retry unless the user explicitly asks.",
24
+ 'If dispatch returns BUDGET, do not start the job yourself and do not keep opening tickets to bypass the cap. Tell the user the host is at its limit.',
25
+ 'On a budget-wait notice, decide whether to add sufficient budget or explicitly deny/cancel. Compare current cumulative usage, required totals and host headroom: small grants may leave the worker paused. Host ceilings cannot be raised by foundations_grant. A terminal failed/cancelled ticket cannot be revived by a grant. Do not foundations_dispatch a replacement ticket for the same work.',
18
26
  ].join('\n');
19
27
  export const DEFAULT_WINDOW = 128000;
20
28
  /**
@@ -268,6 +276,8 @@ export function renderTickets(rows) {
268
276
  'accepted means received. enqueued means placed on the execution queue. started is the only status that means work has begun.',
269
277
  'A ticket notice is not something the user said. accepted is not enqueued, and enqueued is not started.',
270
278
  'publish only records an intent to deliver. The words you write next are the reply to the user. Tell the user the result. Do not say accepted, enqueued, or publish.',
279
+ 'accepted can mean the ticket is waiting for an execution slot. enqueued means it entered the execution queue. started is the only status that means work has begun. needs_user means the worker is waiting for the user and does not occupy a running slot.',
280
+ 'A failed ticket that already had a published result is not an undelivered result. Ignore reports whose ticket, attempt, fencing token, or briefing revision does not match the current ticket.',
271
281
  'When you open a ticket, estimate wallMs and maxTokens for the size of the task and put them in the foundations_dispatch budget. When the worker uses up that time or those tokens, the notice asks you to call foundations_grant. Do not call the ticket a failure before that grant.',
272
282
  ...lines,
273
283
  ].join('\n');
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Official Computer Use access controls, exposed only when `ctx.cuaAccess`
3
+ * is composed. Runtime app consent still uses the approval-intent card in
4
+ * the session; this surface manages system permissions and saved grants.
5
+ */
6
+ import { toolError } from "./errors.js";
7
+ const SYSTEM_PERMISSIONS = new Set(['accessibility', 'screenRecording']);
8
+ function service(ctx) {
9
+ return ctx.get?.('cuaAccess');
10
+ }
11
+ export async function cuaSnapshot(ctx, locale = 'en') {
12
+ const access = service(ctx);
13
+ if (!access)
14
+ return { available: false };
15
+ try {
16
+ const [systemStatus, applications, ptcConfiguration, applicationIcons] = await Promise.all([
17
+ typeof access.systemStatus === 'function' ? access.systemStatus() : null,
18
+ typeof access.applications === 'function' ? access.applications() : null,
19
+ typeof access.ptcConfiguration === 'function' ? access.ptcConfiguration() : null,
20
+ typeof access.applicationIcons === 'function' ? access.applicationIcons() : null,
21
+ ]);
22
+ return {
23
+ available: true,
24
+ locale,
25
+ systemStatus,
26
+ applications,
27
+ ptcConfiguration,
28
+ applicationIcons,
29
+ };
30
+ }
31
+ catch (error) {
32
+ const message = error instanceof Error ? error.message : 'Computer Use access could not be read.';
33
+ return { available: true, error: message };
34
+ }
35
+ }
36
+ export async function cuaAction(ctx, input) {
37
+ const access = service(ctx);
38
+ if (!access)
39
+ return toolError('UNAVAILABLE', 'Computer Use is not installed on this host.');
40
+ const locale = typeof input.locale === 'string' && input.locale !== '' ? input.locale : 'en';
41
+ const action = input.action;
42
+ try {
43
+ if (action === 'requestPermission') {
44
+ if (!SYSTEM_PERMISSIONS.has(String(input.permission))) {
45
+ return toolError('VALIDATION', 'A supported system permission is required.');
46
+ }
47
+ const systemStatus = await access.requestPermission(input.permission, locale);
48
+ return { ok: true, systemStatus };
49
+ }
50
+ if (action === 'openSettings') {
51
+ if (!SYSTEM_PERMISSIONS.has(String(input.permission))) {
52
+ return toolError('VALIDATION', 'A supported system permission is required.');
53
+ }
54
+ await access.openSettings(input.permission, locale);
55
+ return { ok: true };
56
+ }
57
+ if (action === 'revoke') {
58
+ if (typeof input.id !== 'string' || input.id === '')
59
+ return toolError('VALIDATION', 'An application id is required.');
60
+ await access.revoke(input.id);
61
+ return { ok: true };
62
+ }
63
+ if (action === 'retryApproval') {
64
+ if (typeof input.id !== 'string' || input.id === '')
65
+ return toolError('VALIDATION', 'An application id is required.');
66
+ await access.retryApproval(input.id);
67
+ return { ok: true };
68
+ }
69
+ if (action === 'enablePersistentPtc') {
70
+ await access.enablePersistentPtc();
71
+ return { ok: true };
72
+ }
73
+ return toolError('VALIDATION', 'An official Computer Use action is required.');
74
+ }
75
+ catch (error) {
76
+ const message = error instanceof Error ? error.message : 'The Computer Use action could not be completed.';
77
+ return toolError('UNAVAILABLE', message);
78
+ }
79
+ }
package/dist/desk.js CHANGED
@@ -1,9 +1,31 @@
1
1
  /** Workbench routes inside the DSH process. The browser calls /dsh-bot/api. */
2
- import { readFileSync } from 'node:fs';
3
- import { dirname, join } from 'node:path';
2
+ import { mkdirSync, readFileSync } from 'node:fs';
3
+ import { dirname, join, resolve } from 'node:path';
4
4
  import { openLedger, validIdempotencyKey } from "./desk-ledger.js";
5
5
  import { openSessionPreviews } from "./session-previews.js";
6
6
  import { purgeSessionFiles, sessionDirectory, writeBotMarker } from "./session-files.js";
7
+ /**
8
+ * Working directory for workbench-created sessions. THREADY_SESSION_CWD wins;
9
+ * otherwise <DSH_HOME>/workspace, so the model does not start inside DSH_HOME
10
+ * (owner-token, profiles/, persona.sqlite). Empty only when neither is set,
11
+ * which keeps DSH's own default (the server process cwd).
12
+ * @param {Record<string, string | undefined>} env
13
+ * @param {{ mkdir?: boolean }} [options]
14
+ */
15
+ export function defaultSessionCwd(env, options = {}) {
16
+ const explicit = (env.THREADY_SESSION_CWD ?? '').trim();
17
+ const home = (env.DSH_HOME ?? '').trim();
18
+ const cwd = explicit !== '' ? resolve(explicit) : home !== '' ? join(resolve(home), 'workspace') : '';
19
+ if (cwd !== '' && options.mkdir !== false) {
20
+ try {
21
+ mkdirSync(cwd, { recursive: true, mode: 0o700 });
22
+ }
23
+ catch {
24
+ /* session/create reports a bad cwd */
25
+ }
26
+ }
27
+ return cwd;
28
+ }
7
29
  const API = '/session-foundations/api';
8
30
  const PREVIEW_SESSION = /^(?:session|worker)-[A-Za-z0-9-]+$/;
9
31
  const SECRET_KEY = /token|secret|password|authorization|api[-_]?key|cookie/i;