dsh-taskbridge 1.4.2 → 1.5.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +34 -2
  2. package/README.md +10 -8
  3. package/bin/dsh-delegate-mcp.d.ts +20 -3
  4. package/bin/dsh-delegate-mcp.js +15 -0
  5. package/codex/dsh-taskbridge.toml +180 -16
  6. package/docs/INTRODUCTION.md +2 -2
  7. package/docs/INTRODUCTION.zh.md +2 -2
  8. package/docs/codex-integration.md +11 -13
  9. package/docs/conversation-placement.md +44 -7
  10. package/docs/plugin-market.md +1 -1
  11. package/docs/redaction-contract.md +47 -4
  12. package/docs/releases/1.5.0-token-benchmark.zh.md +73 -0
  13. package/docs/releases/1.5.0.zh.md +51 -0
  14. package/docs/releases/1.5.1.zh.md +70 -0
  15. package/docs/runtime-compatibility.md +4 -4
  16. package/docs/silent-wait.md +157 -3
  17. package/docs/taskbridge-upgrade.md +1 -1
  18. package/docs/worker-permissions.md +154 -17
  19. package/lib/client.js +298 -103
  20. package/package.json +9 -3
  21. package/src/client/api.js +315 -34
  22. package/src/client/index.jsx +151 -67
  23. package/src/codex/installer.js +251 -11
  24. package/src/config/redact.js +72 -11
  25. package/src/http/execution-plane.js +124 -10
  26. package/src/index.d.ts +347 -0
  27. package/src/index.js +88 -5
  28. package/src/jobs/activity.js +102 -9
  29. package/src/jobs/continuation-identity.js +283 -0
  30. package/src/jobs/engine.js +491 -55
  31. package/src/jobs/history.js +96 -0
  32. package/src/mcp/continuation.js +317 -0
  33. package/src/mcp/metrics.js +366 -0
  34. package/src/mcp/server.js +1203 -53
  35. package/src/mcp/wait.js +338 -73
  36. package/src/review/prompts.js +145 -126
  37. package/src/runtime/agent-runner.js +330 -0
  38. package/src/runtime/permissions.js +192 -2
  39. package/src/runtime/question-call.js +162 -0
  40. package/src/runtime/questions.js +909 -0
  41. package/src/runtime/sandbox.js +363 -358
  42. package/src/runtime/session-placement.js +1207 -1121
  43. package/src/version.js +121 -0
  44. package/src/workspace/worktrees.js +70 -4
@@ -1,358 +1,363 @@
1
- // Per-task DSH policy for delegated worker sessions.
2
- //
3
- // A worker must be able to modify its own workspace. DSH keeps that fact in the
4
- // Session event log: `sandbox/mode` is folded by `ctx.sandboxPolicy` and
5
- // `approval/policy` is folded by `ctx.approval`. Writing the events is therefore
6
- // only half the job — the two services that read them back are what actually
7
- // make a run confined, so this module installs the policy through the official
8
- // writers and then READS IT BACK through the resolving services:
9
- //
10
- // * `ctx.sandboxPolicy.resolve({ session })` must answer the requested mode and
11
- // the Session's own workspace root, and
12
- // * `ctx.approval.effectivePolicy(session)` must answer the requested stance,
13
- // and an escalation asked by that session must actually be rejected without
14
- // reaching an approval answerer when no bridge is armed (a `never` session
15
- // rejects deterministically).
16
- //
17
- // Any of these being unavailable, refusing, or disagreeing with what was written
18
- // is a fail-closed refusal raised BEFORE the prompt is delivered
19
- // ({@link SANDBOX_CODES}). Appending the events and hoping is exactly the failure
20
- // mode this contract removes: a session that carries the events but is not
21
- // actually confined would be reported as protected while it was not.
22
- //
23
- // ## The approval stance now has two values, and exactly one of them is per-run
24
- //
25
- // `never` remains the stance of every run WITHOUT a permission bridge, which is
26
- // still the default and still the fail-closed answer: nothing in DSH can prompt
27
- // this plugin, so an escalation is refused immediately and the worker is told so.
28
- //
29
- // `ask` is installed for ONE run, and only when that run hands over an ARMED
30
- // bridge ({@link ./permissions.js}) bound to the Agent being driven. The bridge is
31
- // the answerer: `ctx.approval.request()` dispatches `approval/request` as an
32
- // agent-scoped waterfall, the bridge decides whether the request is its own, and
33
- // the commander decides `allow-once`/`reject` out of band. The standing sandbox
34
- // mode is NOT widened by this: a grant applies to the single call that asked, and
35
- // `workspace-write` stays the Session's mode for the whole run.
36
- //
37
- // The two facts are verified together, and a bridge that is present but not armed
38
- // is treated as NO bridge (the run keeps `never`) rather than as a promise to
39
- // answer a question this plugin cannot see.
40
- //
41
- // Every value set here is per Session and per run: a continuation re-applies it,
42
- // so a resumed thread converges on the current delegate contract instead of
43
- // inheriting an older, possibly interactive policy. Nothing here touches the
44
- // operator's ordinary sessions or the read-only review composition, because it is
45
- // only ever called for a delegated worker run.
46
-
47
- import { sameSessionPath } from './session-placement.js';
48
-
49
- /** Stable delegated-session policy values. */
50
- export const DELEGATE_SANDBOX_MODE = 'workspace-write';
51
- /** The stance of a delegated run with NO permission bridge: deterministic rejection. */
52
- export const DELEGATE_APPROVAL_POLICY = 'never';
53
- /** The stance of a delegated run whose ARMED bridge answers its own requests. */
54
- export const DELEGATE_BRIDGED_APPROVAL_POLICY = 'ask';
55
-
56
- /** Refusal codes for a worker session that cannot be made safe to drive. */
57
- export const SANDBOX_CODES = Object.freeze({
58
- unavailable: 'RUN_SANDBOX_POLICY_UNAVAILABLE',
59
- });
60
-
61
- /**
62
- * Stable reasons carried in `details.reason`.
63
- *
64
- * They are fixed strings chosen by this module — never a caller-supplied value —
65
- * so an operator can tell which capability was missing without reading a raw
66
- * upstream error into a job record.
67
- */
68
- const REASONS = Object.freeze({
69
- noSession: 'session.append unavailable',
70
- noPolicyService: 'sandbox policy service unavailable',
71
- noApprovalService: 'approval service unavailable',
72
- writeRejected: 'policy event rejected',
73
- sandboxUnreadable: 'sandbox policy could not be read back',
74
- approvalUnreadable: 'approval policy could not be read back',
75
- sandboxMismatch: 'sandbox policy read back disagrees',
76
- approvalMismatch: 'approval policy read back disagrees',
77
- // A bridge was handed over but is not usable as the answerer for THIS Agent: it
78
- // is unarmed, disposed, or bound to another conversation. Such a bridge is not
79
- // a promise this plugin can keep, so the run keeps the deterministic `never`
80
- // stance instead of installing an `ask` nobody services.
81
- bridgeUnarmed: 'the permission bridge is not armed for this session',
82
- });
83
-
84
- /** Raised before a delegated prompt when its session policy cannot be installed. */
85
- export class SandboxPolicyError extends Error {
86
- /**
87
- * @param {string} code - stable machine code.
88
- * @param {string} message - bounded operator-facing explanation.
89
- * @param {object} [details] - non-secret facts.
90
- */
91
- constructor(code, message, details = {}) {
92
- super(message);
93
- this.name = 'SandboxPolicyError';
94
- this.code = code;
95
- this.details = details;
96
- }
97
- }
98
-
99
- /**
100
- * The two native services that own a Session's policy.
101
- *
102
- * Both are read live on every call (`ctx.get(name, false)`), for the same reason
103
- * the placement controllers are: DSH may compose a service after this plugin
104
- * activated, and a load-time snapshot would refuse every run forever on a harness
105
- * that composed it moments later.
106
- * @param {object} ctx - plugin context.
107
- * @returns {{ sandboxPolicy: object | null, approval: object | null }} the live services, or null.
108
- */
109
- export function policyServicesOf(ctx) {
110
- return {
111
- sandboxPolicy: readOptionalService(ctx, 'sandboxPolicy'),
112
- approval: readOptionalService(ctx, 'approval'),
113
- };
114
- }
115
-
116
- /**
117
- * Read one optional native service without turning absence into a throw.
118
- * @param {object} ctx - plugin context.
119
- * @param {string} name - service name.
120
- * @returns {object | null} the service, or null when absent or unreadable.
121
- */
122
- function readOptionalService(ctx, name) {
123
- if (ctx === null || ctx === undefined || typeof ctx.get !== 'function') return null;
124
- try {
125
- return ctx.get(name, false) ?? null;
126
- } catch {
127
- // An unreadable service is an ABSENT service: the run is then refused with
128
- // `RUN_SANDBOX_POLICY_UNAVAILABLE` instead of surfacing a property error.
129
- return null;
130
- }
131
- }
132
-
133
- /**
134
- * The Session a delegated run's policy belongs to.
135
- *
136
- * A live native Agent carries its Session; a Session passed directly is accepted
137
- * too, so a caller that already resolved one does not have to re-wrap it.
138
- * @param {object} agentOrSession - native Agent or Session.
139
- * @returns {object | null} the Session, or null.
140
- */
141
- function sessionOf(agentOrSession) {
142
- const candidate = agentOrSession?.session ?? agentOrSession ?? null;
143
- if (candidate === null || typeof candidate !== 'object') return null;
144
- return typeof candidate.append === 'function' ? candidate : null;
145
- }
146
-
147
- /**
148
- * Install the delegate policy for one worker Session and prove it took effect.
149
- *
150
- * The policy is intentionally applied on every run, including an explicit
151
- * continuation, so a resumed session converges on the current contract.
152
- *
153
- * The approval stance is decided by CAPABILITY, never by configuration:
154
- *
155
- * * a run that hands over an ARMED bridge bound to this Agent gets `ask`, and the
156
- * bridge is the answerer the seam will consult;
157
- * * every other run — including one whose bridge is absent, unarmed, disposed or
158
- * bound elsewhere — gets `never`, which the native service resolves by
159
- * rejecting the ask before any answerer runs.
160
- *
161
- * Either way the SAME read-back proves what was installed, and `workspace-write`
162
- * is installed and verified exactly as before. Nothing here ever writes a wider
163
- * sandbox mode: a bridge can only answer a per-call escalation the native tool
164
- * asked for, and that grant never becomes the Session's standing mode.
165
- * @param {object} agentOrSession - native Agent or Session.
166
- * @param {object} [services] - `{ sandboxPolicy, approval }`; both are natively available
167
- * and are required for the policy to be verifiable.
168
- * @param {object} [options] - `bridge`: the run's {@link PermissionBridge}, when it has one.
169
- * @returns {{ mode: string, approvalPolicy: string, workspaceRoot: string, bridged: boolean }} verified facts.
170
- * @throws {SandboxPolicyError} when the Session cannot accept the events, when either
171
- * service is missing, or when either service does not read the policy back.
172
- */
173
- export function configureDelegatedSession(agentOrSession, services = {}, options = {}) {
174
- const session = sessionOf(agentOrSession);
175
- if (session === null) {
176
- throw new SandboxPolicyError(
177
- SANDBOX_CODES.unavailable,
178
- 'the delegated DSH session cannot accept sandbox policy events, so the worker was not started',
179
- { reason: REASONS.noSession },
180
- );
181
- }
182
- const sandboxPolicy = services?.sandboxPolicy ?? null;
183
- const approval = services?.approval ?? null;
184
- // Capability checks come BEFORE anything is written: a run that could not be
185
- // verified must not leave a half-installed policy on a live Session.
186
- assertCapability(sandboxPolicy, 'resolve', REASONS.noPolicyService,
187
- 'the DSH sandbox policy service is unavailable, so the worker could not be confined');
188
- assertCapability(approval, 'effectivePolicy', REASONS.noApprovalService,
189
- 'the DSH approval service is unavailable, so the worker\'s approval stance could not be established');
190
-
191
- // The stance is `ask` ONLY for a bridge that can actually answer: armed, not
192
- // disposed, and bound to the very Agent this policy is installed for. A bridge
193
- // that fails any of those is treated as no bridge (see {@link REASONS.bridgeUnarmed}).
194
- const bridge = options?.bridge ?? null;
195
- const bridged = bridgeUsableFor(bridge, agentOrSession, session);
196
- const stance = bridged ? DELEGATE_BRIDGED_APPROVAL_POLICY : DELEGATE_APPROVAL_POLICY;
197
-
198
- // `sandbox/mode` carries the whole post-change state (the whole-value event
199
- // rule), and `approval/policy` carries the stance the next ask resolves under.
200
- // `never` is deterministic rejection, not automatic approval: an escalation
201
- // asked by this session is refused without reaching any answerer. `ask` is not
202
- // approval either — it delegates the question to the composed answerers, of
203
- // which this run's bridge is one, and an unanswerable question still fails closed.
204
- try {
205
- session.append('sandbox/mode', { mode: DELEGATE_SANDBOX_MODE });
206
- session.append('approval/policy', { policy: stance });
207
- } catch (error) {
208
- throw new SandboxPolicyError(
209
- SANDBOX_CODES.unavailable,
210
- 'the delegated DSH session rejected its sandbox policy, so the worker was not started',
211
- { reason: REASONS.writeRejected, cause: typeof error?.code === 'string' ? error.code : null },
212
- );
213
- }
214
-
215
- const resolved = readSandboxPolicy(sandboxPolicy, session);
216
- const observed = readApprovalPolicy(approval, session);
217
-
218
- if (resolved.mode !== DELEGATE_SANDBOX_MODE) {
219
- throw new SandboxPolicyError(
220
- SANDBOX_CODES.unavailable,
221
- 'the DSH sandbox policy does not resolve as installed, so the worker was not started',
222
- { reason: REASONS.sandboxMismatch, expected: DELEGATE_SANDBOX_MODE, observed: resolved.mode },
223
- );
224
- }
225
- // A `workspace-write` session with no workspace root would write nowhere; a root
226
- // that is not the Session's own directory would write somewhere else. Both are
227
- // the same operator situation: the confinement does not cover this conversation.
228
- // The comparison is `sameSessionPath` — the one canonical-directory identity this
229
- // plugin already uses to place and to resume sessions — so a separator, a
230
- // trailing slash or a letter case on Windows cannot make one directory look like
231
- // another (or a different one look the same) here.
232
- const headerCwd = typeof session.header?.cwd === 'string' ? session.header.cwd : null;
233
- if (typeof resolved.workspaceRoot !== 'string' || resolved.workspaceRoot === '') {
234
- throw new SandboxPolicyError(
235
- SANDBOX_CODES.unavailable,
236
- 'the DSH sandbox policy reports no workspace root for this session, so the worker was not started',
237
- { reason: REASONS.sandboxMismatch },
238
- );
239
- }
240
- if (headerCwd !== null && !sameSessionPath(resolved.workspaceRoot, headerCwd)) {
241
- throw new SandboxPolicyError(
242
- SANDBOX_CODES.unavailable,
243
- 'the DSH sandbox policy resolves another workspace than this session\'s own, so the worker was not started',
244
- { reason: REASONS.sandboxMismatch, sessionPath: headerCwd, workspaceRoot: resolved.workspaceRoot },
245
- );
246
- }
247
- if (observed !== stance) {
248
- throw new SandboxPolicyError(
249
- SANDBOX_CODES.unavailable,
250
- bridged
251
- ? 'the DSH approval policy does not resolve as the armed bridge stance, so the worker was not started'
252
- : 'the DSH approval policy does not resolve as installed, so the worker was not started',
253
- { reason: REASONS.approvalMismatch, expected: stance, observed },
254
- );
255
- }
256
- return {
257
- mode: resolved.mode,
258
- approvalPolicy: observed,
259
- workspaceRoot: resolved.workspaceRoot,
260
- // Whether an armed bridge is the reason this Session asks instead of rejecting.
261
- bridged,
262
- };
263
- }
264
-
265
- /**
266
- * Whether a bridge can actually answer this run's requests.
267
- *
268
- * The three facts are checked together because any one of them missing makes the
269
- * `ask` stance a promise nobody keeps: an unarmed bridge never answers, a disposed
270
- * one answers `unavailable`, and a bridge bound to another Agent refuses every
271
- * request as foreign. In all three cases the run keeps `never` and is told so by
272
- * the read-back, instead of installing a stance whose answerer cannot exist.
273
- * @param {object | null} bridge - the run's permission bridge, when it has one.
274
- * @param {unknown} agentOrSession - the policy subject.
275
- * @param {object} session - the Session the policy is installed on.
276
- * @returns {boolean} true when the bridge is the answerer for this Session.
277
- */
278
- function bridgeUsableFor(bridge, agentOrSession, session) {
279
- if (bridge === null || bridge === undefined || typeof bridge !== 'object') return false;
280
- if (bridge.armed !== true || bridge.disposed === true) return false;
281
- if (typeof bridge.owns !== 'function') return false;
282
- const agent = agentOrSession?.session !== undefined ? agentOrSession : { session };
283
- try {
284
- // The bridge's own identity rule decides, on the same shape a live request has.
285
- return bridge.owns({ agent, toolName: '', callId: '' }) === true;
286
- } catch {
287
- return false;
288
- }
289
- }
290
-
291
- /**
292
- * Refuse a service that cannot answer the question the policy needs answered.
293
- * @param {unknown} service - native service or null.
294
- * @param {string} method - the call the policy verifies through.
295
- * @param {string} reason - stable `details.reason`.
296
- * @param {string} message - operator-facing explanation.
297
- * @returns {void}
298
- * @throws {SandboxPolicyError} when the call is absent.
299
- */
300
- function assertCapability(service, method, reason, message) {
301
- if (service === null || typeof service !== 'object' || typeof service[method] !== 'function') {
302
- throw new SandboxPolicyError(SANDBOX_CODES.unavailable, message, { reason });
303
- }
304
- }
305
-
306
- /**
307
- * Read the resolved sandbox policy back through the owning service.
308
- *
309
- * This is the same call an enforcing tool layer makes at each capability
310
- * boundary, so a value read here is what the next confined call will run under.
311
- * @param {object} sandboxPolicy - `ctx.sandboxPolicy`.
312
- * @param {object} session - the delegated Session, and the exact policy subject.
313
- * @returns {{ mode: unknown, workspaceRoot: unknown }} resolved policy facts.
314
- * @throws {SandboxPolicyError} when the service refuses to answer.
315
- */
316
- function readSandboxPolicy(sandboxPolicy, session) {
317
- let resolved;
318
- try {
319
- resolved = sandboxPolicy.resolve({ session });
320
- } catch (error) {
321
- throw new SandboxPolicyError(
322
- SANDBOX_CODES.unavailable,
323
- 'the DSH sandbox policy could not be resolved for this session, so the worker was not started',
324
- { reason: REASONS.sandboxUnreadable, cause: typeof error?.code === 'string' ? error.code : null },
325
- );
326
- }
327
- if (resolved === null || typeof resolved !== 'object') {
328
- throw new SandboxPolicyError(
329
- SANDBOX_CODES.unavailable,
330
- 'the DSH sandbox policy service answered without a policy, so the worker was not started',
331
- { reason: REASONS.sandboxUnreadable },
332
- );
333
- }
334
- return { mode: resolved.mode, workspaceRoot: resolved.workspaceRoot };
335
- }
336
-
337
- /**
338
- * Read the Session's effective approval stance back through the owning service.
339
- *
340
- * `never` is the only stance that makes the worker unable to wait for an approval
341
- * prompt this plugin cannot answer, so anything else — including a service that
342
- * answers with a non-string — is refused rather than interpreted.
343
- * @param {object} approval - `ctx.approval`.
344
- * @param {object} session - the delegated Session.
345
- * @returns {unknown} the effective policy.
346
- * @throws {SandboxPolicyError} when the service refuses to answer.
347
- */
348
- function readApprovalPolicy(approval, session) {
349
- try {
350
- return approval.effectivePolicy(session);
351
- } catch (error) {
352
- throw new SandboxPolicyError(
353
- SANDBOX_CODES.unavailable,
354
- 'the DSH approval policy could not be read for this session, so the worker was not started',
355
- { reason: REASONS.approvalUnreadable, cause: typeof error?.code === 'string' ? error.code : null },
356
- );
357
- }
358
- }
1
+ // Per-task DSH policy for delegated worker sessions.
2
+ //
3
+ // A worker must be able to modify its own workspace. DSH keeps that fact in the
4
+ // Session event log: `sandbox/mode` is folded by `ctx.sandboxPolicy` and
5
+ // `approval/policy` is folded by `ctx.approval`. Writing the events is therefore
6
+ // only half the job — the two services that read them back are what actually
7
+ // make a run confined, so this module installs the policy through the official
8
+ // writers and then READS IT BACK through the resolving services:
9
+ //
10
+ // * `ctx.sandboxPolicy.resolve({ session })` must answer the requested mode and
11
+ // the Session's own workspace root, and
12
+ // * `ctx.approval.effectivePolicy(session)` must answer the requested stance,
13
+ // and an escalation asked by that session must actually be rejected without
14
+ // reaching an approval answerer when no bridge is armed (a `never` session
15
+ // rejects deterministically).
16
+ //
17
+ // Any of these being unavailable, refusing, or disagreeing with what was written
18
+ // is a fail-closed refusal raised BEFORE the prompt is delivered
19
+ // ({@link SANDBOX_CODES}). Appending the events and hoping is exactly the failure
20
+ // mode this contract removes: a session that carries the events but is not
21
+ // actually confined would be reported as protected while it was not.
22
+ //
23
+ // ## The approval stance now has two values, and exactly one of them is per-run
24
+ //
25
+ // `never` remains the stance of every run WITHOUT a permission bridge, which is
26
+ // still the default and still the fail-closed answer: nothing in DSH can prompt
27
+ // this plugin, so an escalation is refused immediately and the worker is told so.
28
+ //
29
+ // `ask` is installed for ONE run, and only when that run hands over an ARMED
30
+ // bridge ({@link ./permissions.js}) bound to the Agent being driven. The bridge is
31
+ // the answerer: `ctx.approval.request()` dispatches `approval/request` as an
32
+ // agent-scoped waterfall, the bridge decides whether the request is its own, and
33
+ // the commander decides `allow-once`/`reject` out of band. The standing sandbox
34
+ // mode is NOT widened by this: a grant applies to the single call that asked, and
35
+ // `workspace-write` stays the Session's mode for the whole run.
36
+ //
37
+ // The two facts are verified together, and a bridge that is present but not armed
38
+ // is treated as NO bridge (the run keeps `never`) rather than as a promise to
39
+ // answer a question this plugin cannot see.
40
+ //
41
+ // Every value set here is per Session and per run: a continuation re-applies it,
42
+ // so a resumed thread converges on the current delegate contract instead of
43
+ // inheriting an older, possibly interactive policy. Nothing here touches the
44
+ // operator's ordinary sessions or the read-only review composition, because it is
45
+ // only ever called for a delegated worker run.
46
+
47
+ import { sameSessionPath } from './session-placement.js';
48
+
49
+ /** Stable delegated-session policy values. */
50
+ export const DELEGATE_SANDBOX_MODE = 'workspace-write';
51
+ /** The stance of a delegated run with NO permission bridge: deterministic rejection. */
52
+ export const DELEGATE_APPROVAL_POLICY = 'never';
53
+ /** The stance of a delegated run whose ARMED bridge answers its own requests. */
54
+ export const DELEGATE_BRIDGED_APPROVAL_POLICY = 'ask';
55
+
56
+ /** Refusal codes for a worker session that cannot be made safe to drive. */
57
+ export const SANDBOX_CODES = Object.freeze({
58
+ unavailable: 'RUN_SANDBOX_POLICY_UNAVAILABLE',
59
+ });
60
+
61
+ /**
62
+ * Stable reasons carried in `details.reason`.
63
+ *
64
+ * They are fixed strings chosen by this module — never a caller-supplied value —
65
+ * so an operator can tell which capability was missing without reading a raw
66
+ * upstream error into a job record.
67
+ */
68
+ const REASONS = Object.freeze({
69
+ noSession: 'session.append unavailable',
70
+ noPolicyService: 'sandbox policy service unavailable',
71
+ noApprovalService: 'approval service unavailable',
72
+ writeRejected: 'policy event rejected',
73
+ sandboxUnreadable: 'sandbox policy could not be read back',
74
+ approvalUnreadable: 'approval policy could not be read back',
75
+ sandboxMismatch: 'sandbox policy read back disagrees',
76
+ approvalMismatch: 'approval policy read back disagrees',
77
+ // A bridge was handed over but is not usable as the answerer for THIS Agent: it
78
+ // is unarmed, disposed, or bound to another conversation. Such a bridge is not
79
+ // a promise this plugin can keep, so the run keeps the deterministic `never`
80
+ // stance instead of installing an `ask` nobody services.
81
+ bridgeUnarmed: 'the permission bridge is not armed for this session',
82
+ });
83
+
84
+ /** Raised before a delegated prompt when its session policy cannot be installed. */
85
+ export class SandboxPolicyError extends Error {
86
+ /**
87
+ * @param {string} code - stable machine code.
88
+ * @param {string} message - bounded operator-facing explanation.
89
+ * @param {object} [details] - non-secret facts.
90
+ */
91
+ constructor(code, message, details = {}) {
92
+ super(message);
93
+ this.name = 'SandboxPolicyError';
94
+ this.code = code;
95
+ this.details = details;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * The two native services that own a Session's policy.
101
+ *
102
+ * Both are read live on every call (`ctx.get(name, false)`), for the same reason
103
+ * the placement controllers are: DSH may compose a service after this plugin
104
+ * activated, and a load-time snapshot would refuse every run forever on a harness
105
+ * that composed it moments later.
106
+ * @param {object} ctx - plugin context.
107
+ * @returns {{ sandboxPolicy: object | null, approval: object | null }} the live services, or null.
108
+ */
109
+ export function policyServicesOf(ctx) {
110
+ return {
111
+ sandboxPolicy: readOptionalService(ctx, 'sandboxPolicy'),
112
+ approval: readOptionalService(ctx, 'approval'),
113
+ // The DSH Agent Teams service (the feature behind the model menu's 「Use Agent Teams」
114
+ // switch). Read live like the others: a composition may mount it after this plugin
115
+ // activated, and its ABSENCE must be reported as "not available" rather than
116
+ // silently turning a requested team run into an ordinary one.
117
+ agentTeams: readOptionalService(ctx, 'agentTeams'),
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Read one optional native service without turning absence into a throw.
123
+ * @param {object} ctx - plugin context.
124
+ * @param {string} name - service name.
125
+ * @returns {object | null} the service, or null when absent or unreadable.
126
+ */
127
+ function readOptionalService(ctx, name) {
128
+ if (ctx === null || ctx === undefined || typeof ctx.get !== 'function') return null;
129
+ try {
130
+ return ctx.get(name, false) ?? null;
131
+ } catch {
132
+ // An unreadable service is an ABSENT service: the run is then refused with
133
+ // `RUN_SANDBOX_POLICY_UNAVAILABLE` instead of surfacing a property error.
134
+ return null;
135
+ }
136
+ }
137
+
138
+ /**
139
+ * The Session a delegated run's policy belongs to.
140
+ *
141
+ * A live native Agent carries its Session; a Session passed directly is accepted
142
+ * too, so a caller that already resolved one does not have to re-wrap it.
143
+ * @param {object} agentOrSession - native Agent or Session.
144
+ * @returns {object | null} the Session, or null.
145
+ */
146
+ function sessionOf(agentOrSession) {
147
+ const candidate = agentOrSession?.session ?? agentOrSession ?? null;
148
+ if (candidate === null || typeof candidate !== 'object') return null;
149
+ return typeof candidate.append === 'function' ? candidate : null;
150
+ }
151
+
152
+ /**
153
+ * Install the delegate policy for one worker Session and prove it took effect.
154
+ *
155
+ * The policy is intentionally applied on every run, including an explicit
156
+ * continuation, so a resumed session converges on the current contract.
157
+ *
158
+ * The approval stance is decided by CAPABILITY, never by configuration:
159
+ *
160
+ * * a run that hands over an ARMED bridge bound to this Agent gets `ask`, and the
161
+ * bridge is the answerer the seam will consult;
162
+ * * every other run — including one whose bridge is absent, unarmed, disposed or
163
+ * bound elsewhere — gets `never`, which the native service resolves by
164
+ * rejecting the ask before any answerer runs.
165
+ *
166
+ * Either way the SAME read-back proves what was installed, and `workspace-write`
167
+ * is installed and verified exactly as before. Nothing here ever writes a wider
168
+ * sandbox mode: a bridge can only answer a per-call escalation the native tool
169
+ * asked for, and that grant never becomes the Session's standing mode.
170
+ * @param {object} agentOrSession - native Agent or Session.
171
+ * @param {object} [services] - `{ sandboxPolicy, approval }`; both are natively available
172
+ * and are required for the policy to be verifiable.
173
+ * @param {object} [options] - `bridge`: the run's {@link PermissionBridge}, when it has one.
174
+ * @returns {{ mode: string, approvalPolicy: string, workspaceRoot: string, bridged: boolean }} verified facts.
175
+ * @throws {SandboxPolicyError} when the Session cannot accept the events, when either
176
+ * service is missing, or when either service does not read the policy back.
177
+ */
178
+ export function configureDelegatedSession(agentOrSession, services = {}, options = {}) {
179
+ const session = sessionOf(agentOrSession);
180
+ if (session === null) {
181
+ throw new SandboxPolicyError(
182
+ SANDBOX_CODES.unavailable,
183
+ 'the delegated DSH session cannot accept sandbox policy events, so the worker was not started',
184
+ { reason: REASONS.noSession },
185
+ );
186
+ }
187
+ const sandboxPolicy = services?.sandboxPolicy ?? null;
188
+ const approval = services?.approval ?? null;
189
+ // Capability checks come BEFORE anything is written: a run that could not be
190
+ // verified must not leave a half-installed policy on a live Session.
191
+ assertCapability(sandboxPolicy, 'resolve', REASONS.noPolicyService,
192
+ 'the DSH sandbox policy service is unavailable, so the worker could not be confined');
193
+ assertCapability(approval, 'effectivePolicy', REASONS.noApprovalService,
194
+ 'the DSH approval service is unavailable, so the worker\'s approval stance could not be established');
195
+
196
+ // The stance is `ask` ONLY for a bridge that can actually answer: armed, not
197
+ // disposed, and bound to the very Agent this policy is installed for. A bridge
198
+ // that fails any of those is treated as no bridge (see {@link REASONS.bridgeUnarmed}).
199
+ const bridge = options?.bridge ?? null;
200
+ const bridged = bridgeUsableFor(bridge, agentOrSession, session);
201
+ const stance = bridged ? DELEGATE_BRIDGED_APPROVAL_POLICY : DELEGATE_APPROVAL_POLICY;
202
+
203
+ // `sandbox/mode` carries the whole post-change state (the whole-value event
204
+ // rule), and `approval/policy` carries the stance the next ask resolves under.
205
+ // `never` is deterministic rejection, not automatic approval: an escalation
206
+ // asked by this session is refused without reaching any answerer. `ask` is not
207
+ // approval either — it delegates the question to the composed answerers, of
208
+ // which this run's bridge is one, and an unanswerable question still fails closed.
209
+ try {
210
+ session.append('sandbox/mode', { mode: DELEGATE_SANDBOX_MODE });
211
+ session.append('approval/policy', { policy: stance });
212
+ } catch (error) {
213
+ throw new SandboxPolicyError(
214
+ SANDBOX_CODES.unavailable,
215
+ 'the delegated DSH session rejected its sandbox policy, so the worker was not started',
216
+ { reason: REASONS.writeRejected, cause: typeof error?.code === 'string' ? error.code : null },
217
+ );
218
+ }
219
+
220
+ const resolved = readSandboxPolicy(sandboxPolicy, session);
221
+ const observed = readApprovalPolicy(approval, session);
222
+
223
+ if (resolved.mode !== DELEGATE_SANDBOX_MODE) {
224
+ throw new SandboxPolicyError(
225
+ SANDBOX_CODES.unavailable,
226
+ 'the DSH sandbox policy does not resolve as installed, so the worker was not started',
227
+ { reason: REASONS.sandboxMismatch, expected: DELEGATE_SANDBOX_MODE, observed: resolved.mode },
228
+ );
229
+ }
230
+ // A `workspace-write` session with no workspace root would write nowhere; a root
231
+ // that is not the Session's own directory would write somewhere else. Both are
232
+ // the same operator situation: the confinement does not cover this conversation.
233
+ // The comparison is `sameSessionPath` — the one canonical-directory identity this
234
+ // plugin already uses to place and to resume sessions — so a separator, a
235
+ // trailing slash or a letter case on Windows cannot make one directory look like
236
+ // another (or a different one look the same) here.
237
+ const headerCwd = typeof session.header?.cwd === 'string' ? session.header.cwd : null;
238
+ if (typeof resolved.workspaceRoot !== 'string' || resolved.workspaceRoot === '') {
239
+ throw new SandboxPolicyError(
240
+ SANDBOX_CODES.unavailable,
241
+ 'the DSH sandbox policy reports no workspace root for this session, so the worker was not started',
242
+ { reason: REASONS.sandboxMismatch },
243
+ );
244
+ }
245
+ if (headerCwd !== null && !sameSessionPath(resolved.workspaceRoot, headerCwd)) {
246
+ throw new SandboxPolicyError(
247
+ SANDBOX_CODES.unavailable,
248
+ 'the DSH sandbox policy resolves another workspace than this session\'s own, so the worker was not started',
249
+ { reason: REASONS.sandboxMismatch, sessionPath: headerCwd, workspaceRoot: resolved.workspaceRoot },
250
+ );
251
+ }
252
+ if (observed !== stance) {
253
+ throw new SandboxPolicyError(
254
+ SANDBOX_CODES.unavailable,
255
+ bridged
256
+ ? 'the DSH approval policy does not resolve as the armed bridge stance, so the worker was not started'
257
+ : 'the DSH approval policy does not resolve as installed, so the worker was not started',
258
+ { reason: REASONS.approvalMismatch, expected: stance, observed },
259
+ );
260
+ }
261
+ return {
262
+ mode: resolved.mode,
263
+ approvalPolicy: observed,
264
+ workspaceRoot: resolved.workspaceRoot,
265
+ // Whether an armed bridge is the reason this Session asks instead of rejecting.
266
+ bridged,
267
+ };
268
+ }
269
+
270
+ /**
271
+ * Whether a bridge can actually answer this run's requests.
272
+ *
273
+ * The three facts are checked together because any one of them missing makes the
274
+ * `ask` stance a promise nobody keeps: an unarmed bridge never answers, a disposed
275
+ * one answers `unavailable`, and a bridge bound to another Agent refuses every
276
+ * request as foreign. In all three cases the run keeps `never` and is told so by
277
+ * the read-back, instead of installing a stance whose answerer cannot exist.
278
+ * @param {object | null} bridge - the run's permission bridge, when it has one.
279
+ * @param {unknown} agentOrSession - the policy subject.
280
+ * @param {object} session - the Session the policy is installed on.
281
+ * @returns {boolean} true when the bridge is the answerer for this Session.
282
+ */
283
+ function bridgeUsableFor(bridge, agentOrSession, session) {
284
+ if (bridge === null || bridge === undefined || typeof bridge !== 'object') return false;
285
+ if (bridge.armed !== true || bridge.disposed === true) return false;
286
+ if (typeof bridge.owns !== 'function') return false;
287
+ const agent = agentOrSession?.session !== undefined ? agentOrSession : { session };
288
+ try {
289
+ // The bridge's own identity rule decides, on the same shape a live request has.
290
+ return bridge.owns({ agent, toolName: '', callId: '' }) === true;
291
+ } catch {
292
+ return false;
293
+ }
294
+ }
295
+
296
+ /**
297
+ * Refuse a service that cannot answer the question the policy needs answered.
298
+ * @param {unknown} service - native service or null.
299
+ * @param {string} method - the call the policy verifies through.
300
+ * @param {string} reason - stable `details.reason`.
301
+ * @param {string} message - operator-facing explanation.
302
+ * @returns {void}
303
+ * @throws {SandboxPolicyError} when the call is absent.
304
+ */
305
+ function assertCapability(service, method, reason, message) {
306
+ if (service === null || typeof service !== 'object' || typeof service[method] !== 'function') {
307
+ throw new SandboxPolicyError(SANDBOX_CODES.unavailable, message, { reason });
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Read the resolved sandbox policy back through the owning service.
313
+ *
314
+ * This is the same call an enforcing tool layer makes at each capability
315
+ * boundary, so a value read here is what the next confined call will run under.
316
+ * @param {object} sandboxPolicy - `ctx.sandboxPolicy`.
317
+ * @param {object} session - the delegated Session, and the exact policy subject.
318
+ * @returns {{ mode: unknown, workspaceRoot: unknown }} resolved policy facts.
319
+ * @throws {SandboxPolicyError} when the service refuses to answer.
320
+ */
321
+ function readSandboxPolicy(sandboxPolicy, session) {
322
+ let resolved;
323
+ try {
324
+ resolved = sandboxPolicy.resolve({ session });
325
+ } catch (error) {
326
+ throw new SandboxPolicyError(
327
+ SANDBOX_CODES.unavailable,
328
+ 'the DSH sandbox policy could not be resolved for this session, so the worker was not started',
329
+ { reason: REASONS.sandboxUnreadable, cause: typeof error?.code === 'string' ? error.code : null },
330
+ );
331
+ }
332
+ if (resolved === null || typeof resolved !== 'object') {
333
+ throw new SandboxPolicyError(
334
+ SANDBOX_CODES.unavailable,
335
+ 'the DSH sandbox policy service answered without a policy, so the worker was not started',
336
+ { reason: REASONS.sandboxUnreadable },
337
+ );
338
+ }
339
+ return { mode: resolved.mode, workspaceRoot: resolved.workspaceRoot };
340
+ }
341
+
342
+ /**
343
+ * Read the Session's effective approval stance back through the owning service.
344
+ *
345
+ * `never` is the only stance that makes the worker unable to wait for an approval
346
+ * prompt this plugin cannot answer, so anything else — including a service that
347
+ * answers with a non-string — is refused rather than interpreted.
348
+ * @param {object} approval - `ctx.approval`.
349
+ * @param {object} session - the delegated Session.
350
+ * @returns {unknown} the effective policy.
351
+ * @throws {SandboxPolicyError} when the service refuses to answer.
352
+ */
353
+ function readApprovalPolicy(approval, session) {
354
+ try {
355
+ return approval.effectivePolicy(session);
356
+ } catch (error) {
357
+ throw new SandboxPolicyError(
358
+ SANDBOX_CODES.unavailable,
359
+ 'the DSH approval policy could not be read for this session, so the worker was not started',
360
+ { reason: REASONS.approvalUnreadable, cause: typeof error?.code === 'string' ? error.code : null },
361
+ );
362
+ }
363
+ }