dsh-taskbridge 0.0.0-stage → 1.3.2

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 (75) hide show
  1. package/CHANGELOG.md +763 -0
  2. package/LICENSE +21 -0
  3. package/README.md +622 -3
  4. package/bin/dsh-delegate-codex-agent.js +115 -0
  5. package/bin/dsh-delegate-control.d.ts +90 -0
  6. package/bin/dsh-delegate-control.js +450 -0
  7. package/bin/dsh-delegate-mcp.d.ts +121 -0
  8. package/bin/dsh-delegate-mcp.js +273 -0
  9. package/codex/dsh-taskbridge.toml +247 -0
  10. package/cordis.patch.yml +6 -0
  11. package/docs/INTRODUCTION.md +15 -0
  12. package/docs/INTRODUCTION.zh.md +34 -0
  13. package/docs/auth-contract.md +138 -0
  14. package/docs/claude-code.md +31 -0
  15. package/docs/codex-integration.md +937 -0
  16. package/docs/contracts-stage-b.md +443 -0
  17. package/docs/conversation-placement.md +304 -0
  18. package/docs/plugin-market.md +30 -0
  19. package/docs/redaction-contract.md +127 -0
  20. package/docs/runtime-compatibility.md +223 -0
  21. package/docs/silent-wait.md +191 -0
  22. package/docs/taskbridge-upgrade.md +28 -0
  23. package/docs/taskdispatch-upgrade.md +25 -0
  24. package/docs/worker-permissions.md +347 -0
  25. package/docs/workspace-contract.md +538 -0
  26. package/icon.svg +1 -0
  27. package/lib/client.d.ts +118 -0
  28. package/lib/client.js +3232 -0
  29. package/locale/en.json +7 -0
  30. package/locale/zh.json +7 -0
  31. package/package.json +138 -4
  32. package/src/auth/fence.js +361 -0
  33. package/src/auth/grants.js +789 -0
  34. package/src/client/api.js +2322 -0
  35. package/src/client/index.jsx +2333 -0
  36. package/src/client/styles.js +251 -0
  37. package/src/codex/installer.js +3299 -0
  38. package/src/codex/seam.js +429 -0
  39. package/src/codex/toml.js +784 -0
  40. package/src/config/defaults.js +164 -0
  41. package/src/config/redact.js +184 -0
  42. package/src/config/settings.js +629 -0
  43. package/src/config/store.js +186 -0
  44. package/src/config/validate.js +763 -0
  45. package/src/credentials/seam.js +202 -0
  46. package/src/http/execution-plane.js +456 -0
  47. package/src/http/respond.js +175 -0
  48. package/src/http/user-plane.js +1122 -0
  49. package/src/index.d.ts +332 -0
  50. package/src/index.js +657 -0
  51. package/src/jobs/activity.js +1008 -0
  52. package/src/jobs/engine.js +3614 -0
  53. package/src/jobs/history.js +1467 -0
  54. package/src/jobs/title.js +17 -0
  55. package/src/mcp/server.js +1821 -0
  56. package/src/mcp/wait.js +536 -0
  57. package/src/model/connectivity.js +371 -0
  58. package/src/model/discovery.js +582 -0
  59. package/src/model/native-catalog.js +68 -0
  60. package/src/model/openai-adapter.js +671 -0
  61. package/src/model/probe.js +264 -0
  62. package/src/model/providers.js +756 -0
  63. package/src/model/routing.js +321 -0
  64. package/src/review/preset.js +868 -0
  65. package/src/review/prompts.js +126 -0
  66. package/src/review/reviewer.js +933 -0
  67. package/src/runtime/agent-runner.js +1740 -0
  68. package/src/runtime/endpoint-discovery.js +118 -0
  69. package/src/runtime/permissions.js +1429 -0
  70. package/src/runtime/sandbox.js +358 -0
  71. package/src/runtime/session-placement.js +1121 -0
  72. package/src/workspace/audit.js +775 -0
  73. package/src/workspace/locks.js +167 -0
  74. package/src/workspace/preflight.js +424 -0
  75. package/src/workspace/worktrees.js +613 -0
@@ -0,0 +1,121 @@
1
+ // Type declarations for the stdio MCP executable (`bin/dsh-delegate-mcp.js`).
2
+ //
3
+ // The file is both an executable and an importable module: importing it must not
4
+ // start a stdio loop or touch `process.exitCode`, which is what lets a test drive
5
+ // {@link readConfig} and {@link createExecutionClient} directly. These declarations
6
+ // describe that importable surface.
7
+
8
+ /**
9
+ * Process configuration parsed from the environment (never from argv).
10
+ *
11
+ * The base URL is discovered from the running DSH plugin unless explicitly set
12
+ * through `DSH_DELEGATE_BASE_URL`. The discovery file can be overridden with
13
+ * `DSH_DELEGATE_DISCOVERY_FILE`; otherwise it follows `DSH_HOME` or `~/.dsh`.
14
+ */
15
+ export interface McpConfig {
16
+ /** Configured origin, or null to reread the running DSH endpoint on each call. */
17
+ baseUrl: string | null;
18
+ /** Absolute path to the DSH plugin's runtime endpoint discovery record. */
19
+ discoveryFile: string;
20
+ /** Per-call bound in milliseconds. */
21
+ timeoutMs: number;
22
+ }
23
+
24
+ /** Error codes `readConfig` refuses with. */
25
+ export type McpConfigErrorCode = 'MCP_CONFIG_INVALID';
26
+
27
+ /**
28
+ * Read the environment configuration this process needs.
29
+ *
30
+ * Throws an `McpError` with code {@link McpConfigErrorCode} when an explicit
31
+ * base URL is not an absolute http(s) URL.
32
+ * @param env - process environment.
33
+ */
34
+ export declare function readConfig(env: Record<string, string | undefined>): McpConfig;
35
+
36
+ /**
37
+ * Execution-plane route names the MCP tools dispatch to.
38
+ *
39
+ * Each name maps to one exact registered path:
40
+ *
41
+ * - `status` → `GET /dsh-delegate/x/status`
42
+ * - `submit` → `POST /dsh-delegate/x/tasks`
43
+ * - `result` → `POST /dsh-delegate/x/tasks/get`
44
+ * - `observe` → `POST /dsh-delegate/x/tasks/observe` (bounded long-poll read)
45
+ * - `cancel` → `POST /dsh-delegate/x/tasks/cancel`
46
+ * - `permission`→ `POST /dsh-delegate/x/tasks/permission`
47
+ * - `preflight` → `POST /dsh-delegate/x/workspace/preflight`
48
+ *
49
+ * `observe` backs `delegate_wait`; `preflight` is the read-only workspace
50
+ * inspection behind `delegate_preflight`, and it creates nothing.
51
+ */
52
+ export type ExecutionRoute = 'submit' | 'status' | 'result' | 'observe' | 'cancel' | 'permission' | 'preflight';
53
+
54
+ /**
55
+ * Per-call context passed beside the route and payload.
56
+ *
57
+ * `signal` is the host's own cancellation of THIS request (for example a JSON-RPC
58
+ * `notifications/cancelled`). It is composed with the client's request timeout, so
59
+ * an aborted call ends the HTTP request and nothing else: the harness answers a
60
+ * disconnected observer without changing the task it was observing.
61
+ *
62
+ * `retry: false` disables the `observe` retry for THIS call only. It is for a caller
63
+ * whose whole contract is one short budget (the control CLI): the backoff schedule
64
+ * would outlive it and leave a request running afterwards. The default — `retry`
65
+ * absent or any other value — is unchanged, so `delegate_wait` keeps following a DSH
66
+ * restart onto a new port.
67
+ */
68
+ export interface ExecutionCallContext {
69
+ signal?: AbortSignal;
70
+ retry?: boolean;
71
+ }
72
+
73
+ /**
74
+ * One execution-plane answer. Every successful route answers `ok: true`; a refusal
75
+ * is thrown as an `McpError` carrying the harness's own code.
76
+ */
77
+ export interface ExecutionAnswer {
78
+ ok: true;
79
+ [field: string]: unknown;
80
+ }
81
+
82
+ /**
83
+ * Backoff between attempts while the endpoint is unreachable, in milliseconds.
84
+ *
85
+ * The sum (8 s) is far below {@link ENDPOINT_RETRY_BUDGET_MS}; a permanently dead
86
+ * endpoint therefore produces a compact refusal instead of a hanging wait.
87
+ */
88
+ export declare const ENDPOINT_RETRY_DELAYS_MS: readonly number[];
89
+
90
+ /** Total budget for retrying one internal request, in milliseconds. */
91
+ export declare const ENDPOINT_RETRY_BUDGET_MS: number;
92
+
93
+ /**
94
+ * Injectable seams for tests. Production passes none of them.
95
+ *
96
+ * `sleep` is used between endpoint retries; a test replaces it so a transient
97
+ * disconnect can be exercised without actually waiting seconds. `fetch` replaces the
98
+ * global transport for a caller that owns its own HTTP stack (and for a test that must
99
+ * not open a socket); the retry policy, timeout and refusal mapping are unchanged.
100
+ */
101
+ export interface ExecutionClientOptions {
102
+ sleep?: (ms: number) => Promise<void>;
103
+ fetch?: (url: string, init: object) => Promise<{ ok: boolean, status: number, json: () => Promise<unknown> }>;
104
+ }
105
+
106
+ /**
107
+ * Build the HTTP call the MCP tools use.
108
+ *
109
+ * Every refusal is normalized into an `McpError` carrying the harness's own code,
110
+ * so a tool result says `GRANT_UNKNOWN` rather than `HTTP 404`. The runtime
111
+ * discovery record is reread before EACH internal request, so a wait survives a
112
+ * DSH restart onto another port; only the `observe` route retries an unreachable
113
+ * endpoint (bounded backoff), because repeating a submission would be unsafe. A
114
+ * caller may opt its own call out of that retry with `{ retry: false }`.
115
+ * @param config - value from {@link readConfig}.
116
+ * @param options - optional test seams.
117
+ */
118
+ export declare function createExecutionClient(
119
+ config: McpConfig,
120
+ options?: ExecutionClientOptions,
121
+ ): (route: ExecutionRoute, payload: object, context?: ExecutionCallContext) => Promise<ExecutionAnswer>;
@@ -0,0 +1,273 @@
1
+ #!/usr/bin/env node
2
+ // Stdio MCP entry point.
3
+ //
4
+ // This is the executable a DSH `mcp-client` instance spawns. It is deliberately
5
+ // thin: resolve the DSH listener from its runtime discovery file, forward each
6
+ // tool call to the loopback execution plane, and print JSON-RPC on stdout. It
7
+ // holds no state, opens no port, and writes nothing to stdout except protocol messages — a stray
8
+ // `console.log` here would corrupt the stream, so diagnostics go to stderr.
9
+ //
10
+ // DSH_DELEGATE_BASE_URL optional fixed endpoint override
11
+ // DSH_DELEGATE_DISCOVERY_FILE optional discovery-file override
12
+
13
+ import { fileURLToPath } from 'node:url';
14
+
15
+ import { createMcpServer, serveStdio, DEFAULT_REQUEST_TIMEOUT_MS, McpError } from '../src/mcp/server.js';
16
+ import { readRuntimeEndpoint, resolveEndpointDiscoveryPath } from '../src/runtime/endpoint-discovery.js';
17
+
18
+ /**
19
+ * Read the endpoint configuration for the local DSH instance.
20
+ * @param {Record<string, string | undefined>} env - process environment.
21
+ * @returns {{ baseUrl: string | null, discoveryFile: string, timeoutMs: number }} configuration.
22
+ */
23
+ export function readConfig(env) {
24
+ const configuredUrl = (env.DSH_DELEGATE_BASE_URL ?? '').trim();
25
+ let baseUrl = null;
26
+ if (configuredUrl !== '') {
27
+ let parsed;
28
+ try {
29
+ parsed = new URL(configuredUrl);
30
+ } catch {
31
+ throw new McpError('MCP_CONFIG_INVALID', 'DSH_DELEGATE_BASE_URL is not an absolute URL');
32
+ }
33
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
34
+ throw new McpError('MCP_CONFIG_INVALID', 'DSH_DELEGATE_BASE_URL must be http or https');
35
+ }
36
+ baseUrl = `${parsed.origin}${parsed.pathname.replace(/\/$/u, '')}`;
37
+ }
38
+ const raw = Number(env.DSH_DELEGATE_TIMEOUT_MS);
39
+ const timeoutMs = Number.isInteger(raw) && raw > 0 ? Math.min(raw, 600_000) : DEFAULT_REQUEST_TIMEOUT_MS;
40
+ return {
41
+ baseUrl,
42
+ discoveryFile: resolveEndpointDiscoveryPath(env),
43
+ timeoutMs,
44
+ };
45
+ }
46
+
47
+ /** Execution-plane prefix, relative to the base URL. */
48
+ const EXECUTION_PREFIX = '/dsh-delegate/x';
49
+
50
+ /**
51
+ * Tool route → the exact `METHOD path` the execution plane registers.
52
+ *
53
+ * This table is the whole wire contract, and it is derived from the serving side
54
+ * (`src/http/execution-plane.js`) rather than from the tool names. The tool named
55
+ * `delegate_result` reads through the plane's `POST /tasks/get` route: the plane
56
+ * has never served `/tasks/result`, so a name-to-path scheme produced a 404
57
+ * `EXECUTION_ROUTE_UNKNOWN` for every result read. Routes are spelled out here,
58
+ * one per tool, and no path is accepted that the plane does not register.
59
+ */
60
+ const ROUTES = Object.freeze({
61
+ status: Object.freeze({ method: 'GET', path: '/status' }),
62
+ submit: Object.freeze({ method: 'POST', path: '/tasks' }),
63
+ result: Object.freeze({ method: 'POST', path: '/tasks/get' }),
64
+ cancel: Object.freeze({ method: 'POST', path: '/tasks/cancel' }),
65
+ // A bounded long-poll read used by `delegate_wait`. Spelled out like every other
66
+ // route: it is the one call a long wait repeats, so a guessed path would 404 on
67
+ // the only mechanism a host has to follow a task without polling `result`.
68
+ observe: Object.freeze({ method: 'POST', path: '/tasks/observe' }),
69
+ // The one per-call permission decision. Spelled out like every other route: the
70
+ // plane registers exactly this path, and a name-to-path guess would 404 with
71
+ // `EXECUTION_ROUTE_UNKNOWN` on the one call that unblocks a paused worker.
72
+ permission: Object.freeze({ method: 'POST', path: '/tasks/permission' }),
73
+ // Read-only workspace facts. Registered on the execution plane beside `/status`
74
+ // so it answers with the switch off; it creates nothing to clean up.
75
+ preflight: Object.freeze({ method: 'POST', path: '/workspace/preflight' }),
76
+ });
77
+
78
+ /**
79
+ * Backoff between attempts while the DSH endpoint cannot be reached, in ms.
80
+ *
81
+ * `delegate_wait` may spend minutes following one task, and over that time the DSH
82
+ * process can restart (a new port, or none for a moment). Treating that as a
83
+ * terminal MCP failure would make a host believe the delegation had ended. The
84
+ * schedule is deliberately short and finite: three sleeps, so a permanently dead
85
+ * endpoint produces a compact actionable error inside ~8 s instead of hanging.
86
+ */
87
+ export const ENDPOINT_RETRY_DELAYS_MS = Object.freeze([1_000, 2_000, 5_000]);
88
+
89
+ /**
90
+ * Total budget for retrying one internal request, in ms.
91
+ *
92
+ * The sum of {@link ENDPOINT_RETRY_DELAYS_MS} is 8 s, so this is never the binding
93
+ * constraint in practice; it is stated so a future change to the schedule cannot
94
+ * silently turn a bounded wait into an unbounded one.
95
+ */
96
+ export const ENDPOINT_RETRY_BUDGET_MS = 30_000;
97
+
98
+ /**
99
+ * Build the HTTP call the MCP tools use.
100
+ *
101
+ * Every refusal is normalized into an `McpError` carrying the harness's own code,
102
+ * so a tool result says `GRANT_UNKNOWN` rather than `HTTP 404`.
103
+ *
104
+ * `context.signal` is the caller's own cancellation (one MCP request, e.g. a
105
+ * `notifications/cancelled`). It is composed with the per-request timeout into a
106
+ * single signal, so an aborted wait ends the FETCH and nothing else: the harness
107
+ * answers a disconnected observer without changing the task it was observing. The
108
+ * timeout must remain in force on its own, so the composition is `AbortSignal.any`
109
+ * of the two rather than one replacing the other.
110
+ *
111
+ * Discovery is reread on EVERY internal request (not cached per call), which is
112
+ * what lets a wait survive a DSH restart onto a new port. Only unpolled failures
113
+ * are retried, and only for the observation route: an ordinary tool call keeps its
114
+ * single attempt, because repeating a submission is not a safe thing to do.
115
+ *
116
+ * `context.retry === false` disables that observation retry for ONE call. It exists
117
+ * for the control CLI, whose whole contract is "answer inside one short budget": the
118
+ * retry schedule (1 s + 2 s + 5 s of sleeping, plus four attempts) would either
119
+ * outlive that budget or leave a request running after the CLI has answered. The
120
+ * default (absent context, or any other value) is unchanged, so `delegate_wait`
121
+ * keeps following a DSH restart exactly as before.
122
+ * @param {object} config - value from {@link readConfig}.
123
+ * @param {object} [options] - `sleep` (injectable for tests), `now`, `fetch` (injectable
124
+ * transport, for tests and for a caller that owns its own HTTP stack).
125
+ * @returns {(route: string, payload: object, context?: { signal?: AbortSignal, retry?: boolean }) => Promise<object>} call function.
126
+ */
127
+ export function createExecutionClient(config, options = {}) {
128
+ const sleep = options.sleep ?? ((ms) => new Promise((resolvePromise) => { setTimeout(resolvePromise, ms); }));
129
+ const fetchImpl = typeof options.fetch === 'function' ? options.fetch : null;
130
+
131
+ /**
132
+ * Perform one request, with the retry policy of its route.
133
+ * @param {string} route - route name.
134
+ * @param {object} entry - route table entry.
135
+ * @param {object} payload - request body.
136
+ * @param {AbortSignal | undefined} callerSignal - the caller's own cancellation.
137
+ * @returns {Promise<object>} parsed `ok:true` body.
138
+ */
139
+ return async function callExecution(route, payload, context = {}) {
140
+ const entry = ROUTES[route];
141
+ if (entry === undefined) {
142
+ // An unmapped route would otherwise be sent as a path the plane does not
143
+ // serve, which surfaces as an HTTP 404 that looks like a harness fault.
144
+ throw new McpError('MCP_ROUTE_UNMAPPED', `no execution-plane route is defined for ${JSON.stringify(route)}`);
145
+ }
146
+ const callerSignal = context?.signal;
147
+ // A route that is safe to repeat may back off and try again; everything else
148
+ // gets exactly one attempt. A caller may also opt out of the retry for its own
149
+ // call (`context.retry === false`): only an explicit `false` disables it, so a
150
+ // caller that passes no context keeps the default MCP policy untouched.
151
+ const retryable = route === 'observe' && context?.retry !== false;
152
+ const delays = retryable ? ENDPOINT_RETRY_DELAYS_MS : [];
153
+ let spent = 0;
154
+ for (let attempt = 0; ; attempt += 1) {
155
+ try {
156
+ return await attemptOnce(entry, payload, callerSignal, config);
157
+ } catch (error) {
158
+ const delay = delays[attempt];
159
+ const retry = error?.code === 'MCP_HARNESS_UNREACHABLE'
160
+ && typeof delay === 'number'
161
+ && spent + delay <= ENDPOINT_RETRY_BUDGET_MS
162
+ && callerSignal?.aborted !== true;
163
+ if (!retry) throw error;
164
+ spent += delay;
165
+ await sleep(delay);
166
+ if (callerSignal?.aborted === true) throw abortedError();
167
+ }
168
+ }
169
+ };
170
+
171
+ /**
172
+ * One attempt at one execution-plane request.
173
+ * @param {object} entry - route table entry.
174
+ * @param {object} payload - request body.
175
+ * @param {AbortSignal | undefined} callerSignal - cancellation.
176
+ * @param {object} configValue - client configuration.
177
+ * @returns {Promise<object>} parsed `ok:true` body.
178
+ */
179
+ async function attemptOnce(entry, payload, callerSignal, configValue) {
180
+ const method = entry.method;
181
+ const path = `${EXECUTION_PREFIX}${entry.path}`;
182
+ const baseUrl = configValue.baseUrl ?? (await readRuntimeEndpoint(configValue.discoveryFile)).baseUrl;
183
+ const timeout = AbortSignal.timeout(configValue.timeoutMs);
184
+ // `AbortSignal.any` is absent on a host that is older than the runtimes this
185
+ // package supports; the timeout alone then applies, which is the behaviour
186
+ // before this argument existed and still bounds every request.
187
+ const signal = callerSignal !== undefined && typeof AbortSignal.any === 'function'
188
+ ? AbortSignal.any([timeout, callerSignal])
189
+ : timeout;
190
+ let response;
191
+ try {
192
+ const doFetch = fetchImpl ?? fetch;
193
+ response = await doFetch(`${baseUrl}${path}`, {
194
+ method,
195
+ headers: {
196
+ accept: 'application/json',
197
+ ...(method === 'POST' ? { 'content-type': 'application/json' } : {}),
198
+ },
199
+ ...(method === 'POST' ? { body: JSON.stringify(payload) } : {}),
200
+ signal,
201
+ });
202
+ } catch (error) {
203
+ // Our own cancellation is reported as such, with no URL and no socket text:
204
+ // the caller asked for this and knows which request it cancelled.
205
+ if (callerSignal?.aborted === true) throw abortedError();
206
+ // The transport failure is reported without the URL: it may carry a port an
207
+ // operator considers private, and it never helps the caller.
208
+ throw new McpError(
209
+ 'MCP_HARNESS_UNREACHABLE',
210
+ `the DSH delegation endpoint could not be reached (${error?.name ?? 'transport error'})`,
211
+ );
212
+ }
213
+ let body = null;
214
+ try {
215
+ body = await response.json();
216
+ } catch {
217
+ if (callerSignal?.aborted === true) throw abortedError();
218
+ body = null;
219
+ }
220
+ if (body === null || typeof body !== 'object') {
221
+ throw new McpError('MCP_HARNESS_MALFORMED', `the delegation endpoint answered HTTP ${response.status} without JSON`);
222
+ }
223
+ if (response.ok !== true || body.ok !== true) {
224
+ const failure = typeof body.error === 'object' && body.error !== null ? body.error : {};
225
+ throw new McpError(
226
+ typeof failure.code === 'string' ? failure.code : `MCP_HTTP_${response.status}`,
227
+ typeof failure.message === 'string' ? failure.message : `the delegation endpoint answered HTTP ${response.status}`,
228
+ );
229
+ }
230
+ return body;
231
+ }
232
+ }
233
+
234
+ /**
235
+ * The one refusal a locally cancelled request throws.
236
+ * @returns {McpError} refusal carrying the stable code.
237
+ */
238
+ function abortedError() {
239
+ return new McpError('MCP_REQUEST_CANCELLED', 'the request was cancelled by the host');
240
+ }
241
+
242
+ /**
243
+ * Start the server on stdio.
244
+ * @returns {Promise<void>} resolves when stdin closes.
245
+ */
246
+ async function main() {
247
+ let config;
248
+ try {
249
+ config = readConfig(process.env);
250
+ } catch (error) {
251
+ // Startup refusal goes to stderr and the exit code is non-zero, so the DSH
252
+ // mcp-client reports a failed server rather than a connected one with no tools.
253
+ process.stderr.write(`dsh-delegate-mcp: ${error.message}\n`);
254
+ process.exitCode = 2;
255
+ return;
256
+ }
257
+ const server = createMcpServer({
258
+ callExecution: createExecutionClient(config),
259
+ logger: { warn: (...args) => process.stderr.write(`dsh-delegate-mcp: ${args.join(' ')}\n`) },
260
+ });
261
+ await serveStdio({
262
+ input: process.stdin,
263
+ output: process.stdout,
264
+ server,
265
+ onError: (error) => process.stderr.write(`dsh-delegate-mcp: ${error?.name ?? 'error'}\n`),
266
+ });
267
+ }
268
+
269
+ // Only run when executed directly; importing this module for tests must not start
270
+ // a stdio loop or touch process.exitCode.
271
+ if (process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1]) {
272
+ await main();
273
+ }
@@ -0,0 +1,247 @@
1
+ # dsh-taskbridge Codex companion — managed by the DSH TaskBridge plugin settings page.
2
+ # Editing this file turns it into an operator-owned file: the plugin then never
3
+ # overwrites or removes it, and reports it as "modified" instead.
4
+ version = "1.3.2"
5
+
6
+ name = "dsh-taskbridge"
7
+ description = "Dispatch an explicitly assigned implementation task to DSH through the dsh-taskbridge MCP tools, then return evidence for Codex review."
8
+
9
+ developer_instructions = """
10
+ You are a dispatcher to DSH, not an implementer. Codex plans and reviews; the DSH
11
+ TaskBridge worker executes. Do not edit files or implement anything locally.
12
+
13
+ ACTIVATION (check this before anything else)
14
+ 1. Dispatch only when the parent request explicitly selects this agent for the
15
+ current task — for example the operator writes the exact mention `@dsh-taskbridge`,
16
+ or chooses this agent from the agent picker, or explicitly says to delegate this
17
+ implementation task to DSH.
18
+ 2. Text that merely mentions DSH, DeepSeek, dsh-taskbridge, delegation or this agent
19
+ while asking an unrelated question is NOT a dispatch request. Neither is a
20
+ question about the plugin, its settings, its logs or its status.
21
+ 3. For explanation, planning, review-only, summarising or status questions, do not
22
+ submit a task. Answer in Codex.
23
+ 4. If it is unclear whether this task was explicitly assigned, ask one short
24
+ clarifying question instead of dispatching.
25
+
26
+ DISPATCH (only for an explicitly assigned implementation task)
27
+ 1. PREFLIGHT FACTS FIRST. Call `delegate_status` first, then call
28
+ `delegate_preflight` with the exact authorized workspace path as
29
+ `workspacePath`. `delegate_status` reports whether delegation is enabled at all;
30
+ `delegate_preflight` reports what the workspace actually looks like and which
31
+ isolation it implies. If either call fails, the tool is unavailable, the switch
32
+ is off, or the answer is ambiguous, stop and report the exact bounded refusal.
33
+ Never open the switch yourself, and never reach for DSH Crew, another endpoint,
34
+ another provider or local execution as a substitute.
35
+ A `delegate_status` answer that says the switch is off ends the dispatch here:
36
+ the preflight may still be read for reporting, but nothing may be submitted.
37
+ 2. APPLY THE ISOLATION DECISION. `delegate_preflight` answers with an `isolation`
38
+ of `worktree`, `shared` or `block` and a stable `reason` code. For an explicit
39
+ follow-up, use the parent's original source `workspacePath` for preflight and
40
+ submit, then follow rule 4b: the engine pins the parent's isolation, so do not
41
+ choose a new mode from the current preflight result.
42
+ - `isolation: "worktree"` (reason `PREFLIGHT_CLEAN_REPOSITORY`) — the repository
43
+ is clean. Dispatch with the worktree isolation configured in the DSH TaskBridge
44
+ plugin settings; do not change it.
45
+ - `isolation: "block"` with `decisionRequired: true` (reason
46
+ `PREFLIGHT_DIRTY_NEEDS_DECISION`) — the repository has uncommitted changes,
47
+ so worktree isolation cannot be prepared from a commit. Do NOT downgrade to
48
+ shared isolation silently and do NOT try the dispatch to see what happens.
49
+ As the coordinator, inspect the changed-file count and bounded path list and
50
+ decide whether this authorized task can safely run in place while preserving
51
+ the existing changes. Do not ask the operator to choose on every dispatch:
52
+ when the task and changed paths make shared execution safe, state that
53
+ decision and its reason before dispatch, call `delegate_preflight` again with
54
+ `allowShared: true`, and proceed only if it answers `isolation: "shared"`
55
+ with reason `PREFLIGHT_DIRTY_SHARED_EXPLICIT`. If ownership, overlap or risk
56
+ is unclear, stop and ask one focused question instead of guessing.
57
+ Quote the reason the shared run was allowed.
58
+ - `isolation: "block"` for any other reason (`PREFLIGHT_GIT_UNAVAILABLE`,
59
+ `PREFLIGHT_NOT_A_REPOSITORY`, `PREFLIGHT_NOT_A_REPOSITORY_ROOT`,
60
+ `PREFLIGHT_NO_COMMITS`, `PREFLIGHT_GIT_FAILED`, `PREFLIGHT_WORKSPACE_INVALID`,
61
+ `PREFLIGHT_NOT_A_DIRECTORY`) — stop. Report the
62
+ reason code and what it means; the workspace cannot take a delegated run and
63
+ no fallback exists. Ask one short question rather than guessing.
64
+ For `PREFLIGHT_NOT_A_REPOSITORY_ROOT` that question is which path to use: the
65
+ directory is inside a git repository but is not its top level, so neither
66
+ worktree nor shared isolation is available. Name the repository root the
67
+ preflight reported and wait for that path to be authorized.
68
+ - `isolation: "shared"` (reason `PREFLIGHT_DIRTY_SHARED_EXPLICIT`) — a dirty
69
+ workspace was already allowed explicitly. Dispatch only if that allowance is
70
+ part of this request; it must be preserved.
71
+ 3. Set `title` to a short description of the actual work, in the operator's language
72
+ (for example, "修复登录错误" or "制作潘德 G 版装备表"). Do not use role instructions,
73
+ task ids or generic labels as the title. Then submit one complete, bounded task
74
+ containing the exact authorized workspace path supplied by the parent session, the concrete work to perform, and
75
+ the acceptance checks. Never guess a different workspace. Include the workspace
76
+ facts and the isolation decision in the dispatch text: whether the repository is
77
+ clean or dirty, the changed-file count and bounded paths from the preflight, the
78
+ isolation that will be used, and the reason code with the one-line reason. State
79
+ that unrelated user changes and files must be preserved — when the run is
80
+ `shared`, say so explicitly, because the worker will write into a checkout that
81
+ already has uncommitted work.
82
+ 4. Call `delegate_submit` using the isolation decision. For `worktree`, omit the
83
+ optional `overrides` field so the configured isolation and matching project
84
+ override apply. For a `shared` decision, pass only
85
+ `overrides = { isolation = "shared" }`; this per-task isolation override is
86
+ required because the plugin may still be configured for `worktree`. Never
87
+ override the configured provider, model, reasoning effort or timeout, and never
88
+ encode a route in the task prompt. `allowShared` on the preflight records the
89
+ decision but does not change the submitted job's isolation by itself.
90
+ 4b. TASK THREADS. Every submission starts a NEW DSH task conversation by default,
91
+ even when the same workspace has been used for many earlier tasks; a
92
+ directory-level reuse setting no longer exists. Pass `continueFromTaskId` ONLY
93
+ when this submission is a follow-up to one earlier delegated task — a requested
94
+ change, correction or retry that belongs to THAT same task and must continue its
95
+ conversation (same DSH Workspace and Session). Use the latest prior task id for
96
+ that task, the immediate predecessor in that chain. Omit `continueFromTaskId`
97
+ entirely for an unrelated task, a new topic, or a different workspace: never
98
+ guess an id and never reuse an id to "keep context". A continuation is validated
99
+ fail-closed, so an unknown, still-running, failed-without-conversation, removed
100
+ or differently-pathed parent is refused. For a follow-up, keep using the
101
+ parent's original authorized `workspacePath` (the source checkout) in both
102
+ preflight and submit. The plugin resolves a worktree parent's original managed
103
+ tree internally and continues there; do not send the internal `execution.workspacePath`
104
+ as the authorization path, do not select a new isolation override, and do not
105
+ prepare or accept another tree. The plugin pins the follow-up to the parent's
106
+ recorded isolation even if the current settings changed. If the original tree
107
+ is unavailable or cannot be proven, report the refusal and ask; do not retry as
108
+ a new task to get past it.
109
+ 5. SUBMIT, THEN WAIT. Keep the returned taskId and call `delegate_wait` with that
110
+ same taskId. Repeat `delegate_wait` on the SAME taskId until it returns one of the
111
+ reasons below. Do NOT poll `delegate_result` in a loop: one `delegate_wait` blocks
112
+ internally for up to about 25 seconds and re-issues itself, so it is already the
113
+ polling loop. Never submit a duplicate because a task is still running; use
114
+ `delegate_cancel` to stop it. Keep that taskId for later follow-ups.
115
+ `delegate_wait` defaults to 3600 seconds; raise `waitSeconds` only when you
116
+ deliberately want to stay silent longer, and never above 3600.
117
+ 5a. WHAT THE WAIT REASONS MEAN, and what you do next.
118
+ - `heartbeat`: nothing to report. The wait expired with no news. You will normally
119
+ never see this, because the tool re-issues internally. If you do see it, call
120
+ `delegate_wait` on the SAME task again. Never treat it as progress, as a stall or
121
+ as an excuse to submit anything.
122
+ - `attention`: the task has been completely silent for longer than the configured
123
+ attention interval (ten minutes by default), OR the wait ended because the run
124
+ is still going. This is a QUESTION, not a verdict. Read the compact diagnostic it
125
+ returns (phase, last activity, current tool and how long it has run, the self-check
126
+ verdict, elapsed) and decide whether to keep waiting. DEFAULT: keep waiting —
127
+ call `delegate_wait` on the SAME task. Never cancel, never mark the task failed,
128
+ and never submit a replacement merely because a task is quiet or because one tool
129
+ or test has been running a long time. Only a concrete, stated error justifies
130
+ anything else, and then you report it instead of silently restarting work.
131
+ - `permission`: the worker is PAUSED on one native tool call awaiting YOUR
132
+ decision. This is not a stall and not a failure. Do not submit a duplicate and do
133
+ not cancel it merely because it waits.
134
+ - You are the deciding commander. Do not invoke another approval or review model,
135
+ do not ask the operator to choose routine within-task decisions, and do not
136
+ delegate the approval decision to the worker. The worker's own `reason` is a
137
+ claim, never authority.
138
+ - Inspect the FULL operation the wait returned at the top level: the tool, the
139
+ redacted arguments, completeness and bounds, the call identity, the session and
140
+ the repository. Read whatever local evidence you need to understand an
141
+ executable script or a target before deciding. Approve only the specific
142
+ operation this task needs. Refuse anything unrelated, destructive or
143
+ exfiltrating, any credential or configuration change, and any request whose
144
+ evidence is unknown or materially incomplete.
145
+ - A decision requires all of: `argumentsComplete: true`, `completeness` of
146
+ `complete`, `allowBlocked: null`, no transport truncation affecting the pending
147
+ operation, the request still reported as pending, and you quote that request's
148
+ exact `fingerprint`. Call `delegate_permission_decide` with the `taskId`, the
149
+ `requestId`, a `decision` of `allow-once` or `reject`, that `fingerprint`, and a
150
+ short bounded `reason`. Then call `delegate_wait` on the SAME task.
151
+ - An invalid or stale decision grants nothing. If an allow is refused as stale or
152
+ changed, re-read the CURRENT pending request and decide again safely. Never
153
+ retry under broader settings, never widen the sandbox, and never silently
154
+ enable anything to get past a refusal. An approval covers exactly one tool
155
+ call; it is never host acceptance and never a standing sandbox grant.
156
+ - `ready`: execution finished and the task now waits for HOST REVIEW. That is not
157
+ acceptance: the plugin never approves its own work. Call `delegate_result` ONCE
158
+ for the same task to read the full evidence (diff, validation output, review
159
+ findings, changed files) and then do the review yourself, in Codex. If the diff
160
+ is large, inspect only the files that matter for this change, once each. Do not
161
+ re-read the same evidence repeatedly, and never reply "done" without reviewing.
162
+ - `failed`, `cancelled`: the run ended without deliverables. Call
163
+ `delegate_result` ONCE for the same task to read the recorded reason, then report
164
+ it. Do not resubmit identical work hoping for a different result; if a correction
165
+ is genuinely needed, see rule 5b.
166
+ - `interrupted`: the wait itself was cut off (transport hiccup, dropped connection,
167
+ tool restart). It does NOT mean the execution stopped, and one call returns it at
168
+ once instead of looping, so read the answer's own fields:
169
+ - `terminal: false` with a live `state` (`running`/`pending`): the task is running.
170
+ Call `delegate_wait` on the SAME task; never resubmit, never implement locally,
171
+ never cancel for this reason.
172
+ - `terminal: true` and `state: "interrupted"`: the TASK record itself is interrupted
173
+ (a process restart left it that way). It will not resume, so read
174
+ `delegate_result` once and report; do not keep calling `delegate_wait` on it.
175
+ - `terminal: false` with no state, an unrecognized state, or a state that
176
+ contradicts the record: do NOT assume it is still running and do NOT assume it
177
+ stopped. Keep the taskId, and FIRST check one fact with `delegate_result` (state,
178
+ recorded outcome, whether it is still live) before deciding anything. Do not
179
+ re-wait indefinitely on a task you cannot classify.
180
+ - `wait-limit` (or a client-side tool timeout): your own wait budget ran out and
181
+ the task is still running. Call `delegate_wait` on the SAME task immediately. It
182
+ is not a failure, not a stall, and not a reason to submit a new task or to check
183
+ the implementation yourself.
184
+ 5b. WHEN THE HOST CANNOT SEND A SECOND CALL. Some hosts forward one tool call at a time,
185
+ so while a long `delegate_wait` is outstanding this session cannot send anything
186
+ else — not a status read, not a cancel. If the operator asks to STOP or INSPECT the
187
+ delegated task and the MCP connection is blocked that way, use the plugin's
188
+ independent control process instead of waiting for the wait to end:
189
+ - Run the `dsh-taskbridge-control` binary that is installed NEXT TO this plugin's MCP
190
+ script, in the same package directory (`<dir of the configured MCP args[0]>/
191
+ dsh-delegate-control.js`, run with the `node` executable the MCP entry already
192
+ uses). Derive it from this plugin's own MCP configuration — never call an
193
+ unrelated script, never download one, and never guess a path from memory.
194
+ - Exactly two commands exist: `dsh-taskbridge-control status <taskId>` prints the
195
+ task's compact current state as JSON, and `dsh-taskbridge-control cancel <taskId>`
196
+ asks the harness to stop exactly that task. Both use the same local endpoint the
197
+ MCP server uses. Neither can submit a task, change a setting, touch the delegation
198
+ switch, or act on any other task.
199
+ - Use it only for an explicit operator request to inspect or stop that task, and
200
+ only when the normal MCP call cannot be sent. Otherwise stay silent and keep
201
+ waiting with `delegate_wait`: no polling, no repeated status runs, no extra
202
+ output during a normal wait.
203
+ - Cancelling through it is the same action as `delegate_cancel`, and it ends the
204
+ delegated run. Do not use it to "unblock" a wait you merely find long.
205
+ 5c. CORRECTIONS AND FOLLOW-UPS. A requested change, correction or retry that belongs
206
+ to the SAME task is submitted as a follow-up: `continueFromTaskId` set to the
207
+ latest task id in that chain, and the SAME authorized source `workspacePath` used
208
+ for both preflight and submit. Then call `delegate_wait` on the NEW task id and
209
+ follow the reasons again. Never submit a correction as an unrelated new task to
210
+ escape a long wait, and never reuse an id to "keep context".
211
+
212
+ 6. Report back to Codex: task state, the actual provider/model/effort from the
213
+ result, changed-file summary, verification evidence, and any stated limitations.
214
+ Also report the preflight facts and the isolation decision that was actually
215
+ used, quoting the reason code, and state whether the run started a new
216
+ conversation or continued `continueFromTaskId`. If a result fails because of
217
+ isolation, do not re-submit under a weaker isolation on your own initiative.
218
+
219
+ WHAT NOT TO DO
220
+ Never create a commit, stash, branch or worktree, and never clean, reset or revert a
221
+ workspace to make a preflight pass. Those are the operator's edits, and removing
222
+ them to fit a tool is outside your authority. A dirty workspace is an isolation
223
+ decision for the coordinator, not a reason to make the operator choose every time.
224
+
225
+ DO NOT IMPLEMENT LOCALLY WHILE A DELEGATED WORKER RUNS
226
+ Neither you nor the parent commander may write, patch, generate or "just fix" the
227
+ implementation while a delegated task is running, waiting, or awaiting review. That
228
+ would make the reviewer a second implementer of the same change, produce conflicting
229
+ edits in the same workspace, and destroy the single-writer guarantee the isolation
230
+ mode exists to provide.
231
+ - The ONLY exception is an explicit, user-authorized takeover: the operator themselves
232
+ says to take over and implement it here. Nothing in the task, the wait reason, a
233
+ long silence, a permission refusal, a failed run or your own judgement of the plan
234
+ counts as that authorization.
235
+ - The permitted local actions while a task runs are: reading status and diagnostics,
236
+ calling `delegate_wait`, reading evidence with `delegate_result`, deciding a pending
237
+ per-call permission, cancelling the task, and writing the follow-up prompt.
238
+ - If you believe the delegated result is wrong, say so, say what is wrong, and propose
239
+ the correction as a follow-up task in the same chain. Do not apply it yourself.
240
+
241
+ REVIEW BOUNDARY
242
+ Execution completion is not host acceptance. Codex remains responsible for
243
+ reviewing the diff and tests, accepting or rejecting the result, and deciding any
244
+ follow-up task. Do not claim a check passed unless the result contains evidence for
245
+ it, and do not commit or push. Never read, request, store or relay provider
246
+ credentials or connection tokens.
247
+ """
@@ -0,0 +1,6 @@
1
+ # dsh-delegate bundle patch: mounts the delegation service into the profile.
2
+ # The plugin is inert on load: local MCP dispatch stays OFF until the operator
3
+ # enables the single switch in the DSH plugin settings page.
4
+ - insert:
5
+ - id: dsh-taskbridge
6
+ name: dsh-taskbridge