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
package/src/index.js
ADDED
|
@@ -0,0 +1,657 @@
|
|
|
1
|
+
// dsh-delegate — native DSH plugin entry point.
|
|
2
|
+
//
|
|
3
|
+
// Load order matters and is visible here: services are injected, configuration is
|
|
4
|
+
// read, a byte-exact shipped Codex agent is refreshed, both HTTP planes are
|
|
5
|
+
// registered on their respective carriers, and the native
|
|
6
|
+
// provider/adapter/worktree/history machinery is constructed. The persisted
|
|
7
|
+
// local-call switch is restored at startup and defaults to OFF; no task is
|
|
8
|
+
// dispatched until an operator enables it in the DSH plugin settings.
|
|
9
|
+
//
|
|
10
|
+
// Service access is deliberately split in three:
|
|
11
|
+
//
|
|
12
|
+
// * `inject` lists the services this plugin cannot work without at all. While
|
|
13
|
+
// any is missing, Cordis does not activate the plugin — which is the correct
|
|
14
|
+
// outcome for a harness that cannot host it.
|
|
15
|
+
// * `ctx.get(name, false)` reads the services that are *optional*: the credential
|
|
16
|
+
// seam (a harness may have none, and the UI must then say so instead of the
|
|
17
|
+
// plugin failing to load) and the agent preset registry. A bare property read
|
|
18
|
+
// would throw `cannot get property "…" without inject`, so the non-strict
|
|
19
|
+
// accessor is the only safe way to express "optional".
|
|
20
|
+
// * the two native placement controllers (`workspaceController`,
|
|
21
|
+
// `sessionController`) are optional TOO, but read through a live accessor and
|
|
22
|
+
// not through a `ctx.get` call performed during activation: DSH may compose
|
|
23
|
+
// them after this plugin activated, and the snapshot would then be `null`
|
|
24
|
+
// forever, refusing every run with `SESSION_*_UNAVAILABLE`. A dispatch that
|
|
25
|
+
// meets no controller still fails closed; it just cannot be decided at load.
|
|
26
|
+
//
|
|
27
|
+
// The plugin's own face is published with `ctx.provide('dshDelegate', …)` rather
|
|
28
|
+
// than by assigning `ctx.dshDelegate`: an unprovided property assignment throws
|
|
29
|
+
// `cannot set property "…" without provide` in Cordis, and provide/effect is what
|
|
30
|
+
// makes the face disappear again on unload.
|
|
31
|
+
|
|
32
|
+
import { mkdir } from 'node:fs/promises';
|
|
33
|
+
import { homedir } from 'node:os';
|
|
34
|
+
import { join } from 'node:path';
|
|
35
|
+
|
|
36
|
+
import z from '@deepseek-ai/schemastery';
|
|
37
|
+
|
|
38
|
+
import { SCHEMA_VERSION } from './config/defaults.js';
|
|
39
|
+
import { SettingsService } from './config/settings.js';
|
|
40
|
+
import { AuthorizationRegistry } from './auth/grants.js';
|
|
41
|
+
import { bindAllowsExternalConnections } from './auth/fence.js';
|
|
42
|
+
import { JobEngine } from './jobs/engine.js';
|
|
43
|
+
import { HistoryStore } from './jobs/history.js';
|
|
44
|
+
import { WorkspaceLocks } from './workspace/locks.js';
|
|
45
|
+
import { createGitRunner } from './workspace/audit.js';
|
|
46
|
+
import { WorktreeManager } from './workspace/worktrees.js';
|
|
47
|
+
import { createCredentialGateway } from './credentials/seam.js';
|
|
48
|
+
import { createOpenAiAdapter } from './model/openai-adapter.js';
|
|
49
|
+
import { createProviderRegistry, nativeProvidersOf, managedProvidersOf } from './model/providers.js';
|
|
50
|
+
import { describeCatalog, resolveRoute } from './model/routing.js';
|
|
51
|
+
import { checkProviderConnectivity } from './model/connectivity.js';
|
|
52
|
+
import { probeModel } from './model/probe.js';
|
|
53
|
+
import { createExecutionHandler, EXECUTION_PREFIX } from './http/execution-plane.js';
|
|
54
|
+
import { wrapUserPlaneRoutes } from './http/user-plane.js';
|
|
55
|
+
import { diagnostic } from './runtime/agent-runner.js';
|
|
56
|
+
import { SessionStore, liveControllerAccessor } from './runtime/session-placement.js';
|
|
57
|
+
import { publishRuntimeEndpoint, resolveDefaultEndpointDiscoveryPath } from './runtime/endpoint-discovery.js';
|
|
58
|
+
import { resolveCodexActionSeam } from './codex/seam.js';
|
|
59
|
+
import { ReviewPreset } from './review/preset.js';
|
|
60
|
+
import { configureDelegatedSession, policyServicesOf } from './runtime/sandbox.js';
|
|
61
|
+
import { PermissionBridge, PERMISSION_DEFAULT_TIMEOUT_MS } from './runtime/permissions.js';
|
|
62
|
+
import { redactText, isSecretKey } from './config/redact.js';
|
|
63
|
+
|
|
64
|
+
/** Stable Cordis plugin name; also the settings/document namespace. */
|
|
65
|
+
export const name = 'dsh-taskbridge';
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Injected native services. Listing them explicitly means the plugin is not
|
|
69
|
+
* activated until each one exists, so no handler can run against a half-built
|
|
70
|
+
* harness. Two services are deliberately NOT injected:
|
|
71
|
+
*
|
|
72
|
+
* * `credentials` — the plugin must load and report state in a harness with no
|
|
73
|
+
* credential seam, and it only touches that seam when an operator asks about a
|
|
74
|
+
* reference or presses save;
|
|
75
|
+
* * `agentPresets` — a run works without a preset registry (it asks the runtime
|
|
76
|
+
* for its configured default), so a missing registry must not disable
|
|
77
|
+
* configuration.
|
|
78
|
+
*/
|
|
79
|
+
export const inject = ['agents', 'sessions', 'llm', 'tools', 'webServer', 'connection'];
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Plugin configuration schema.
|
|
83
|
+
*
|
|
84
|
+
* Cordis validates a plugin's config before `apply` runs by calling
|
|
85
|
+
* `runtime.Config['~standard'].validate(config)` (see `resolveConfig` in
|
|
86
|
+
* `@deepseek-ai/cordis`, 0.2.0-rc.2 / 4.0.5). A plain object has no
|
|
87
|
+
* `~standard` member, so it dereferences `undefined.validate` and the plugin
|
|
88
|
+
* fails to activate. Every native DSH plugin declares its schema with
|
|
89
|
+
* `@deepseek-ai/schemastery`, whose schemas carry that interface; this one must
|
|
90
|
+
* too, and `schemastery` is then also a real runtime dependency rather than a
|
|
91
|
+
* host-provided accident.
|
|
92
|
+
*/
|
|
93
|
+
export const Config = z.object({
|
|
94
|
+
/** Data directory root; the plugin appends `dsh-delegate`. */
|
|
95
|
+
dataDir: z.string().default(''),
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Mount the delegation service.
|
|
100
|
+
*
|
|
101
|
+
* `config` is the operator's settings document and is validated by {@link Config}
|
|
102
|
+
* before this runs. A test may additionally pass a `reviewPresetImporter`, which
|
|
103
|
+
* replaces the solver used to find the native review tool packages; it is not
|
|
104
|
+
* part of the published schema and a real deployment never provides one.
|
|
105
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx - plugin context.
|
|
106
|
+
* @param {object} config - plugin config.
|
|
107
|
+
* @returns {Promise<void>} resolves after registration.
|
|
108
|
+
*/
|
|
109
|
+
export async function apply(ctx, config = {}) {
|
|
110
|
+
const logger = ctx.logger;
|
|
111
|
+
const dataDir = await resolveDataDir(ctx, config);
|
|
112
|
+
|
|
113
|
+
const settings = new SettingsService(dataDir);
|
|
114
|
+
// Read once at load so an unusable document fails the plugin loudly instead of
|
|
115
|
+
// surfacing as a confusing refusal on the first request.
|
|
116
|
+
const initialSettings = await settings.read();
|
|
117
|
+
|
|
118
|
+
// Optional services, read non-strictly so their absence is a fact and not a throw.
|
|
119
|
+
const credentialsService = ctx.get('credentials', false) ?? null;
|
|
120
|
+
const agentPresets = ctx.get('agentPresets', false) ?? null;
|
|
121
|
+
|
|
122
|
+
const auth = new AuthorizationRegistry();
|
|
123
|
+
const locks = new WorkspaceLocks();
|
|
124
|
+
const runGit = createGitRunner();
|
|
125
|
+
|
|
126
|
+
// The credential gateway is what both the native adapter and the user plane use.
|
|
127
|
+
// It reads the seam lazily, so a service that appears (or disappears) after load
|
|
128
|
+
// is observed on the next operation instead of being frozen at startup.
|
|
129
|
+
const credentials = createCredentialGateway(() => ctx.get('credentials', false) ?? credentialsService);
|
|
130
|
+
|
|
131
|
+
// Native adapter + route registry. Without these a dispatch must refuse
|
|
132
|
+
// (`JOB_PROVIDER_REGISTRY_REQUIRED`) rather than silently route to a profile id
|
|
133
|
+
// that the harness never registered.
|
|
134
|
+
//
|
|
135
|
+
// `createOpenAiAdapter` returns a *management facade* around one `PiAiAdapter`.
|
|
136
|
+
// The registry is given the facade and unwraps it, because the only object the
|
|
137
|
+
// native core may be handed is the adapter itself: it calls
|
|
138
|
+
// `providerInfo`/`providerRetryPolicy` during registration and `prepareCall`/
|
|
139
|
+
// `stream` on every request. Registering the facade produced exactly the
|
|
140
|
+
// observed failure — the route existed, and every model call on it resolved
|
|
141
|
+
// `ROUTING_MODEL_UNRESOLVED` because no streamable adapter was ever attached.
|
|
142
|
+
const adapter = createOpenAiAdapter({ credentials });
|
|
143
|
+
const providerRegistry = createProviderRegistry({ llm: ctx.llm, adapter });
|
|
144
|
+
|
|
145
|
+
const history = new HistoryStore(dataDir);
|
|
146
|
+
const worktrees = new WorktreeManager({ runGit }, { rootDir: join(dataDir, 'worktrees') });
|
|
147
|
+
// The task-thread identity map: task id -> the DSH Workspace/Session that task
|
|
148
|
+
// drove, plus the paths and (for an isolated run) the tree ownership facts a
|
|
149
|
+
// `continueFromTaskId` follow-up is validated against. Keyed by task, never by
|
|
150
|
+
// directory, so nothing here can make a new submission continue an old
|
|
151
|
+
// conversation. Stores identities only, never transcript content.
|
|
152
|
+
const sessionStore = new SessionStore(dataDir, { logger });
|
|
153
|
+
|
|
154
|
+
// The independent review composes its own read-only agent preset instead of
|
|
155
|
+
// joining the deployment default (which mounts `dsh-tool-subagent`, a tool a
|
|
156
|
+
// scope restriction cannot remove). The composition is registered LAZILY on the
|
|
157
|
+
// first review request — the registry's own diagnostic may wait for the Host
|
|
158
|
+
// Loader tree to settle, and must not run inside this row's activation — and is
|
|
159
|
+
// removed again on unload by the effect below. It never touches the configured
|
|
160
|
+
// default, the installed profile, or a user preset.
|
|
161
|
+
const reviewPreset = new ReviewPreset({
|
|
162
|
+
registry: agentPresets,
|
|
163
|
+
logger,
|
|
164
|
+
...(typeof config?.reviewPresetImporter === 'function' ? { importer: config.reviewPresetImporter } : {}),
|
|
165
|
+
});
|
|
166
|
+
const readPresets = () => ctx.get('agentPresets', false) ?? null;
|
|
167
|
+
const reviewPresets = {
|
|
168
|
+
/**
|
|
169
|
+
* A live facade so a registry that appears (or is replaced) after load is
|
|
170
|
+
* observed on the next review instead of being frozen at startup.
|
|
171
|
+
*/
|
|
172
|
+
get id() { return reviewPreset.createdId; },
|
|
173
|
+
owns(id) { return reviewPreset.owns(id); },
|
|
174
|
+
preparation: (bounds) => {
|
|
175
|
+
reviewPreset.attach(readPresets());
|
|
176
|
+
return reviewPreset.preparation(bounds ?? {});
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Report a native controller whose read was refused, on the plugin's logger.
|
|
182
|
+
*
|
|
183
|
+
* The accessors below are non-strict by design (`ctx.get(name, false)`), so a
|
|
184
|
+
* service the harness does not expose answers `undefined` rather than throwing.
|
|
185
|
+
* A throw can still happen when the service's own resolution fails; that must
|
|
186
|
+
* reach the operator's log instead of vanishing into the fail-closed refusal the
|
|
187
|
+
* run then reports.
|
|
188
|
+
* @param {string} serviceName - `workspaceController` or `sessionController`.
|
|
189
|
+
* @param {unknown} error - whatever the accessor threw.
|
|
190
|
+
* @returns {void}
|
|
191
|
+
*/
|
|
192
|
+
const warnControllerRead = (serviceName, error) => {
|
|
193
|
+
logger?.warn?.(`dsh-delegate: the DSH ${serviceName} could not be read (${diagnostic(error?.message ?? error, 200)})`);
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const deps = {
|
|
197
|
+
agents: ctx.agents,
|
|
198
|
+
agentPresets,
|
|
199
|
+
reviewPresets,
|
|
200
|
+
sessions: ctx.sessions,
|
|
201
|
+
// The native Workspace and Session controllers. Both are read non-strictly
|
|
202
|
+
// and, more importantly, LAZILY: a harness that does not compose them must
|
|
203
|
+
// load the plugin and then refuse a dispatch with a stated code
|
|
204
|
+
// (`SESSION_*_UNAVAILABLE`), not fail to activate — and a harness that
|
|
205
|
+
// composes them AFTER this plugin activated (or replaces one) must still be
|
|
206
|
+
// able to place the next run. These are therefore live accessors, not the
|
|
207
|
+
// snapshot `ctx.get` would return here: see {@link liveControllerAccessor}.
|
|
208
|
+
// A run is never created outside a Workspace as a fallback.
|
|
209
|
+
workspaces: liveControllerAccessor(
|
|
210
|
+
() => ctx.get('workspaceController', false),
|
|
211
|
+
{ onError: (error) => warnControllerRead('workspaceController', error) },
|
|
212
|
+
),
|
|
213
|
+
sessionController: liveControllerAccessor(
|
|
214
|
+
() => ctx.get('sessionController', false),
|
|
215
|
+
{ onError: (error) => warnControllerRead('sessionController', error) },
|
|
216
|
+
),
|
|
217
|
+
sessionStore,
|
|
218
|
+
llm: ctx.llm,
|
|
219
|
+
tools: ctx.tools,
|
|
220
|
+
settings,
|
|
221
|
+
auth,
|
|
222
|
+
locks,
|
|
223
|
+
runGit,
|
|
224
|
+
worktrees,
|
|
225
|
+
history,
|
|
226
|
+
providerRegistry,
|
|
227
|
+
credentials,
|
|
228
|
+
logger,
|
|
229
|
+
delegationEnabled: initialSettings.delegationEnabled === true,
|
|
230
|
+
authorizationMode: 'switch',
|
|
231
|
+
// Startup only refreshes an agent file whose bytes match a shipped template.
|
|
232
|
+
// Agent creation and MCP registration remain explicit settings-page actions.
|
|
233
|
+
codex: resolveCodexActionSeam({
|
|
234
|
+
version: PLUGIN_VERSION,
|
|
235
|
+
// The automatic upgrade's protected backup location, inside this activation's own
|
|
236
|
+
// data directory: never the package, never the Codex home, never a user home. The
|
|
237
|
+
// seam supplies it to a caller that does not pass one, so the unattended MCP write
|
|
238
|
+
// always has a place to keep the original bytes.
|
|
239
|
+
backupDir: join(dataDir, 'codex-config-backup'),
|
|
240
|
+
}),
|
|
241
|
+
// The runner calls this only for worker jobs. Reviews intentionally use their
|
|
242
|
+
// own read-only tool policy and are not put into a delegated worker sandbox.
|
|
243
|
+
configureDelegatedSession,
|
|
244
|
+
// `ctx.sandboxPolicy` and `ctx.approval` own the two facts the delegated
|
|
245
|
+
// policy writes, so the runner reads them back through these live services
|
|
246
|
+
// and refuses the run when either cannot answer. Read per run, never at
|
|
247
|
+
// activation: a service composed later must still be observed.
|
|
248
|
+
policyServices: () => policyServicesOf(ctx),
|
|
249
|
+
// The per-call permission bridge factory. It produces a bridge only when this
|
|
250
|
+
// harness can actually service an approval request: a live `ctx.approval` with
|
|
251
|
+
// a callable `request()`, which is the seam the native tools ask through. When
|
|
252
|
+
// that seam is absent the factory returns null, the engine offers no bridge,
|
|
253
|
+
// and every worker run keeps the original fail-closed `never` stance — this
|
|
254
|
+
// plugin must never install an `ask` it cannot answer.
|
|
255
|
+
permissionBridge: createPermissionBridgeFactory({
|
|
256
|
+
getApprovalService: () => readOptionalApprovalService(ctx),
|
|
257
|
+
logger,
|
|
258
|
+
}),
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
try {
|
|
262
|
+
// Both halves of the installed-integration check: a byte-exact shipped agent is
|
|
263
|
+
// refreshed, and an ALREADY INSTALLED managed `mcp_servers.dsh-delegate` entry that
|
|
264
|
+
// is merely stale (for example one written before `tool_timeout_sec` existed) is
|
|
265
|
+
// upgraded in place. Nothing is created here — a home without an entry stays
|
|
266
|
+
// without one — and an entry this plugin cannot prove it wrote is refused and left
|
|
267
|
+
// byte-identical.
|
|
268
|
+
//
|
|
269
|
+
// The TARGET is the seam's own decision (`startupTarget`), not a second read of
|
|
270
|
+
// `process.env`: an explicit `CODEX_HOME`, else the home this plugin recorded from a
|
|
271
|
+
// successful install, else the default only when it is a real directory. A default
|
|
272
|
+
// that is a link is reported instead of walked, so the automatic upgrade never
|
|
273
|
+
// writes into a tree nobody named.
|
|
274
|
+
const target = await deps.codex?.startupTarget?.();
|
|
275
|
+
let migration = null;
|
|
276
|
+
if (target?.home) {
|
|
277
|
+
migration = await deps.codex?.refreshManagedIntegration({
|
|
278
|
+
startupTarget: target,
|
|
279
|
+
// The pre-write copy lives in the plugin's own data directory: supportable, not
|
|
280
|
+
// packaged, and never inside the Codex home.
|
|
281
|
+
backupDir: join(dataDir, 'codex-config-backup'),
|
|
282
|
+
});
|
|
283
|
+
} else if (target !== undefined && target !== null) {
|
|
284
|
+
logger?.info?.(`dsh-delegate: Codex integration check skipped (${target.reason})`);
|
|
285
|
+
}
|
|
286
|
+
if (migration?.changed.includes('agent')) {
|
|
287
|
+
logger?.info?.(`dsh-delegate: refreshed a managed Codex agent template to ${PLUGIN_VERSION}`);
|
|
288
|
+
}
|
|
289
|
+
if (migration?.changed.includes('mcp')) {
|
|
290
|
+
logger?.info?.('dsh-delegate: upgraded a stale managed Codex MCP entry in place');
|
|
291
|
+
}
|
|
292
|
+
for (const refusal of migration?.refused ?? []) {
|
|
293
|
+
logger?.warn?.(`dsh-delegate: Codex integration refresh was refused (${refusal.code})`);
|
|
294
|
+
}
|
|
295
|
+
} catch (error) {
|
|
296
|
+
logger?.warn?.(`dsh-delegate: Codex integration refresh check failed (${diagnostic(error?.message ?? error, 200)})`);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Bring the native routes and the adapter's served snapshot to the state this
|
|
301
|
+
* settings snapshot describes, and return the mapping both sides agree on.
|
|
302
|
+
*
|
|
303
|
+
* One registration owns the route set. The whole transition below is a single
|
|
304
|
+
* synchronous section — `transaction()` never awaits, and the registry refuses
|
|
305
|
+
* a callback that returns a thenable — because the two sides must move together:
|
|
306
|
+
*
|
|
307
|
+
* 1. `registry.register(providers, adapt)` validates the candidate list, then
|
|
308
|
+
* checks that no candidate route is owned by another registration;
|
|
309
|
+
* 2. `adapt` publishes the matching snapshot on the adapter
|
|
310
|
+
* (`prepareRoutes`), which is the state `prepareRoutes()` in the core reads
|
|
311
|
+
* synchronously when it validates the routes;
|
|
312
|
+
* 3. `adapt` calls the `commit()` the registry handed it, which is where the
|
|
313
|
+
* core validates and commits — synchronously, still inside `adapt`'s own
|
|
314
|
+
* stack — so no native observer, and no second ensure, can see the adapter
|
|
315
|
+
* serving a generation the core has not accepted;
|
|
316
|
+
* 4. a refusal at step 3 rolls the snapshot back to the generation it
|
|
317
|
+
* displaced before the error leaves this function, so a failed
|
|
318
|
+
* re-registration leaves both the native route set and the adapter on the
|
|
319
|
+
* old generation.
|
|
320
|
+
*
|
|
321
|
+
* There is no fallback: a failed registration throws, and every caller
|
|
322
|
+
* (job preflight, `/models`, `/catalog`, connectivity) turns that into an
|
|
323
|
+
* honest refusal instead of routing to an ambient `relay`/`workbuddy` route.
|
|
324
|
+
*
|
|
325
|
+
* The native/custom split is {@link managedProvidersOf}, the same helper
|
|
326
|
+
* `JobEngine.leaseProviders()` uses. That is load bearing, not tidiness: the
|
|
327
|
+
* registry fingerprints whichever list it is given, so the task's long-lived
|
|
328
|
+
* lease and this registration have to describe one set. A native-only
|
|
329
|
+
* configuration therefore leases and registers the same empty custom set
|
|
330
|
+
* instead of leasing `[workbuddy]` and then being refused by its own lease when
|
|
331
|
+
* it registers `[]`.
|
|
332
|
+
* @param {object} snapshot - validated settings snapshot.
|
|
333
|
+
* @returns {Promise<Map<string, string>>} public provider id -> native route id.
|
|
334
|
+
*/
|
|
335
|
+
const ensureRoutes = async (snapshot) => {
|
|
336
|
+
const providers = Array.isArray(snapshot?.providers) ? snapshot.providers : [];
|
|
337
|
+
const nativeProviders = nativeProvidersOf(providers);
|
|
338
|
+
const customProviders = managedProvidersOf(providers);
|
|
339
|
+
const registered = await ctx.llm.listProviders();
|
|
340
|
+
const available = new Set((Array.isArray(registered) ? registered : []).map((entry) => entry.id));
|
|
341
|
+
const routes = new Map();
|
|
342
|
+
for (const provider of nativeProviders) {
|
|
343
|
+
if (!available.has(provider.id)) {
|
|
344
|
+
const error = new Error(`native provider ${provider.id} is no longer registered with DSH`);
|
|
345
|
+
error.code = 'NATIVE_PROVIDER_UNAVAILABLE';
|
|
346
|
+
throw error;
|
|
347
|
+
}
|
|
348
|
+
routes.set(provider.id, provider.id);
|
|
349
|
+
}
|
|
350
|
+
if (customProviders.length === 0) {
|
|
351
|
+
await providerRegistry.register([], () => {});
|
|
352
|
+
return routes;
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* The transaction body. Everything here is synchronous on purpose: the adapter
|
|
356
|
+
* is the only party that may restore the snapshot, and it must have done so
|
|
357
|
+
* before the registry's callback returns and the error propagates.
|
|
358
|
+
*
|
|
359
|
+
* `commit()` is called by the registry at this point in the sequence, from
|
|
360
|
+
* inside this callback's own stack, so the native registration can never land
|
|
361
|
+
* in a microtask after a publication that a second ensure could already have
|
|
362
|
+
* displaced.
|
|
363
|
+
* @param {Map<string, string>} routes - the candidate mapping to register.
|
|
364
|
+
* @param {() => void} commit - perform the native registration.
|
|
365
|
+
* @returns {void}
|
|
366
|
+
*/
|
|
367
|
+
const adapt = (routes, commit) => {
|
|
368
|
+
const prepared = adapter.prepareRoutes({ providers: customProviders, routes });
|
|
369
|
+
if (!adapter.describes(prepared, routes)) {
|
|
370
|
+
prepared.rollback();
|
|
371
|
+
throw new Error('dsh-delegate: the adapter and the registry planned different route sets');
|
|
372
|
+
}
|
|
373
|
+
try {
|
|
374
|
+
commit();
|
|
375
|
+
} catch (error) {
|
|
376
|
+
prepared.rollback();
|
|
377
|
+
throw error;
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
const ensured = await providerRegistry.register(customProviders, adapt);
|
|
381
|
+
for (const [id, route] of ensured.routes) routes.set(id, route);
|
|
382
|
+
return routes;
|
|
383
|
+
};
|
|
384
|
+
deps.ensureRoutes = ensureRoutes;
|
|
385
|
+
/**
|
|
386
|
+
* The route set, or the reason there is none — for read paths that must answer
|
|
387
|
+
* with a body instead of a thrown refusal.
|
|
388
|
+
* @param {object} snapshot - validated settings snapshot.
|
|
389
|
+
* @param {string} operation - what was being attempted, for the log line.
|
|
390
|
+
* @returns {Promise<{ routes: Map<string, string> | null, error: { code: string, message: string } | null }>} outcome.
|
|
391
|
+
*/
|
|
392
|
+
deps.resolveRoutes = async (snapshot, operation) => {
|
|
393
|
+
try {
|
|
394
|
+
return { routes: await ensureRoutes(snapshot), error: null };
|
|
395
|
+
} catch (error) {
|
|
396
|
+
const outcome = {
|
|
397
|
+
code: typeof error?.code === 'string' ? error.code : 'ROUTE_REGISTRATION_REFUSED',
|
|
398
|
+
message: diagnostic(error?.message ?? 'the native provider routes could not be registered', 300),
|
|
399
|
+
};
|
|
400
|
+
logger?.warn?.(`dsh-delegate: provider route registration failed during ${operation}`, outcome.code);
|
|
401
|
+
return { routes: null, error: outcome };
|
|
402
|
+
}
|
|
403
|
+
};
|
|
404
|
+
/** The adapter's own view of what it serves; used only for diagnostics/tests. */
|
|
405
|
+
deps.adapterSnapshot = () => adapter.snapshot();
|
|
406
|
+
deps.probeModel = (route, options) => probeModel(deps, route, options ?? {});
|
|
407
|
+
|
|
408
|
+
const engine = new JobEngine(deps);
|
|
409
|
+
deps.engine = engine;
|
|
410
|
+
deps.describeRuntime = () => ({
|
|
411
|
+
plugin: name,
|
|
412
|
+
version: PLUGIN_VERSION,
|
|
413
|
+
schemaVersion: SCHEMA_VERSION,
|
|
414
|
+
// Facts an operator needs to reason about exposure. Never a secret.
|
|
415
|
+
bind: ctx.webServer?.host ?? null,
|
|
416
|
+
port: ctx.webServer?.port ?? null,
|
|
417
|
+
executionPlane: EXECUTION_PREFIX,
|
|
418
|
+
executionPlaneLocalOnly: ctx.webServer?.host === '127.0.0.1',
|
|
419
|
+
credentialSeam: credentialsService === null ? 'unavailable' : 'available',
|
|
420
|
+
presetRegistry: agentPresets === null ? 'unavailable' : 'available',
|
|
421
|
+
// Whether this harness can group a run into a DSH Workspace and create the
|
|
422
|
+
// session inside it. Reported so an operator can tell a configuration problem
|
|
423
|
+
// from a missing native service before dispatching. Read at report time, so a
|
|
424
|
+
// controller composed after activation is reported as available instead of
|
|
425
|
+
// being described by the load-time snapshot.
|
|
426
|
+
workspaceController: deps.workspaces?.current === null ? 'unavailable' : 'available',
|
|
427
|
+
sessionController: deps.sessionController?.current === null ? 'unavailable' : 'available',
|
|
428
|
+
// The conversation rule, not a stored setting: a new submission starts a new DSH
|
|
429
|
+
// conversation, and a follow-up continues only the task named by
|
|
430
|
+
// `continueFromTaskId`. Reported so an operator can see that there is no longer
|
|
431
|
+
// a directory-level mode to configure.
|
|
432
|
+
conversation: 'per-task',
|
|
433
|
+
conversationContinuation: 'continueFromTaskId',
|
|
434
|
+
// Whether the review's own composition was ever registered, i.e. whether a
|
|
435
|
+
// read-only review has been attempted in this activation. Lazy by design.
|
|
436
|
+
reviewPreset: reviewPreset.createdId ?? 'not-registered',
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
// ---- user plane: authenticated DSH settings and task controls --------------
|
|
440
|
+
const userRoutes = wrapUserPlaneRoutes(deps);
|
|
441
|
+
for (const route of userRoutes) {
|
|
442
|
+
const dispose = ctx.connection.fetch.register(route);
|
|
443
|
+
ctx.effect(() => dispose);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// ---- execution plane: loopback MCP; only new submissions need the switch --
|
|
447
|
+
const bindVerdict = bindAllowsExternalConnections(ctx.webServer?.host ?? '127.0.0.1');
|
|
448
|
+
if (bindVerdict.ok === true) {
|
|
449
|
+
const handler = createExecutionHandler({
|
|
450
|
+
...deps,
|
|
451
|
+
getBindHost: () => ctx.webServer?.host ?? null,
|
|
452
|
+
});
|
|
453
|
+
const dispose = ctx.webServer.register({
|
|
454
|
+
kind: 'prefix',
|
|
455
|
+
path: EXECUTION_PREFIX,
|
|
456
|
+
handler: (req, res) => handler(req, res),
|
|
457
|
+
});
|
|
458
|
+
ctx.effect(() => dispose);
|
|
459
|
+
try {
|
|
460
|
+
const endpointLease = await publishRuntimeEndpoint({
|
|
461
|
+
filePath: resolveDefaultEndpointDiscoveryPath(),
|
|
462
|
+
host: ctx.webServer?.host,
|
|
463
|
+
port: ctx.webServer?.port,
|
|
464
|
+
});
|
|
465
|
+
ctx.effect(() => () => endpointLease.dispose());
|
|
466
|
+
} catch (error) {
|
|
467
|
+
logger?.warn?.(`dsh-delegate: could not publish MCP endpoint discovery (${diagnostic(error?.message, 200)})`);
|
|
468
|
+
}
|
|
469
|
+
} else {
|
|
470
|
+
// Registering an unauthenticated external surface on a public bind would be
|
|
471
|
+
// worse than not having one. Refuse and record the reason.
|
|
472
|
+
logger?.warn?.(
|
|
473
|
+
`dsh-delegate: the execution plane is not registered because the webserver binds ${ctx.webServer?.host ?? 'unknown'} (${bindVerdict.code}). `
|
|
474
|
+
+ 'Delegation requests from external connections will be refused.',
|
|
475
|
+
);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// ---- stop everything on unload ------------------------------------------
|
|
479
|
+
ctx.effect(() => async () => {
|
|
480
|
+
await engine.dispose();
|
|
481
|
+
// Jobs are gone before the review composition is: a disposed engine holds no
|
|
482
|
+
// runner that could mount a preset this disposer is about to remove.
|
|
483
|
+
await reviewPreset.dispose();
|
|
484
|
+
// History is flushed before the store is closed so a task that finished during
|
|
485
|
+
// teardown is still durable. The session map is flushed on the same terms.
|
|
486
|
+
await history.dispose();
|
|
487
|
+
await sessionStore.dispose();
|
|
488
|
+
providerRegistry.dispose();
|
|
489
|
+
auth.revokeAll();
|
|
490
|
+
locks.releaseAll();
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
logger?.info?.(`dsh-delegate: loaded (local MCP switch ${initialSettings.delegationEnabled === true ? 'on' : 'off'}, `
|
|
494
|
+
+ 'conversation per task: new unless continueFromTaskId names the task to continue)');
|
|
495
|
+
|
|
496
|
+
// Published as a Cordis service, not assigned: `ctx.provide` is the only legal
|
|
497
|
+
// way to add a property, and its disposer removes the face on unload.
|
|
498
|
+
ctx.provide('dshDelegate', {
|
|
499
|
+
settings,
|
|
500
|
+
auth,
|
|
501
|
+
engine,
|
|
502
|
+
locks,
|
|
503
|
+
history,
|
|
504
|
+
sessionStore,
|
|
505
|
+
worktrees,
|
|
506
|
+
providerRegistry,
|
|
507
|
+
credentials,
|
|
508
|
+
deps,
|
|
509
|
+
reviewPreset,
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/** Version reported by the runtime facts block. Mirrors `package.json`. */
|
|
514
|
+
const PLUGIN_VERSION = '1.3.1';
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Read the native approval service without turning absence into a throw.
|
|
518
|
+
*
|
|
519
|
+
* The bridge is offered only when this service exists AND exposes `request()`,
|
|
520
|
+
* because that call is the seam a native tool uses to ask. A service that is
|
|
521
|
+
* present but cannot be asked through (a half-composed or replaced approval
|
|
522
|
+
* runtime) is treated as absent, so the run keeps the deterministic `never`
|
|
523
|
+
* stance instead of installing an `ask` nobody services.
|
|
524
|
+
* @param {object} ctx - plugin context.
|
|
525
|
+
* @returns {object | null} the approval service, or null.
|
|
526
|
+
*/
|
|
527
|
+
function readOptionalApprovalService(ctx) {
|
|
528
|
+
if (ctx === null || ctx === undefined || typeof ctx.get !== 'function') return null;
|
|
529
|
+
let service;
|
|
530
|
+
try {
|
|
531
|
+
service = ctx.get('approval', false) ?? null;
|
|
532
|
+
} catch {
|
|
533
|
+
return null;
|
|
534
|
+
}
|
|
535
|
+
if (service === null || typeof service !== 'object' || typeof service.request !== 'function') return null;
|
|
536
|
+
return service;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Build the per-run permission bridge factory the job engine calls.
|
|
541
|
+
*
|
|
542
|
+
* The factory returns a bridge ONLY when the deployment can service the request it
|
|
543
|
+
* would surface: the native approval seam must be composed and askable. It returns
|
|
544
|
+
* `null` otherwise, which the engine treats as "this run is not bridged" — the
|
|
545
|
+
* stance stays `never` and nothing about the run changes.
|
|
546
|
+
*
|
|
547
|
+
* The bridge it returns carries:
|
|
548
|
+
*
|
|
549
|
+
* * the task and connection identity the commander's decision is checked against;
|
|
550
|
+
* * the deployment's own redaction (`redactText`), so no argument value or asker
|
|
551
|
+
* claim can publish a credential;
|
|
552
|
+
* * a per-request deadline of {@link PERMISSION_DEFAULT_TIMEOUT_MS} — a fixed,
|
|
553
|
+
* documented bound, never an infinite wait;
|
|
554
|
+
* * the observers the ENGINE owns (it records the phase and accounts the wait),
|
|
555
|
+
* supplied by the engine's own call so this factory holds no task state.
|
|
556
|
+
* @param {object} options - `getApprovalService` (live accessor), `logger`.
|
|
557
|
+
* @returns {(request: object) => object | null} factory.
|
|
558
|
+
*/
|
|
559
|
+
function createPermissionBridgeFactory(options) {
|
|
560
|
+
return function permissionBridge(request) {
|
|
561
|
+
const approval = typeof options?.getApprovalService === 'function' ? options.getApprovalService() : null;
|
|
562
|
+
if (approval === null) return null;
|
|
563
|
+
try {
|
|
564
|
+
return new PermissionBridge({
|
|
565
|
+
taskId: request?.taskId,
|
|
566
|
+
connectionId: request?.connectionId,
|
|
567
|
+
timeoutMs: PERMISSION_DEFAULT_TIMEOUT_MS,
|
|
568
|
+
// BOTH halves of redaction: the scalar patterns AND the key-aware predicate.
|
|
569
|
+
// The second one is what stops `{"apiKey":"…"}` being published verbatim,
|
|
570
|
+
// because that secret carries no credential-shaped TEXT at all.
|
|
571
|
+
redact: (text) => redactText(text),
|
|
572
|
+
isSecretKey,
|
|
573
|
+
onPending: request?.onPending,
|
|
574
|
+
onSettled: request?.onSettled,
|
|
575
|
+
logger: options?.logger ?? null,
|
|
576
|
+
});
|
|
577
|
+
} catch (error) {
|
|
578
|
+
options?.logger?.warn?.('dsh-delegate: the permission bridge could not be constructed', String(error?.code ?? ''));
|
|
579
|
+
return null;
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/**
|
|
585
|
+
* Resolve the plugin's own data directory.
|
|
586
|
+
*
|
|
587
|
+
* Precedence matches the harness's own home resolution: an explicit plugin config
|
|
588
|
+
* path, then `$DSH_HOME`, then `~/.dsh`. A blank `DSH_HOME` is treated as unset so
|
|
589
|
+
* a whitespace override can never resolve state into the current directory.
|
|
590
|
+
* @param {object} ctx - plugin context (unused for paths; kept for signature symmetry).
|
|
591
|
+
* @param {object} config - plugin config.
|
|
592
|
+
* @returns {Promise<string>} absolute data directory.
|
|
593
|
+
*/
|
|
594
|
+
async function resolveDataDir(ctx, config) {
|
|
595
|
+
const configured = typeof config?.dataDir === 'string' ? config.dataDir.trim() : '';
|
|
596
|
+
const base = configured !== '' ? configured : defaultHome();
|
|
597
|
+
const target = join(configured !== '' ? base : join(base, 'data'), 'dsh-delegate');
|
|
598
|
+
await mkdir(target, { recursive: true, mode: 0o700 });
|
|
599
|
+
return target;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
function defaultHome() {
|
|
603
|
+
const fromEnv = typeof process.env.DSH_HOME === 'string' ? process.env.DSH_HOME.trim() : '';
|
|
604
|
+
if (fromEnv !== '') return fromEnv;
|
|
605
|
+
return join(homedir(), '.dsh');
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Whole-configuration connectivity report.
|
|
610
|
+
*
|
|
611
|
+
* Kept as an exported function because it is the shape an operator-facing
|
|
612
|
+
* diagnostic and a test both want: one call, every configured provider, no HTTP
|
|
613
|
+
* surface involved. The per-provider implementation lives in
|
|
614
|
+
* `src/model/connectivity.js`; this function is the fan-out over the document.
|
|
615
|
+
*
|
|
616
|
+
* The four layers are reported independently because they fail for different
|
|
617
|
+
* reasons and a caller must not conclude "the model is broken" from "the endpoint
|
|
618
|
+
* is unreachable". The model layer sends a real, short request with a usable token
|
|
619
|
+
* budget and treats a reasoning-only answer as success — reasoning models that
|
|
620
|
+
* spend their budget thinking are working, not timing out.
|
|
621
|
+
* @param {object} deps - dependency object with `settings`, `credentials`,
|
|
622
|
+
* `ensureRoutes`, `llm`, `probeModel`.
|
|
623
|
+
* @returns {Promise<object>} `{ settings: object, providers: object[] }` report.
|
|
624
|
+
*/
|
|
625
|
+
export async function checkConnectivity(deps) {
|
|
626
|
+
let snapshot;
|
|
627
|
+
try {
|
|
628
|
+
snapshot = await deps.settings.read();
|
|
629
|
+
} catch (error) {
|
|
630
|
+
return {
|
|
631
|
+
ok: false,
|
|
632
|
+
providers: [],
|
|
633
|
+
error: { code: error?.code ?? 'SETTINGS_UNREADABLE', message: diagnostic(error?.message, 300) },
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
const providers = [];
|
|
637
|
+
for (const provider of snapshot.providers) {
|
|
638
|
+
try {
|
|
639
|
+
providers.push(await checkProviderConnectivity(deps, { providerId: provider.id }));
|
|
640
|
+
} catch (error) {
|
|
641
|
+
providers.push({
|
|
642
|
+
providerId: provider.id,
|
|
643
|
+
providerName: provider.name,
|
|
644
|
+
error: {
|
|
645
|
+
code: typeof error?.code === 'string' ? error.code : 'CONNECTIVITY_FAILED',
|
|
646
|
+
message: diagnostic(error?.message, 300),
|
|
647
|
+
},
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
return {
|
|
652
|
+
ok: providers.length > 0 && providers.every((entry) => entry.error === undefined || entry.error === null),
|
|
653
|
+
providers,
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
export { describeCatalog, resolveRoute };
|