@dsmm/dsmm 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.
- package/LICENSE +103 -0
- package/README.md +67 -2
- package/agent-presets/dsmm-builder/agent.cordis.yml +210 -0
- package/agent-presets/dsmm-builder/preset.yml +3 -0
- package/agent-presets/dsmm-clarifier/agent.cordis.yml +34 -0
- package/agent-presets/dsmm-clarifier/preset.yml +3 -0
- package/agent-presets/dsmm-code-search/agent.cordis.yml +34 -0
- package/agent-presets/dsmm-code-search/preset.yml +3 -0
- package/agent-presets/dsmm-creative/agent.cordis.yml +31 -0
- package/agent-presets/dsmm-creative/preset.yml +3 -0
- package/agent-presets/dsmm-doc-search/agent.cordis.yml +34 -0
- package/agent-presets/dsmm-doc-search/preset.yml +3 -0
- package/agent-presets/dsmm-media-reader/agent.cordis.yml +34 -0
- package/agent-presets/dsmm-media-reader/preset.yml +3 -0
- package/agent-presets/dsmm-oracle/agent.cordis.yml +31 -0
- package/agent-presets/dsmm-oracle/preset.yml +3 -0
- package/agent-presets/dsmm-oracle-2nd/agent.cordis.yml +31 -0
- package/agent-presets/dsmm-oracle-2nd/preset.yml +3 -0
- package/agent-presets/dsmm-orchestrator/agent.cordis.yml +215 -0
- package/agent-presets/dsmm-orchestrator/preset.yml +3 -0
- package/agent-presets/dsmm-plan-critic/agent.cordis.yml +33 -0
- package/agent-presets/dsmm-plan-critic/preset.yml +3 -0
- package/agent-presets/dsmm-planner/agent.cordis.yml +33 -0
- package/agent-presets/dsmm-planner/preset.yml +3 -0
- package/agent-presets/dsmm-reviewer/agent.cordis.yml +33 -0
- package/agent-presets/dsmm-reviewer/preset.yml +3 -0
- package/cordis.patch.yml +8 -0
- package/docs/agent-presets.md +17 -0
- package/docs/compatibility.md +46 -0
- package/docs/design.md +237 -0
- package/docs/lsp.md +40 -0
- package/docs/migration-from-ocmm.md +48 -0
- package/docs/model-routing.md +16 -0
- package/docs/releasing.md +50 -0
- package/docs/research/deepseek-v4-pro.md +74 -0
- package/docs/research/oh-dsh.md +96 -0
- package/docs/roadmap.md +207 -0
- package/docs/runtime-recovery.md +67 -0
- package/docs/safety-guards.md +55 -0
- package/docs/settings-status.md +51 -0
- package/docs/skill-sync.md +20 -0
- package/lib/commands.d.ts +13 -0
- package/lib/commands.js +55 -0
- package/lib/dsh-events.d.ts +13 -0
- package/lib/dsh-events.js +2 -0
- package/lib/dsh-types.d.ts +308 -0
- package/lib/dsh-types.js +2 -0
- package/lib/guards.d.ts +10 -0
- package/lib/guards.js +252 -0
- package/lib/index.d.ts +31 -0
- package/lib/index.js +54 -0
- package/lib/lsp.d.ts +30 -0
- package/lib/lsp.js +154 -0
- package/lib/mode.d.ts +6 -0
- package/lib/mode.js +62 -0
- package/lib/model-family.d.ts +6 -0
- package/lib/model-family.js +49 -0
- package/lib/model-routing.d.ts +11 -0
- package/lib/model-routing.js +103 -0
- package/lib/plan-validation.d.ts +3 -0
- package/lib/plan-validation.js +119 -0
- package/lib/preset-materializer.d.ts +36 -0
- package/lib/preset-materializer.js +258 -0
- package/lib/preset-registry.d.ts +5 -0
- package/lib/preset-registry.js +126 -0
- package/lib/preset-skills.d.ts +12 -0
- package/lib/preset-skills.js +28 -0
- package/lib/prompts.d.ts +13 -0
- package/lib/prompts.js +82 -0
- package/lib/recovery-policy.d.ts +25 -0
- package/lib/recovery-policy.js +252 -0
- package/lib/role-subagents.d.ts +6 -0
- package/lib/role-subagents.js +54 -0
- package/lib/roles.d.ts +28 -0
- package/lib/roles.js +239 -0
- package/lib/runtime-recovery.d.ts +5 -0
- package/lib/runtime-recovery.js +149 -0
- package/lib/session-scope.d.ts +4 -0
- package/lib/session-scope.js +17 -0
- package/lib/settings.d.ts +112 -0
- package/lib/settings.js +363 -0
- package/lib/shell-command.d.ts +18 -0
- package/lib/shell-command.js +492 -0
- package/lib/skills.d.ts +18 -0
- package/lib/skills.js +64 -0
- package/lib/state.d.ts +13 -0
- package/lib/state.js +64 -0
- package/lib/status.d.ts +46 -0
- package/lib/status.js +155 -0
- package/package.json +124 -4
- package/patches/agent-presets-root.example.cordis.patch.yml +14 -0
- package/patches/ocmm-lsp-mcp.example.cordis.patch.yml +15 -0
- package/prompts/deepseek-flash.md +11 -0
- package/prompts/deepseek-v4-pro.md +14 -0
- package/prompts/deepwork.md +32 -0
- package/skills/brainstorming/SKILL.md +15 -0
- package/skills/debugging/SKILL.md +12 -0
- package/skills/debugging/references/logging.md +91 -0
- package/skills/debugging/references/methodology/00-setup.md +108 -0
- package/skills/debugging/references/methodology/02-investigate.md +67 -0
- package/skills/debugging/references/methodology/03-flaky-triage.md +69 -0
- package/skills/debugging/references/methodology/04-hard-reasoning-escalation.md +83 -0
- package/skills/debugging/references/methodology/05-escalate.md +69 -0
- package/skills/debugging/references/methodology/06-fix.md +123 -0
- package/skills/debugging/references/methodology/08-qa.md +94 -0
- package/skills/debugging/references/methodology/09-cleanup.md +164 -0
- package/skills/debugging/references/methodology/partial-runtime-evidence.md +217 -0
- package/skills/debugging/references/runtimes/bundled-js-binary.md +415 -0
- package/skills/debugging/references/runtimes/go.md +252 -0
- package/skills/debugging/references/runtimes/native-binary.md +484 -0
- package/skills/debugging/references/runtimes/node.md +260 -0
- package/skills/debugging/references/runtimes/python.md +248 -0
- package/skills/debugging/references/runtimes/rust.md +234 -0
- package/skills/debugging/references/scripts/dap.mjs +533 -0
- package/skills/debugging/references/tools/dap.md +89 -0
- package/skills/debugging/references/tools/ghidra.md +212 -0
- package/skills/debugging/references/tools/playwright-cli.md +316 -0
- package/skills/debugging/references/tools/pwndbg.md +263 -0
- package/skills/debugging/references/tools/pwntools.md +265 -0
- package/skills/dispatching-parallel-agents/SKILL.md +14 -0
- package/skills/receiving-code-review/SKILL.md +13 -0
- package/skills/remove-ai-slops/SKILL.md +14 -0
- package/skills/requesting-code-review/SKILL.md +10 -0
- package/skills/subagent-driven-development/SKILL.md +13 -0
- package/skills/writing-plans/SKILL.md +14 -0
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Zero-dependency DAP REPL, modeled on oh-my-pi's debug tool. DAP framing is UTF-8 byte based.
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { createConnection } from "node:net";
|
|
5
|
+
import { resolve } from "node:path";
|
|
6
|
+
import { createInterface } from "node:readline";
|
|
7
|
+
import { stdin, stdout, stderr, env } from "node:process";
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
9
|
+
|
|
10
|
+
export const MAX_ROWS = 100;
|
|
11
|
+
export const MAX_OUTPUT_BYTES = 32 * 1024;
|
|
12
|
+
|
|
13
|
+
export function isTcpAdapterSpec(spec) {
|
|
14
|
+
if (typeof spec !== "string") return false;
|
|
15
|
+
const separator = spec.lastIndexOf(":");
|
|
16
|
+
return separator > 0 &&
|
|
17
|
+
!spec.includes("/") &&
|
|
18
|
+
!spec.includes("\\") &&
|
|
19
|
+
/^\d+$/.test(spec.slice(separator + 1));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function tokenizeCommand(input) {
|
|
23
|
+
const tokens = [];
|
|
24
|
+
let token = "";
|
|
25
|
+
let quote = null;
|
|
26
|
+
let tokenStarted = false;
|
|
27
|
+
|
|
28
|
+
for (const character of input.trim()) {
|
|
29
|
+
if (quote) {
|
|
30
|
+
if (character === quote) quote = null;
|
|
31
|
+
else token += character;
|
|
32
|
+
tokenStarted = true;
|
|
33
|
+
} else if (character === "\"" || character === "'") {
|
|
34
|
+
quote = character;
|
|
35
|
+
tokenStarted = true;
|
|
36
|
+
} else if (/\s/.test(character)) {
|
|
37
|
+
if (tokenStarted) {
|
|
38
|
+
tokens.push(token);
|
|
39
|
+
token = "";
|
|
40
|
+
tokenStarted = false;
|
|
41
|
+
}
|
|
42
|
+
} else {
|
|
43
|
+
token += character;
|
|
44
|
+
tokenStarted = true;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (quote) return null;
|
|
49
|
+
if (tokenStarted) tokens.push(token);
|
|
50
|
+
return tokens;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function parseBreakpointSpec(spec) {
|
|
54
|
+
if (typeof spec !== "string") return null;
|
|
55
|
+
const match = /^(.*):(\d+)$/.exec(spec);
|
|
56
|
+
if (!match || !match[1]) return null;
|
|
57
|
+
return { file: match[1], line: Number(match[2]) };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export class DapFrameParser {
|
|
61
|
+
constructor() { this.buffer = Buffer.alloc(0); }
|
|
62
|
+
push(chunk) {
|
|
63
|
+
this.buffer = Buffer.concat([this.buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
|
|
64
|
+
const messages = [];
|
|
65
|
+
while (true) {
|
|
66
|
+
const marker = this.buffer.indexOf(Buffer.from("\r\n\r\n"));
|
|
67
|
+
if (marker < 0) break;
|
|
68
|
+
const header = this.buffer.subarray(0, marker).toString("ascii");
|
|
69
|
+
const match = header.match(/(?:^|\r\n)Content-Length:\s*(\d+)/i);
|
|
70
|
+
if (!match) { this.buffer = this.buffer.subarray(marker + 4); continue; }
|
|
71
|
+
const length = Number(match[1]);
|
|
72
|
+
const start = marker + 4;
|
|
73
|
+
if (this.buffer.length < start + length) break;
|
|
74
|
+
const body = this.buffer.subarray(start, start + length);
|
|
75
|
+
this.buffer = this.buffer.subarray(start + length);
|
|
76
|
+
try { messages.push(JSON.parse(body.toString("utf8"))); } catch { /* malformed frames are ignored */ }
|
|
77
|
+
}
|
|
78
|
+
return messages;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const timeoutMs = Number(env.DAP_TIMEOUT_MS || 15000);
|
|
83
|
+
let transport = null;
|
|
84
|
+
let ownedCleanup = null;
|
|
85
|
+
let cleanupPromise = null;
|
|
86
|
+
let parser = null;
|
|
87
|
+
let nextSeq = 1;
|
|
88
|
+
let initialized = false;
|
|
89
|
+
let terminated = false;
|
|
90
|
+
let exitReported = false;
|
|
91
|
+
let currentStop = null;
|
|
92
|
+
let topFrame = null;
|
|
93
|
+
let processStarted = false;
|
|
94
|
+
let sessionFailure = null;
|
|
95
|
+
let setupTerminal = null;
|
|
96
|
+
const pending = new Map();
|
|
97
|
+
const breakpoints = new Map();
|
|
98
|
+
// Event-driven waits. A tight `await setImmediate` busy-loop starves Bun's socket
|
|
99
|
+
// data callbacks (the `initialized` event then never processes and launch deadlocks),
|
|
100
|
+
// so every wait subscribes to the actual DAP event instead of polling state.
|
|
101
|
+
const eventWaiters = new Map();
|
|
102
|
+
function onEvent(name) {
|
|
103
|
+
if (sessionFailure) return Promise.reject(sessionFailure);
|
|
104
|
+
return new Promise((resolve, reject) => {
|
|
105
|
+
const list = eventWaiters.get(name) || [];
|
|
106
|
+
list.push({ resolve, reject });
|
|
107
|
+
eventWaiters.set(name, list);
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
function emitEvent(name, value) {
|
|
111
|
+
const list = eventWaiters.get(name) || [];
|
|
112
|
+
eventWaiters.delete(name);
|
|
113
|
+
for (const wait of list) wait.resolve(value);
|
|
114
|
+
}
|
|
115
|
+
function rejectEventWaiters(cause) {
|
|
116
|
+
for (const list of eventWaiters.values()) {
|
|
117
|
+
for (const wait of list) wait.reject(cause);
|
|
118
|
+
}
|
|
119
|
+
eventWaiters.clear();
|
|
120
|
+
}
|
|
121
|
+
function wakeEventWaiters(value) {
|
|
122
|
+
for (const list of eventWaiters.values()) {
|
|
123
|
+
for (const wait of list) wait.resolve(value);
|
|
124
|
+
}
|
|
125
|
+
eventWaiters.clear();
|
|
126
|
+
}
|
|
127
|
+
function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
|
|
128
|
+
|
|
129
|
+
function errorKind(cause) {
|
|
130
|
+
return cause?.message === "timeout" ? "timeout" : cause?.message === "adapter-error" ? "adapter-error" : "adapter-failed";
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function rejectPending(cause) {
|
|
134
|
+
const error = typeof cause === "string" ? new Error(cause) : cause;
|
|
135
|
+
for (const wait of pending.values()) wait.reject(error);
|
|
136
|
+
pending.clear();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function resetSessionState(cause = new Error("adapter-failed")) {
|
|
140
|
+
rejectPending(cause);
|
|
141
|
+
rejectEventWaiters(cause);
|
|
142
|
+
transport = null;
|
|
143
|
+
parser = null;
|
|
144
|
+
nextSeq = 1;
|
|
145
|
+
initialized = false;
|
|
146
|
+
terminated = false;
|
|
147
|
+
exitReported = false;
|
|
148
|
+
currentStop = null;
|
|
149
|
+
topFrame = null;
|
|
150
|
+
processStarted = false;
|
|
151
|
+
sessionFailure = cause?.reported ? cause : null;
|
|
152
|
+
breakpoints.clear();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function reclaimSession(cause = new Error("adapter-failed")) {
|
|
156
|
+
if (cleanupPromise) return cleanupPromise;
|
|
157
|
+
const cleanup = transport?.cleanup ?? ownedCleanup;
|
|
158
|
+
transport = null;
|
|
159
|
+
ownedCleanup = null;
|
|
160
|
+
resetSessionState(cause);
|
|
161
|
+
const reclaim = (async () => {
|
|
162
|
+
try {
|
|
163
|
+
if (cleanup) await cleanup();
|
|
164
|
+
} catch {
|
|
165
|
+
// Cleanup is fail-closed: state is already reset and retries must not hang.
|
|
166
|
+
}
|
|
167
|
+
})();
|
|
168
|
+
cleanupPromise = reclaim;
|
|
169
|
+
reclaim.then(() => {
|
|
170
|
+
if (cleanupPromise === reclaim) cleanupPromise = null;
|
|
171
|
+
});
|
|
172
|
+
return reclaim;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function cleanupSession(cause) {
|
|
176
|
+
await reclaimSession(cause);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function waitForCleanup() {
|
|
180
|
+
if (cleanupPromise) await cleanupPromise;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function throwIfSessionFailed() {
|
|
184
|
+
if (sessionFailure) throw sessionFailure;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function throwIfSetupTerminated() {
|
|
188
|
+
if (setupTerminal) throw setupTerminal;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function beginSetup() {
|
|
192
|
+
setupTerminal = null;
|
|
193
|
+
sessionFailure = null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const debugTraffic = Boolean(env.DAP_DEBUG);
|
|
197
|
+
function trace(direction, message) { if (debugTraffic) stderr.write(`DAP ${direction} ${JSON.stringify(message).slice(0, 300)}\n`); }
|
|
198
|
+
function line(text) { stdout.write(`${text}\n`); }
|
|
199
|
+
function error(kind, detail = "") { line(`ERR: ${kind}${detail ? ` ${detail}` : ""}`); }
|
|
200
|
+
function reportExit() {
|
|
201
|
+
if (exitReported || setupTerminal?.exitReported) return;
|
|
202
|
+
exitReported = true;
|
|
203
|
+
if (setupTerminal) setupTerminal.exitReported = true;
|
|
204
|
+
line("EXIT: terminated");
|
|
205
|
+
}
|
|
206
|
+
function markTerminated() {
|
|
207
|
+
setupTerminal ??= Object.assign(new Error("terminated"), { reported: true, exitReported: false });
|
|
208
|
+
terminated = true;
|
|
209
|
+
currentStop = null;
|
|
210
|
+
rejectPending(setupTerminal);
|
|
211
|
+
wakeEventWaiters(setupTerminal);
|
|
212
|
+
reportExit();
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function truncateUtf8(value, maxBytes) {
|
|
216
|
+
const source = String(value ?? "");
|
|
217
|
+
const totalBytes = Buffer.byteLength(source);
|
|
218
|
+
if (totalBytes <= maxBytes) return { text: source, droppedBytes: 0 };
|
|
219
|
+
let text = "";
|
|
220
|
+
let usedBytes = 0;
|
|
221
|
+
for (const character of source) {
|
|
222
|
+
const characterBytes = Buffer.byteLength(character);
|
|
223
|
+
if (usedBytes + characterBytes > maxBytes) break;
|
|
224
|
+
text += character;
|
|
225
|
+
usedBytes += characterBytes;
|
|
226
|
+
}
|
|
227
|
+
return { text, droppedBytes: totalBytes - usedBytes };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function writeBoundedAdapterLine(prefix, value) {
|
|
231
|
+
const availableBytes = Math.max(0, MAX_OUTPUT_BYTES - Buffer.byteLength(prefix) - 1);
|
|
232
|
+
const truncated = truncateUtf8(value, availableBytes);
|
|
233
|
+
stdout.write(`${prefix}${truncated.text}\n`);
|
|
234
|
+
if (truncated.droppedBytes > 0) line(`TRUNCATED: bytes dropped=${truncated.droppedBytes}`);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function send(message) {
|
|
238
|
+
trace(">", message);
|
|
239
|
+
const body = Buffer.from(JSON.stringify(message));
|
|
240
|
+
transport.write(Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`), body]));
|
|
241
|
+
}
|
|
242
|
+
function request(command, args = {}) {
|
|
243
|
+
if (setupTerminal) return Promise.reject(setupTerminal);
|
|
244
|
+
if (sessionFailure) return Promise.reject(sessionFailure);
|
|
245
|
+
if (!transport || terminated) return Promise.reject(new Error("no-session"));
|
|
246
|
+
const seq = nextSeq++;
|
|
247
|
+
send({ type: "request", seq, command, arguments: args });
|
|
248
|
+
return new Promise((resolve, reject) => {
|
|
249
|
+
const timer = setTimeout(() => { pending.delete(seq); reject(new Error("timeout")); }, timeoutMs);
|
|
250
|
+
pending.set(seq, { resolve: value => { clearTimeout(timer); resolve(value); }, reject: value => { clearTimeout(timer); reject(value); } });
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
function onMessage(message) {
|
|
254
|
+
trace("<", message);
|
|
255
|
+
if (message.type === "response") {
|
|
256
|
+
const wait = pending.get(message.request_seq);
|
|
257
|
+
if (!wait) return;
|
|
258
|
+
pending.delete(message.request_seq);
|
|
259
|
+
if (message.success === false) wait.reject(new Error("adapter-error")); else wait.resolve(message);
|
|
260
|
+
} else if (message.type === "event") {
|
|
261
|
+
if (message.event === "initialized") { initialized = true; emitEvent("initialized"); }
|
|
262
|
+
if (message.event === "stopped") { currentStop = message.body || {}; emitEvent("stopped", currentStop); }
|
|
263
|
+
if (message.event === "process") { processStarted = true; emitEvent("process"); }
|
|
264
|
+
if (message.event === "terminated" || message.event === "exited") markTerminated();
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
function connectTransport(write, read, cleanup) {
|
|
268
|
+
const active = { write: chunk => write.write(chunk), cleanup };
|
|
269
|
+
transport = active;
|
|
270
|
+
ownedCleanup = cleanup;
|
|
271
|
+
const activeParser = new DapFrameParser();
|
|
272
|
+
parser = activeParser;
|
|
273
|
+
read.on("data", chunk => {
|
|
274
|
+
if (transport !== active) return;
|
|
275
|
+
for (const message of activeParser.push(chunk)) onMessage(message);
|
|
276
|
+
});
|
|
277
|
+
const failTransport = () => {
|
|
278
|
+
if (transport !== active || cleanupPromise) return;
|
|
279
|
+
if (terminated) {
|
|
280
|
+
void cleanupSession();
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
const cause = Object.assign(new Error("adapter-failed"), { reported: true });
|
|
284
|
+
void cleanupSession(cause);
|
|
285
|
+
error("adapter-failed");
|
|
286
|
+
};
|
|
287
|
+
read.on("error", failTransport);
|
|
288
|
+
read.on("end", failTransport);
|
|
289
|
+
read.on("close", failTransport);
|
|
290
|
+
}
|
|
291
|
+
function connectSocket(socket) { connectTransport(socket, socket, () => socket.destroy()); }
|
|
292
|
+
async function startAdapter(spec) {
|
|
293
|
+
if (isTcpAdapterSpec(spec)) {
|
|
294
|
+
const separator = spec.lastIndexOf(":");
|
|
295
|
+
const socket = createConnection(Number(spec.slice(separator + 1)), spec.slice(0, separator));
|
|
296
|
+
try {
|
|
297
|
+
await new Promise((resolve, reject) => { socket.once("connect", resolve); socket.once("error", reject); });
|
|
298
|
+
connectSocket(socket);
|
|
299
|
+
} catch (cause) {
|
|
300
|
+
socket.destroy();
|
|
301
|
+
throw cause;
|
|
302
|
+
}
|
|
303
|
+
} else {
|
|
304
|
+
// A .mjs/.cjs/.js adapter spec runs under the current Bun/Node runtime (for
|
|
305
|
+
// example, the fixture adapter). Bun also accepts .ts; native Node does not
|
|
306
|
+
// rely on TypeScript execution here. Other specs are adapter executables.
|
|
307
|
+
const isScript = /\.(mjs|cjs|js)$/.test(spec) || (Boolean(process.versions.bun) && /\.ts$/.test(spec));
|
|
308
|
+
const [cmd, argv] = isScript ? [process.execPath, [spec]] : [spec, []];
|
|
309
|
+
const child = spawn(cmd, argv, { stdio: ["pipe", "pipe", "inherit"] });
|
|
310
|
+
try {
|
|
311
|
+
await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
|
|
312
|
+
} catch (cause) {
|
|
313
|
+
child.kill();
|
|
314
|
+
throw cause;
|
|
315
|
+
}
|
|
316
|
+
connectTransport(child.stdin, child.stdout, () => {
|
|
317
|
+
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
|
|
318
|
+
return new Promise(resolve => {
|
|
319
|
+
child.once("exit", resolve);
|
|
320
|
+
child.kill();
|
|
321
|
+
});
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
// Waits for a stopped event. When `required` is false this is a best-effort grace
|
|
326
|
+
// window (e.g. an optional stop-on-entry); it returns on the first stop OR on timeout
|
|
327
|
+
// without failing, so adapters that run straight to a breakpoint are not broken.
|
|
328
|
+
async function waitForStop(required = true, graceMs) {
|
|
329
|
+
throwIfSessionFailed();
|
|
330
|
+
if (currentStop || terminated) return Boolean(currentStop);
|
|
331
|
+
const budget = graceMs ?? timeoutMs;
|
|
332
|
+
await Promise.race([onEvent("stopped"), onEvent("terminated"), sleep(budget)]);
|
|
333
|
+
throwIfSessionFailed();
|
|
334
|
+
if (required && !currentStop && !terminated) throw new Error("timeout");
|
|
335
|
+
return Boolean(currentStop);
|
|
336
|
+
}
|
|
337
|
+
// Waits for the adapter's `initialized` event, event-driven (never a busy-loop).
|
|
338
|
+
async function waitInitialized() {
|
|
339
|
+
throwIfSetupTerminated();
|
|
340
|
+
throwIfSessionFailed();
|
|
341
|
+
if (initialized) return;
|
|
342
|
+
await Promise.race([onEvent("initialized"), sleep(timeoutMs)]);
|
|
343
|
+
throwIfSetupTerminated();
|
|
344
|
+
throwIfSessionFailed();
|
|
345
|
+
if (!initialized) throw new Error("timeout");
|
|
346
|
+
}
|
|
347
|
+
// Adapters gate the `initialized` event on a recognized adapterID (debugpy withholds
|
|
348
|
+
// it for unknown IDs, hanging the handshake). Infer a known ID from the adapter spec.
|
|
349
|
+
function adapterIdFor(spec) {
|
|
350
|
+
const base = String(spec).split(/[\\/]/).pop().toLowerCase();
|
|
351
|
+
if (base.includes("debugpy") || base.includes("python")) return "debugpy";
|
|
352
|
+
if (base.includes("lldb")) return "lldb-dap";
|
|
353
|
+
if (base.includes("dlv") || base.includes("delve")) return "dlv";
|
|
354
|
+
if (base.includes("js-debug")) return "js-debug";
|
|
355
|
+
if (base.includes("gdb")) return "gdb";
|
|
356
|
+
return "ocmm";
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
async function confirmLldbLaunch() {
|
|
360
|
+
throwIfSetupTerminated();
|
|
361
|
+
throwIfSessionFailed();
|
|
362
|
+
if (processStarted || currentStop) return true;
|
|
363
|
+
await Promise.race([onEvent("process"), onEvent("stopped"), onEvent("terminated"), sleep(timeoutMs)]);
|
|
364
|
+
throwIfSetupTerminated();
|
|
365
|
+
throwIfSessionFailed();
|
|
366
|
+
return processStarted || Boolean(currentStop);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async function launch(adapter, program, args) {
|
|
370
|
+
await waitForCleanup();
|
|
371
|
+
if (transport) return error("adapter-error", "session already exists");
|
|
372
|
+
beginSetup();
|
|
373
|
+
try {
|
|
374
|
+
await startAdapter(adapter);
|
|
375
|
+
throwIfSetupTerminated();
|
|
376
|
+
const adapterID = adapterIdFor(adapter);
|
|
377
|
+
await request("initialize", { clientID: "ocmm-dap", adapterID, linesStartAt1: true, columnsStartAt1: true, pathFormat: "path" });
|
|
378
|
+
throwIfSetupTerminated();
|
|
379
|
+
// Send launch BEFORE awaiting `initialized`: debugpy's adapter defers/flushes the
|
|
380
|
+
// initialized event until further client activity, so waiting for it first
|
|
381
|
+
// deadlocks the handshake. DAP allows launch any time after the initialize
|
|
382
|
+
// response; `initialized` is only required before configurationDone.
|
|
383
|
+
// stopOnEntry yields an initial stopped event with a real threadId, so the client
|
|
384
|
+
// can set breakpoints and inspect from a valid stopped state before continuing.
|
|
385
|
+
// `console: "internalConsole"` is REQUIRED by debugpy (without it the launch never
|
|
386
|
+
// spawns the debug server -> "Server is not available"); lldb-dap ignores it.
|
|
387
|
+
// lldb-dap reports the launch response success unreliably (false even when the
|
|
388
|
+
// process started and stopped); the process/stopped EVENTS are the real signal,
|
|
389
|
+
// so a non-success launch response is tolerated, not fatal.
|
|
390
|
+
try {
|
|
391
|
+
await request("launch", { program, args, console: "internalConsole", justMyCode: false, stopOnEntry: true });
|
|
392
|
+
throwIfSetupTerminated();
|
|
393
|
+
} catch (cause) {
|
|
394
|
+
throwIfSetupTerminated();
|
|
395
|
+
if (adapterID !== "lldb-dap" || cause?.message !== "adapter-error" || !await confirmLldbLaunch()) throw cause;
|
|
396
|
+
}
|
|
397
|
+
await waitInitialized();
|
|
398
|
+
throwIfSetupTerminated();
|
|
399
|
+
await request("configurationDone");
|
|
400
|
+
throwIfSetupTerminated();
|
|
401
|
+
// Best-effort: lldb-dap stops at entry, other adapters run to the first breakpoint.
|
|
402
|
+
await waitForStop(false, 2000);
|
|
403
|
+
throwIfSetupTerminated();
|
|
404
|
+
throwIfSessionFailed();
|
|
405
|
+
line("READY: launch");
|
|
406
|
+
} catch (cause) {
|
|
407
|
+
await cleanupSession();
|
|
408
|
+
if (!cause?.reported && !setupTerminal) error(errorKind(cause));
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
async function snapshot() {
|
|
412
|
+
if (terminated) { reportExit(); return; }
|
|
413
|
+
if (!currentStop) return;
|
|
414
|
+
try {
|
|
415
|
+
const response = await request("stackTrace", { threadId: currentStop?.threadId || 1, levels: 1 });
|
|
416
|
+
topFrame = response.body?.stackFrames?.[0];
|
|
417
|
+
const f = topFrame;
|
|
418
|
+
if (f) writeBoundedAdapterLine("STOP: ", `stopped reason=${currentStop?.reason || "unknown"} threadId=${currentStop?.threadId || ""} ${f.name} at ${f.source?.path || "?"}:${f.line || 0}:${f.column || 0}`);
|
|
419
|
+
else writeBoundedAdapterLine("STOP: ", `stopped reason=${currentStop?.reason || "unknown"} threadId=${currentStop?.threadId || ""} ? at ?:0:0`);
|
|
420
|
+
} catch (cause) { if (!cause?.reported) error(errorKind(cause)); }
|
|
421
|
+
}
|
|
422
|
+
function boundedTable(header, rows) {
|
|
423
|
+
const all = rows.map(row => row.join("\t"));
|
|
424
|
+
const chosen = all.slice(0, MAX_ROWS);
|
|
425
|
+
const prefix = `${header.join("\t")}\n`;
|
|
426
|
+
let output = prefix;
|
|
427
|
+
let count = 0;
|
|
428
|
+
for (const row of chosen) {
|
|
429
|
+
const candidate = `${row}\n`;
|
|
430
|
+
if (Buffer.byteLength(output + candidate) > MAX_OUTPUT_BYTES) break;
|
|
431
|
+
output += candidate; count++;
|
|
432
|
+
}
|
|
433
|
+
stdout.write(output);
|
|
434
|
+
const rowDropped = all.length - count;
|
|
435
|
+
const byteDropped = Buffer.byteLength(all.slice(count).join("\n") + (all.length > count ? "\n" : ""));
|
|
436
|
+
if (rowDropped > 0 || byteDropped > 0) line(`TRUNCATED: rows dropped=${rowDropped} bytes dropped=${byteDropped}`);
|
|
437
|
+
}
|
|
438
|
+
async function command(input) {
|
|
439
|
+
const parts = tokenizeCommand(input);
|
|
440
|
+
if (!parts) return error("invalid-args");
|
|
441
|
+
const cmd = parts.shift();
|
|
442
|
+
if (!cmd) return;
|
|
443
|
+
if (cmd === "quit") { await cleanupSession(); process.exit(0); }
|
|
444
|
+
if (cmd === "launch") {
|
|
445
|
+
const adapter = parts.shift();
|
|
446
|
+
const program = parts.shift();
|
|
447
|
+
if (!adapter || !program) return error("invalid-args");
|
|
448
|
+
return launch(adapter, program, parts);
|
|
449
|
+
}
|
|
450
|
+
if (cmd === "attach") {
|
|
451
|
+
await waitForCleanup();
|
|
452
|
+
if (transport) return error("adapter-error", "session already exists");
|
|
453
|
+
beginSetup();
|
|
454
|
+
const endpoint = parts.shift();
|
|
455
|
+
if (!isTcpAdapterSpec(endpoint)) return error("invalid-args");
|
|
456
|
+
try {
|
|
457
|
+
await startAdapter(endpoint);
|
|
458
|
+
throwIfSetupTerminated();
|
|
459
|
+
await request("initialize", { clientID: "ocmm-dap", adapterID: "debugpy", linesStartAt1: true, columnsStartAt1: true, pathFormat: "path" });
|
|
460
|
+
throwIfSetupTerminated();
|
|
461
|
+
await request("attach", { justMyCode: false });
|
|
462
|
+
throwIfSetupTerminated();
|
|
463
|
+
await waitInitialized();
|
|
464
|
+
throwIfSetupTerminated();
|
|
465
|
+
await request("configurationDone");
|
|
466
|
+
throwIfSetupTerminated();
|
|
467
|
+
line("READY: attach");
|
|
468
|
+
} catch (cause) {
|
|
469
|
+
await cleanupSession();
|
|
470
|
+
if (!cause?.reported && !setupTerminal) error(errorKind(cause));
|
|
471
|
+
}
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
if (!transport) return error("no-session");
|
|
475
|
+
try {
|
|
476
|
+
if (cmd === "break" || cmd === "rmbreak") {
|
|
477
|
+
const breakpoint = parseBreakpointSpec(parts[0]);
|
|
478
|
+
if (!breakpoint) return error("invalid-args");
|
|
479
|
+
const { file, line: lineNumber } = breakpoint;
|
|
480
|
+
const set = breakpoints.get(file) || [];
|
|
481
|
+
const next = cmd === "break" ? [...set.filter(x => x.line !== lineNumber), { line: lineNumber }] : set.filter(x => x.line !== lineNumber);
|
|
482
|
+
const response = await request("setBreakpoints", { source: { path: file }, breakpoints: next });
|
|
483
|
+
breakpoints.set(file, next);
|
|
484
|
+
if (response.body?.breakpoints?.some(bp => bp.verified === false)) error("unverified-breakpoint"); else line(`BREAK: ${file}:${lineNumber}`);
|
|
485
|
+
} else if (["continue", "step", "next", "stepin", "stepout", "pause"].includes(cmd)) {
|
|
486
|
+
const dapCmd = { step: "next", stepin: "stepIn", stepout: "stepOut" }[cmd] || cmd;
|
|
487
|
+
const threadId = currentStop?.threadId || 1;
|
|
488
|
+
currentStop = null;
|
|
489
|
+
await request(dapCmd, { threadId });
|
|
490
|
+
// Wait for the resulting stopped event (breakpoint hit / step completed) before
|
|
491
|
+
// snapshotting; without this the stack is read while the debuggee is still running.
|
|
492
|
+
if (await waitForStop()) await snapshot();
|
|
493
|
+
else if (terminated) reportExit();
|
|
494
|
+
} else if (cmd === "stack") {
|
|
495
|
+
const r = await request("stackTrace", { threadId: currentStop?.threadId || 1, levels: Number(parts[0]) || 100 });
|
|
496
|
+
boundedTable(["FRAME", "NAME", "FILE", "LINE", "COLUMN"], (r.body?.stackFrames || []).map(f => [String(f.id), f.name, f.source?.path || "", String(f.line || ""), String(f.column || "")]));
|
|
497
|
+
} else if (cmd === "scopes") {
|
|
498
|
+
const r = await request("scopes", { frameId: topFrame?.id || 42 });
|
|
499
|
+
boundedTable(["NAME", "VARIABLES_REFERENCE"], (r.body?.scopes || []).map(s => [s.name, String(s.variablesReference)]));
|
|
500
|
+
} else if (cmd === "vars") {
|
|
501
|
+
if (!parts[0]) return error("invalid-args");
|
|
502
|
+
const r = await request("variables", { variablesReference: Number(parts[0]) });
|
|
503
|
+
boundedTable(["NAME", "VALUE"], (r.body?.variables || []).map(v => [v.name, v.value ?? ""]));
|
|
504
|
+
} else if (cmd === "eval") {
|
|
505
|
+
if (!parts.length) return error("invalid-args");
|
|
506
|
+
const r = await request("evaluate", { expression: parts.join(" "), frameId: topFrame?.id || 42 });
|
|
507
|
+
writeBoundedAdapterLine("EVAL\t", r.body?.result ?? "");
|
|
508
|
+
} else if (cmd === "threads") {
|
|
509
|
+
const r = await request("threads"); boundedTable(["ID", "NAME"], (r.body?.threads || []).map(t => [String(t.id), t.name]));
|
|
510
|
+
} else if (cmd === "sessions") line("SESSION\tSTATE\n1\tactive");
|
|
511
|
+
else if (cmd === "terminate") {
|
|
512
|
+
await request("terminate", { restart: false });
|
|
513
|
+
markTerminated();
|
|
514
|
+
await cleanupSession();
|
|
515
|
+
}
|
|
516
|
+
else error("invalid-args");
|
|
517
|
+
} catch (cause) { if (!cause?.reported) error(errorKind(cause)); }
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
function isMainModule() {
|
|
521
|
+
if (typeof import.meta.main === "boolean") return import.meta.main;
|
|
522
|
+
const entrypoint = process.argv[1];
|
|
523
|
+
return typeof entrypoint === "string" && pathToFileURL(resolve(entrypoint)).href === import.meta.url;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
if (isMainModule()) {
|
|
527
|
+
// Serialize stdin commands: fire-and-forget (`void command(...)`) lets a `continue`
|
|
528
|
+
// race ahead of the launch handshake's configurationDone, and the adapter then
|
|
529
|
+
// drops or rejects the out-of-order request. Each line awaits the previous command.
|
|
530
|
+
let chain = Promise.resolve();
|
|
531
|
+
const rl = createInterface({ input: stdin, crlfDelay: Infinity });
|
|
532
|
+
rl.on("line", value => { chain = chain.then(() => command(value)).catch(() => {}); });
|
|
533
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# DAP Client (`dap.mjs`) — Drive the Debugger's Protocol, Not Its Text
|
|
2
|
+
|
|
3
|
+
**Design modeled on the `debug` tool of oh-my-pi (https://github.com/can1357/oh-my-pi, branch omp2).** Their harness proved the useful shape: one structured debug surface with bounded output, stop snapshots, and classified errors. This script brings the same discipline to any shell without registering a tool or adding a dependency.
|
|
4
|
+
|
|
5
|
+
Debuggers that speak the Debug Adapter Protocol (DAP) expose a machine-readable JSON protocol. Driving DAP beats screen-scraping a PTY for the same reason an API beats OCR: structured stops, variables, and errors. **If an already-available debugger speaks DAP, use this script instead of parsing `gdb` or `pdb` text.**
|
|
6
|
+
|
|
7
|
+
The script is at `references/scripts/dap.mjs`. It is zero dependency and runs with Node; Bun is compatible when it is already available.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## When to use which interface
|
|
12
|
+
|
|
13
|
+
| Situation | Use |
|
|
14
|
+
|---|---|
|
|
15
|
+
| Source-level debugging of Python, Go, Node, or native code with breakpoints, stepping, and variables | `dap.mjs` |
|
|
16
|
+
| Browser-served JS, or anything already in Chrome | Scripted CDP — see `references/runtimes/node.md` |
|
|
17
|
+
| Stripped binary, no source, no symbols | Ghidra (static) plus the matching live-debugging reference |
|
|
18
|
+
| The debugger has no DAP mode | pwndbg, with the output-budget rule from `references/methodology/00-setup.md` |
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## Start the REPL
|
|
23
|
+
|
|
24
|
+
`dap.mjs` is a persistent REPL: it reads one command per line on stdin and writes bounded text on stdout. Keep it running for the debug session, send it commands through its stdin, and watch its stdout for `STOP:` rather than polling.
|
|
25
|
+
|
|
26
|
+
PowerShell / Node:
|
|
27
|
+
|
|
28
|
+
```powershell
|
|
29
|
+
$dapScript = Join-Path $PWD "skills\debugging\references\scripts\dap.mjs"
|
|
30
|
+
node $dapScript
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
If Bun is already installed and selected for the session, the equivalent is `bun $dapScript`. The client uses its current runtime to launch `.mjs`, `.cjs`, and `.js` adapter scripts; Bun also accepts `.ts` adapter scripts. Native Node execution does not assume a TypeScript loader.
|
|
34
|
+
|
|
35
|
+
Do not install, download, or globally add an adapter to use this client. Supply an adapter executable or script that is already present in the project, toolchain, or user-approved environment. If no suitable adapter is available, report that boundary and use the runtime reference's supported non-DAP method.
|
|
36
|
+
|
|
37
|
+
### Commands
|
|
38
|
+
|
|
39
|
+
| Command | Effect |
|
|
40
|
+
|---|---|
|
|
41
|
+
| `launch <adapter> <program> [args...]` | Spawn an already-available stdio adapter executable or `.mjs`/`.cjs`/`.js` script, then launch the program; adapter and program are required |
|
|
42
|
+
| `attach <host:port>` | Connect to an already-listening adapter over TCP and attach |
|
|
43
|
+
| `break <file>:<line>` / `rmbreak <file>:<line>` | Set or remove a source breakpoint |
|
|
44
|
+
| `continue` / `step` / `next` / `stepin` / `stepout` / `pause` | Execution control; each prints a `STOP:` snapshot when the debuggee next stops |
|
|
45
|
+
| `stack [limit]` | TSV backtrace, bounded |
|
|
46
|
+
| `scopes` | Scopes of the top frame with their `variablesReference` values |
|
|
47
|
+
| `vars <ref>` | Variables below a `variablesReference` from `scopes`; references are session-scoped |
|
|
48
|
+
| `eval <expr>` | Evaluate in the top frame |
|
|
49
|
+
| `threads` / `sessions` | Thread list / session state |
|
|
50
|
+
| `terminate` / `quit` | End the debuggee / exit the REPL |
|
|
51
|
+
|
|
52
|
+
`<host:port>` means a host with a numeric port only. A Windows path such as `C:\workspace\adapter.mjs` is an adapter path, not a TCP endpoint. Wrap adapter, program, and breakpoint paths containing spaces in either single or double quotes; backslashes are literal and the REPL never evaluates a shell command. An unmatched quote or missing `launch` adapter/program returns `ERR: invalid-args`.
|
|
53
|
+
|
|
54
|
+
### Output contract
|
|
55
|
+
|
|
56
|
+
- Tabular results are TSV with a header row.
|
|
57
|
+
- Hard caps are `MAX_ROWS = 100` and `MAX_OUTPUT_BYTES = 32 KB`. Overflow prints `TRUNCATED: rows dropped=N bytes dropped=M`; output is never silently cut.
|
|
58
|
+
- Every adapter-derived stdout value, including `STOP:` frame/reason/path fields and `EVAL` results, is UTF-8 byte-bounded to 32 KB. A clipped line emits `TRUNCATED: bytes dropped=N` immediately after it.
|
|
59
|
+
- After every continue or step, stdout emits `STOP: stopped reason=<why> threadId=<id> <frame> at <file>:<line>:<col>`. A debuggee exit emits `EXIT: terminated`.
|
|
60
|
+
- Errors are one classified line: `ERR: invalid-args | no-session | adapter-failed | unverified-breakpoint | timeout | terminated | adapter-error`.
|
|
61
|
+
- Every request has a 15-second timeout (override only with `DAP_TIMEOUT_MS`); a timeout does not close an otherwise usable session.
|
|
62
|
+
- A rejected or timed-out launch, configuration, or attach handshake never reports `READY`; the client cleans up that failed setup so a later launch or attach can retry.
|
|
63
|
+
- Set `DAP_DEBUG=1` only when protocol traffic itself is needed; it writes capped raw-message previews to stderr.
|
|
64
|
+
|
|
65
|
+
### Adapter behavior handled by the client
|
|
66
|
+
|
|
67
|
+
- **debugpy** requires `console: "internalConsole"` in the launch request and can withhold `initialized` for unknown `adapterID` values. The client sends the recognized ID when the adapter path identifies debugpy and launches before awaiting the event.
|
|
68
|
+
- **lldb-dap** can report a false launch response after starting successfully, and can report `threadId: 0` at entry. The client treats process and stopped events as the signal.
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Existing-adapter example
|
|
73
|
+
|
|
74
|
+
With an existing project-local adapter script, quote any path that contains spaces:
|
|
75
|
+
|
|
76
|
+
```text
|
|
77
|
+
launch "C:\workspace path\tools\project-dap-adapter.mjs" "C:\workspace path\src\program.js"
|
|
78
|
+
break "C:\workspace path\src\program.js:12"
|
|
79
|
+
continue
|
|
80
|
+
STOP: stopped reason=breakpoint threadId=1 main at C:\workspace path\src\program.js:12:1
|
|
81
|
+
stack
|
|
82
|
+
scopes
|
|
83
|
+
vars 6
|
|
84
|
+
eval total
|
|
85
|
+
terminate
|
|
86
|
+
quit
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Cleanup is part of the session: terminate the debuggee, then quit the REPL. `quit` destroys a socket transport or kills an adapter process started by this client; journal any wrapper scripts you created according to the skill's cleanup phase.
|