@cjhyy/code-shell-capability-coding 0.8.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/README.md +69 -0
- package/THIRD_PARTY_NOTICES.md +206 -0
- package/dist/bin/agent-server-stdio.d.ts +1 -0
- package/dist/bin/agent-server-stdio.js +4 -0
- package/dist/capability-runtime.d.ts +22 -0
- package/dist/capability-runtime.js +88 -0
- package/dist/cc-orchestrator/agent-adapter.d.ts +55 -0
- package/dist/cc-orchestrator/agent-adapter.js +143 -0
- package/dist/cc-orchestrator/cc-capability.d.ts +20 -0
- package/dist/cc-orchestrator/cc-capability.js +57 -0
- package/dist/cc-orchestrator/codex-session-discovery.d.ts +45 -0
- package/dist/cc-orchestrator/codex-session-discovery.js +251 -0
- package/dist/cc-orchestrator/codex-session-history.d.ts +39 -0
- package/dist/cc-orchestrator/codex-session-history.js +249 -0
- package/dist/cc-orchestrator/codex-user-text.d.ts +9 -0
- package/dist/cc-orchestrator/codex-user-text.js +25 -0
- package/dist/cc-orchestrator/external-agent-bindings.d.ts +27 -0
- package/dist/cc-orchestrator/external-agent-bindings.js +150 -0
- package/dist/cc-orchestrator/external-agent-changes.d.ts +19 -0
- package/dist/cc-orchestrator/external-agent-changes.js +231 -0
- package/dist/cc-orchestrator/external-agent-driver.d.ts +19 -0
- package/dist/cc-orchestrator/external-agent-driver.js +284 -0
- package/dist/cc-orchestrator/external-agent-session-store.d.ts +36 -0
- package/dist/cc-orchestrator/external-agent-session-store.js +185 -0
- package/dist/cc-orchestrator/index.d.ts +10 -0
- package/dist/cc-orchestrator/index.js +10 -0
- package/dist/cc-orchestrator/related-session-discovery.d.ts +21 -0
- package/dist/cc-orchestrator/related-session-discovery.js +77 -0
- package/dist/cc-orchestrator/relevance-judge.d.ts +16 -0
- package/dist/cc-orchestrator/relevance-judge.js +38 -0
- package/dist/cc-orchestrator/session-discovery.d.ts +99 -0
- package/dist/cc-orchestrator/session-discovery.js +295 -0
- package/dist/cc-orchestrator/session-history.d.ts +55 -0
- package/dist/cc-orchestrator/session-history.js +150 -0
- package/dist/external-agents/config.d.ts +3 -0
- package/dist/external-agents/config.js +16 -0
- package/dist/external-agents/types.d.ts +32 -0
- package/dist/external-agents/types.js +1 -0
- package/dist/external-runtimes/claude-code/event-translator.d.ts +54 -0
- package/dist/external-runtimes/claude-code/event-translator.js +201 -0
- package/dist/external-runtimes/claude-code/mcp-config.d.ts +84 -0
- package/dist/external-runtimes/claude-code/mcp-config.js +175 -0
- package/dist/external-runtimes/claude-code/runtime.d.ts +56 -0
- package/dist/external-runtimes/claude-code/runtime.js +168 -0
- package/dist/external-runtimes/codex/app-server-client.d.ts +66 -0
- package/dist/external-runtimes/codex/app-server-client.js +244 -0
- package/dist/external-runtimes/codex/event-translator.d.ts +68 -0
- package/dist/external-runtimes/codex/event-translator.js +187 -0
- package/dist/external-runtimes/codex/index.d.ts +7 -0
- package/dist/external-runtimes/codex/index.js +6 -0
- package/dist/external-runtimes/codex/runtime.d.ts +128 -0
- package/dist/external-runtimes/codex/runtime.js +216 -0
- package/dist/external-runtimes/index.d.ts +37 -0
- package/dist/external-runtimes/index.js +27 -0
- package/dist/external-runtimes/session-factory.d.ts +97 -0
- package/dist/external-runtimes/session-factory.js +110 -0
- package/dist/external-runtimes/shared/mcp-bridge.d.ts +66 -0
- package/dist/external-runtimes/shared/mcp-bridge.js +365 -0
- package/dist/external-runtimes/shared/session-context-store.d.ts +83 -0
- package/dist/external-runtimes/shared/session-context-store.js +114 -0
- package/dist/external-runtimes/shared/spawn-env.d.ts +30 -0
- package/dist/external-runtimes/shared/spawn-env.js +41 -0
- package/dist/git/parse-log.d.ts +14 -0
- package/dist/git/parse-log.js +21 -0
- package/dist/git/utils.d.ts +49 -0
- package/dist/git/utils.js +161 -0
- package/dist/git/worktree/crud.d.ts +108 -0
- package/dist/git/worktree/crud.js +415 -0
- package/dist/git/worktree/diff.d.ts +14 -0
- package/dist/git/worktree/diff.js +83 -0
- package/dist/git/worktree/git-exec.d.ts +7 -0
- package/dist/git/worktree/git-exec.js +86 -0
- package/dist/git/worktree/index.d.ts +6 -0
- package/dist/git/worktree/index.js +6 -0
- package/dist/git/worktree/query.d.ts +43 -0
- package/dist/git/worktree/query.js +128 -0
- package/dist/git/worktree/slug.d.ts +12 -0
- package/dist/git/worktree/slug.js +59 -0
- package/dist/git/worktree.d.ts +1 -0
- package/dist/git/worktree.js +5 -0
- package/dist/index.capability.d.ts +7 -0
- package/dist/index.capability.js +190 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.git.d.ts +4 -0
- package/dist/index.git.js +4 -0
- package/dist/index.js +18 -0
- package/dist/index.orchestration.d.ts +7 -0
- package/dist/index.orchestration.js +5 -0
- package/dist/lsp/client.d.ts +41 -0
- package/dist/lsp/client.js +192 -0
- package/dist/lsp/manager.d.ts +53 -0
- package/dist/lsp/manager.js +248 -0
- package/dist/lsp/root-path.d.ts +9 -0
- package/dist/lsp/root-path.js +12 -0
- package/dist/lsp/servers.d.ts +16 -0
- package/dist/lsp/servers.js +60 -0
- package/dist/prompt/coding.md +42 -0
- package/dist/quota/credentials.d.ts +3 -0
- package/dist/quota/credentials.js +80 -0
- package/dist/quota/index.d.ts +36 -0
- package/dist/quota/index.js +161 -0
- package/dist/quota/types.d.ts +48 -0
- package/dist/quota/types.js +13 -0
- package/dist/review/review-prompt.d.ts +28 -0
- package/dist/review/review-prompt.js +81 -0
- package/dist/tools/apply-patch/LICENSE-codex +201 -0
- package/dist/tools/apply-patch/NOTICE.md +29 -0
- package/dist/tools/apply-patch/applier.d.ts +26 -0
- package/dist/tools/apply-patch/applier.js +306 -0
- package/dist/tools/apply-patch/backup-targets.d.ts +10 -0
- package/dist/tools/apply-patch/backup-targets.js +30 -0
- package/dist/tools/apply-patch/eol.d.ts +4 -0
- package/dist/tools/apply-patch/eol.js +9 -0
- package/dist/tools/apply-patch/index.d.ts +20 -0
- package/dist/tools/apply-patch/index.js +106 -0
- package/dist/tools/apply-patch/parser.d.ts +17 -0
- package/dist/tools/apply-patch/parser.js +209 -0
- package/dist/tools/apply-patch/seek-sequence.d.ts +18 -0
- package/dist/tools/apply-patch/seek-sequence.js +123 -0
- package/dist/tools/apply-patch/types.d.ts +49 -0
- package/dist/tools/apply-patch/types.js +13 -0
- package/dist/tools/brief.d.ts +6 -0
- package/dist/tools/brief.js +41 -0
- package/dist/tools/check-quota.d.ts +14 -0
- package/dist/tools/check-quota.js +38 -0
- package/dist/tools/drive-agent.d.ts +52 -0
- package/dist/tools/drive-agent.js +1184 -0
- package/dist/tools/lsp.d.ts +6 -0
- package/dist/tools/lsp.js +220 -0
- package/dist/tools/notebook-edit.d.ts +6 -0
- package/dist/tools/notebook-edit.js +127 -0
- package/dist/tools/worktree.d.ts +10 -0
- package/dist/tools/worktree.js +363 -0
- package/package.json +60 -0
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import { createInterface } from "node:readline";
|
|
3
|
+
import { pathWithCommonBins } from "./cc-capability.js";
|
|
4
|
+
import { killProcessGroup } from "@cjhyy/code-shell-core/extension";
|
|
5
|
+
/** Pure: reduce collected output lines + exit code to a result. Unit-testable. */
|
|
6
|
+
export function runWithLines(adapter, lines, exitCode) {
|
|
7
|
+
const parsed = adapter.parseResult(lines);
|
|
8
|
+
return { ...parsed, exitCode, lines };
|
|
9
|
+
}
|
|
10
|
+
const codexImageFlagCache = new Map();
|
|
11
|
+
const CODEX_IMAGE_PROBE_TIMEOUT_MS = 5_000;
|
|
12
|
+
const AGENT_TERMINATE_GRACE_MS = 500;
|
|
13
|
+
function listPosixProcessTree(rootPid) {
|
|
14
|
+
return new Promise((resolve) => {
|
|
15
|
+
execFile("ps", ["-axo", "pid=,ppid="], { encoding: "utf8" }, (err, stdout) => {
|
|
16
|
+
if (err) {
|
|
17
|
+
resolve([rootPid]);
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
const childrenByParent = new Map();
|
|
21
|
+
for (const line of stdout.split("\n")) {
|
|
22
|
+
const [pidText, parentText] = line.trim().split(/\s+/, 2);
|
|
23
|
+
const pid = Number(pidText);
|
|
24
|
+
const parentPid = Number(parentText);
|
|
25
|
+
if (!Number.isInteger(pid) || !Number.isInteger(parentPid))
|
|
26
|
+
continue;
|
|
27
|
+
const children = childrenByParent.get(parentPid) ?? [];
|
|
28
|
+
children.push(pid);
|
|
29
|
+
childrenByParent.set(parentPid, children);
|
|
30
|
+
}
|
|
31
|
+
const pids = [];
|
|
32
|
+
const visit = (pid) => {
|
|
33
|
+
if (pids.includes(pid))
|
|
34
|
+
return;
|
|
35
|
+
pids.push(pid);
|
|
36
|
+
for (const childPid of childrenByParent.get(pid) ?? [])
|
|
37
|
+
visit(childPid);
|
|
38
|
+
};
|
|
39
|
+
visit(rootPid);
|
|
40
|
+
resolve(pids);
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function isPidAlive(pid) {
|
|
45
|
+
try {
|
|
46
|
+
process.kill(pid, 0);
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function delay(ms) {
|
|
54
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
55
|
+
}
|
|
56
|
+
async function waitForPidsToExit(pids, timeoutMs) {
|
|
57
|
+
const deadline = Date.now() + timeoutMs;
|
|
58
|
+
while ([...pids].some(isPidAlive)) {
|
|
59
|
+
if (Date.now() >= deadline)
|
|
60
|
+
return false;
|
|
61
|
+
await delay(25);
|
|
62
|
+
}
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
function signalPids(pids, killSignal) {
|
|
66
|
+
for (const pid of pids) {
|
|
67
|
+
try {
|
|
68
|
+
process.kill(pid, killSignal);
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
// already gone
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async function terminateAttachedProcessTree(child) {
|
|
76
|
+
const pid = child.pid;
|
|
77
|
+
if (!pid) {
|
|
78
|
+
try {
|
|
79
|
+
child.kill("SIGKILL");
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
// already gone
|
|
83
|
+
}
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (process.platform === "win32") {
|
|
87
|
+
// Windows has no POSIX SIGTERM semantics or negative-pid groups. Reap the
|
|
88
|
+
// tree via taskkill, then use positive-pid process.kill as the fallback the
|
|
89
|
+
// platform supports when taskkill is unavailable/races.
|
|
90
|
+
await killProcessGroup(pid, { graceMs: AGENT_TERMINATE_GRACE_MS });
|
|
91
|
+
if (isPidAlive(pid)) {
|
|
92
|
+
try {
|
|
93
|
+
process.kill(pid);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
// already gone
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const trackedPids = new Set(await listPosixProcessTree(pid));
|
|
102
|
+
signalPids(trackedPids, "SIGTERM");
|
|
103
|
+
if (await waitForPidsToExit(trackedPids, AGENT_TERMINATE_GRACE_MS))
|
|
104
|
+
return;
|
|
105
|
+
// Capture descendants created during the grace window while the leader is
|
|
106
|
+
// still addressable, but retain the first snapshot so reparented stubborn
|
|
107
|
+
// descendants cannot disappear from the escalation set.
|
|
108
|
+
for (const treePid of await listPosixProcessTree(pid))
|
|
109
|
+
trackedPids.add(treePid);
|
|
110
|
+
signalPids(trackedPids, "SIGKILL");
|
|
111
|
+
await waitForPidsToExit(trackedPids, 1_000);
|
|
112
|
+
}
|
|
113
|
+
function abortError() {
|
|
114
|
+
const err = new Error("Agent run aborted");
|
|
115
|
+
err.name = "AbortError";
|
|
116
|
+
return err;
|
|
117
|
+
}
|
|
118
|
+
function throwIfAborted(signal) {
|
|
119
|
+
if (signal?.aborted)
|
|
120
|
+
throw abortError();
|
|
121
|
+
}
|
|
122
|
+
function createCodexImageProbe(command, cwd, signal) {
|
|
123
|
+
return new Promise((resolve, reject) => {
|
|
124
|
+
if (signal?.aborted) {
|
|
125
|
+
reject(abortError());
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
const child = spawn(command, ["exec", "--help"], {
|
|
129
|
+
cwd,
|
|
130
|
+
env: { ...process.env, PATH: pathWithCommonBins() },
|
|
131
|
+
windowsHide: true,
|
|
132
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
133
|
+
});
|
|
134
|
+
let out = "";
|
|
135
|
+
let settled = false;
|
|
136
|
+
let terminating = false;
|
|
137
|
+
const cleanup = () => {
|
|
138
|
+
clearTimeout(timer);
|
|
139
|
+
signal?.removeEventListener("abort", onAbort);
|
|
140
|
+
};
|
|
141
|
+
const done = (value) => {
|
|
142
|
+
if (settled)
|
|
143
|
+
return;
|
|
144
|
+
settled = true;
|
|
145
|
+
cleanup();
|
|
146
|
+
resolve(value);
|
|
147
|
+
};
|
|
148
|
+
const fail = (err) => {
|
|
149
|
+
if (settled)
|
|
150
|
+
return;
|
|
151
|
+
settled = true;
|
|
152
|
+
cleanup();
|
|
153
|
+
reject(err);
|
|
154
|
+
};
|
|
155
|
+
const onAbort = () => {
|
|
156
|
+
if (settled || terminating)
|
|
157
|
+
return;
|
|
158
|
+
terminating = true;
|
|
159
|
+
cleanup();
|
|
160
|
+
void terminateAttachedProcessTree(child).then(() => fail(abortError()));
|
|
161
|
+
};
|
|
162
|
+
const timer = setTimeout(() => {
|
|
163
|
+
if (settled || terminating)
|
|
164
|
+
return;
|
|
165
|
+
terminating = true;
|
|
166
|
+
cleanup();
|
|
167
|
+
void terminateAttachedProcessTree(child).then(() => done(false));
|
|
168
|
+
}, CODEX_IMAGE_PROBE_TIMEOUT_MS);
|
|
169
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
170
|
+
if (signal?.aborted)
|
|
171
|
+
onAbort();
|
|
172
|
+
child.stdout?.on("data", (chunk) => {
|
|
173
|
+
out += chunk.toString("utf8");
|
|
174
|
+
});
|
|
175
|
+
child.stderr?.on("data", (chunk) => {
|
|
176
|
+
out += chunk.toString("utf8");
|
|
177
|
+
});
|
|
178
|
+
child.on("error", () => {
|
|
179
|
+
if (!terminating)
|
|
180
|
+
done(false);
|
|
181
|
+
});
|
|
182
|
+
child.on("exit", () => {
|
|
183
|
+
if (!terminating)
|
|
184
|
+
done(/(?:^|\s)-i(?:,|\s)|--image\b/.test(out));
|
|
185
|
+
});
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
export function detectCodexImageInput(command, cwd, signal) {
|
|
189
|
+
if (signal)
|
|
190
|
+
return createCodexImageProbe(command, cwd, signal);
|
|
191
|
+
const cached = codexImageFlagCache.get(command);
|
|
192
|
+
if (cached)
|
|
193
|
+
return cached;
|
|
194
|
+
const probe = createCodexImageProbe(command, cwd);
|
|
195
|
+
codexImageFlagCache.set(command, probe);
|
|
196
|
+
return probe;
|
|
197
|
+
}
|
|
198
|
+
/** Spawn ONE headless agent run, collect stream-json to exit, return result.
|
|
199
|
+
* No time concept — a single turn. Honors AbortSignal (kills the child). */
|
|
200
|
+
export function runAgentOnce(adapter, opts, signal) {
|
|
201
|
+
return new Promise((resolve, reject) => {
|
|
202
|
+
void (async () => {
|
|
203
|
+
throwIfAborted(signal);
|
|
204
|
+
const codexImageInputSupported = adapter.kind === "codex" && (opts.imagePaths?.length ?? 0) > 0
|
|
205
|
+
? await detectCodexImageInput(opts.command, opts.cwd, signal).catch((err) => {
|
|
206
|
+
if (signal?.aborted || err?.name === "AbortError")
|
|
207
|
+
throw err;
|
|
208
|
+
return false;
|
|
209
|
+
})
|
|
210
|
+
: false;
|
|
211
|
+
throwIfAborted(signal);
|
|
212
|
+
const args = adapter.buildArgs({
|
|
213
|
+
prompt: opts.prompt,
|
|
214
|
+
resumeSessionId: opts.resumeSessionId,
|
|
215
|
+
model: opts.model,
|
|
216
|
+
permissionMode: opts.permissionMode ?? "default",
|
|
217
|
+
cwd: opts.cwd,
|
|
218
|
+
imagePaths: opts.imagePaths,
|
|
219
|
+
codexImageInputSupported,
|
|
220
|
+
});
|
|
221
|
+
throwIfAborted(signal);
|
|
222
|
+
// claude takes the prompt in argv (`-p <prompt>`) and wants stdin closed
|
|
223
|
+
// (verified: avoids a 3s wait). codex `exec` reads the prompt from stdin
|
|
224
|
+
// (argv ends with `-`), so adapters that set promptViaStdin get a piped
|
|
225
|
+
// stdin we write the prompt to.
|
|
226
|
+
const viaStdin = adapter.promptViaStdin === true;
|
|
227
|
+
const child = spawn(opts.command, args, {
|
|
228
|
+
cwd: opts.cwd,
|
|
229
|
+
env: { ...process.env, PATH: pathWithCommonBins() },
|
|
230
|
+
// Keep the agent in the owning worker/app process group. If that owner
|
|
231
|
+
// is force-terminated, the CLI and its descendants must not escape into
|
|
232
|
+
// a detached group that can keep editing the workspace unseen.
|
|
233
|
+
detached: false,
|
|
234
|
+
stdio: [viaStdin ? "pipe" : "ignore", "pipe", "pipe"],
|
|
235
|
+
});
|
|
236
|
+
let settled = false;
|
|
237
|
+
let abortRequested = false;
|
|
238
|
+
let termination;
|
|
239
|
+
const cleanup = () => {
|
|
240
|
+
signal?.removeEventListener("abort", onAbort);
|
|
241
|
+
};
|
|
242
|
+
const onAbort = () => {
|
|
243
|
+
if (abortRequested)
|
|
244
|
+
return;
|
|
245
|
+
abortRequested = true;
|
|
246
|
+
termination = terminateAttachedProcessTree(child);
|
|
247
|
+
};
|
|
248
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
249
|
+
if (signal?.aborted)
|
|
250
|
+
onAbort();
|
|
251
|
+
if (viaStdin && child.stdin) {
|
|
252
|
+
child.stdin.end(opts.prompt);
|
|
253
|
+
}
|
|
254
|
+
const lines = [];
|
|
255
|
+
if (child.stdout) {
|
|
256
|
+
const rl = createInterface({ input: child.stdout });
|
|
257
|
+
rl.on("line", (line) => lines.push(line));
|
|
258
|
+
}
|
|
259
|
+
child.on("error", (err) => {
|
|
260
|
+
if (settled)
|
|
261
|
+
return;
|
|
262
|
+
settled = true;
|
|
263
|
+
cleanup();
|
|
264
|
+
// A missing binary is the most common failure (user hasn't installed the
|
|
265
|
+
// CLI, or GUI-launched Electron's PATH misses it). Turn the cryptic
|
|
266
|
+
// "spawn codex ENOENT" into something actionable that names the command.
|
|
267
|
+
if (err.code === "ENOENT") {
|
|
268
|
+
reject(new Error(`未找到命令 "${opts.command}"。请先安装该 CLI 并确保它在 PATH 中(${adapter.kind === "codex" ? "Codex CLI" : "Claude Code CLI"})。`));
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
reject(err);
|
|
272
|
+
});
|
|
273
|
+
child.on("exit", (code) => {
|
|
274
|
+
if (settled)
|
|
275
|
+
return;
|
|
276
|
+
settled = true;
|
|
277
|
+
cleanup();
|
|
278
|
+
void (termination ?? Promise.resolve()).then(() => {
|
|
279
|
+
resolve(runWithLines(adapter, lines, code));
|
|
280
|
+
});
|
|
281
|
+
});
|
|
282
|
+
})().catch(reject);
|
|
283
|
+
});
|
|
284
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export type ExternalAgentCli = "claude" | "codex";
|
|
2
|
+
export interface ExternalAgentSessionBinding {
|
|
3
|
+
cli: ExternalAgentCli;
|
|
4
|
+
sessionId: string;
|
|
5
|
+
codeShellSessionId?: string;
|
|
6
|
+
cwd: string;
|
|
7
|
+
workspaceRoot?: string;
|
|
8
|
+
worktreePath?: string;
|
|
9
|
+
worktreeBranch?: string;
|
|
10
|
+
worktreeBaseRef?: string;
|
|
11
|
+
isolation?: "current" | "worktree" | "none";
|
|
12
|
+
createdAt: number;
|
|
13
|
+
lastUsedAt: number;
|
|
14
|
+
/** @deprecated Use lastUsedAt. Kept while reading v1 snapshots. */
|
|
15
|
+
updatedAt: number;
|
|
16
|
+
}
|
|
17
|
+
export type ExternalAgentSessionRecord = Omit<ExternalAgentSessionBinding, "createdAt" | "lastUsedAt" | "updatedAt"> & {
|
|
18
|
+
createdAt?: number;
|
|
19
|
+
lastUsedAt?: number;
|
|
20
|
+
updatedAt?: number;
|
|
21
|
+
};
|
|
22
|
+
export declare function defaultExternalAgentSessionStorePath(): string;
|
|
23
|
+
export declare class ExternalAgentSessionStore {
|
|
24
|
+
private readonly file;
|
|
25
|
+
constructor(file?: string);
|
|
26
|
+
/** Snapshot all known bindings. Returned objects are detached from the
|
|
27
|
+
* persisted array so read-only consumers (for example room discovery) can
|
|
28
|
+
* correlate worktree sessions without gaining a mutation path. */
|
|
29
|
+
list(): ExternalAgentSessionBinding[];
|
|
30
|
+
get(cli: ExternalAgentCli, sessionId: string): ExternalAgentSessionBinding | undefined;
|
|
31
|
+
record(binding: ExternalAgentSessionRecord): void;
|
|
32
|
+
private load;
|
|
33
|
+
private save;
|
|
34
|
+
private withLock;
|
|
35
|
+
}
|
|
36
|
+
export declare const externalAgentSessionStore: ExternalAgentSessionStore;
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { codeShellHome, logger, normalizeCwdPath } from "@cjhyy/code-shell-core/extension";
|
|
4
|
+
const LOCK_WAIT_MS = 5_000;
|
|
5
|
+
const LOCK_STALE_MS = 30_000;
|
|
6
|
+
const LOCK_POLL_MS = 10;
|
|
7
|
+
export function defaultExternalAgentSessionStorePath() {
|
|
8
|
+
return join(codeShellHome(), "external-agent-sessions.json");
|
|
9
|
+
}
|
|
10
|
+
export class ExternalAgentSessionStore {
|
|
11
|
+
file;
|
|
12
|
+
constructor(file = defaultExternalAgentSessionStorePath()) {
|
|
13
|
+
this.file = file;
|
|
14
|
+
}
|
|
15
|
+
/** Snapshot all known bindings. Returned objects are detached from the
|
|
16
|
+
* persisted array so read-only consumers (for example room discovery) can
|
|
17
|
+
* correlate worktree sessions without gaining a mutation path. */
|
|
18
|
+
list() {
|
|
19
|
+
return this.load().map((binding) => ({ ...binding }));
|
|
20
|
+
}
|
|
21
|
+
get(cli, sessionId) {
|
|
22
|
+
if (!sessionId)
|
|
23
|
+
return undefined;
|
|
24
|
+
return this.load().find((s) => s.cli === cli && s.sessionId === sessionId);
|
|
25
|
+
}
|
|
26
|
+
record(binding) {
|
|
27
|
+
if (!binding.sessionId || !binding.cwd)
|
|
28
|
+
return;
|
|
29
|
+
this.withLock(() => {
|
|
30
|
+
const loaded = this.load();
|
|
31
|
+
const existing = loaded.find((s) => s.cli === binding.cli && s.sessionId === binding.sessionId);
|
|
32
|
+
const now = binding.lastUsedAt ?? binding.updatedAt ?? Date.now();
|
|
33
|
+
const next = {
|
|
34
|
+
cli: binding.cli,
|
|
35
|
+
sessionId: binding.sessionId,
|
|
36
|
+
...((binding.codeShellSessionId ?? existing?.codeShellSessionId)
|
|
37
|
+
? { codeShellSessionId: binding.codeShellSessionId ?? existing?.codeShellSessionId }
|
|
38
|
+
: {}),
|
|
39
|
+
cwd: normalizeCwdPath(binding.cwd),
|
|
40
|
+
...((binding.workspaceRoot ?? existing?.workspaceRoot)
|
|
41
|
+
? { workspaceRoot: normalizeCwdPath(binding.workspaceRoot ?? existing.workspaceRoot) }
|
|
42
|
+
: {}),
|
|
43
|
+
...((binding.worktreePath ?? existing?.worktreePath)
|
|
44
|
+
? { worktreePath: normalizeCwdPath(binding.worktreePath ?? existing.worktreePath) }
|
|
45
|
+
: {}),
|
|
46
|
+
...((binding.worktreeBranch ?? existing?.worktreeBranch)
|
|
47
|
+
? { worktreeBranch: binding.worktreeBranch ?? existing?.worktreeBranch }
|
|
48
|
+
: {}),
|
|
49
|
+
...((binding.worktreeBaseRef ?? existing?.worktreeBaseRef)
|
|
50
|
+
? { worktreeBaseRef: binding.worktreeBaseRef ?? existing?.worktreeBaseRef }
|
|
51
|
+
: {}),
|
|
52
|
+
...((binding.isolation ?? existing?.isolation)
|
|
53
|
+
? { isolation: binding.isolation ?? existing?.isolation }
|
|
54
|
+
: {}),
|
|
55
|
+
createdAt: binding.createdAt ?? existing?.createdAt ?? now,
|
|
56
|
+
lastUsedAt: now,
|
|
57
|
+
updatedAt: now,
|
|
58
|
+
};
|
|
59
|
+
const sessions = loaded.filter((s) => !(s.cli === binding.cli && s.sessionId === binding.sessionId));
|
|
60
|
+
sessions.push(next);
|
|
61
|
+
this.save(sessions);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
load() {
|
|
65
|
+
if (!existsSync(this.file))
|
|
66
|
+
return [];
|
|
67
|
+
try {
|
|
68
|
+
const raw = readFileSync(this.file, "utf-8");
|
|
69
|
+
const parsed = JSON.parse(raw);
|
|
70
|
+
if (!parsed || !Array.isArray(parsed.sessions))
|
|
71
|
+
return [];
|
|
72
|
+
return parsed.sessions.filter(isBinding).map(normalizeBinding);
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
logger.warn("external_agent_session_store.load_failed", {
|
|
76
|
+
cat: "cc",
|
|
77
|
+
file: this.file,
|
|
78
|
+
error: err instanceof Error ? err.message : String(err),
|
|
79
|
+
});
|
|
80
|
+
return [];
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
save(sessions) {
|
|
84
|
+
const dir = dirname(this.file);
|
|
85
|
+
if (!existsSync(dir))
|
|
86
|
+
mkdirSync(dir, { recursive: true });
|
|
87
|
+
const snapshot = { version: 2, sessions };
|
|
88
|
+
const tmp = `${this.file}.${process.pid}.${Date.now()}.tmp`;
|
|
89
|
+
try {
|
|
90
|
+
writeFileSync(tmp, JSON.stringify(snapshot, null, 2) + "\n", "utf-8");
|
|
91
|
+
renameSync(tmp, this.file);
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
rmSync(tmp, { force: true });
|
|
95
|
+
throw err;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
withLock(fn) {
|
|
99
|
+
const dir = dirname(this.file);
|
|
100
|
+
if (!existsSync(dir))
|
|
101
|
+
mkdirSync(dir, { recursive: true });
|
|
102
|
+
// TODO: move this sync polling lock to an async write queue; callers can
|
|
103
|
+
// otherwise block the event loop for up to LOCK_WAIT_MS under contention.
|
|
104
|
+
const lockDir = `${this.file}.lock`;
|
|
105
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
106
|
+
while (true) {
|
|
107
|
+
try {
|
|
108
|
+
mkdirSync(lockDir);
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
const code = err.code;
|
|
113
|
+
if (code !== "EEXIST")
|
|
114
|
+
throw err;
|
|
115
|
+
if (removeStaleLock(lockDir))
|
|
116
|
+
continue;
|
|
117
|
+
if (Date.now() >= deadline) {
|
|
118
|
+
throw new Error(`timed out waiting for external agent session store lock: ${lockDir}`, {
|
|
119
|
+
cause: err,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
sleepSync(LOCK_POLL_MS);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
try {
|
|
126
|
+
return fn();
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
rmSync(lockDir, { recursive: true, force: true });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function normalizeBinding(binding) {
|
|
134
|
+
const updatedAt = finiteTimestamp(binding.updatedAt) ?? Date.now();
|
|
135
|
+
const lastUsedAt = finiteTimestamp(binding.lastUsedAt) ?? updatedAt;
|
|
136
|
+
const createdAt = finiteTimestamp(binding.createdAt) ?? lastUsedAt;
|
|
137
|
+
return {
|
|
138
|
+
...binding,
|
|
139
|
+
cwd: normalizeCwdPath(binding.cwd),
|
|
140
|
+
...(binding.workspaceRoot ? { workspaceRoot: normalizeCwdPath(binding.workspaceRoot) } : {}),
|
|
141
|
+
...(binding.worktreePath ? { worktreePath: normalizeCwdPath(binding.worktreePath) } : {}),
|
|
142
|
+
createdAt,
|
|
143
|
+
lastUsedAt,
|
|
144
|
+
updatedAt: lastUsedAt,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
function finiteTimestamp(value) {
|
|
148
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
149
|
+
}
|
|
150
|
+
function removeStaleLock(lockDir) {
|
|
151
|
+
try {
|
|
152
|
+
if (Date.now() - statSync(lockDir).mtimeMs <= LOCK_STALE_MS)
|
|
153
|
+
return false;
|
|
154
|
+
rmSync(lockDir, { recursive: true, force: true });
|
|
155
|
+
return true;
|
|
156
|
+
}
|
|
157
|
+
catch (err) {
|
|
158
|
+
if (err.code === "ENOENT")
|
|
159
|
+
return true;
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function sleepSync(ms) {
|
|
164
|
+
try {
|
|
165
|
+
const view = new Int32Array(new SharedArrayBuffer(4));
|
|
166
|
+
Atomics.wait(view, 0, 0, ms);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
const until = Date.now() + ms;
|
|
170
|
+
while (Date.now() < until) {
|
|
171
|
+
// fallback for runtimes where Atomics.wait is unavailable
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
function isBinding(value) {
|
|
176
|
+
if (!value || typeof value !== "object")
|
|
177
|
+
return false;
|
|
178
|
+
const v = value;
|
|
179
|
+
return ((v.cli === "claude" || v.cli === "codex") &&
|
|
180
|
+
typeof v.sessionId === "string" &&
|
|
181
|
+
v.sessionId.length > 0 &&
|
|
182
|
+
typeof v.cwd === "string" &&
|
|
183
|
+
v.cwd.length > 0);
|
|
184
|
+
}
|
|
185
|
+
export const externalAgentSessionStore = new ExternalAgentSessionStore();
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** External coding-agent orchestration surface. */
|
|
2
|
+
export * from "./cc-capability.js";
|
|
3
|
+
export * from "./agent-adapter.js";
|
|
4
|
+
export * from "./external-agent-driver.js";
|
|
5
|
+
export * from "./session-discovery.js";
|
|
6
|
+
export * from "./codex-session-discovery.js";
|
|
7
|
+
export * from "./related-session-discovery.js";
|
|
8
|
+
export * from "./relevance-judge.js";
|
|
9
|
+
export * from "./session-history.js";
|
|
10
|
+
export * from "./codex-session-history.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** External coding-agent orchestration surface. */
|
|
2
|
+
export * from "./cc-capability.js";
|
|
3
|
+
export * from "./agent-adapter.js";
|
|
4
|
+
export * from "./external-agent-driver.js";
|
|
5
|
+
export * from "./session-discovery.js";
|
|
6
|
+
export * from "./codex-session-discovery.js";
|
|
7
|
+
export * from "./related-session-discovery.js";
|
|
8
|
+
export * from "./relevance-judge.js";
|
|
9
|
+
export * from "./session-history.js";
|
|
10
|
+
export * from "./codex-session-history.js";
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type ExternalAgentSessionBinding, type ExternalAgentCli } from "./external-agent-session-store.js";
|
|
2
|
+
import { type DiscoveredSession, type DiscoverOptions } from "./session-discovery.js";
|
|
3
|
+
export interface RelatedSessionDiscoveryOptions {
|
|
4
|
+
claudeHome?: string;
|
|
5
|
+
codexHome?: string;
|
|
6
|
+
/** Test seam; production reads DriveAgent's durable binding store. */
|
|
7
|
+
bindings?: readonly ExternalAgentSessionBinding[];
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* List sessions that belong to the selected cwd plus DriveAgent sessions
|
|
11
|
+
* launched in worktrees associated with it. The external CLI's own recorded
|
|
12
|
+
* cwd is retained on every row and becomes the authoritative path when opening
|
|
13
|
+
* the session.
|
|
14
|
+
*/
|
|
15
|
+
export declare function discoverRelatedSessions(cli: ExternalAgentCli, cwd: string, opts?: DiscoverOptions, discovery?: RelatedSessionDiscoveryOptions): DiscoveredSession[];
|
|
16
|
+
/** Cheap total for the related-session list. Exact-cwd sessions come from the
|
|
17
|
+
* CLI index; delegated cwd totals come from durable DriveAgent bindings so we
|
|
18
|
+
* do not deep-read every transcript just to decide whether "load more" is
|
|
19
|
+
* needed. A stale binding can only overestimate this hint; loading all then
|
|
20
|
+
* returns the authoritative discovered length. */
|
|
21
|
+
export declare function countRelatedSessions(cli: ExternalAgentCli, cwd: string, discovery?: RelatedSessionDiscoveryOptions): number;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import { externalAgentSessionStore, } from "./external-agent-session-store.js";
|
|
4
|
+
import { countSessions, discoverSessions, } from "./session-discovery.js";
|
|
5
|
+
import { countCodexSessions, discoverCodexSessionsForCwds } from "./codex-session-discovery.js";
|
|
6
|
+
/**
|
|
7
|
+
* List sessions that belong to the selected cwd plus DriveAgent sessions
|
|
8
|
+
* launched in worktrees associated with it. The external CLI's own recorded
|
|
9
|
+
* cwd is retained on every row and becomes the authoritative path when opening
|
|
10
|
+
* the session.
|
|
11
|
+
*/
|
|
12
|
+
export function discoverRelatedSessions(cli, cwd, opts = {}, discovery = {}) {
|
|
13
|
+
const root = resolve(cwd);
|
|
14
|
+
const bindings = discovery.bindings ?? externalAgentSessionStore.list();
|
|
15
|
+
const expectedIdsByCwd = new Map();
|
|
16
|
+
expectedIdsByCwd.set(root, new Set());
|
|
17
|
+
for (const binding of bindings) {
|
|
18
|
+
if (binding.cli !== cli || !isRelatedBinding(binding, root))
|
|
19
|
+
continue;
|
|
20
|
+
const bindingCwd = resolve(binding.cwd);
|
|
21
|
+
const ids = expectedIdsByCwd.get(bindingCwd) ?? new Set();
|
|
22
|
+
ids.add(binding.sessionId);
|
|
23
|
+
expectedIdsByCwd.set(bindingCwd, ids);
|
|
24
|
+
}
|
|
25
|
+
const candidateCwds = [...expectedIdsByCwd.keys()];
|
|
26
|
+
const candidates = cli === "codex"
|
|
27
|
+
? discoverCodexSessionsForCwds(candidateCwds, discovery.codexHome ?? join(homedir(), ".codex"), opts, ({ sessionId, cwd: sessionCwd }) => {
|
|
28
|
+
const normalizedCwd = resolve(sessionCwd);
|
|
29
|
+
return (normalizedCwd === root || expectedIdsByCwd.get(normalizedCwd)?.has(sessionId) === true);
|
|
30
|
+
})
|
|
31
|
+
: candidateCwds.flatMap((candidateCwd) => discoverSessions(candidateCwd, discovery.claudeHome ?? join(homedir(), ".claude"), candidateCwd === root ? opts : { sinceMs: opts.sinceMs, now: opts.now }));
|
|
32
|
+
const deduped = new Map();
|
|
33
|
+
for (const session of candidates) {
|
|
34
|
+
const sessionCwd = resolve(session.cwd);
|
|
35
|
+
const expectedIds = expectedIdsByCwd.get(sessionCwd);
|
|
36
|
+
// The selected cwd shows every native CLI session. Related worktree cwd
|
|
37
|
+
// buckets show only sessions CodeShell actually delegated there.
|
|
38
|
+
if (sessionCwd !== root && !expectedIds?.has(session.sessionId))
|
|
39
|
+
continue;
|
|
40
|
+
const key = `${cli}:${session.sessionId}`;
|
|
41
|
+
const prior = deduped.get(key);
|
|
42
|
+
if (!prior || session.lastModified > prior.lastModified)
|
|
43
|
+
deduped.set(key, session);
|
|
44
|
+
}
|
|
45
|
+
let selected = [...deduped.values()].sort((a, b) => b.lastModified - a.lastModified);
|
|
46
|
+
if (opts.sinceMs && opts.sinceMs > 0) {
|
|
47
|
+
const cutoff = (opts.now ?? Date.now()) - opts.sinceMs;
|
|
48
|
+
selected = selected.filter((session) => session.lastModified >= cutoff);
|
|
49
|
+
}
|
|
50
|
+
if (opts.limit && opts.limit > 0)
|
|
51
|
+
selected = selected.slice(0, opts.limit);
|
|
52
|
+
return selected;
|
|
53
|
+
}
|
|
54
|
+
/** Cheap total for the related-session list. Exact-cwd sessions come from the
|
|
55
|
+
* CLI index; delegated cwd totals come from durable DriveAgent bindings so we
|
|
56
|
+
* do not deep-read every transcript just to decide whether "load more" is
|
|
57
|
+
* needed. A stale binding can only overestimate this hint; loading all then
|
|
58
|
+
* returns the authoritative discovered length. */
|
|
59
|
+
export function countRelatedSessions(cli, cwd, discovery = {}) {
|
|
60
|
+
const root = resolve(cwd);
|
|
61
|
+
const exact = cli === "codex"
|
|
62
|
+
? countCodexSessions(root, discovery.codexHome ?? join(homedir(), ".codex"))
|
|
63
|
+
: countSessions(root, discovery.claudeHome ?? join(homedir(), ".claude"));
|
|
64
|
+
const relatedIds = new Set();
|
|
65
|
+
for (const binding of discovery.bindings ?? externalAgentSessionStore.list()) {
|
|
66
|
+
if (binding.cli !== cli || !isRelatedBinding(binding, root))
|
|
67
|
+
continue;
|
|
68
|
+
if (resolve(binding.cwd) !== root)
|
|
69
|
+
relatedIds.add(binding.sessionId);
|
|
70
|
+
}
|
|
71
|
+
return exact + relatedIds.size;
|
|
72
|
+
}
|
|
73
|
+
function isRelatedBinding(binding, root) {
|
|
74
|
+
return [binding.cwd, binding.workspaceRoot, binding.worktreePath]
|
|
75
|
+
.filter((value) => typeof value === "string" && value.length > 0)
|
|
76
|
+
.some((value) => resolve(value) === root);
|
|
77
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Scheduling decision for a continued external coding-agent run. */
|
|
2
|
+
export interface JudgeDecision {
|
|
3
|
+
action: "continue-same" | "continue-fresh" | "stop";
|
|
4
|
+
handoffSummary?: string;
|
|
5
|
+
reason: string;
|
|
6
|
+
}
|
|
7
|
+
export interface JudgeInput {
|
|
8
|
+
goal?: string;
|
|
9
|
+
lastResult: string;
|
|
10
|
+
nextPrompt: string;
|
|
11
|
+
}
|
|
12
|
+
/** Injected aux-model call: takes a prompt, returns raw text. */
|
|
13
|
+
export type AuxLlm = (prompt: string) => Promise<string>;
|
|
14
|
+
export declare function buildJudgePrompt(input: JudgeInput): string;
|
|
15
|
+
export declare function parseJudgeResponse(raw: string): JudgeDecision;
|
|
16
|
+
export declare function judgeContinuation(input: JudgeInput, llm: AuxLlm): Promise<JudgeDecision>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const SYSTEM = `You decide how a scheduled task loop should continue after one run.
|
|
2
|
+
Reply with ONLY a JSON object: {"action": "continue-same"|"continue-fresh"|"stop", "handoffSummary"?: string, "reason": string}.
|
|
3
|
+
- "stop": the goal is met; no more runs needed.
|
|
4
|
+
- "continue-same": next run should resume the SAME session (work is related, keep context).
|
|
5
|
+
- "continue-fresh": next run should start a FRESH session because the next step is unrelated to what was just done; put a short context summary in handoffSummary.`;
|
|
6
|
+
export function buildJudgePrompt(input) {
|
|
7
|
+
return [
|
|
8
|
+
SYSTEM,
|
|
9
|
+
input.goal ? `\nOverall goal: ${input.goal}` : "",
|
|
10
|
+
`\nWhat the last run produced:\n${input.lastResult.slice(0, 4000)}`,
|
|
11
|
+
`\nThe next scheduled prompt:\n${input.nextPrompt}`,
|
|
12
|
+
`\nDecision JSON:`,
|
|
13
|
+
].join("\n");
|
|
14
|
+
}
|
|
15
|
+
export function parseJudgeResponse(raw) {
|
|
16
|
+
try {
|
|
17
|
+
const m = raw.match(/\{[\s\S]*\}/);
|
|
18
|
+
const d = JSON.parse(m ? m[0] : raw);
|
|
19
|
+
if (d.action === "stop" || d.action === "continue-fresh" || d.action === "continue-same") {
|
|
20
|
+
return {
|
|
21
|
+
action: d.action,
|
|
22
|
+
handoffSummary: typeof d.handoffSummary === "string" ? d.handoffSummary : undefined,
|
|
23
|
+
reason: typeof d.reason === "string" ? d.reason : "",
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
/* fall through */
|
|
29
|
+
}
|
|
30
|
+
return {
|
|
31
|
+
action: "continue-same",
|
|
32
|
+
reason: "unparseable judge output; defaulting to continue-same",
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export async function judgeContinuation(input, llm) {
|
|
36
|
+
const raw = await llm(buildJudgePrompt(input));
|
|
37
|
+
return parseJudgeResponse(raw);
|
|
38
|
+
}
|