@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.
Files changed (134) hide show
  1. package/README.md +69 -0
  2. package/THIRD_PARTY_NOTICES.md +206 -0
  3. package/dist/bin/agent-server-stdio.d.ts +1 -0
  4. package/dist/bin/agent-server-stdio.js +4 -0
  5. package/dist/capability-runtime.d.ts +22 -0
  6. package/dist/capability-runtime.js +88 -0
  7. package/dist/cc-orchestrator/agent-adapter.d.ts +55 -0
  8. package/dist/cc-orchestrator/agent-adapter.js +143 -0
  9. package/dist/cc-orchestrator/cc-capability.d.ts +20 -0
  10. package/dist/cc-orchestrator/cc-capability.js +57 -0
  11. package/dist/cc-orchestrator/codex-session-discovery.d.ts +45 -0
  12. package/dist/cc-orchestrator/codex-session-discovery.js +251 -0
  13. package/dist/cc-orchestrator/codex-session-history.d.ts +39 -0
  14. package/dist/cc-orchestrator/codex-session-history.js +249 -0
  15. package/dist/cc-orchestrator/codex-user-text.d.ts +9 -0
  16. package/dist/cc-orchestrator/codex-user-text.js +25 -0
  17. package/dist/cc-orchestrator/external-agent-bindings.d.ts +27 -0
  18. package/dist/cc-orchestrator/external-agent-bindings.js +150 -0
  19. package/dist/cc-orchestrator/external-agent-changes.d.ts +19 -0
  20. package/dist/cc-orchestrator/external-agent-changes.js +231 -0
  21. package/dist/cc-orchestrator/external-agent-driver.d.ts +19 -0
  22. package/dist/cc-orchestrator/external-agent-driver.js +284 -0
  23. package/dist/cc-orchestrator/external-agent-session-store.d.ts +36 -0
  24. package/dist/cc-orchestrator/external-agent-session-store.js +185 -0
  25. package/dist/cc-orchestrator/index.d.ts +10 -0
  26. package/dist/cc-orchestrator/index.js +10 -0
  27. package/dist/cc-orchestrator/related-session-discovery.d.ts +21 -0
  28. package/dist/cc-orchestrator/related-session-discovery.js +77 -0
  29. package/dist/cc-orchestrator/relevance-judge.d.ts +16 -0
  30. package/dist/cc-orchestrator/relevance-judge.js +38 -0
  31. package/dist/cc-orchestrator/session-discovery.d.ts +99 -0
  32. package/dist/cc-orchestrator/session-discovery.js +295 -0
  33. package/dist/cc-orchestrator/session-history.d.ts +55 -0
  34. package/dist/cc-orchestrator/session-history.js +150 -0
  35. package/dist/external-agents/config.d.ts +3 -0
  36. package/dist/external-agents/config.js +16 -0
  37. package/dist/external-agents/types.d.ts +32 -0
  38. package/dist/external-agents/types.js +1 -0
  39. package/dist/external-runtimes/claude-code/event-translator.d.ts +54 -0
  40. package/dist/external-runtimes/claude-code/event-translator.js +201 -0
  41. package/dist/external-runtimes/claude-code/mcp-config.d.ts +84 -0
  42. package/dist/external-runtimes/claude-code/mcp-config.js +175 -0
  43. package/dist/external-runtimes/claude-code/runtime.d.ts +56 -0
  44. package/dist/external-runtimes/claude-code/runtime.js +168 -0
  45. package/dist/external-runtimes/codex/app-server-client.d.ts +66 -0
  46. package/dist/external-runtimes/codex/app-server-client.js +244 -0
  47. package/dist/external-runtimes/codex/event-translator.d.ts +68 -0
  48. package/dist/external-runtimes/codex/event-translator.js +187 -0
  49. package/dist/external-runtimes/codex/index.d.ts +7 -0
  50. package/dist/external-runtimes/codex/index.js +6 -0
  51. package/dist/external-runtimes/codex/runtime.d.ts +128 -0
  52. package/dist/external-runtimes/codex/runtime.js +216 -0
  53. package/dist/external-runtimes/index.d.ts +37 -0
  54. package/dist/external-runtimes/index.js +27 -0
  55. package/dist/external-runtimes/session-factory.d.ts +97 -0
  56. package/dist/external-runtimes/session-factory.js +110 -0
  57. package/dist/external-runtimes/shared/mcp-bridge.d.ts +66 -0
  58. package/dist/external-runtimes/shared/mcp-bridge.js +365 -0
  59. package/dist/external-runtimes/shared/session-context-store.d.ts +83 -0
  60. package/dist/external-runtimes/shared/session-context-store.js +114 -0
  61. package/dist/external-runtimes/shared/spawn-env.d.ts +30 -0
  62. package/dist/external-runtimes/shared/spawn-env.js +41 -0
  63. package/dist/git/parse-log.d.ts +14 -0
  64. package/dist/git/parse-log.js +21 -0
  65. package/dist/git/utils.d.ts +49 -0
  66. package/dist/git/utils.js +161 -0
  67. package/dist/git/worktree/crud.d.ts +108 -0
  68. package/dist/git/worktree/crud.js +415 -0
  69. package/dist/git/worktree/diff.d.ts +14 -0
  70. package/dist/git/worktree/diff.js +83 -0
  71. package/dist/git/worktree/git-exec.d.ts +7 -0
  72. package/dist/git/worktree/git-exec.js +86 -0
  73. package/dist/git/worktree/index.d.ts +6 -0
  74. package/dist/git/worktree/index.js +6 -0
  75. package/dist/git/worktree/query.d.ts +43 -0
  76. package/dist/git/worktree/query.js +128 -0
  77. package/dist/git/worktree/slug.d.ts +12 -0
  78. package/dist/git/worktree/slug.js +59 -0
  79. package/dist/git/worktree.d.ts +1 -0
  80. package/dist/git/worktree.js +5 -0
  81. package/dist/index.capability.d.ts +7 -0
  82. package/dist/index.capability.js +190 -0
  83. package/dist/index.d.ts +18 -0
  84. package/dist/index.git.d.ts +4 -0
  85. package/dist/index.git.js +4 -0
  86. package/dist/index.js +18 -0
  87. package/dist/index.orchestration.d.ts +7 -0
  88. package/dist/index.orchestration.js +5 -0
  89. package/dist/lsp/client.d.ts +41 -0
  90. package/dist/lsp/client.js +192 -0
  91. package/dist/lsp/manager.d.ts +53 -0
  92. package/dist/lsp/manager.js +248 -0
  93. package/dist/lsp/root-path.d.ts +9 -0
  94. package/dist/lsp/root-path.js +12 -0
  95. package/dist/lsp/servers.d.ts +16 -0
  96. package/dist/lsp/servers.js +60 -0
  97. package/dist/prompt/coding.md +42 -0
  98. package/dist/quota/credentials.d.ts +3 -0
  99. package/dist/quota/credentials.js +80 -0
  100. package/dist/quota/index.d.ts +36 -0
  101. package/dist/quota/index.js +161 -0
  102. package/dist/quota/types.d.ts +48 -0
  103. package/dist/quota/types.js +13 -0
  104. package/dist/review/review-prompt.d.ts +28 -0
  105. package/dist/review/review-prompt.js +81 -0
  106. package/dist/tools/apply-patch/LICENSE-codex +201 -0
  107. package/dist/tools/apply-patch/NOTICE.md +29 -0
  108. package/dist/tools/apply-patch/applier.d.ts +26 -0
  109. package/dist/tools/apply-patch/applier.js +306 -0
  110. package/dist/tools/apply-patch/backup-targets.d.ts +10 -0
  111. package/dist/tools/apply-patch/backup-targets.js +30 -0
  112. package/dist/tools/apply-patch/eol.d.ts +4 -0
  113. package/dist/tools/apply-patch/eol.js +9 -0
  114. package/dist/tools/apply-patch/index.d.ts +20 -0
  115. package/dist/tools/apply-patch/index.js +106 -0
  116. package/dist/tools/apply-patch/parser.d.ts +17 -0
  117. package/dist/tools/apply-patch/parser.js +209 -0
  118. package/dist/tools/apply-patch/seek-sequence.d.ts +18 -0
  119. package/dist/tools/apply-patch/seek-sequence.js +123 -0
  120. package/dist/tools/apply-patch/types.d.ts +49 -0
  121. package/dist/tools/apply-patch/types.js +13 -0
  122. package/dist/tools/brief.d.ts +6 -0
  123. package/dist/tools/brief.js +41 -0
  124. package/dist/tools/check-quota.d.ts +14 -0
  125. package/dist/tools/check-quota.js +38 -0
  126. package/dist/tools/drive-agent.d.ts +52 -0
  127. package/dist/tools/drive-agent.js +1184 -0
  128. package/dist/tools/lsp.d.ts +6 -0
  129. package/dist/tools/lsp.js +220 -0
  130. package/dist/tools/notebook-edit.d.ts +6 -0
  131. package/dist/tools/notebook-edit.js +127 -0
  132. package/dist/tools/worktree.d.ts +10 -0
  133. package/dist/tools/worktree.js +363 -0
  134. package/package.json +60 -0
@@ -0,0 +1,27 @@
1
+ export type ExternalAgentCli = "claude" | "codex";
2
+ export interface ExternalAgentRunBinding {
3
+ cli: ExternalAgentCli;
4
+ externalSessionId: string;
5
+ codeShellSessionId: string;
6
+ cwd: string;
7
+ worktreePath?: string;
8
+ worktreeBranch?: string;
9
+ createdAt: number;
10
+ lastUsedAt: number;
11
+ }
12
+ export declare function externalAgentBindingsPath(home?: string): string;
13
+ export declare class ExternalAgentBindingStore {
14
+ private readonly filePath?;
15
+ constructor(filePath?: string | undefined);
16
+ get(externalSessionId: string): ExternalAgentRunBinding | undefined;
17
+ upsert(next: Omit<ExternalAgentRunBinding, "createdAt" | "lastUsedAt">): ExternalAgentRunBinding;
18
+ private read;
19
+ private write;
20
+ private file;
21
+ }
22
+ export declare function detectExternalAgentWorktree(cwd: string): {
23
+ worktreePath?: string;
24
+ worktreeBranch?: string;
25
+ };
26
+ export declare function externalAgentResumeCwdError(binding: ExternalAgentRunBinding): string | undefined;
27
+ export declare const externalAgentBindingStore: ExternalAgentBindingStore;
@@ -0,0 +1,150 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { execFileSync } from "node:child_process";
4
+ import { codeShellHome, SessionManager } from "@cjhyy/code-shell-core/extension";
5
+ export function externalAgentBindingsPath(home = codeShellHome()) {
6
+ return join(home, "external-agents", "bindings.json");
7
+ }
8
+ export class ExternalAgentBindingStore {
9
+ filePath;
10
+ constructor(filePath) {
11
+ this.filePath = filePath;
12
+ }
13
+ get(externalSessionId) {
14
+ return this.read({ failOnCorrupt: true }).bindings[externalSessionId];
15
+ }
16
+ upsert(next) {
17
+ const data = this.read({ failOnCorrupt: false });
18
+ const existing = data.bindings[next.externalSessionId];
19
+ const now = Date.now();
20
+ const binding = {
21
+ ...next,
22
+ codeShellSessionId: next.codeShellSessionId || existing?.codeShellSessionId || "",
23
+ createdAt: existing?.createdAt ?? now,
24
+ lastUsedAt: now,
25
+ };
26
+ data.bindings[next.externalSessionId] = binding;
27
+ this.write(data);
28
+ return binding;
29
+ }
30
+ read(opts) {
31
+ const file = this.file();
32
+ if (!existsSync(file))
33
+ return { bindings: {} };
34
+ try {
35
+ const parsed = JSON.parse(readFileSync(file, "utf-8"));
36
+ if (parsed && typeof parsed.bindings === "object" && parsed.bindings) {
37
+ return { bindings: parsed.bindings };
38
+ }
39
+ if (opts.failOnCorrupt) {
40
+ throw new Error(`external agent bindings file is corrupt: expected object with bindings`);
41
+ }
42
+ return { bindings: {} };
43
+ }
44
+ catch (err) {
45
+ if (opts.failOnCorrupt) {
46
+ throw new Error(`external agent bindings file is corrupt or unreadable: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
47
+ }
48
+ return { bindings: {} };
49
+ }
50
+ }
51
+ write(data) {
52
+ const file = this.file();
53
+ mkdirSync(dirname(file), { recursive: true });
54
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
55
+ writeFileSync(tmp, JSON.stringify(data, null, 2), "utf-8");
56
+ renameSync(tmp, file);
57
+ }
58
+ file() {
59
+ return this.filePath ?? externalAgentBindingsPath();
60
+ }
61
+ }
62
+ export function detectExternalAgentWorktree(cwd) {
63
+ if (!existsSync(cwd))
64
+ return {};
65
+ try {
66
+ const root = git(cwd, ["rev-parse", "--show-toplevel"]);
67
+ const branch = git(root, ["branch", "--show-current"]);
68
+ const entries = parseWorktreeList(git(root, ["worktree", "list", "--porcelain"]));
69
+ const current = entries.find((entry) => resolve(entry.path) === resolve(root));
70
+ const main = entries[0];
71
+ if (!current || !branch || !main || resolve(current.path) === resolve(main.path))
72
+ return {};
73
+ return { worktreePath: root, worktreeBranch: branch };
74
+ }
75
+ catch {
76
+ return {};
77
+ }
78
+ }
79
+ export function externalAgentResumeCwdError(binding) {
80
+ if (existsSync(binding.cwd))
81
+ return undefined;
82
+ const branch = binding.worktreeBranch;
83
+ if (branch && branchExistsForBinding(binding)) {
84
+ return (`Error: external ${binding.cli} session ${binding.externalSessionId} is bound to cwd ` +
85
+ `${binding.cwd}, but that directory no longer exists. Worktree branch ${branch} still ` +
86
+ `exists; recreate the worktree at ${binding.worktreePath ?? binding.cwd} before resuming.`);
87
+ }
88
+ return (`Error: external ${binding.cli} session ${binding.externalSessionId} is bound to cwd ` +
89
+ `${binding.cwd}, but the workspace deleted${branch ? ` and branch ${branch} is gone` : ""}. ` +
90
+ `Start a new external session.`);
91
+ }
92
+ function branchExistsForBinding(binding) {
93
+ if (!binding.worktreeBranch)
94
+ return false;
95
+ for (const cwd of candidateGitCwds(binding)) {
96
+ if (!cwd || !existsSync(cwd))
97
+ continue;
98
+ try {
99
+ const out = git(cwd, ["branch", "--list", binding.worktreeBranch]);
100
+ if (out.length > 0)
101
+ return true;
102
+ }
103
+ catch {
104
+ // Try the next candidate.
105
+ }
106
+ }
107
+ return false;
108
+ }
109
+ function candidateGitCwds(binding) {
110
+ const candidates = new Set();
111
+ if (existsSync(binding.cwd))
112
+ candidates.add(binding.cwd);
113
+ if (binding.codeShellSessionId) {
114
+ const sessionCwd = new SessionManager().readSessionMainRoot(binding.codeShellSessionId);
115
+ if (sessionCwd)
116
+ candidates.add(sessionCwd);
117
+ }
118
+ candidates.add(process.cwd());
119
+ candidates.add(dirname(binding.cwd));
120
+ candidates.add(dirname(dirname(binding.cwd)));
121
+ return [...candidates];
122
+ }
123
+ function parseWorktreeList(raw) {
124
+ if (!raw.trim())
125
+ return [];
126
+ const entries = [];
127
+ let current = { path: "", branch: "" };
128
+ for (const line of raw.split("\n")) {
129
+ if (line.startsWith("worktree ")) {
130
+ if (current.path)
131
+ entries.push(current);
132
+ current = { path: line.slice(9), branch: "" };
133
+ }
134
+ else if (line.startsWith("branch ")) {
135
+ current.branch = line.slice(7).replace("refs/heads/", "");
136
+ }
137
+ }
138
+ if (current.path)
139
+ entries.push(current);
140
+ return entries;
141
+ }
142
+ function git(cwd, args) {
143
+ return execFileSync("git", args, {
144
+ cwd,
145
+ encoding: "utf-8",
146
+ timeout: 10000,
147
+ stdio: ["ignore", "pipe", "ignore"],
148
+ }).trim();
149
+ }
150
+ export const externalAgentBindingStore = new ExternalAgentBindingStore();
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Parse claude transcript JSONL text → deduped list of changed file paths.
3
+ * Each line is `{ message: { content: [{ type:"tool_use", name, input }] } }`.
4
+ * Exported for direct unit testing without a transcript file on disk.
5
+ */
6
+ export declare function extractChangedFilesFromClaudeLines(text: string): string[];
7
+ /** Locate `<claudeHome>/projects/<encodeCwd(cwd)>/<sid>.jsonl` and extract changes. */
8
+ export declare function readClaudeChangedFiles(cwd: string, sessionId: string, claudeHome?: string): string[];
9
+ /**
10
+ * Parse codex rollout JSONL text → changed file paths. Codex tool calls are
11
+ * `{type:"response_item", payload:{type:"function_call", name, arguments}}` or
12
+ * `{...custom_tool_call, input}`. apply_patch carries the patch text; write/edit
13
+ * carry a file path in arguments. Exported for unit testing.
14
+ */
15
+ export declare function extractChangedFilesFromCodexLines(text: string): string[];
16
+ /** Locate a codex rollout by threadId+cwd under `<codexHome>/sessions` and extract changes. */
17
+ export declare function readCodexChangedFiles(cwd: string, threadId: string, codexHome?: string): string[];
18
+ /** Dispatch by CLI. Unknown cli → []. Never throws. */
19
+ export declare function readExternalChangedFiles(cli: string, cwd: string, sessionId: string): string[];
@@ -0,0 +1,231 @@
1
+ import { readFileSync, existsSync, readdirSync, statSync, openSync, readSync, closeSync, } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { homedir } from "node:os";
4
+ import { encodeCwd } from "./session-discovery.js";
5
+ import { logger } from "@cjhyy/code-shell-core/extension";
6
+ /**
7
+ * #6 — attribute file changes made by a background external agent (DriveAgent
8
+ * running `claude` / `codex`). Those Edit/Write calls land in the external CLI's
9
+ * own transcript, invisible to the host's in-session file-change aggregator.
10
+ * Given the external session id + cwd, locate that transcript and extract the
11
+ * set of changed files, so the UI can show "N files edited" for the run.
12
+ *
13
+ * Read-only; tolerant — a malformed line is skipped, a missing transcript
14
+ * returns []. Never throws for the caller.
15
+ */
16
+ const CLAUDE_WRITE_TOOLS = new Set(["Write", "Edit", "MultiEdit", "NotebookEdit"]);
17
+ const CODEX_WRITE_TOOLS = new Set(["apply_patch", "ApplyPatch", "write_file", "edit_file"]);
18
+ /** Pull the changed-file path out of a claude tool_use input block. */
19
+ function claudeInputPath(input) {
20
+ if (!input || typeof input !== "object")
21
+ return undefined;
22
+ const o = input;
23
+ const p = o.file_path ?? o.notebook_path;
24
+ return typeof p === "string" && p.length > 0 ? p : undefined;
25
+ }
26
+ /**
27
+ * Parse claude transcript JSONL text → deduped list of changed file paths.
28
+ * Each line is `{ message: { content: [{ type:"tool_use", name, input }] } }`.
29
+ * Exported for direct unit testing without a transcript file on disk.
30
+ */
31
+ export function extractChangedFilesFromClaudeLines(text) {
32
+ const seen = new Set();
33
+ for (const line of text.split("\n")) {
34
+ if (!line.trim())
35
+ continue;
36
+ let d;
37
+ try {
38
+ d = JSON.parse(line);
39
+ }
40
+ catch {
41
+ continue;
42
+ }
43
+ const content = d?.message?.content;
44
+ if (!Array.isArray(content))
45
+ continue;
46
+ for (const block of content) {
47
+ if (block &&
48
+ typeof block === "object" &&
49
+ block.type === "tool_use" &&
50
+ CLAUDE_WRITE_TOOLS.has(block.name ?? "")) {
51
+ const p = claudeInputPath(block.input);
52
+ if (p)
53
+ seen.add(p);
54
+ }
55
+ }
56
+ }
57
+ return [...seen];
58
+ }
59
+ /** Locate `<claudeHome>/projects/<encodeCwd(cwd)>/<sid>.jsonl` and extract changes. */
60
+ export function readClaudeChangedFiles(cwd, sessionId, claudeHome = join(homedir(), ".claude")) {
61
+ const file = join(claudeHome, "projects", encodeCwd(cwd), `${sessionId}.jsonl`);
62
+ if (!existsSync(file))
63
+ return [];
64
+ let text;
65
+ try {
66
+ text = readFileSync(file, "utf-8");
67
+ }
68
+ catch {
69
+ return [];
70
+ }
71
+ return extractChangedFilesFromClaudeLines(text);
72
+ }
73
+ /**
74
+ * Parse codex rollout JSONL text → changed file paths. Codex tool calls are
75
+ * `{type:"response_item", payload:{type:"function_call", name, arguments}}` or
76
+ * `{...custom_tool_call, input}`. apply_patch carries the patch text; write/edit
77
+ * carry a file path in arguments. Exported for unit testing.
78
+ */
79
+ export function extractChangedFilesFromCodexLines(text) {
80
+ const seen = new Set();
81
+ for (const line of text.split("\n")) {
82
+ if (!line.trim())
83
+ continue;
84
+ let d;
85
+ try {
86
+ d = JSON.parse(line);
87
+ }
88
+ catch {
89
+ continue;
90
+ }
91
+ if (d?.type !== "response_item" || !d.payload)
92
+ continue;
93
+ const p = d.payload;
94
+ const name = typeof p.name === "string" ? p.name : "";
95
+ if (!CODEX_WRITE_TOOLS.has(name))
96
+ continue;
97
+ // function_call.arguments is a JSON string; custom_tool_call.input a string.
98
+ const rawArgs = typeof p.arguments === "string" ? p.arguments : typeof p.input === "string" ? p.input : "";
99
+ for (const f of filesFromCodexArgs(name, rawArgs))
100
+ seen.add(f);
101
+ }
102
+ return [...seen];
103
+ }
104
+ /** Pull file paths out of a codex tool's arguments string. */
105
+ function filesFromCodexArgs(name, raw) {
106
+ if (!raw)
107
+ return [];
108
+ if (name === "apply_patch" || name === "ApplyPatch") {
109
+ // apply_patch payload wraps a patch; headers look like `*** Update File: <p>`
110
+ // or `*** Add File: <p>`. Match those directly off the raw text.
111
+ const out = [];
112
+ const re = /\*\*\*\s+(?:Update|Add|Delete) File:\s+(.+)/g;
113
+ let m;
114
+ while ((m = re.exec(raw)) !== null) {
115
+ const f = m[1]?.trim();
116
+ if (f)
117
+ out.push(f);
118
+ }
119
+ return out;
120
+ }
121
+ try {
122
+ const a = JSON.parse(raw);
123
+ const p = a.file_path ?? a.path;
124
+ return typeof p === "string" && p ? [p] : [];
125
+ }
126
+ catch {
127
+ return [];
128
+ }
129
+ }
130
+ /** Locate a codex rollout by threadId+cwd under `<codexHome>/sessions` and extract changes. */
131
+ export function readCodexChangedFiles(cwd, threadId, codexHome = join(homedir(), ".codex")) {
132
+ const file = findRolloutFile(codexHome, cwd, threadId);
133
+ if (!file)
134
+ return [];
135
+ let text;
136
+ try {
137
+ text = readFileSync(file, "utf-8");
138
+ }
139
+ catch {
140
+ return [];
141
+ }
142
+ return extractChangedFilesFromCodexLines(text);
143
+ }
144
+ /** Dispatch by CLI. Unknown cli → []. Never throws. */
145
+ export function readExternalChangedFiles(cli, cwd, sessionId) {
146
+ try {
147
+ const files = cli === "codex"
148
+ ? readCodexChangedFiles(cwd, sessionId)
149
+ : readClaudeChangedFiles(cwd, sessionId);
150
+ logger.debug("changed_files.external.extracted", {
151
+ cat: "changed_files",
152
+ cli,
153
+ cwd,
154
+ externalSessionId: sessionId,
155
+ size: files.length,
156
+ files,
157
+ });
158
+ return files;
159
+ }
160
+ catch (err) {
161
+ logger.debug("changed_files.external.extract_failed", {
162
+ cat: "changed_files",
163
+ cli,
164
+ cwd,
165
+ externalSessionId: sessionId,
166
+ error: err instanceof Error ? err.message : String(err),
167
+ });
168
+ return [];
169
+ }
170
+ }
171
+ // ── codex rollout location (mirrors codex-session-history.ts) ──────────────
172
+ function findRolloutFile(codexHome, cwd, threadId) {
173
+ const root = join(codexHome, "sessions");
174
+ if (!existsSync(root))
175
+ return undefined;
176
+ for (const file of walkRollouts(root)) {
177
+ let meta;
178
+ try {
179
+ meta = readSessionMeta(file);
180
+ }
181
+ catch {
182
+ continue;
183
+ }
184
+ if (meta && meta.id === threadId && meta.cwd === cwd)
185
+ return file;
186
+ }
187
+ return undefined;
188
+ }
189
+ function* walkRollouts(root) {
190
+ let entries;
191
+ try {
192
+ entries = readdirSync(root);
193
+ }
194
+ catch {
195
+ return;
196
+ }
197
+ for (const name of entries) {
198
+ const full = join(root, name);
199
+ let st;
200
+ try {
201
+ st = statSync(full);
202
+ }
203
+ catch {
204
+ continue;
205
+ }
206
+ if (st.isDirectory())
207
+ yield* walkRollouts(full);
208
+ else if (name.startsWith("rollout-") && name.endsWith(".jsonl"))
209
+ yield full;
210
+ }
211
+ }
212
+ function readSessionMeta(file, maxBytes = 1 << 16) {
213
+ const fd = openSync(file, "r");
214
+ let text;
215
+ try {
216
+ const buf = Buffer.alloc(maxBytes);
217
+ const n = readSync(fd, buf, 0, maxBytes, 0);
218
+ text = buf.toString("utf-8", 0, n);
219
+ }
220
+ finally {
221
+ closeSync(fd);
222
+ }
223
+ const nl = text.indexOf("\n");
224
+ const first = (nl === -1 ? text : text.slice(0, nl)).trim();
225
+ if (!first)
226
+ return undefined;
227
+ const d = JSON.parse(first);
228
+ if (d.type !== "session_meta" || !d.payload)
229
+ return undefined;
230
+ return { id: d.payload.id, cwd: d.payload.cwd };
231
+ }
@@ -0,0 +1,19 @@
1
+ import type { AgentAdapter, BuildArgsOpts, PermissionMode } from "./agent-adapter.js";
2
+ export interface AgentRunResult {
3
+ sessionId: string;
4
+ finalText: string;
5
+ isError: boolean;
6
+ exitCode: number | null;
7
+ lines: string[];
8
+ }
9
+ /** Pure: reduce collected output lines + exit code to a result. Unit-testable. */
10
+ export declare function runWithLines(adapter: AgentAdapter, lines: string[], exitCode: number | null): AgentRunResult;
11
+ export interface DriverRunOpts extends Omit<BuildArgsOpts, "permissionMode"> {
12
+ permissionMode?: PermissionMode;
13
+ }
14
+ export declare function detectCodexImageInput(command: string, cwd: string, signal?: AbortSignal): Promise<boolean>;
15
+ /** Spawn ONE headless agent run, collect stream-json to exit, return result.
16
+ * No time concept — a single turn. Honors AbortSignal (kills the child). */
17
+ export declare function runAgentOnce(adapter: AgentAdapter, opts: DriverRunOpts & {
18
+ command: string;
19
+ }, signal?: AbortSignal): Promise<AgentRunResult>;