@thready-web/dsh-bot-plugin 0.1.0-beta.13 → 0.1.0-beta.15

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.
Files changed (28) hide show
  1. package/README.md +7 -1
  2. package/dist/desk.js +10 -1
  3. package/dist/http.js +29 -1
  4. package/dist/index.js +44 -3
  5. package/dist/permission-default.js +167 -0
  6. package/dist/permissions.js +18 -0
  7. package/dist/work-child.js +5 -4
  8. package/dist/worker-permission.js +75 -0
  9. package/package.json +1 -1
  10. package/public/assets/{SourceEditor-BjtoMvcX.js → SourceEditor-BO-dBzgs.js} +3 -3
  11. package/public/assets/{cssMode--96PQtWh.js → cssMode-DS6FrlOm.js} +1 -1
  12. package/public/assets/{freemarker2-Bz-HlISL.js → freemarker2-CGb0OuSj.js} +1 -1
  13. package/public/assets/{handlebars-D9ScJ8AM.js → handlebars-CUN0Cg4v.js} +1 -1
  14. package/public/assets/{html-Czc0jojJ.js → html-CaIExM4O.js} +1 -1
  15. package/public/assets/{htmlMode-CCww5Z1w.js → htmlMode-Dhe_MncL.js} +1 -1
  16. package/public/assets/index-y0M-tjxv.js +72 -0
  17. package/public/assets/{javascript-B-yRZSiz.js → javascript-DWKDEiw7.js} +1 -1
  18. package/public/assets/{jsonMode-ASWsY833.js → jsonMode-DUsRTm16.js} +1 -1
  19. package/public/assets/{liquid-BGoox2vJ.js → liquid-8f0k7Cew.js} +1 -1
  20. package/public/assets/{mdx-DHgvnl_U.js → mdx-DwiR07zG.js} +1 -1
  21. package/public/assets/{python-BJvVD30_.js → python-BUXAkB2e.js} +1 -1
  22. package/public/assets/{razor-0PwR35mu.js → razor-8WRmhi1w.js} +1 -1
  23. package/public/assets/{tsMode-3ETp8Gdh.js → tsMode-Ckwe9Xvg.js} +1 -1
  24. package/public/assets/{typescript-BT0iTK6K.js → typescript-6GBBBhTx.js} +1 -1
  25. package/public/assets/{xml-BTaNc_uT.js → xml-BOrtj3K3.js} +1 -1
  26. package/public/assets/{yaml-Dr7LW3tK.js → yaml-YMA-FldX.js} +1 -1
  27. package/public/index.html +1 -1
  28. package/public/assets/index-ztUdW074.js +0 -72
package/README.md CHANGED
@@ -83,7 +83,13 @@ Parked `needs_user` tickets still count toward the combined unfinished cap (`slo
83
83
 
84
84
  Workers share the owner's workspace. There is no filesystem isolation; briefings should state file boundaries, or dependent work should stay serial.
85
85
 
86
- Workers use the `foundations-files` preset: official file tools plus official `@deepseek-ai/dsh-tool-bash` and `@deepseek-ai/dsh-tool-jobs`. A canvas worker uses `foundations-canvas` instead, which mounts the file tools with `write` and `edit` disabled and does not mount bash or jobs. Preview bytes go through `canvas_write`, not the workspace. 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.
86
+ Workers use the `foundations-files` preset: official file tools plus official `@deepseek-ai/dsh-tool-bash` and `@deepseek-ai/dsh-tool-jobs`. A canvas worker uses `foundations-canvas` instead, which mounts the file tools with `write` and `edit` disabled and does not mount bash or jobs. Preview bytes go through `canvas_write`, not the workspace. The tool preset does not mount the web preset or add writable roots. Sandbox mode and approval policy are copied from the parent main session at dispatch, not left on the host `workspace-write` pin. 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
+ ## Default permission for new main sessions
89
+
90
+ A new bot main session used to keep the host composition default, which is `workspace-write` when that preset matches the composed sandbox and approval defaults. The workbench now has an instance-wide default. When `permission-default.json` has no `defaultPreset` field, a main session created afterward starts at `danger-full-access` (Fully allow / 完全允许): full file access and no approval prompts. Change it in the session permissions drawer. The choice is stored in the profile data directory and read again after a restart. It applies through `permissionPresets.set`, so the session's sandbox mode and approval policy change with it.
91
+
92
+ The setting does not rewrite a session that already exists, and a permission set on one session stays on that session. It also does not write the host `permission` settings namespace, because that namespace is pinned onto every fresh Agent. A worker does not read this default. When `foundations_dispatch` creates it, the worker inherits the parent main session's current preset (`permissionPresets.set` after the host pin). A later change on the main session does not rewrite a worker that already exists. See [docs/permission-default.md](docs/permission-default.md).
87
93
 
88
94
  Runnable examples (any one of these is enough; `config.work` wins over the environment):
89
95
 
package/dist/desk.js CHANGED
@@ -221,10 +221,19 @@ export function createDesk(options) {
221
221
  return { status: 502, body: { error: 'bot_marker_failed', sessionId } };
222
222
  }
223
223
  }
224
+ const reused = Boolean(reusable) && sessionId === reusable.sessionId;
224
225
  ledger.rememberSession(key, sessionId);
226
+ if (!reused) {
227
+ try {
228
+ options.onFreshMain?.(sessionId);
229
+ }
230
+ catch {
231
+ /* creation already succeeded; agent/created applies a saved pending id */
232
+ }
233
+ }
225
234
  return {
226
235
  status: 201,
227
- body: { sessionId, kind: 'bot', marker, reused: Boolean(reusable) && sessionId === reusable.sessionId },
236
+ body: { sessionId, kind: 'bot', marker, reused },
228
237
  };
229
238
  }
230
239
  /**
package/dist/http.js CHANGED
@@ -11,6 +11,7 @@ import { serveWorkspaceImage } from "./workspace-image.js";
11
11
  import { selectBrowserHome } from "./workspace-files.js";
12
12
  import { toolError } from "./errors.js";
13
13
  import { permissionView, setPermission } from "./permissions.js";
14
+ import { applyFreshMainPermission, forgetPending, permissionDefaultFile, permissionDefaultView, rememberFreshMain, setDefaultPermission, } from "./permission-default.js";
14
15
  import { cuaAction, cuaSnapshot } from "./cua-access.js";
15
16
  import { provisionSession } from "./provision.js";
16
17
  import { handleWorkApi, openPageLive, openWorkLive } from "./work-http.js";
@@ -62,6 +63,18 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
62
63
  stillAttached: sessionId => attachedSession(ctx, sessionId),
63
64
  rpc: (endpoint, args, req) => hostRpc(req, endpoint, args),
64
65
  usage: req => hostUsage(req),
66
+ onFreshMain: sessionId => {
67
+ if (storeDir === '')
68
+ return;
69
+ const file = permissionDefaultFile(storeDir);
70
+ try {
71
+ rememberFreshMain(file, sessionId);
72
+ applyFreshMainPermission(ctx, file, sessionId, id => engine.isBot(id));
73
+ }
74
+ catch (error) {
75
+ ctx.logger?.warn?.('session-foundations: default permission was not armed session=%s %s', sessionId, error instanceof Error ? error.message : String(error));
76
+ }
77
+ },
65
78
  files: {
66
79
  home: selectBrowserHome(process.env, extras.filesHome),
67
80
  dshHome: process.env.DSH_HOME ?? '',
@@ -277,9 +290,24 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
277
290
  const sessionId = url.searchParams.get('sessionId') ?? '';
278
291
  return send(res, 200, { ok: true, ...permissionView(ctx, sessionId) });
279
292
  }
293
+ if (req.method === 'GET' && path === '/session-foundations/api/permissions/default') {
294
+ if (storeDir === '')
295
+ return send(res, 503, toolError('UNAVAILABLE', 'Permission defaults need a profile data directory.'));
296
+ return send(res, 200, { ok: true, ...permissionDefaultView(ctx, permissionDefaultFile(storeDir)) });
297
+ }
298
+ if (req.method === 'POST' && path === '/session-foundations/api/permissions/default') {
299
+ if (storeDir === '')
300
+ return send(res, 503, toolError('UNAVAILABLE', 'Permission defaults need a profile data directory.'));
301
+ const body = await readJson(req);
302
+ return sendTool(res, setDefaultPermission(ctx, permissionDefaultFile(storeDir), typeof body.name === 'string' ? body.name : ''));
303
+ }
280
304
  if (req.method === 'POST' && path === '/session-foundations/api/permissions') {
281
305
  const body = await readJson(req);
282
- return sendTool(res, setPermission(ctx, typeof body.sessionId === 'string' ? body.sessionId : '', typeof body.name === 'string' ? body.name : ''));
306
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId : '';
307
+ const result = setPermission(ctx, sessionId, typeof body.name === 'string' ? body.name : '');
308
+ if (result.ok !== false && storeDir !== '')
309
+ forgetPending(permissionDefaultFile(storeDir), sessionId);
310
+ return sendTool(res, result);
283
311
  }
284
312
  if (req.method === 'GET' && path === '/session-foundations/api/authorization') {
285
313
  const authorization = getAuthorization();
package/dist/index.js CHANGED
@@ -21,6 +21,8 @@ import { openCanvasStore } from "./canvas-store.js";
21
21
  import { backlogCanvases, bindCanvasCards, createCardLog, publishCardLog } from "./card-log.js";
22
22
  import { canvasToolDefinitions } from "./canvas-tools.js";
23
23
  import { forgetWorker, rememberWorker } from "./worker-handles.js";
24
+ import { applyFreshMainPermission, permissionDefaultFile } from "./permission-default.js";
25
+ import { applyWorkerPermission, dropWorkerPermission, rememberWorkerPermission } from "./worker-permission.js";
24
26
  export const name = 'session-foundations';
25
27
  // Cordis throws if a plugin reads a service it did not inject. Crash recovery reads the session log through this one.
26
28
  export const inject = [
@@ -212,6 +214,22 @@ export function apply(ctx, config = {}) {
212
214
  ctx.on('agent/created', (payload) => {
213
215
  const agent = payload?.agent;
214
216
  pinMainReasoning(agent, id => engine.isBot(id));
217
+ if (typeof agent?.id === 'string') {
218
+ try {
219
+ const source = typeof payload?.source === 'string' && payload.source !== '' ? payload.source : 'startup';
220
+ const inherited = applyWorkerPermission(ctx, agent.id, source);
221
+ // `rejected` stays pending so the create path can retry once the session is visible.
222
+ if (!inherited.applied &&
223
+ inherited.reason !== 'not-pending' &&
224
+ inherited.reason !== 'not-startup' &&
225
+ inherited.reason !== 'rejected') {
226
+ ctx.logger?.warn?.('session-foundations: worker permission was not inherited session=%s reason=%s', agent.id, inherited.reason);
227
+ }
228
+ }
229
+ catch (error) {
230
+ ctx.logger?.warn?.('session-foundations: worker permission inheritance failed session=%s %s', agent.id, error instanceof Error ? error.message : String(error));
231
+ }
232
+ }
215
233
  if (!agent?.id || !engine.isBot(agent.id))
216
234
  return;
217
235
  let session = null;
@@ -225,6 +243,12 @@ export function apply(ctx, config = {}) {
225
243
  parentSessionId: session?.header?.parentSession ?? null,
226
244
  seeded: session?.header?.isSeeded === true,
227
245
  });
246
+ try {
247
+ applyFreshMainPermission(ctx, permissionDefaultFile(dataDir), agent.id, id => engine.isBot(id));
248
+ }
249
+ catch (error) {
250
+ ctx.logger?.warn?.('session-foundations: default permission was not applied session=%s %s', agent.id, error instanceof Error ? error.message : String(error));
251
+ }
228
252
  });
229
253
  ctx.on('agent/inbox/inserted', (payload) => {
230
254
  pinMainReasoning(payload?.agent, id => engine.isBot(id));
@@ -398,6 +422,8 @@ function startWork(ctx, store, engine, config, cards, onDrop = () => { }) {
398
422
  if (isFenced(spec.ownerSessionId) || isFenced(spec.sessionId)) {
399
423
  throw Object.assign(new Error('session is being deleted'), { code: 'DELETING' });
400
424
  }
425
+ // Snapshot before create. The host pin runs inside create, on agent/created.
426
+ rememberWorkerPermission(ctx, spec.sessionId, spec.ownerSessionId);
401
427
  let cwd = '';
402
428
  let model = null;
403
429
  try {
@@ -425,9 +451,24 @@ function startWork(ctx, store, engine, config, cards, onDrop = () => { }) {
425
451
  options.meta = { ...(options.meta ?? {}), agentPreset: preset };
426
452
  options.setup = workerFileSetup(ctx, preset);
427
453
  }
428
- const handle = await ctx.agents.create(options);
429
- rememberWorker(spec.sessionId, handle);
430
- return spec.sessionId;
454
+ try {
455
+ const handle = await ctx.agents.create(options);
456
+ rememberWorker(spec.sessionId, handle);
457
+ try {
458
+ const inherited = applyWorkerPermission(ctx, spec.sessionId, 'startup');
459
+ if (!inherited.applied && inherited.reason !== 'not-pending' && inherited.reason !== 'not-startup') {
460
+ ctx.logger?.warn?.('session-foundations: worker permission was not inherited session=%s parent=%s reason=%s', spec.sessionId, spec.ownerSessionId, inherited.reason);
461
+ }
462
+ }
463
+ catch (error) {
464
+ ctx.logger?.warn?.('session-foundations: worker permission inheritance failed session=%s %s', spec.sessionId, error instanceof Error ? error.message : String(error));
465
+ }
466
+ return spec.sessionId;
467
+ }
468
+ catch (error) {
469
+ dropWorkerPermission(spec.sessionId);
470
+ throw error;
471
+ }
431
472
  },
432
473
  recordCard: input => {
433
474
  cards.record(ctx, input);
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Instance-wide default permission for bot main sessions created from now on.
3
+ *
4
+ * The host's `permission` settings namespace pins `defaultPreset` onto every
5
+ * fresh Agent, including workers. This file does not write that namespace.
6
+ * A new bot main session is applied later through `permissionPresets.set`,
7
+ * the same sandbox-mode and approval-policy write the per-session control uses.
8
+ * Sessions that already exist, and any explicit per-session choice, are left
9
+ * alone. Workers are never added to the pending list. A worker copies its
10
+ * parent main session at creation (`worker-permission.ts`), not this file.
11
+ */
12
+ import { existsSync, readFileSync } from 'node:fs';
13
+ import { dirname, join } from 'node:path';
14
+ import { toolError } from "./errors.js";
15
+ import { ensureDir, writeAtomic } from "./fs-safe.js";
16
+ import { permissionView, setPermission } from "./permissions.js";
17
+ /** Official preset id for full file access and no approval prompts. */
18
+ export const PRODUCT_DEFAULT_PRESET = 'danger-full-access';
19
+ const MAIN_SESSION = /^session-[A-Za-z0-9-]+$/;
20
+ const RESERVED = new Set(['auto', 'custom']);
21
+ export function permissionDefaultFile(dataDir) {
22
+ return join(dataDir, 'permission-default.json');
23
+ }
24
+ function readBody(file) {
25
+ if (!existsSync(file))
26
+ return { body: {}, corrupt: false };
27
+ try {
28
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
29
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
30
+ return { body: {}, corrupt: true };
31
+ return { body: parsed, corrupt: false };
32
+ }
33
+ catch {
34
+ return { body: {}, corrupt: true };
35
+ }
36
+ }
37
+ function pendingOf(value) {
38
+ if (!Array.isArray(value))
39
+ return [];
40
+ const ids = value.filter((item) => typeof item === 'string' && MAIN_SESSION.test(item));
41
+ return [...new Set(ids)];
42
+ }
43
+ function interpretStored(body, corrupt) {
44
+ if (corrupt)
45
+ return { stored: null, ignoredStored: true };
46
+ if (!Object.hasOwn(body, 'defaultPreset'))
47
+ return { stored: null, ignoredStored: false };
48
+ const value = body.defaultPreset;
49
+ if (typeof value !== 'string' || value === '' || RESERVED.has(value))
50
+ return { stored: null, ignoredStored: true };
51
+ return { stored: value, ignoredStored: false };
52
+ }
53
+ export function readPermissionDefault(file) {
54
+ const { body, corrupt } = readBody(file);
55
+ const interpreted = interpretStored(body, corrupt);
56
+ return { ...interpreted, pending: pendingOf(body.pending), corrupt };
57
+ }
58
+ function writeBody(file, body) {
59
+ ensureDir(dirname(file));
60
+ writeAtomic(file, `${JSON.stringify(body, null, 2)}\n`);
61
+ }
62
+ /**
63
+ * Preset a new main session should receive. A missing or unusable stored
64
+ * value uses Fully allow when the live catalog contains it.
65
+ */
66
+ export function resolveDefaultPreset(stored, allowed) {
67
+ if (stored && allowed.includes(stored))
68
+ return stored;
69
+ if (allowed.includes(PRODUCT_DEFAULT_PRESET))
70
+ return PRODUCT_DEFAULT_PRESET;
71
+ return '';
72
+ }
73
+ function allowedPresets(options) {
74
+ return options.map(option => option.value).filter(value => value !== '' && !RESERVED.has(value));
75
+ }
76
+ export function permissionDefaultView(ctx, file) {
77
+ const catalog = permissionView(ctx, '');
78
+ const saved = readPermissionDefault(file);
79
+ const options = catalog.defaultOptions.filter(option => !RESERVED.has(option.value));
80
+ const allowed = allowedPresets(options);
81
+ const ignoredStored = saved.ignoredStored || (saved.stored !== null && !allowed.includes(saved.stored));
82
+ const defaultPreset = catalog.available ? resolveDefaultPreset(saved.stored, allowed) : '';
83
+ return {
84
+ available: catalog.available,
85
+ defaultPreset,
86
+ stored: saved.stored,
87
+ ignoredStored,
88
+ options,
89
+ productDefault: PRODUCT_DEFAULT_PRESET,
90
+ scope: 'new-main-session',
91
+ hostDefault: catalog.defaultPreset,
92
+ };
93
+ }
94
+ export function setDefaultPermission(ctx, file, name) {
95
+ if (typeof name !== 'string' || name === '' || RESERVED.has(name)) {
96
+ return toolError('VALIDATION', 'A configured preset is required. Auto and custom cannot be the default for new sessions.');
97
+ }
98
+ const catalog = permissionView(ctx, '');
99
+ if (!catalog.available) {
100
+ return toolError('UNAVAILABLE', 'Official permission presets are not composed on this host.');
101
+ }
102
+ const allowed = new Set(allowedPresets(catalog.defaultOptions));
103
+ if (!allowed.has(name)) {
104
+ return toolError('VALIDATION', 'That preset is not a configured permission mode.');
105
+ }
106
+ const { body } = readBody(file);
107
+ writeBody(file, { ...body, defaultPreset: name });
108
+ return { ok: true, ...permissionDefaultView(ctx, file) };
109
+ }
110
+ /** Remember a workbench-created main session until its first live permission write. */
111
+ export function rememberFreshMain(file, sessionId) {
112
+ if (!MAIN_SESSION.test(sessionId))
113
+ return false;
114
+ const { body } = readBody(file);
115
+ const pending = pendingOf(body.pending);
116
+ if (pending.includes(sessionId))
117
+ return true;
118
+ writeBody(file, { ...body, pending: [...pending, sessionId] });
119
+ return true;
120
+ }
121
+ /** An explicit per-session choice wins over the global default. */
122
+ export function forgetPending(file, sessionId) {
123
+ const { body } = readBody(file);
124
+ const pending = pendingOf(body.pending);
125
+ if (!pending.includes(sessionId))
126
+ return false;
127
+ writeBody(file, { ...body, pending: pending.filter(id => id !== sessionId) });
128
+ return true;
129
+ }
130
+ function consumePending(file, sessionId) {
131
+ const { body } = readBody(file);
132
+ const pending = pendingOf(body.pending);
133
+ if (!pending.includes(sessionId))
134
+ return false;
135
+ writeBody(file, { ...body, pending: pending.filter(id => id !== sessionId) });
136
+ return true;
137
+ }
138
+ function restorePending(file, sessionId) {
139
+ const { body } = readBody(file);
140
+ const pending = pendingOf(body.pending);
141
+ if (pending.includes(sessionId))
142
+ return;
143
+ writeBody(file, { ...body, pending: [...pending, sessionId] });
144
+ }
145
+ /**
146
+ * Apply the configured default once, through the official preset setter.
147
+ * A session that is not pending is not touched, so a later change to the
148
+ * global default does not rewrite it.
149
+ */
150
+ export function applyFreshMainPermission(ctx, file, sessionId, isBot) {
151
+ if (!MAIN_SESSION.test(sessionId) || !isBot(sessionId))
152
+ return { applied: false, reason: 'not-main' };
153
+ if (!consumePending(file, sessionId))
154
+ return { applied: false, reason: 'not-pending' };
155
+ const view = permissionDefaultView(ctx, file);
156
+ if (!view.available || view.defaultPreset === '') {
157
+ restorePending(file, sessionId);
158
+ return { applied: false, reason: view.available ? 'unresolved' : 'unavailable' };
159
+ }
160
+ const result = setPermission(ctx, sessionId, view.defaultPreset);
161
+ if (result.ok === false) {
162
+ if (result.code === 'NOT_FOUND' || result.code === 'UNAVAILABLE')
163
+ restorePending(file, sessionId);
164
+ return { applied: false, reason: 'rejected' };
165
+ }
166
+ return { applied: true, reason: 'applied', preset: view.defaultPreset };
167
+ }
@@ -4,6 +4,9 @@
4
4
  * The write path is `ctx.permissionPresets.set(session, name)`. Auto is
5
5
  * offered only when the live catalog includes it (the experimental package
6
6
  * has registered it). This is a settings concern, not a transcript card.
7
+ * The instance default for a future main session is `permission-default.ts`;
8
+ * a worker copies its parent with `worker-permission.ts`. Both call this
9
+ * setter and do not invent a second sandbox policy.
7
10
  */
8
11
  import { toolError } from "./errors.js";
9
12
  function sessionOf(ctx, sessionId) {
@@ -31,6 +34,21 @@ function optionList(value) {
31
34
  return [option];
32
35
  });
33
36
  }
37
+ /**
38
+ * The preset the live session is actually running under.
39
+ * A missing session does not fall back to the catalog composition default:
40
+ * that default is the host pin, not this session's policy.
41
+ */
42
+ export function effectivePermission(ctx, sessionId) {
43
+ const service = ctx.get?.('permissionPresets');
44
+ if (!service || typeof service.catalog !== 'function' || typeof service.current !== 'function') {
45
+ return { available: false, found: false, preset: '' };
46
+ }
47
+ const session = sessionOf(ctx, sessionId);
48
+ if (!session)
49
+ return { available: true, found: false, preset: '' };
50
+ return { available: true, found: true, preset: String(service.current(session) ?? '') };
51
+ }
34
52
  export function permissionView(ctx, sessionId) {
35
53
  const service = ctx.get?.('permissionPresets');
36
54
  if (!service || typeof service.catalog !== 'function') {
@@ -3,10 +3,11 @@
3
3
  * so their request header otherwise lists only host tools.
4
4
  * This preset mounts official file tools and official command tools
5
5
  * (`@deepseek-ai/dsh-tool-bash`, `@deepseek-ai/dsh-tool-jobs`). It does not
6
- * change the host sandbox mode, add writable roots, or mount the web preset
7
- * (no web_fetch, subagent, or other profile tools). The session cwd copied
8
- * at create remains the workspace-write boundary; bash uses the already
9
- * composed host bash-sandbox and approval policy.
6
+ * mount the web preset (no web_fetch, subagent, or other profile tools),
7
+ * add writable roots, or itself change the sandbox mode or approval policy.
8
+ * Those knobs are copied from the parent main session when the worker is
9
+ * created. The session cwd copied at create remains the workspace path;
10
+ * bash uses the composed host bash-sandbox under the inherited sandbox mode.
10
11
  */
11
12
  export const WORKER_FILE_PRESET = 'foundations-files';
12
13
  /**
@@ -0,0 +1,75 @@
1
+ import { effectivePermission, permissionView, setPermission } from "./permissions.js";
2
+ const WORKER_ID = /^worker-[A-Za-z0-9][A-Za-z0-9._-]*$/;
3
+ const SKIP_SOURCE = new Set(['resume', 'clear', 'compact']);
4
+ const pending = new Map();
5
+ function snapshotParent(ctx, parentId) {
6
+ if (typeof parentId !== 'string' || parentId === '')
7
+ return { preset: '', reason: 'missing' };
8
+ const effective = effectivePermission(ctx, parentId);
9
+ if (!effective.available)
10
+ return { preset: '', reason: 'unavailable' };
11
+ if (!effective.found || effective.preset === '')
12
+ return { preset: '', reason: 'missing' };
13
+ if (effective.preset === 'custom')
14
+ return { preset: '', reason: 'custom' };
15
+ const known = permissionView(ctx, '').options.some(option => option.value === effective.preset);
16
+ if (!known)
17
+ return { preset: '', reason: 'invalid' };
18
+ return { preset: effective.preset, reason: 'ok' };
19
+ }
20
+ /**
21
+ * Record the parent preset before `agents.create`. A worker id that does not
22
+ * match the ticket child form is ignored, so this cannot arm an unrelated agent.
23
+ */
24
+ export function rememberWorkerPermission(ctx, workerId, parentId) {
25
+ if (!WORKER_ID.test(workerId))
26
+ return null;
27
+ const snap = snapshotParent(ctx, parentId);
28
+ const intent = {
29
+ workerId,
30
+ parentId,
31
+ preset: snap.preset,
32
+ reason: snap.reason,
33
+ };
34
+ pending.set(workerId, intent);
35
+ return intent;
36
+ }
37
+ /** Drop an intent when create fails before a worker exists. */
38
+ export function dropWorkerPermission(workerId) {
39
+ pending.delete(workerId);
40
+ }
41
+ /** Test isolation. Production create either applies or drops its own intent. */
42
+ export function clearPendingWorkerPermissions() {
43
+ pending.clear();
44
+ }
45
+ export function pendingWorkerPermission(workerId) {
46
+ return pending.get(workerId) ?? null;
47
+ }
48
+ /**
49
+ * Apply the snapshotted parent preset once.
50
+ * `resume`, `clear`, and `compact` do not consume the intent: those events
51
+ * are not the creation pin. A missing source is treated as creation because
52
+ * the only writer of an intent is the dispatch create path.
53
+ * An empty snapshot fails closed: the host pin is left in place, and the
54
+ * instance default is not substituted.
55
+ */
56
+ export function applyWorkerPermission(ctx, workerId, source = 'startup') {
57
+ const intent = pending.get(workerId);
58
+ if (!intent)
59
+ return { applied: false, reason: 'not-pending' };
60
+ if (SKIP_SOURCE.has(source))
61
+ return { applied: false, reason: 'not-startup' };
62
+ if (intent.preset === '') {
63
+ pending.delete(workerId);
64
+ return { applied: false, reason: intent.reason };
65
+ }
66
+ const result = setPermission(ctx, workerId, intent.preset);
67
+ if (result.ok === false) {
68
+ if (result.code === 'NOT_FOUND' || result.code === 'UNAVAILABLE')
69
+ return { applied: false, reason: 'rejected' };
70
+ pending.delete(workerId);
71
+ return { applied: false, reason: 'rejected' };
72
+ }
73
+ pending.delete(workerId);
74
+ return { applied: true, reason: 'applied', preset: intent.preset };
75
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thready-web/dsh-bot-plugin",
3
- "version": "0.1.0-beta.13",
3
+ "version": "0.1.0-beta.15",
4
4
  "type": "module",
5
5
  "description": "DSH bot plugin: session persona, memory, work, hash routing, and the workbench. Pinned to @deepseek-ai/dsh 0.2.2-rc.1.",
6
6
  "license": "MIT",