@zoraxylia/dsh-codex-adapter 0.0.0-stage → 0.1.0

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 (87) hide show
  1. package/.claude-plugin/marketplace.json +15 -0
  2. package/.claude-plugin/plugin.json +8 -0
  3. package/.mcp.json +8 -0
  4. package/LICENSE +21 -0
  5. package/README.de.md +480 -0
  6. package/README.es.md +480 -0
  7. package/README.fr.md +480 -0
  8. package/README.hi.md +480 -0
  9. package/README.id.md +480 -0
  10. package/README.ja.md +478 -0
  11. package/README.ko.md +480 -0
  12. package/README.md +483 -2
  13. package/README.pt.md +480 -0
  14. package/README.ru.md +480 -0
  15. package/README.th.md +480 -0
  16. package/README.tr.md +480 -0
  17. package/README.vi.md +480 -0
  18. package/README.zh-TW.md +478 -0
  19. package/README.zh.md +482 -0
  20. package/agents/ds-flash.md +17 -0
  21. package/agents/ds-pro.md +17 -0
  22. package/agy/agents/ds-flash.md +18 -0
  23. package/agy/agents/ds-pro.md +18 -0
  24. package/agy/skills/dsh-config/SKILL.md +6 -0
  25. package/agy/skills/dsh-playbook/SKILL.md +65 -0
  26. package/agy/skills/dsh-status/SKILL.md +6 -0
  27. package/codex/agents/ds-flash.toml +23 -0
  28. package/codex/agents/ds-pro.toml +23 -0
  29. package/codex/prompts/dsh-config.md +3 -0
  30. package/codex/prompts/dsh-playbook.md +60 -0
  31. package/codex/prompts/dsh-status.md +1 -0
  32. package/commands/config.md +9 -0
  33. package/commands/off.md +5 -0
  34. package/commands/on.md +5 -0
  35. package/commands/playbook.md +64 -0
  36. package/commands/status.md +5 -0
  37. package/cordis.patch.yml +4 -0
  38. package/docs/images/dsh-crew-host.png +0 -0
  39. package/docs/images/dsh-crew-jobs.png +0 -0
  40. package/docs/images/dsh-crew-logo.png +0 -0
  41. package/docs/images/dsh-crew-overview.png +0 -0
  42. package/grok/agents/ds-flash.md +19 -0
  43. package/grok/agents/ds-pro.md +19 -0
  44. package/grok/commands/dsh-config.md +9 -0
  45. package/grok/commands/dsh-playbook.md +66 -0
  46. package/grok/commands/dsh-status.md +5 -0
  47. package/lib/client.js +2684 -0
  48. package/lib/server.mjs +15417 -0
  49. package/package.json +137 -4
  50. package/scripts/build-client.mjs +23 -0
  51. package/scripts/build-mcp.mjs +43 -0
  52. package/scripts/fake-agy.sh +23 -0
  53. package/scripts/release-local.mjs +87 -0
  54. package/scripts/smoke-bundle.mjs +166 -0
  55. package/scripts/smoke-cwd.mjs +41 -0
  56. package/scripts/smoke-pack.mjs +285 -0
  57. package/scripts/smoke.mjs +79 -0
  58. package/scripts/verify-cli-workers.mjs +133 -0
  59. package/scripts/verify-wpc10-client.mjs +237 -0
  60. package/scripts/verify-wpc14-proc-endpoints.mjs +356 -0
  61. package/scripts/verify-wpc9-guardrails.mjs +432 -0
  62. package/src/cli-workers.mjs +396 -0
  63. package/src/client/index.tsx +1133 -0
  64. package/src/client/jobs-view.ts +374 -0
  65. package/src/cwd-lock.mjs +91 -0
  66. package/src/hub/index.mjs +643 -0
  67. package/src/hub-client.mjs +72 -0
  68. package/src/i18n.mjs +19 -0
  69. package/src/install/cli.mjs +34 -0
  70. package/src/install/install.mjs +577 -0
  71. package/src/jobs.mjs +289 -0
  72. package/src/multimodal.mjs +744 -0
  73. package/src/origin-guard.mjs +133 -0
  74. package/src/paths.mjs +43 -0
  75. package/src/plugin-env.mjs +65 -0
  76. package/src/proc-kill.mjs +208 -0
  77. package/src/process-info.mjs +60 -0
  78. package/src/provider-probe.mjs +35 -0
  79. package/src/server.mjs +438 -0
  80. package/src/status-shard.mjs +95 -0
  81. package/src/tier-binding.mjs +63 -0
  82. package/src/vision-route.mjs +139 -0
  83. package/src/worker-profiles.mjs +95 -0
  84. package/src/worker-question.mjs +22 -0
  85. package/statusline/statusline.sh +14 -0
  86. package/statusline/worker-segment.sh +35 -0
  87. package/worker.cordis.yml +77 -0
package/src/jobs.mjs ADDED
@@ -0,0 +1,289 @@
1
+ // Job manager: each job runs one dsh-jsonrpc-agent runtime via the DSH SDK.
2
+ // Progress derived from session.event notifications; status mirrored to a
3
+ // JSON file so the Claude Code statusline (and anything else) can render it.
4
+
5
+ import { readFileSync, mkdirSync, existsSync } from 'node:fs';
6
+ import { createShardWriter } from './status-shard.mjs';
7
+ import { acquireCwdLock } from './cwd-lock.mjs';
8
+ import { ORIGIN_CHAIN_ENV, ORIGIN_DEPTH_ENV } from './origin-guard.mjs';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { dirname, join, resolve } from 'node:path';
11
+ import { homedir } from 'node:os';
12
+
13
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
14
+ const CONFIG_DIR = join(homedir(), '.config', 'dsh-crew');
15
+ const STATUS_FILE = join(CONFIG_DIR, 'status.json');
16
+ const RUNTIME_BIN = join(ROOT, 'node_modules', '.bin', 'dsh-jsonrpc-agent');
17
+ const CORDIS = join(ROOT, 'worker.cordis.yml');
18
+
19
+ export const TIERS = {
20
+ flash: { model: 'deepseek-v4-flash', label: 'V4 Flash' },
21
+ pro: { model: 'deepseek-v4-pro', label: 'V4 Pro' },
22
+ };
23
+
24
+ function loadDotEnv() {
25
+ const out = {};
26
+ try {
27
+ for (const line of readFileSync(join(CONFIG_DIR, '.env'), 'utf8').split('\n')) {
28
+ const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);
29
+ if (m && m[2]) out[m[1]] = m[2];
30
+ }
31
+ } catch {}
32
+ return out;
33
+ }
34
+
35
+ const jobs = new Map();
36
+ let nextId = 1;
37
+ const shard = createShardWriter('mcp');
38
+
39
+ // Job shapes now carry an execution backend: 'standalone' (DSH runtime here),
40
+ // 'cli' (external coding CLI via cli-workers.mjs — backend/profile name it),
41
+ // and hub jobs (hub/index.mjs view) keep their own mode: 'hub'. Additive only.
42
+ function backendOf(j) { return j.backend ?? 'standalone'; }
43
+ function profileOf(j) { return j.profile ?? null; }
44
+ function modeOf(j) { return j.mode ?? (j.backend ? 'cli' : 'standalone'); }
45
+
46
+ /** Bounded task preview with a visible truncation marker (PATTERN-AUDIT D3). */
47
+ function clipTask(task, cap = 300) {
48
+ return task.length > cap ? task.slice(0, cap) + '…' : task;
49
+ }
50
+
51
+ export function publishStatus() {
52
+ shard.publish([...jobs.values()].map((j) => ({
53
+ id: j.id, tier: j.tier, model: j.model, provider: j.provider, effort: j.effort, status: j.status, source: j.source,
54
+ task: clipTask(j.task), cwd: j.cwd, turn: j.turn, step: j.step, toolCalls: j.toolCalls,
55
+ currentTool: j.currentTool, tokens: j.tokens,
56
+ backend: backendOf(j), profile: profileOf(j), mode: modeOf(j),
57
+ liveness: j.liveness ?? null,
58
+ // WPC10: last CLI stream event, so the panel can say how long a stalled
59
+ // job has been quiet (mirrors v.activity.lastEventAt used by the MCP tools).
60
+ activityLastEventAt: j.activity?.lastEventAt ?? null,
61
+ // WPC14: the OS process behind the job (CLI workers: detached process
62
+ // group; standalone runtimes: the lazily-spawned dsh runtime). Hub jobs
63
+ // publish through hub/index.mjs and carry no pid. Ghost tombstones
64
+ // snapshot this mirror, so the pid rides into the board's ghost registry.
65
+ pid: j.pid ?? null, pgid: j.pgid ?? null,
66
+ origin_depth: j.origin_depth ?? null, origin_chain: j.origin_chain ?? null,
67
+ startedAt: j.startedAt, endedAt: j.endedAt,
68
+ })));
69
+ }
70
+
71
+ export function jobView(j, { withResult = false } = {}) {
72
+ const v = {
73
+ id: j.id, tier: j.tier, model: j.model, provider: j.provider, effort: j.effort, status: j.status, source: j.source,
74
+ task: clipTask(j.task), turn: j.turn, step: j.step, currentTool: j.currentTool,
75
+ tokens: j.tokens, toolCalls: j.toolCalls,
76
+ backend: backendOf(j), profile: profileOf(j), mode: modeOf(j),
77
+ cwd: j.cwd,
78
+ // WPC14: pid (+ pgid when the worker leads its own process group) so the
79
+ // panel can probe and kill the OS process of an orphaned ghost job.
80
+ pid: j.pid ?? null, pgid: j.pgid ?? null,
81
+ origin_depth: j.origin_depth ?? null, origin_chain: j.origin_chain ?? null,
82
+ startedAt: j.startedAt, endedAt: j.endedAt,
83
+ };
84
+ // CLI jobs: live activity + liveness ("在动" vs "卡死") for dsh_worker_status.
85
+ if (j.activity) {
86
+ v.activity = {
87
+ events: j.activity.events,
88
+ lastEventAt: j.activity.lastEventAt,
89
+ staleSeconds: j.activity.lastEventAt
90
+ ? Math.round((Date.now() - Date.parse(j.activity.lastEventAt)) / 1000)
91
+ : null,
92
+ };
93
+ v.liveness = j.liveness ?? null;
94
+ }
95
+ if (withResult) { v.result = j.result; v.error = j.error; v.stopReason = j.stopReason; }
96
+ return v;
97
+ }
98
+
99
+ export function listJobs() { return [...jobs.values()]; }
100
+ export function getJob(id) { return jobs.get(id); }
101
+
102
+ /** Register a job created elsewhere (cli-workers.mjs) in the shared registry. */
103
+ export function registerJob(job) {
104
+ jobs.set(job.id, job);
105
+ publishStatus();
106
+ return job;
107
+ }
108
+
109
+ export async function startJob({ task, tier = 'flash', effort = 'max', cwd, maxTokens = 49_152, timeoutMs = 1_800_000, source = 'api', origin = null, allowConcurrentCwd = false, provider, model }) {
110
+ const tierInfo = TIERS[tier];
111
+ if (!tierInfo) throw new Error(`unknown tier "${tier}" (expected: ${Object.keys(TIERS).join(', ')})`);
112
+ // The caller (the MCP server, which owns session-level config) may bind this
113
+ // tier to a route the HOST has configured — a local model, typically. Blank
114
+ // is not a binding: it falls back to the tier's built-in DeepSeek route
115
+ // rather than dispatching to "". See tier-binding.mjs and issue #10.
116
+ const dispatchProvider = typeof provider === 'string' && provider.trim() !== '' ? provider.trim() : 'deepseek-official';
117
+ const dispatchModel = typeof model === 'string' && model.trim() !== '' ? model.trim() : tierInfo.model;
118
+ if (!['off', 'high', 'max'].includes(effort)) throw new Error(`unknown effort "${effort}" (expected: off, high, max)`);
119
+
120
+ const workspace = resolve(cwd ?? process.cwd());
121
+ const id = `job-${nextId++}-${Date.now().toString(36)}`;
122
+ const startedAt = new Date().toISOString();
123
+
124
+ // Cwd advisory lock FIRST: a conflicting dispatch is refused before any
125
+ // SDK import, key check or runtime spawn can happen (and every later
126
+ // failure path releases it — see the catch below and the run finally).
127
+ let releaseLock = null;
128
+ if (!allowConcurrentCwd) {
129
+ releaseLock = acquireCwdLock({ cwd: workspace, jobId: id, backend: 'standalone', mode: 'standalone', startedAt }).release;
130
+ }
131
+
132
+ const job = {
133
+ id, tier, model: dispatchModel, provider: dispatchProvider, effort, task, source, cwd: workspace,
134
+ status: 'running', turn: 0, step: 0, currentTool: null, toolCalls: 0,
135
+ tokens: { input: 0, output: 0, reasoning: 0 },
136
+ startedAt, endedAt: null,
137
+ origin_depth: origin?.depth ?? null, origin_chain: origin?.chain ?? null,
138
+ result: null, error: null, stopReason: null, harness: null,
139
+ waiters: [], _releaseCwdLock: releaseLock,
140
+ };
141
+
142
+ try {
143
+ // The DSH SDK is only needed by the standalone dispatch path, so it is
144
+ // loaded lazily here instead of being a top-level import. The bundled MCP
145
+ // server keeps every @deepseek-ai/* package external (see scripts/build-mcp.mjs):
146
+ // hub mode never touches the SDK, and an installed copy without the package
147
+ // fails on this line - with a hint - instead of dying at module load.
148
+ let DeepSeekHarness;
149
+ try {
150
+ ({ DeepSeekHarness } = await import('@deepseek-ai/dsh-sdk-client'));
151
+ } catch (err) {
152
+ if (err?.code === 'ERR_MODULE_NOT_FOUND') {
153
+ const hint = new Error(`@deepseek-ai/dsh-sdk-client not installed; standalone dispatch requires it - run pnpm install in ${ROOT}, or use hub mode (dsh_worker_config mode=hub) so jobs run inside a DSH instance`);
154
+ hint.code = 'ERR_MODULE_NOT_FOUND';
155
+ throw hint;
156
+ }
157
+ throw err;
158
+ }
159
+
160
+ if (!existsSync(RUNTIME_BIN)) throw new Error(`dsh-jsonrpc-agent not installed at ${RUNTIME_BIN}; run pnpm install in ${ROOT}`);
161
+ const dotEnv = loadDotEnv();
162
+ if (!process.env.DEEPSEEK_API_KEY && !dotEnv.DEEPSEEK_API_KEY) {
163
+ throw new Error(`DEEPSEEK_API_KEY not found in env or ${join(CONFIG_DIR, '.env')}`);
164
+ }
165
+
166
+ const harness = new DeepSeekHarness({
167
+ launch: {
168
+ command: RUNTIME_BIN,
169
+ args: [CORDIS],
170
+ cwd: workspace,
171
+ env: {
172
+ ...process.env,
173
+ ...dotEnv,
174
+ DSH_CWD: workspace,
175
+ DSH_SESSION_ROOT: join(CONFIG_DIR, 'sessions'),
176
+ DSH_REASONING_EFFORT: effort,
177
+ // Origin guard: the worker runtime inherits the dispatch chain, so a
178
+ // crew instance it starts itself continues the chain (WPC9).
179
+ ...(origin ? { [ORIGIN_CHAIN_ENV]: JSON.stringify(origin.chain), [ORIGIN_DEPTH_ENV]: String(origin.depth) } : {}),
180
+ },
181
+ requestTimeoutMs: timeoutMs,
182
+ },
183
+ cwd: workspace,
184
+ provider: dispatchProvider,
185
+ model: dispatchModel,
186
+ maxTokens,
187
+ });
188
+ job.harness = harness;
189
+ jobs.set(id, job);
190
+
191
+ const sessionId = id;
192
+ const onNotification = (n) => {
193
+ // WPC14: the standalone runtime process exists once the run has started
194
+ // (the SDK client spawns it lazily). Capture its pid on the first
195
+ // notification so views, shard mirrors and ghost tombstones carry it —
196
+ // and track it while running, since a failed handshake makes the SDK
197
+ // swap in a fresh client (new subprocess).
198
+ if (job.status === 'running') {
199
+ const child = harness.client?.child;
200
+ if (child?.pid && job.pid !== child.pid) { job.pid = child.pid; publishStatus(); }
201
+ }
202
+ if (n.method === 'session.status') return;
203
+ if (n.method !== 'session.event') return;
204
+ if (n.params?.sessionId && n.params.sessionId !== sessionId) return;
205
+ const e = n.params.event;
206
+ if (!e?.type) return;
207
+ switch (e.type) {
208
+ case 'step/start': job.turn = e.data?.turn ?? job.turn; job.step = e.data?.step ?? job.step; break;
209
+ case 'tool/call': job.currentTool = e.data?.name ?? null; job.toolCalls += 1; break;
210
+ case 'tool/result': job.currentTool = null; break;
211
+ case 'assistant/message': {
212
+ const u = e.data?.usage;
213
+ if (u) {
214
+ job.tokens.input += u.inputTokens ?? 0;
215
+ job.tokens.output += u.outputTokens ?? 0;
216
+ job.tokens.reasoning += u.reasoningTokens ?? 0;
217
+ }
218
+ break;
219
+ }
220
+ case 'turn/end': job.stopReason = e.data?.reason?.kind ?? null; break;
221
+ }
222
+ publishStatus();
223
+ };
224
+
225
+ job.promise = harness
226
+ .run(task, { sessionId, onNotification })
227
+ .then((result) => {
228
+ job.result = result.finalResponse ?? '';
229
+ const lastEnd = [...(result.events ?? [])].reverse().find((ev) => ev?.type === 'turn/end');
230
+ job.stopReason = lastEnd?.data?.reason?.kind ?? job.stopReason;
231
+ job.status = job.stopReason === 'completed' ? 'done' : 'failed';
232
+ if (job.status === 'failed' && !job.error) job.error = `turn ended with reason: ${job.stopReason ?? 'unknown'}`;
233
+ })
234
+ .catch((err) => {
235
+ job.status = job.status === 'cancelled' ? 'cancelled' : 'failed';
236
+ job.error = err?.message ?? String(err);
237
+ })
238
+ .finally(async () => {
239
+ job.endedAt = new Date().toISOString();
240
+ job.currentTool = null;
241
+ try { await harness.close(); } catch {}
242
+ // Release the cwd lock on EVERY terminal path: done, failed,
243
+ // cancelled, request-timeout (harness rejects) all land here.
244
+ job._releaseCwdLock?.();
245
+ job._releaseCwdLock = null;
246
+ publishStatus();
247
+ for (const w of job.waiters.splice(0)) w();
248
+ });
249
+ } catch (err) {
250
+ // Failed start (SDK missing, no API key, spawn error, ...): settle the
251
+ // record and free the lock so the cwd never stays locked.
252
+ job.status = 'failed';
253
+ job.error = err?.message ?? String(err);
254
+ job.endedAt = new Date().toISOString();
255
+ job._releaseCwdLock?.();
256
+ job._releaseCwdLock = null;
257
+ publishStatus();
258
+ throw err;
259
+ }
260
+
261
+ publishStatus();
262
+ return job;
263
+ }
264
+
265
+ export async function waitJob(id, timeoutMs) {
266
+ const job = jobs.get(id);
267
+ if (!job) throw new Error(`no such job: ${id}`);
268
+ if (job.status !== 'running') return job;
269
+ let timer;
270
+ await Promise.race([
271
+ new Promise((res) => job.waiters.push(res)),
272
+ timeoutMs ? new Promise((res) => { timer = setTimeout(res, timeoutMs); }) : new Promise(() => {}),
273
+ ]);
274
+ // The losing branch's timer would otherwise pin the event loop for its full
275
+ // remaining duration and delay server exit after a job settles.
276
+ if (timer) clearTimeout(timer);
277
+ return job;
278
+ }
279
+
280
+ export async function cancelJob(id) {
281
+ const job = jobs.get(id);
282
+ if (!job) throw new Error(`no such job: ${id}`);
283
+ if (job.status !== 'running') return job;
284
+ job.status = 'cancelled';
285
+ job.error = 'cancelled by request';
286
+ try { await job.harness.close(); } catch {}
287
+ publishStatus();
288
+ return job;
289
+ }