dsh-taskbridge 0.0.0-stage → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +754 -0
- package/LICENSE +21 -0
- package/README.md +624 -3
- package/bin/dsh-delegate-codex-agent.js +115 -0
- package/bin/dsh-delegate-control.d.ts +90 -0
- package/bin/dsh-delegate-control.js +450 -0
- package/bin/dsh-delegate-mcp.d.ts +121 -0
- package/bin/dsh-delegate-mcp.js +273 -0
- package/codex/dsh-delegate.toml +245 -0
- package/cordis.patch.yml +6 -0
- package/docs/INTRODUCTION.md +15 -0
- package/docs/INTRODUCTION.zh.md +32 -0
- package/docs/auth-contract.md +138 -0
- package/docs/claude-code.md +31 -0
- package/docs/codex-integration.md +922 -0
- package/docs/contracts-stage-b.md +443 -0
- package/docs/conversation-placement.md +293 -0
- package/docs/plugin-market.md +30 -0
- package/docs/redaction-contract.md +127 -0
- package/docs/runtime-compatibility.md +220 -0
- package/docs/silent-wait.md +191 -0
- package/docs/taskbridge-upgrade.md +28 -0
- package/docs/taskdispatch-upgrade.md +25 -0
- package/docs/worker-permissions.md +347 -0
- package/docs/workspace-contract.md +538 -0
- package/icon.svg +1 -0
- package/lib/client.d.ts +118 -0
- package/lib/client.js +3232 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +135 -4
- package/src/auth/fence.js +361 -0
- package/src/auth/grants.js +789 -0
- package/src/client/api.js +2322 -0
- package/src/client/index.jsx +2333 -0
- package/src/client/styles.js +251 -0
- package/src/codex/installer.js +3260 -0
- package/src/codex/seam.js +429 -0
- package/src/codex/toml.js +784 -0
- package/src/config/defaults.js +164 -0
- package/src/config/redact.js +184 -0
- package/src/config/settings.js +629 -0
- package/src/config/store.js +186 -0
- package/src/config/validate.js +763 -0
- package/src/credentials/seam.js +202 -0
- package/src/http/execution-plane.js +454 -0
- package/src/http/respond.js +175 -0
- package/src/http/user-plane.js +1122 -0
- package/src/index.d.ts +332 -0
- package/src/index.js +657 -0
- package/src/jobs/activity.js +1008 -0
- package/src/jobs/engine.js +3609 -0
- package/src/jobs/history.js +1467 -0
- package/src/mcp/server.js +1820 -0
- package/src/mcp/wait.js +536 -0
- package/src/model/connectivity.js +371 -0
- package/src/model/discovery.js +582 -0
- package/src/model/native-catalog.js +68 -0
- package/src/model/openai-adapter.js +671 -0
- package/src/model/probe.js +264 -0
- package/src/model/providers.js +756 -0
- package/src/model/routing.js +321 -0
- package/src/review/preset.js +868 -0
- package/src/review/prompts.js +126 -0
- package/src/review/reviewer.js +933 -0
- package/src/runtime/agent-runner.js +1738 -0
- package/src/runtime/endpoint-discovery.js +118 -0
- package/src/runtime/permissions.js +1429 -0
- package/src/runtime/sandbox.js +358 -0
- package/src/runtime/session-placement.js +1103 -0
- package/src/workspace/audit.js +775 -0
- package/src/workspace/locks.js +167 -0
- package/src/workspace/preflight.js +424 -0
- package/src/workspace/worktrees.js +613 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Explicitly install or remove the Codex companion from a terminal.
|
|
3
|
+
//
|
|
4
|
+
// This is the same implementation the DSH settings page drives
|
|
5
|
+
// (`src/codex/installer.js`); the binary exists for scripted installs, CI and
|
|
6
|
+
// operators who prefer a shell. Three rules follow from that:
|
|
7
|
+
//
|
|
8
|
+
// * it is never run implicitly — not on plugin load, not on package install;
|
|
9
|
+
// * `install` writes the agent file and registers the MCP server, `status` only
|
|
10
|
+
// reads, and `remove` deletes only files this plugin still owns;
|
|
11
|
+
// * a refusal is reported in full and exits non-zero, so a script cannot mistake
|
|
12
|
+
// "left your file alone" for success.
|
|
13
|
+
//
|
|
14
|
+
// Exit codes: 0 done, 2 nothing changed because of a refusal/conflict, 1 failure.
|
|
15
|
+
|
|
16
|
+
import { resolve } from 'node:path';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
|
|
19
|
+
import { runCodexAction, readCodexStatus, resolveCodexHome, packageVersion } from '../src/codex/installer.js';
|
|
20
|
+
|
|
21
|
+
const SCRIPT_PATH = fileURLToPath(import.meta.url);
|
|
22
|
+
const ACTIONS = new Set(['install', 'status', 'repair', 'remove']);
|
|
23
|
+
|
|
24
|
+
/** Re-exported so callers that imported it from this bin before 0.1.6 keep working. */
|
|
25
|
+
export { resolveCodexHome };
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Compatibility adapter for the pre-0.1.6 programmatic entry point.
|
|
29
|
+
*
|
|
30
|
+
* The 0.1.6 release moved the logic to `src/codex/installer.js` and made the action
|
|
31
|
+
* cover the MCP entry as well. This wrapper keeps the old call shape
|
|
32
|
+
* (`manageCodexAgent(action, { codexHome })`) and its agent-only state names, so an
|
|
33
|
+
* existing script or test does not silently start writing a Codex config it did not
|
|
34
|
+
* ask for. `install` still registers the MCP server — that is what the settings
|
|
35
|
+
* page's button does — but the *agent* state remains the returned contract.
|
|
36
|
+
* @param {'install'|'status'|'remove'|'repair'} action - action to perform.
|
|
37
|
+
* @param {object} [options] - `codexHome`, `env`.
|
|
38
|
+
* @returns {Promise<{ path: string, mcpPath: string, state: string, mcpState: string }>} agent state.
|
|
39
|
+
*/
|
|
40
|
+
export async function manageCodexAgent(action, { codexHome = resolveCodexHome(), env = process.env } = {}) {
|
|
41
|
+
if (!ACTIONS.has(action)) throw new TypeError('action must be install, status, repair, or remove');
|
|
42
|
+
if (action === 'status') {
|
|
43
|
+
const status = await readCodexStatus({ codexHome, env, version: await packageVersion() });
|
|
44
|
+
return {
|
|
45
|
+
path: status.agent.path,
|
|
46
|
+
mcpPath: status.mcp.path,
|
|
47
|
+
state: status.agent.state,
|
|
48
|
+
mcpState: status.mcp.state,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
const outcome = await runCodexAction(action, { codexHome, env, version: await packageVersion() });
|
|
52
|
+
return {
|
|
53
|
+
path: outcome.status.agent.path,
|
|
54
|
+
mcpPath: outcome.status.mcp.path,
|
|
55
|
+
state: outcome.status.agent.state,
|
|
56
|
+
mcpState: outcome.status.mcp.state,
|
|
57
|
+
changed: outcome.changed,
|
|
58
|
+
refused: outcome.refused,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Human-readable rendering of one outcome.
|
|
64
|
+
* @param {object} outcome - `{ action, changed, refused, status }`.
|
|
65
|
+
* @returns {string[]} lines.
|
|
66
|
+
*/
|
|
67
|
+
function render(outcome) {
|
|
68
|
+
const { status } = outcome;
|
|
69
|
+
const lines = [
|
|
70
|
+
`agent ${status.agent.state}: ${status.agent.path}`,
|
|
71
|
+
`mcp ${status.mcp.state}: ${status.mcp.path}`,
|
|
72
|
+
`entry ${status.mcp.desired.command} ${status.mcp.desired.args.join(' ')}`,
|
|
73
|
+
`ready ${status.ready === true ? 'yes' : 'no'} (the DSH switch is not changed by this command)`,
|
|
74
|
+
];
|
|
75
|
+
for (const entry of outcome.changed) lines.push(`changed: ${entry}`);
|
|
76
|
+
for (const entry of outcome.refused) lines.push(`refused: ${entry.target} ${entry.code}: ${entry.message}`);
|
|
77
|
+
for (const note of status.notes ?? []) lines.push(`note: ${note.code}: ${note.text}`);
|
|
78
|
+
return lines;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function printHelp() {
|
|
82
|
+
process.stdout.write([
|
|
83
|
+
'Usage: dsh-delegate-codex-agent <install|status|repair|remove>',
|
|
84
|
+
'Uses CODEX_HOME when set; otherwise uses ~/.codex.',
|
|
85
|
+
'install/repair write agents/dsh-delegate.toml and register mcp_servers.dsh-delegate in config.toml.',
|
|
86
|
+
'remove deletes only files this plugin still owns; a modified file is left untouched.',
|
|
87
|
+
'Never enables the DSH local-call switch and never edits unrelated Codex settings.',
|
|
88
|
+
].join('\n') + '\n');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function main() {
|
|
92
|
+
const action = process.argv[2];
|
|
93
|
+
if (action === '--help' || action === '-h' || action === undefined) {
|
|
94
|
+
printHelp();
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (!ACTIONS.has(action) || process.argv.length > 3) {
|
|
98
|
+
printHelp();
|
|
99
|
+
process.exitCode = 2;
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
try {
|
|
104
|
+
// `CODEX_HOME` (or the user's `~/.codex`) decides the target; the action itself
|
|
105
|
+
// lives in the shared installer so the CLI and the settings page cannot drift.
|
|
106
|
+
const outcome = await runCodexAction(action, { codexHome: resolveCodexHome(), version: await packageVersion() });
|
|
107
|
+
process.stdout.write(`${render(outcome).join('\n')}\n`);
|
|
108
|
+
if (outcome.refused.length > 0) process.exitCode = 2;
|
|
109
|
+
} catch (error) {
|
|
110
|
+
process.stderr.write(`dsh-delegate-codex-agent: ${error?.message ?? 'operation failed'}\n`);
|
|
111
|
+
process.exitCode = 1;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (process.argv[1] !== undefined && resolve(process.argv[1]) === SCRIPT_PATH) await main();
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Type declarations for the independent control CLI (`bin/dsh-delegate-control.js`).
|
|
2
|
+
//
|
|
3
|
+
// The file is both an executable and an importable module: importing it must not read
|
|
4
|
+
// the environment, contact a plane or touch `process.exitCode`. These declarations
|
|
5
|
+
// describe that importable surface, which is what the tests drive.
|
|
6
|
+
|
|
7
|
+
import type { ExecutionCallContext, ExecutionAnswer, ExecutionRoute, McpConfig } from './dsh-delegate-mcp.js';
|
|
8
|
+
|
|
9
|
+
/** The only two verbs this CLI has. There is no submit, settings or switch verb. */
|
|
10
|
+
export declare const CONTROL_ACTIONS: readonly ['status', 'cancel'];
|
|
11
|
+
|
|
12
|
+
/** How long ONE control command may take end to end, in milliseconds (10 s). */
|
|
13
|
+
export declare const CONTROL_TIMEOUT_MS: number;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The observation bound `status` requests, in milliseconds (1).
|
|
17
|
+
*
|
|
18
|
+
* The smallest POSITIVE wait: the engine and the monitor treat a non-positive wait as
|
|
19
|
+
* "unspecified" and substitute their 25 s default, so `0` would be a long poll, not a
|
|
20
|
+
* status read.
|
|
21
|
+
*/
|
|
22
|
+
export declare const STATUS_WAIT_MS: number;
|
|
23
|
+
|
|
24
|
+
/** Exit codes: a script can tell a refusal from a failure. */
|
|
25
|
+
export declare const EXIT: Readonly<{ ok: 0, refused: 1, usage: 2 }>;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Configuration for one control invocation.
|
|
29
|
+
*
|
|
30
|
+
* `timeoutMs` is the WHOLE-COMMAND budget and is at most {@link CONTROL_TIMEOUT_MS}: the
|
|
31
|
+
* operator override `DSH_DELEGATE_CONTROL_TIMEOUT_MS` may only LOWER the bound, never
|
|
32
|
+
* raise it. A missing or unusable `timeoutMs` falls back to the 10 s default.
|
|
33
|
+
*/
|
|
34
|
+
export interface ControlConfig extends McpConfig {}
|
|
35
|
+
|
|
36
|
+
/** Read the control configuration from the environment. */
|
|
37
|
+
export declare function readControlConfig(env?: Record<string, string | undefined>): ControlConfig;
|
|
38
|
+
|
|
39
|
+
/** Compact one task view for stdout (no diff, no conversation, no secrets). */
|
|
40
|
+
export declare function compactControlTask(task: object | null | undefined): object | null;
|
|
41
|
+
|
|
42
|
+
/** One published scalar: a bounded string, a finite number, a boolean, or null. */
|
|
43
|
+
export type ControlScalar = string | number | boolean | null;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Validate one command line.
|
|
47
|
+
*
|
|
48
|
+
* A malformed command line answers `{ ok: false, code, message }`; the codes are
|
|
49
|
+
* `CONTROL_ARGS_INVALID`, `CONTROL_ACTION_INVALID`, `CONTROL_TASK_ID_REQUIRED` and
|
|
50
|
+
* `CONTROL_TASK_ID_INVALID`.
|
|
51
|
+
*/
|
|
52
|
+
export declare function parseControlArgs(
|
|
53
|
+
argv: string[],
|
|
54
|
+
): { ok: true, action: 'status' | 'cancel', taskId: string } | { ok: false, code: string, message: string };
|
|
55
|
+
|
|
56
|
+
/** One answer: the exit code and the single JSON document for stdout. */
|
|
57
|
+
export interface ControlOutcome {
|
|
58
|
+
exitCode: number;
|
|
59
|
+
output: Record<string, unknown>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Run one control command against the loopback plane.
|
|
64
|
+
*
|
|
65
|
+
* `status` issues exactly one bounded `observe` with `waitMs: STATUS_WAIT_MS`; `cancel`
|
|
66
|
+
* issues one `cancel` for the named task and nothing else. The whole command runs under
|
|
67
|
+
* one caller budget: the client receives `{ signal, retry: false }`, so the observation
|
|
68
|
+
* retry is disabled for it and nothing keeps running after the answer. A refusal —
|
|
69
|
+
* including an exhausted budget (`CONTROL_TIMEOUT`) — is reported as data
|
|
70
|
+
* (`{ ok: false, error: { code, message } }`) with a non-zero exit code.
|
|
71
|
+
*/
|
|
72
|
+
export declare function runControl(
|
|
73
|
+
argv: string[],
|
|
74
|
+
deps?: {
|
|
75
|
+
callExecution?: (route: ExecutionRoute, payload: object, context?: ExecutionCallContext) => Promise<ExecutionAnswer>;
|
|
76
|
+
config?: ControlConfig;
|
|
77
|
+
},
|
|
78
|
+
): Promise<ControlOutcome>;
|
|
79
|
+
|
|
80
|
+
/** The usage text printed for `--help`. */
|
|
81
|
+
export declare const USAGE: string;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Process entry point: one JSON document on stdout, diagnostics on stderr, and an
|
|
85
|
+
* exit code that says what happened.
|
|
86
|
+
*/
|
|
87
|
+
export declare function main(
|
|
88
|
+
argv?: string[],
|
|
89
|
+
io?: { stdout?: (text: string) => void, stderr?: (text: string) => void },
|
|
90
|
+
): Promise<number>;
|
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Independent local control CLI for the delegation plane.
|
|
3
|
+
//
|
|
4
|
+
// Why this exists, and what it refuses to be
|
|
5
|
+
// ------------------------------------------
|
|
6
|
+
// The plugin's stdio MCP server already serves concurrent requests: a `delegate_wait`
|
|
7
|
+
// that is in flight does not stop a `delegate_status` or a `delegate_cancel` from
|
|
8
|
+
// being answered (see `serveStdio` in `src/mcp/server.js`). The bottleneck is the HOST:
|
|
9
|
+
// a client that forwards tool calls one at a time, or one that has a single MCP
|
|
10
|
+
// connection blocked on a long wait, cannot send a second call while the first is
|
|
11
|
+
// outstanding — and the operator is then unable to ask "what is this task doing" or
|
|
12
|
+
// "stop it" without waiting for the wait to end.
|
|
13
|
+
//
|
|
14
|
+
// This binary is that second channel, and nothing more:
|
|
15
|
+
//
|
|
16
|
+
// * it uses the SAME execution client and the SAME endpoint discovery the MCP
|
|
17
|
+
// server uses, against the loopback plane the plugin already serves — no new
|
|
18
|
+
// port, no new route, no new permission, no token, no configuration surface, no
|
|
19
|
+
// long-lived background process;
|
|
20
|
+
// * it supports exactly two verbs, `status <taskId>` and `cancel <taskId>`. There
|
|
21
|
+
// is no submit, no settings write, no switch toggle, no batch form and no way to
|
|
22
|
+
// widen a grant: those actions stay where they were;
|
|
23
|
+
// * `status` uses the bounded `observe` read with the SMALLEST POSITIVE wait
|
|
24
|
+
// (`waitMs: 1`) — a compact task status answered at once, never a diff and never a
|
|
25
|
+
// conversation transcript. It is deliberately not `waitMs: 0`: the engine and the
|
|
26
|
+
// monitor treat a non-positive wait as "unspecified" and substitute their own
|
|
27
|
+
// default bound (25 s), so a zero here waits exactly as long as a full long-poll
|
|
28
|
+
// and blows this command's budget. `1` is the smallest value both sides keep;
|
|
29
|
+
// * the WHOLE command — every attempt included — runs inside one caller budget
|
|
30
|
+
// (10 s by default, may be lowered): one `AbortSignal` composed with the request
|
|
31
|
+
// timeout, and the observation retry disabled for this call. Nothing is left
|
|
32
|
+
// running after the answer, so no promise is raced against the process exiting;
|
|
33
|
+
// * stdout carries one stable JSON document and nothing else, so a script or a
|
|
34
|
+
// companion can parse it; diagnostics go to stderr; a failure exits non-zero;
|
|
35
|
+
// * a request timeout is finite, so a caller cannot be parked indefinitely.
|
|
36
|
+
//
|
|
37
|
+
// Importing this module for tests must not run the CLI: `main` is only invoked when
|
|
38
|
+
// the file is executed directly.
|
|
39
|
+
|
|
40
|
+
import { resolve } from 'node:path';
|
|
41
|
+
import { fileURLToPath } from 'node:url';
|
|
42
|
+
|
|
43
|
+
import { createExecutionClient, readConfig } from './dsh-delegate-mcp.js';
|
|
44
|
+
|
|
45
|
+
const SCRIPT_PATH = fileURLToPath(import.meta.url);
|
|
46
|
+
|
|
47
|
+
/** The only two verbs this CLI has. */
|
|
48
|
+
export const CONTROL_ACTIONS = Object.freeze(['status', 'cancel']);
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* How long one control command may take END TO END, in ms.
|
|
52
|
+
*
|
|
53
|
+
* The bound covers the whole command: client configuration, discovery, the request,
|
|
54
|
+
* the request timeout and any retry the client would otherwise perform. A control
|
|
55
|
+
* command is one bounded read (`observe` with the smallest positive wait) or one
|
|
56
|
+
* cancel, so it is fast by construction. The bound is deliberately much shorter than
|
|
57
|
+
* the MCP server's own `DEFAULT_REQUEST_TIMEOUT_MS` (30 s): an operator asking "what
|
|
58
|
+
* is this task doing" wants an answer or a clear failure, never a long block — that
|
|
59
|
+
* is the whole point of a second channel.
|
|
60
|
+
*
|
|
61
|
+
* It was already 10 s before this bound became real. What was NOT real: `status` sent
|
|
62
|
+
* `waitMs: 0`, the engine and the monitor both treat a non-positive wait as
|
|
63
|
+
* "unspecified" and substitute 25 s, so the request could not finish inside 10 s and
|
|
64
|
+
* the observation retry then extended the whole command further. Both are fixed at
|
|
65
|
+
* their source — the wait is {@link STATUS_WAIT_MS} and the retry is disabled for
|
|
66
|
+
* this call — and the single signal below is what makes the budget the real bound
|
|
67
|
+
* for every attempt rather than for one try.
|
|
68
|
+
*/
|
|
69
|
+
export const CONTROL_TIMEOUT_MS = 10_000;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The observation bound `status` asks for, in ms.
|
|
73
|
+
*
|
|
74
|
+
* ONE millisecond, not zero. Zero is ACCEPTED by the HTTP route and then read by the
|
|
75
|
+
* engine (`clampObserveWait`) and the monitor (`boundedWait`) as "no wait requested",
|
|
76
|
+
* which they replace with their own 25-second default — the opposite of an immediate
|
|
77
|
+
* answer, and longer than this command's whole budget. One millisecond is the smallest
|
|
78
|
+
* positive value those two clamps keep, and it still answers from the task's CURRENT
|
|
79
|
+
* state: a terminal task and a pending permission request are returned before any
|
|
80
|
+
* timer is armed, an unfinished wait observes exactly one slice, and `status` never
|
|
81
|
+
* reads a full result or a diff.
|
|
82
|
+
*/
|
|
83
|
+
export const STATUS_WAIT_MS = 1;
|
|
84
|
+
|
|
85
|
+
/** Exit codes: a script can tell a refusal from a failure. */
|
|
86
|
+
export const EXIT = Object.freeze({
|
|
87
|
+
ok: 0,
|
|
88
|
+
// The plane answered, but with a refusal (unknown task, switch off, transport).
|
|
89
|
+
refused: 1,
|
|
90
|
+
// The command line itself was wrong.
|
|
91
|
+
usage: 2,
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
/** Fields of a task this CLI may publish. Everything else stays on the plane. */
|
|
95
|
+
const TASK_FIELDS = Object.freeze([
|
|
96
|
+
'taskId',
|
|
97
|
+
'state',
|
|
98
|
+
'phase',
|
|
99
|
+
'createdAt',
|
|
100
|
+
'startedAt',
|
|
101
|
+
'endedAt',
|
|
102
|
+
'elapsedMs',
|
|
103
|
+
'lastActivityAt',
|
|
104
|
+
'currentTool',
|
|
105
|
+
'idleForMs',
|
|
106
|
+
'route',
|
|
107
|
+
'cancelledBy',
|
|
108
|
+
'error',
|
|
109
|
+
]);
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Build the process configuration for this CLI.
|
|
113
|
+
*
|
|
114
|
+
* It is the MCP server's own configuration with one difference: the per-request bound
|
|
115
|
+
* is the control bound (10 s), and the operator override
|
|
116
|
+
* `DSH_DELEGATE_CONTROL_TIMEOUT_MS` may only LOWER it. A control answer is one bounded
|
|
117
|
+
* read or one cancel, so "wait longer" is never what an operator wants here; a value
|
|
118
|
+
* above the default is clamped DOWN to it rather than silently raising the bound the
|
|
119
|
+
* comment (and the docs) promise.
|
|
120
|
+
*
|
|
121
|
+
* That 10 s default is a WHOLE-COMMAND budget, not a per-attempt timeout: `runControl`
|
|
122
|
+
* derives the single {@link AbortSignal} that bounds discovery, the request and the
|
|
123
|
+
* client's own retry schedule from it. The default therefore applies even when a
|
|
124
|
+
* caller passes a `deps.config` that carries no usable `timeoutMs` — an explicit
|
|
125
|
+
* config is not a way to lose the bound.
|
|
126
|
+
* @param {Record<string, string | undefined>} env - process environment.
|
|
127
|
+
* @returns {{ baseUrl: string | null, discoveryFile: string, timeoutMs: number }} configuration.
|
|
128
|
+
* @throws {Error} `MCP_CONFIG_INVALID` when the explicit endpoint override is unusable.
|
|
129
|
+
*/
|
|
130
|
+
export function readControlConfig(env = process.env) {
|
|
131
|
+
const base = readConfig(env);
|
|
132
|
+
const raw = Number(env.DSH_DELEGATE_CONTROL_TIMEOUT_MS);
|
|
133
|
+
const requested = Number.isInteger(raw) && raw > 0 ? raw : null;
|
|
134
|
+
return {
|
|
135
|
+
baseUrl: base.baseUrl,
|
|
136
|
+
discoveryFile: base.discoveryFile,
|
|
137
|
+
timeoutMs: requested === null ? CONTROL_TIMEOUT_MS : Math.min(requested, CONTROL_TIMEOUT_MS),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The whole-command budget one run may use, in ms.
|
|
143
|
+
*
|
|
144
|
+
* Read from the configuration the run actually uses, and never above
|
|
145
|
+
* {@link CONTROL_TIMEOUT_MS}: a config whose `timeoutMs` is missing, non-finite or not
|
|
146
|
+
* positive gets the documented default instead of an unbounded run, and a larger one
|
|
147
|
+
* is clamped back to the documented maximum. A caller may only ever SHORTEN the
|
|
148
|
+
* command, which is the same rule the environment override already follows.
|
|
149
|
+
* @param {object | undefined} config - the run's configuration.
|
|
150
|
+
* @returns {number} budget in milliseconds.
|
|
151
|
+
*/
|
|
152
|
+
function controlBudgetMs(config) {
|
|
153
|
+
const configured = config?.timeoutMs;
|
|
154
|
+
if (typeof configured !== 'number' || !Number.isFinite(configured) || configured <= 0) return CONTROL_TIMEOUT_MS;
|
|
155
|
+
return Math.min(CONTROL_TIMEOUT_MS, Math.max(1, Math.trunc(configured)));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Longest string one published field may carry. */
|
|
159
|
+
const MAX_FIELD_CHARS = 400;
|
|
160
|
+
|
|
161
|
+
/** Fields of a nested object this CLI may publish, per key. */
|
|
162
|
+
const ROUTE_FIELDS = Object.freeze(['providerId', 'providerRoute', 'model', 'reasoningEffort', 'isolation']);
|
|
163
|
+
const TOOL_FIELDS = Object.freeze(['name', 'callId']);
|
|
164
|
+
const ERROR_FIELDS = Object.freeze(['code', 'message']);
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Bound one published scalar.
|
|
168
|
+
*
|
|
169
|
+
* Only a string, a finite number, a boolean or null is published, and a string is cut at
|
|
170
|
+
* {@link MAX_FIELD_CHARS}. Everything else — an object where a name was expected, an
|
|
171
|
+
* array, a function, a non-finite number — becomes null rather than reaching stdout as
|
|
172
|
+
* an unbounded or mis-typed value.
|
|
173
|
+
* @param {unknown} value - candidate.
|
|
174
|
+
* @returns {string | number | boolean | null} bounded scalar.
|
|
175
|
+
*/
|
|
176
|
+
function boundedScalar(value) {
|
|
177
|
+
if (typeof value === 'string') return value.length > MAX_FIELD_CHARS ? `${value.slice(0, MAX_FIELD_CHARS)}…` : value;
|
|
178
|
+
if (typeof value === 'boolean') return value;
|
|
179
|
+
if (typeof value === 'number') return Number.isFinite(value) ? value : null;
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Bound one nested object to a fixed key set.
|
|
185
|
+
* @param {unknown} value - candidate.
|
|
186
|
+
* @param {readonly string[]} keys - the ONLY keys that may be published.
|
|
187
|
+
* @returns {object | null} bounded object, or null when there is nothing to publish.
|
|
188
|
+
*/
|
|
189
|
+
function boundedObject(value, keys) {
|
|
190
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
191
|
+
const out = {};
|
|
192
|
+
for (const key of keys) {
|
|
193
|
+
if (value[key] === undefined) continue;
|
|
194
|
+
out[key] = boundedScalar(value[key]);
|
|
195
|
+
}
|
|
196
|
+
return Object.keys(out).length === 0 ? null : out;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Compact one task view for stdout.
|
|
201
|
+
*
|
|
202
|
+
* A control answer must never become a second `delegate_result`: no diff, no
|
|
203
|
+
* execution text, no review prose, no conversation. Only identity, state, timing,
|
|
204
|
+
* routing and the current tool are published. Every scalar is bounded and type-checked,
|
|
205
|
+
* and the nested blocks are rebuilt from a fixed key list — so neither an oversized
|
|
206
|
+
* field nor an unexpected nested object can make the answer unbounded or add fields
|
|
207
|
+
* this CLI never promised.
|
|
208
|
+
* @param {object | null | undefined} task - task view from the plane.
|
|
209
|
+
* @returns {object} compact task.
|
|
210
|
+
*/
|
|
211
|
+
export function compactControlTask(task) {
|
|
212
|
+
if (task === null || typeof task !== 'object' || Array.isArray(task)) return null;
|
|
213
|
+
const out = {};
|
|
214
|
+
for (const key of TASK_FIELDS) {
|
|
215
|
+
if (task[key] === undefined) continue;
|
|
216
|
+
const value = task[key];
|
|
217
|
+
if (key === 'route') {
|
|
218
|
+
const route = boundedObject(value, ROUTE_FIELDS);
|
|
219
|
+
if (route !== null) out.route = route;
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
if (key === 'currentTool') {
|
|
223
|
+
const tool = boundedObject(value, TOOL_FIELDS);
|
|
224
|
+
if (tool !== null) out.currentTool = tool;
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
if (key === 'error') {
|
|
228
|
+
const error = boundedObject(value, ERROR_FIELDS);
|
|
229
|
+
if (error !== null) out.error = error;
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
out[key] = boundedScalar(value);
|
|
233
|
+
}
|
|
234
|
+
return out;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Validate one command line.
|
|
239
|
+
* @param {string[]} argv - arguments after `node`.
|
|
240
|
+
* @returns {{ ok: true, action: string, taskId: string } | { ok: false, code: string, message: string }} parsed command.
|
|
241
|
+
*/
|
|
242
|
+
export function parseControlArgs(argv) {
|
|
243
|
+
if (argv.length !== 2) {
|
|
244
|
+
return {
|
|
245
|
+
ok: false,
|
|
246
|
+
code: 'CONTROL_ARGS_INVALID',
|
|
247
|
+
message: 'usage: dsh-delegate-control <status|cancel> <taskId>',
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
const [action, taskId] = argv;
|
|
251
|
+
if (!CONTROL_ACTIONS.includes(action)) {
|
|
252
|
+
return {
|
|
253
|
+
ok: false,
|
|
254
|
+
code: 'CONTROL_ACTION_INVALID',
|
|
255
|
+
message: `unknown action ${JSON.stringify(action)}; only ${CONTROL_ACTIONS.join(' and ')} exist`,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
if (typeof taskId !== 'string' || taskId.trim() === '') {
|
|
259
|
+
return { ok: false, code: 'CONTROL_TASK_ID_REQUIRED', message: 'a task id is required' };
|
|
260
|
+
}
|
|
261
|
+
// A task id is an opaque identifier the plugin issued. Rejecting control characters
|
|
262
|
+
// and whitespace keeps the answer and the request body honest.
|
|
263
|
+
if (!/^[A-Za-z0-9_.:-]{1,200}$/u.test(taskId)) {
|
|
264
|
+
return { ok: false, code: 'CONTROL_TASK_ID_INVALID', message: 'the task id is not a task identifier this CLI accepts' };
|
|
265
|
+
}
|
|
266
|
+
return { ok: true, action, taskId };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Run one control command against the loopback plane.
|
|
271
|
+
*
|
|
272
|
+
* This is the whole implementation, and it is injected-testable: `callExecution` is
|
|
273
|
+
* the same seam the MCP server uses, so a test can prove the command reaches the
|
|
274
|
+
* right plane route without a socket.
|
|
275
|
+
*
|
|
276
|
+
* ONE budget bounds the whole command. The caller's {@link AbortSignal} is handed to
|
|
277
|
+
* the execution client, which composes it with its own per-request timeout, and the
|
|
278
|
+
* observation retry is disabled for this call (`{ retry: false }`): a control command
|
|
279
|
+
* must neither wait out a backoff schedule nor leave a request running after it has
|
|
280
|
+
* answered. There is no `Promise.race` here on purpose — a race would answer while the
|
|
281
|
+
* request it abandoned kept running, which is exactly what a second channel must not
|
|
282
|
+
* do. The signal is the bound, and the client honours it before and after every
|
|
283
|
+
* attempt.
|
|
284
|
+
* @param {string[]} argv - arguments after `node`.
|
|
285
|
+
* @param {object} [deps] - `callExecution`, `config` (defaults to {@link readControlConfig}).
|
|
286
|
+
* @returns {Promise<{ exitCode: number, output: object }>} exit code and the JSON document.
|
|
287
|
+
*/
|
|
288
|
+
export async function runControl(argv, deps = {}) {
|
|
289
|
+
const parsed = parseControlArgs(argv);
|
|
290
|
+
if (parsed.ok !== true) {
|
|
291
|
+
return {
|
|
292
|
+
exitCode: EXIT.usage,
|
|
293
|
+
output: { ok: false, action: null, error: { code: parsed.code, message: parsed.message } },
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
// Configuration is built INSIDE the guarded region: a bad `DSH_DELEGATE_BASE_URL`,
|
|
297
|
+
// an unreadable env or an injectable client that throws while being created must
|
|
298
|
+
// become the same bounded JSON refusal as any other failure, never an uncaught throw
|
|
299
|
+
// that would reach `main` as a stack trace with non-JSON stdout.
|
|
300
|
+
let callExecution;
|
|
301
|
+
let config;
|
|
302
|
+
try {
|
|
303
|
+
config = deps.config ?? readControlConfig();
|
|
304
|
+
callExecution = deps.callExecution ?? createExecutionClient(config);
|
|
305
|
+
} catch (error) {
|
|
306
|
+
const code = typeof error?.code === 'string' ? error.code : 'CONTROL_CONFIG_INVALID';
|
|
307
|
+
const message = typeof error?.message === 'string'
|
|
308
|
+
? error.message.slice(0, MAX_FIELD_CHARS)
|
|
309
|
+
: 'the control channel could not be configured';
|
|
310
|
+
return {
|
|
311
|
+
exitCode: EXIT.refused,
|
|
312
|
+
output: { ok: false, action: parsed.action, taskId: parsed.taskId, error: { code, message } },
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
// The single bound of this command. It starts here — after the command line and the
|
|
316
|
+
// configuration, which are local and synchronous — and is cleared in `finally`, so a
|
|
317
|
+
// command that answered early leaves no armed timer behind.
|
|
318
|
+
const budgetMs = controlBudgetMs(config);
|
|
319
|
+
const budget = new AbortController();
|
|
320
|
+
const timer = setTimeout(() => {
|
|
321
|
+
try {
|
|
322
|
+
budget.abort();
|
|
323
|
+
} catch {
|
|
324
|
+
// Abort is idempotent and cannot throw in practice.
|
|
325
|
+
}
|
|
326
|
+
}, budgetMs);
|
|
327
|
+
timer.unref?.();
|
|
328
|
+
const context = { signal: budget.signal, retry: false };
|
|
329
|
+
try {
|
|
330
|
+
let outcome;
|
|
331
|
+
if (parsed.action === 'status') {
|
|
332
|
+
// A compact status read, not a long poll: the smallest POSITIVE wait the engine
|
|
333
|
+
// and the monitor both keep (see {@link STATUS_WAIT_MS}), against the existing
|
|
334
|
+
// observation route. Nothing here can read a diff, a result body or a transcript.
|
|
335
|
+
const observation = await callExecution('observe', { taskId: parsed.taskId, waitMs: STATUS_WAIT_MS }, context);
|
|
336
|
+
outcome = {
|
|
337
|
+
exitCode: EXIT.ok,
|
|
338
|
+
output: {
|
|
339
|
+
ok: true,
|
|
340
|
+
action: 'status',
|
|
341
|
+
taskId: parsed.taskId,
|
|
342
|
+
// The compact state a host acts on. It is the plane's own report.
|
|
343
|
+
reason: typeof observation?.reason === 'string' ? observation.reason : null,
|
|
344
|
+
task: compactControlTask(observation?.task),
|
|
345
|
+
},
|
|
346
|
+
};
|
|
347
|
+
} else {
|
|
348
|
+
const result = await callExecution('cancel', { taskId: parsed.taskId }, context);
|
|
349
|
+
outcome = {
|
|
350
|
+
exitCode: EXIT.ok,
|
|
351
|
+
output: {
|
|
352
|
+
ok: true,
|
|
353
|
+
action: 'cancel',
|
|
354
|
+
taskId: parsed.taskId,
|
|
355
|
+
state: typeof result?.task?.state === 'string' ? result.task.state : null,
|
|
356
|
+
task: compactControlTask(result?.task),
|
|
357
|
+
},
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
// The budget expiring while the answer was being assembled is still a timeout: the
|
|
361
|
+
// client was told to give up at that instant, so an answer arriving afterwards is
|
|
362
|
+
// not reported as success.
|
|
363
|
+
if (budget.signal.aborted === true) throw budgetExpired(budgetMs);
|
|
364
|
+
return outcome;
|
|
365
|
+
} catch (error) {
|
|
366
|
+
// A refusal is the plane's answer, and it is reported as data: the caller learns
|
|
367
|
+
// the stable code instead of a stack trace, and no message is invented here. An
|
|
368
|
+
// exhausted budget is its own code, so an operator can tell "too slow" from
|
|
369
|
+
// "refused".
|
|
370
|
+
const expired = budget.signal.aborted === true;
|
|
371
|
+
const code = expired ? 'CONTROL_TIMEOUT' : (typeof error?.code === 'string' ? error.code : 'CONTROL_CALL_FAILED');
|
|
372
|
+
const message = expired
|
|
373
|
+
? `the control command did not answer within ${budgetMs} ms`
|
|
374
|
+
: (typeof error?.message === 'string' ? error.message.slice(0, MAX_FIELD_CHARS) : 'the control request failed');
|
|
375
|
+
return {
|
|
376
|
+
exitCode: EXIT.refused,
|
|
377
|
+
output: { ok: false, action: parsed.action, taskId: parsed.taskId, error: { code, message } },
|
|
378
|
+
};
|
|
379
|
+
} finally {
|
|
380
|
+
clearTimeout(timer);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* The error shape of an exhausted command budget.
|
|
386
|
+
* @param {number} budgetMs - the budget that expired.
|
|
387
|
+
* @returns {Error} error carrying the stable code.
|
|
388
|
+
*/
|
|
389
|
+
function budgetExpired(budgetMs) {
|
|
390
|
+
const error = new Error(`the control command did not answer within ${budgetMs} ms`);
|
|
391
|
+
error.code = 'CONTROL_TIMEOUT';
|
|
392
|
+
return error;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Printed for `--help` and for a malformed command line. */
|
|
396
|
+
export const USAGE = [
|
|
397
|
+
'Usage: dsh-delegate-control <status|cancel> <taskId>',
|
|
398
|
+
'',
|
|
399
|
+
' status <taskId> print the task\'s current compact state as JSON',
|
|
400
|
+
' cancel <taskId> ask the harness to stop exactly that task, then print its state',
|
|
401
|
+
'',
|
|
402
|
+
'Uses the same loopback endpoint and discovery file as the dsh-delegate MCP server',
|
|
403
|
+
'(DSH_DELEGATE_BASE_URL / DSH_DELEGATE_DISCOVERY_FILE are honoured identically).',
|
|
404
|
+
'One command answers within a single bound: 10 s by default, and',
|
|
405
|
+
'DSH_DELEGATE_CONTROL_TIMEOUT_MS may only lower it. It never retries, and it does not',
|
|
406
|
+
'poll: a normal wait stays silent.',
|
|
407
|
+
'It cannot submit a task, change a setting, move the delegation switch, or cancel',
|
|
408
|
+
'any task other than the one named. Exit code 0 = answered, 1 = refused or timed out,',
|
|
409
|
+
'2 = usage.',
|
|
410
|
+
].join('\n');
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Process entry point: one JSON document on stdout, diagnostics on stderr, and an
|
|
414
|
+
* exit code that says what happened.
|
|
415
|
+
* @param {string[]} argv - arguments after the script path.
|
|
416
|
+
* @param {object} [io] - `stdout`/`stderr` writers and optional `callExecution`/`config`
|
|
417
|
+
* dependencies, so an imported entry-point test never contacts the real harness.
|
|
418
|
+
* @returns {Promise<number>} exit code.
|
|
419
|
+
*/
|
|
420
|
+
export async function main(argv = process.argv.slice(2), io = {}) {
|
|
421
|
+
const writeOut = io.stdout ?? ((text) => process.stdout.write(text));
|
|
422
|
+
const writeErr = io.stderr ?? ((text) => process.stderr.write(text));
|
|
423
|
+
if (argv.length === 1 && (argv[0] === '--help' || argv[0] === '-h')) {
|
|
424
|
+
writeOut(`${USAGE}\n`);
|
|
425
|
+
return EXIT.ok;
|
|
426
|
+
}
|
|
427
|
+
// A last line of defence: whatever happens below, stdout gets ONE JSON document and
|
|
428
|
+
// nothing else. `runControl` already turns every failure it knows about into data, so
|
|
429
|
+
// reaching this is a bug — but a bug must not become a stack trace on a channel whose
|
|
430
|
+
// whole contract is machine-readable output.
|
|
431
|
+
let outcome;
|
|
432
|
+
try {
|
|
433
|
+
outcome = await runControl(argv, io);
|
|
434
|
+
} catch (error) {
|
|
435
|
+
const code = typeof error?.code === 'string' ? error.code : 'CONTROL_INTERNAL';
|
|
436
|
+
outcome = { exitCode: EXIT.refused, output: { ok: false, action: null, error: { code, message: 'the control command failed' } } };
|
|
437
|
+
}
|
|
438
|
+
const { exitCode, output } = outcome;
|
|
439
|
+
writeOut(`${JSON.stringify(output, null, 2)}\n`);
|
|
440
|
+
if (exitCode !== EXIT.ok) {
|
|
441
|
+
writeErr(`dsh-delegate-control: ${output?.error?.code ?? 'failed'}\n`);
|
|
442
|
+
}
|
|
443
|
+
return exitCode;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// Only run when executed directly; importing this module for tests must not read the
|
|
447
|
+
// environment, contact a plane or set an exit code.
|
|
448
|
+
if (process.argv[1] !== undefined && resolve(process.argv[1]) === SCRIPT_PATH) {
|
|
449
|
+
process.exitCode = await main();
|
|
450
|
+
}
|