@cjhyy/code-shell-core 0.6.0-rc.13 → 0.6.0-rc.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/capability-control/service.d.ts +2 -0
  2. package/dist/capability-control/service.js +4 -2
  3. package/dist/cc-orchestrator/codex-session-history.js +1 -1
  4. package/dist/cc-orchestrator/external-agent-bindings.js +1 -1
  5. package/dist/cc-orchestrator/external-agent-session-store.js +3 -1
  6. package/dist/cc-orchestrator/session-history.js +2 -2
  7. package/dist/cli/agent-server-stdio.js +7 -2
  8. package/dist/context/compaction.d.ts +8 -1
  9. package/dist/context/compaction.js +49 -4
  10. package/dist/context/manager.d.ts +11 -2
  11. package/dist/context/manager.js +64 -3
  12. package/dist/credentials/inject-credential-tool.d.ts +3 -1
  13. package/dist/credentials/inject-credential-tool.js +29 -10
  14. package/dist/credentials/use-credential-tool.d.ts +1 -0
  15. package/dist/credentials/use-credential-tool.js +3 -0
  16. package/dist/engine/engine.d.ts +9 -0
  17. package/dist/engine/engine.js +96 -17
  18. package/dist/engine/turn-loop.d.ts +3 -1
  19. package/dist/engine/turn-loop.js +4 -2
  20. package/dist/engine/types.d.ts +8 -0
  21. package/dist/git/worktree/crud.d.ts +69 -0
  22. package/dist/git/worktree/crud.js +206 -0
  23. package/dist/git/worktree/diff.d.ts +14 -0
  24. package/dist/git/worktree/diff.js +82 -0
  25. package/dist/git/worktree/git-exec.d.ts +7 -0
  26. package/dist/git/worktree/git-exec.js +51 -0
  27. package/dist/git/worktree/index.d.ts +5 -0
  28. package/dist/git/worktree/index.js +5 -0
  29. package/dist/git/worktree/query.d.ts +42 -0
  30. package/dist/git/worktree/query.js +121 -0
  31. package/dist/git/worktree/slug.d.ts +11 -0
  32. package/dist/git/worktree/slug.js +58 -0
  33. package/dist/git/worktree.d.ts +1 -127
  34. package/dist/git/worktree.js +5 -464
  35. package/dist/index.d.ts +28 -27
  36. package/dist/index.js +24 -24
  37. package/dist/plugins/installer/checkUpdate.d.ts +4 -1
  38. package/dist/plugins/installer/checkUpdate.js +4 -2
  39. package/dist/plugins/installer/install.js +2 -0
  40. package/dist/plugins/installer/parseSource.d.ts +4 -1
  41. package/dist/plugins/installer/parseSource.js +28 -10
  42. package/dist/plugins/installer/update.d.ts +4 -1
  43. package/dist/plugins/installer/update.js +5 -3
  44. package/dist/plugins/parseMarketplaceInput.d.ts +4 -1
  45. package/dist/plugins/parseMarketplaceInput.js +4 -3
  46. package/dist/preset/index.d.ts +1 -0
  47. package/dist/preset/index.js +6 -0
  48. package/dist/prompt/sections/base.md +1 -1
  49. package/dist/protocol/chat-session-manager.js +7 -0
  50. package/dist/protocol/server.d.ts +10 -0
  51. package/dist/protocol/server.js +88 -4
  52. package/dist/protocol/types.d.ts +6 -0
  53. package/dist/protocol/types.js +2 -0
  54. package/dist/runtime/background-shell.js +2 -3
  55. package/dist/services/auto-dream.d.ts +15 -4
  56. package/dist/services/auto-dream.js +20 -20
  57. package/dist/services/dream-consolidation.d.ts +2 -3
  58. package/dist/services/dream-consolidation.js +65 -15
  59. package/dist/services/extract-memories.d.ts +14 -5
  60. package/dist/services/extract-memories.js +20 -3
  61. package/dist/services/global-dream-promotion.d.ts +23 -0
  62. package/dist/services/global-dream-promotion.js +112 -0
  63. package/dist/services/memory-orchestrator.js +347 -34
  64. package/dist/session/memory.d.ts +56 -17
  65. package/dist/session/memory.js +337 -78
  66. package/dist/session/session-manager.d.ts +1 -1
  67. package/dist/session/session-manager.js +6 -6
  68. package/dist/session/transcript.d.ts +1 -1
  69. package/dist/session/transcript.js +17 -5
  70. package/dist/settings/manager.js +43 -12
  71. package/dist/settings/schema.d.ts +21 -0
  72. package/dist/settings/schema.js +12 -0
  73. package/dist/tool-system/builtin/index.js +18 -8
  74. package/dist/tool-system/builtin/memory.js +40 -8
  75. package/dist/tool-system/builtin/view-image.d.ts +2 -2
  76. package/dist/tool-system/builtin/view-image.js +100 -19
  77. package/dist/tool-system/builtin/worktree.d.ts +2 -0
  78. package/dist/tool-system/builtin/worktree.js +59 -11
  79. package/dist/tool-system/context.d.ts +11 -1
  80. package/dist/tool-system/mcp-manager.d.ts +8 -5
  81. package/dist/tool-system/mcp-manager.js +85 -55
  82. package/dist/tool-system/path-policy.d.ts +2 -0
  83. package/dist/tool-system/path-policy.js +28 -12
  84. package/dist/tool-system/workspace-bridge.d.ts +11 -0
  85. package/dist/tool-system/workspace-bridge.js +1 -0
  86. package/dist/types.d.ts +14 -0
  87. package/package.json +1 -1
@@ -1,464 +1,5 @@
1
- /**
2
- * Git worktree management create/remove isolated worktrees for agents.
3
- */
4
- import { execFileSync } from "node:child_process";
5
- import { existsSync, symlinkSync, lstatSync } from "node:fs";
6
- import { join, resolve, dirname } from "node:path";
7
- import { safeSpawnShell } from "../runtime/safe-spawn.js";
8
- import { buildSandboxEnv, mergeShellEnv, defaultShellBinary } from "../runtime/spawn-common.js";
9
- import { resolveExecutable } from "../utils/exec.js";
10
- // git resolved via PATH×PATHEXT on Windows (.cmd/.exe shim); no-op on POSIX.
11
- const GIT_BIN = resolveExecutable("git");
12
- /**
13
- * Pick the setup/cleanup script for the running platform, falling back to
14
- * `default`. Empty/whitespace-only scripts are treated as absent so a project
15
- * can leave a platform key blank without spawning an empty shell. `platform`
16
- * defaults to `process.platform` so callers usually omit it; tests pass a
17
- * fixed value.
18
- */
19
- export function selectPlatformScript(scripts, platform = process.platform) {
20
- if (!scripts)
21
- return undefined;
22
- const key = platform === "darwin" ? "macos" : platform === "win32" ? "windows" : "linux";
23
- // A blank platform key shouldn't shadow a real `default` — fall through.
24
- const platformScript = scripts[key]?.trim() ? scripts[key] : undefined;
25
- const candidate = platformScript ?? scripts.default;
26
- const trimmed = candidate?.trim();
27
- return trimmed ? candidate : undefined;
28
- }
29
- /**
30
- * Validate worktree slug to prevent path traversal attacks.
31
- */
32
- export function validateWorktreeSlug(slug) {
33
- if (slug.trim().length === 0)
34
- throw new Error("Worktree slug cannot be empty");
35
- if (slug.length > 64)
36
- throw new Error("Worktree slug too long (max 64 chars)");
37
- if (/[^a-zA-Z0-9._-]/.test(slug))
38
- throw new Error("Worktree slug contains invalid characters");
39
- if (slug.startsWith(".") || slug.includes(".."))
40
- throw new Error("Worktree slug cannot start with '.' or contain '..'");
41
- }
42
- /**
43
- * Find the canonical git root (resolves worktree → main repo).
44
- */
45
- export function findGitRoot(cwd) {
46
- return findMainWorktreeRoot(cwd);
47
- }
48
- export function findMainWorktreeRoot(cwd) {
49
- const commonDir = execFileSync(GIT_BIN, ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
50
- cwd,
51
- encoding: "utf-8",
52
- timeout: 5000,
53
- }).trim();
54
- return dirname(commonDir);
55
- }
56
- export function findWorktreeForBranch(cwd, branch) {
57
- const normalized = normalizeBranchName(branch);
58
- return listWorktrees(cwd).find((entry) => entry.branch === normalized)?.path;
59
- }
60
- export function assertBranchNotCheckedOut(cwd, branch) {
61
- const existingPath = findWorktreeForBranch(cwd, branch);
62
- if (existingPath) {
63
- throw new Error(`branch ${normalizeBranchName(branch)} already checked out at ${existingPath}`);
64
- }
65
- }
66
- export function branchExists(cwd, branch) {
67
- try {
68
- return (execFileSync(GIT_BIN, ["branch", "--list", normalizeBranchName(branch)], {
69
- cwd,
70
- encoding: "utf-8",
71
- timeout: 10000,
72
- }).trim().length > 0);
73
- }
74
- catch {
75
- return false;
76
- }
77
- }
78
- export function isGitWorktreeRoot(cwd) {
79
- if (!existsSync(join(cwd, ".git")))
80
- return false;
81
- try {
82
- const inside = execFileSync(GIT_BIN, ["rev-parse", "--is-inside-work-tree"], {
83
- cwd,
84
- encoding: "utf-8",
85
- timeout: 5000,
86
- }).trim();
87
- if (inside !== "true")
88
- return false;
89
- const topLevel = execFileSync(GIT_BIN, ["rev-parse", "--path-format=absolute", "--show-toplevel"], {
90
- cwd,
91
- encoding: "utf-8",
92
- timeout: 5000,
93
- }).trim();
94
- return resolve(topLevel) === resolve(cwd);
95
- }
96
- catch {
97
- return false;
98
- }
99
- }
100
- export function currentBranch(cwd) {
101
- try {
102
- const branch = execFileSync(GIT_BIN, ["branch", "--show-current"], {
103
- cwd,
104
- encoding: "utf-8",
105
- timeout: 5000,
106
- }).trim();
107
- return branch || undefined;
108
- }
109
- catch {
110
- return undefined;
111
- }
112
- }
113
- /**
114
- * Create an isolated git worktree for an agent session.
115
- */
116
- export function createWorktree(cwd, slug, sessionId) {
117
- validateWorktreeSlug(slug);
118
- const gitRoot = findGitRoot(cwd);
119
- const branchName = `worktree/${slug}-${sessionId.slice(0, 8)}`;
120
- const worktreePath = resolve(gitRoot, "..", `.worktrees/${slug}-${sessionId.slice(0, 8)}`);
121
- assertBranchNotCheckedOut(gitRoot, branchName);
122
- // Get current branch for later reference
123
- let originalBranch;
124
- try {
125
- originalBranch = execFileSync(GIT_BIN, ["branch", "--show-current"], {
126
- cwd: gitRoot,
127
- encoding: "utf-8",
128
- timeout: 5000,
129
- }).trim();
130
- }
131
- catch {
132
- // Detached HEAD
133
- }
134
- // Create the worktree. Pre-fix this used a quoted command string; the argv
135
- // form keeps branchName/worktreePath as literal positional arguments even
136
- // if a future caller bypasses validateWorktreeSlug.
137
- execFileSync(GIT_BIN, ["worktree", "add", "-b", branchName, worktreePath], {
138
- cwd: gitRoot,
139
- timeout: 30000,
140
- });
141
- // Symlink large directories to avoid disk bloat
142
- symlinkLargeDirectories(gitRoot, worktreePath);
143
- return {
144
- originalCwd: cwd,
145
- worktreePath,
146
- worktreeName: slug,
147
- worktreeBranch: branchName,
148
- originalBranch,
149
- sessionId,
150
- createdAt: Date.now(),
151
- };
152
- }
153
- /**
154
- * Run a project's `localEnvironment.setupScripts` once, in the freshly-created
155
- * worktree's root, right after `git worktree add`. This mirrors Codex's
156
- * local-environment semantics: setup belongs to the *worktree* lifecycle, not
157
- * the conversation — it runs when the isolated copy is born so e.g. `bun
158
- * install` or `cp .env.example .env` happens before the agent works there.
159
- *
160
- * Failure is non-fatal by design (Beta decision 2026-06-08, "警告但继续"): a
161
- * broken setup script shouldn't strand the agent outside a worktree it already
162
- * created. The caller surfaces `output` as a warning and proceeds. cleanup
163
- * scripts are intentionally NOT auto-run on exit (same decision).
164
- *
165
- * Reuses the same sandbox + env primitives as the Bash tool so the setup
166
- * command sees the project's `localEnvironment.env` and runs under the same
167
- * isolation the agent's later commands will.
168
- */
169
- export async function runWorktreeSetup(worktreePath, script, opts = {}) {
170
- const trimmed = script?.trim();
171
- if (!trimmed)
172
- return { skipped: true, ok: true, output: "" };
173
- const shell = defaultShellBinary();
174
- const backend = opts.sandbox;
175
- const baseEnv = backend && backend.name !== "off" ? buildSandboxEnv() : { ...process.env };
176
- const env = mergeShellEnv(baseEnv, opts.shellEnv);
177
- const result = await safeSpawnShell(trimmed, {
178
- cwd: worktreePath,
179
- env,
180
- timeoutMs: opts.timeoutMs ?? 120_000,
181
- maxOutputBytes: 1024 * 1024,
182
- sandbox: backend,
183
- shell,
184
- signal: opts.signal,
185
- });
186
- const parts = [];
187
- if (result.stdout)
188
- parts.push(result.stdout);
189
- if (result.stderr)
190
- parts.push(result.stderr);
191
- const output = parts.join("\n").trim();
192
- if (result.aborted)
193
- return { skipped: false, ok: false, output: output || "setup aborted" };
194
- if (result.timedOut)
195
- return { skipped: false, ok: false, output: output || "setup timed out" };
196
- if (result.spawnFailed) {
197
- return { skipped: false, ok: false, output: result.error ?? "failed to spawn setup script" };
198
- }
199
- return { skipped: false, ok: result.exitCode === 0, output, exitCode: result.exitCode };
200
- }
201
- /**
202
- * Remove a worktree and optionally its branch.
203
- */
204
- export function removeWorktree(worktreePath, removeBranch = false) {
205
- // The MAIN repo root, not the worktree's own toplevel. `git rev-parse
206
- // --show-toplevel` from inside a worktree returns the worktree path, which
207
- // is about to be deleted; the branch-delete must run from the main repo,
208
- // which outlives the worktree. Derive it from the common git dir.
209
- let mainRoot;
210
- try {
211
- const commonDir = execFileSync(GIT_BIN, ["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: worktreePath, encoding: "utf-8", timeout: 5000 }).trim();
212
- mainRoot = dirname(commonDir); // <main>/.git → <main>
213
- }
214
- catch (err) {
215
- throw new Error(`failed to inspect worktree ${worktreePath}: ${gitErrorMessage(err)}`);
216
- }
217
- // Capture the worktree's branch BEFORE removing the worktree — afterwards
218
- // the directory is gone and `git branch --show-current` in it would fail.
219
- let branch = "";
220
- if (removeBranch) {
221
- try {
222
- branch = execFileSync(GIT_BIN, ["branch", "--show-current"], {
223
- cwd: worktreePath,
224
- encoding: "utf-8",
225
- timeout: 5000,
226
- }).trim();
227
- }
228
- catch (err) {
229
- throw new Error(`failed to determine branch for worktree ${worktreePath}: ${gitErrorMessage(err)}`);
230
- }
231
- if (!branch) {
232
- throw new Error(`failed to determine branch for worktree ${worktreePath}`);
233
- }
234
- if (!branch.startsWith("worktree/")) {
235
- throw new Error(`refusing to delete non-CodeShell worktree branch ${branch}`);
236
- }
237
- }
238
- try {
239
- execFileSync(GIT_BIN, ["worktree", "remove", worktreePath, "--force"], {
240
- cwd: mainRoot,
241
- timeout: 30000,
242
- });
243
- }
244
- catch (err) {
245
- throw new Error(`failed to remove worktree ${worktreePath}: ${gitErrorMessage(err)}`);
246
- }
247
- if (removeBranch) {
248
- try {
249
- execFileSync(GIT_BIN, ["branch", "-D", branch], { cwd: mainRoot, timeout: 10000 });
250
- }
251
- catch (err) {
252
- return {
253
- dirRemoved: true,
254
- branch,
255
- branchDeleted: false,
256
- branchError: gitErrorMessage(err),
257
- };
258
- }
259
- }
260
- return removeBranch ? { dirRemoved: true, branch, branchDeleted: true } : { dirRemoved: true };
261
- }
262
- export function worktreeHasUncommittedChanges(worktreePath) {
263
- try {
264
- return (execFileSync(GIT_BIN, ["status", "--porcelain"], {
265
- cwd: worktreePath,
266
- encoding: "utf-8",
267
- timeout: 10000,
268
- }).trim().length > 0);
269
- }
270
- catch {
271
- return false;
272
- }
273
- }
274
- export function worktreeHasUncommittedOrAheadChanges(worktreePath, baseRef) {
275
- if (worktreeHasUncommittedChanges(worktreePath))
276
- return true;
277
- const comparisonBase = baseRef && commitRefExists(worktreePath, baseRef)
278
- ? baseRef
279
- : findComparisonBaseRef(worktreePath);
280
- return comparisonBase ? aheadCommitCount(worktreePath, comparisonBase) > 0 : false;
281
- }
282
- /**
283
- * List active worktrees.
284
- */
285
- export function listWorktrees(cwd, opts = {}) {
286
- const raw = execFileSync(GIT_BIN, ["worktree", "list", "--porcelain"], {
287
- cwd,
288
- encoding: "utf-8",
289
- timeout: 10000,
290
- }).trim();
291
- if (!raw)
292
- return [];
293
- const entries = [];
294
- let current = { path: "", branch: "", head: "" };
295
- for (const line of raw.split("\n")) {
296
- if (line.startsWith("worktree ")) {
297
- if (current.path)
298
- entries.push(current);
299
- current = { path: line.slice(9), branch: "", head: "" };
300
- }
301
- else if (line.startsWith("HEAD ")) {
302
- current.head = line.slice(5, 13);
303
- }
304
- else if (line.startsWith("branch ")) {
305
- current.branch = line.slice(7).replace("refs/heads/", "");
306
- }
307
- }
308
- if (current.path)
309
- entries.push(current);
310
- if (!opts.includeDiffSummary && !opts.workspaceOwners?.length)
311
- return entries;
312
- let mainRoot = "";
313
- try {
314
- mainRoot = findMainWorktreeRoot(cwd);
315
- }
316
- catch {
317
- mainRoot = entries[0]?.path ?? "";
318
- }
319
- const baseRef = opts.includeDiffSummary ? findComparisonBaseRef(mainRoot || cwd) : undefined;
320
- return entries.map((entry) => {
321
- const owners = ownersForWorktree(entry.path, opts.workspaceOwners ?? []);
322
- return {
323
- ...entry,
324
- ...(mainRoot ? { isMain: resolve(entry.path) === resolve(mainRoot) } : {}),
325
- ...(opts.includeDiffSummary ? { diff: diffSummary(entry.path, baseRef) } : {}),
326
- ...(owners.length > 0
327
- ? {
328
- occupiedBySessionIds: owners,
329
- occupiedByOtherSession: owners.some((id) => id !== opts.currentSessionId),
330
- }
331
- : {}),
332
- };
333
- });
334
- }
335
- function ownersForWorktree(path, owners) {
336
- const target = resolve(path);
337
- return owners
338
- .filter((owner) => {
339
- const workspace = owner.workspace;
340
- if (!workspace)
341
- return false;
342
- return resolve(workspace.root) === target;
343
- })
344
- .map((owner) => owner.sessionId);
345
- }
346
- function findComparisonBaseRef(cwd) {
347
- for (const ref of ["main", "master", "origin/main", "origin/master"]) {
348
- if (commitRefExists(cwd, ref))
349
- return ref;
350
- }
351
- return undefined;
352
- }
353
- function commitRefExists(cwd, ref) {
354
- try {
355
- execFileSync(GIT_BIN, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
356
- cwd,
357
- encoding: "utf-8",
358
- timeout: 5000,
359
- });
360
- return true;
361
- }
362
- catch {
363
- return false;
364
- }
365
- }
366
- function diffSummary(cwd, baseRef) {
367
- const dirtyFiles = statusFileSet(cwd);
368
- const committedFiles = baseRef ? changedFilesSinceBase(cwd, baseRef) : new Set();
369
- const changedFiles = new Set([...dirtyFiles, ...committedFiles]);
370
- return {
371
- ...(baseRef ? { baseRef } : {}),
372
- changedFiles: changedFiles.size,
373
- aheadCommits: baseRef ? aheadCommitCount(cwd, baseRef) : 0,
374
- hasUncommittedChanges: dirtyFiles.size > 0,
375
- };
376
- }
377
- function changedFilesSinceBase(cwd, baseRef) {
378
- const out = gitOutput(cwd, ["diff", "--name-only", `${baseRef}...HEAD`]);
379
- const raw = out ?? gitOutput(cwd, ["diff", "--name-only", `${baseRef}..HEAD`]) ?? "";
380
- return new Set(raw
381
- .split("\n")
382
- .map((line) => line.trim())
383
- .filter(Boolean));
384
- }
385
- function aheadCommitCount(cwd, baseRef) {
386
- const out = gitOutput(cwd, ["rev-list", "--count", `${baseRef}..HEAD`]);
387
- const n = Number.parseInt(out?.trim() ?? "0", 10);
388
- return Number.isFinite(n) ? n : 0;
389
- }
390
- function statusFileSet(cwd) {
391
- const raw = gitOutput(cwd, ["status", "--porcelain=v1"]) ?? "";
392
- const files = new Set();
393
- for (const line of raw.split("\n")) {
394
- if (!line.trim())
395
- continue;
396
- const path = line.slice(3).trim();
397
- if (!path)
398
- continue;
399
- const renameTarget = path.includes(" -> ") ? path.split(" -> ").at(-1) : path;
400
- if (renameTarget)
401
- files.add(unquoteGitPath(renameTarget));
402
- }
403
- return files;
404
- }
405
- function unquoteGitPath(path) {
406
- if (!path.startsWith('"') || !path.endsWith('"'))
407
- return path;
408
- try {
409
- return JSON.parse(path);
410
- }
411
- catch {
412
- return path.slice(1, -1);
413
- }
414
- }
415
- function gitOutput(cwd, args) {
416
- try {
417
- return execFileSync(GIT_BIN, args, {
418
- cwd,
419
- encoding: "utf-8",
420
- timeout: 10000,
421
- });
422
- }
423
- catch {
424
- return undefined;
425
- }
426
- }
427
- function gitErrorMessage(err) {
428
- const stderr = err.stderr;
429
- if (Buffer.isBuffer(stderr)) {
430
- const msg = stderr.toString("utf-8").trim();
431
- if (msg)
432
- return msg;
433
- }
434
- if (typeof stderr === "string" && stderr.trim())
435
- return stderr.trim();
436
- return err instanceof Error ? err.message : String(err);
437
- }
438
- function normalizeBranchName(branch) {
439
- return branch.replace(/^refs\/heads\//, "");
440
- }
441
- /**
442
- * Symlink large directories (node_modules, .venv, etc.) from main repo to worktree.
443
- */
444
- function symlinkLargeDirectories(sourceRoot, worktreePath) {
445
- const largeDirs = ["node_modules", ".venv", "vendor", ".pnpm-store"];
446
- // Windows directory symlinks need admin/Developer Mode and throw EPERM for a
447
- // normal user; NTFS junctions don't and behave the same for our purpose
448
- // (share node_modules into the worktree). Use "junction" on win32, "dir"
449
- // elsewhere. Failure stays non-fatal — the worktree just doesn't share dirs.
450
- const linkType = process.platform === "win32" ? "junction" : "dir";
451
- for (const dir of largeDirs) {
452
- const source = join(sourceRoot, dir);
453
- const target = join(worktreePath, dir);
454
- if (existsSync(source) && lstatSync(source).isDirectory() && !existsSync(target)) {
455
- try {
456
- symlinkSync(source, target, linkType);
457
- }
458
- catch {
459
- // Symlink/junction might fail on some systems — non-fatal, the
460
- // worktree just won't share this directory (more disk, still works).
461
- }
462
- }
463
- }
464
- }
1
+ // Compatibility barrel for the pre-split worktree module. The split made the
2
+ // query/create APIs async because they now share the async git executor; all
3
+ // in-repo callers await them, so this barrel intentionally does not add sync
4
+ // wrappers.
5
+ export * from "./worktree/index.js";
package/dist/index.d.ts CHANGED
@@ -3,15 +3,15 @@
3
3
  *
4
4
  * Public API exports.
5
5
  */
6
- export declare const VERSION = "0.6.0-rc.13";
7
- export type { Message, ContentBlock, ToolDefinition, ToolCall, ToolResult, RegisteredTool, TranscriptEvent, TranscriptEventType, SessionState, SessionWorkspace, SessionStatus, TokenUsage, CompiledInput, PermissionDecision, PermissionMode, PermissionRule, TurnPhase, TurnResult, TerminalReason, StreamEvent, StreamCallback, LLMConfig, ClientDefaults, LLMResponse, Settings, MCPServerConfig, } from "./types.js";
6
+ export declare const VERSION = "0.6.0-rc.15";
7
+ export type { Message, ContentBlock, ToolDefinition, ToolCall, ToolResult, RegisteredTool, TranscriptEvent, TranscriptEventType, SessionState, SessionWorkspace, ContextUsageAnchor, SessionStatus, TokenUsage, CompiledInput, PermissionDecision, PermissionMode, PermissionRule, TurnPhase, TurnResult, TerminalReason, StreamEvent, StreamCallback, LLMConfig, ClientDefaults, LLMResponse, Settings, MCPServerConfig, } from "./types.js";
8
8
  export { FrameworkError, LLMError, LLMRateLimitError, ContextLimitError, ToolError, ToolNotFoundError, ToolExecutionError, ToolTimeoutError, PermissionDeniedError, SessionError, TranscriptError, ConfigError, SandboxUnavailableError, } from "./exceptions.js";
9
9
  export { Engine, loadAgentDefinitionsForCwd } from "./engine/engine.js";
10
10
  export type { EngineConfig, EngineHookConfig, EngineResult } from "./engine/types.js";
11
11
  export { resolveLLMConfigForTag } from "./engine/resolve-llm-config.js";
12
12
  export { resolveAuxKey } from "./engine/aux-key.js";
13
13
  export { parseAgentDefinition, serializeAgentDefinition, type AgentDefinition, } from "./agent/agent-definition.js";
14
- export { AgentDefinitionRegistry, type AgentSourceDir, } from "./agent/agent-definition-registry.js";
14
+ export { AgentDefinitionRegistry, type AgentSourceDir } from "./agent/agent-definition-registry.js";
15
15
  export type { CostStateStore, CostStateSnapshot } from "./engine/cost-store.js";
16
16
  export { EngineRuntime } from "./engine/runtime.js";
17
17
  export type { EngineRuntimeOptions } from "./engine/runtime.js";
@@ -25,7 +25,7 @@ export { ModelPool, type ModelEntry } from "./llm/model-pool.js";
25
25
  export { modelEntriesFromConnections } from "./engine/model-connections-pool.js";
26
26
  export { ToolRegistry } from "./tool-system/registry.js";
27
27
  export { ToolExecutor } from "./tool-system/executor.js";
28
- export { PermissionClassifier, HeadlessApprovalBackend, AutoApprovalBackend } from "./tool-system/permission.js";
28
+ export { PermissionClassifier, HeadlessApprovalBackend, AutoApprovalBackend, } from "./tool-system/permission.js";
29
29
  export type { ApprovalBackend } from "./tool-system/permission.js";
30
30
  export { BUILTIN_TOOLS } from "./tool-system/builtin/index.js";
31
31
  export type { BuiltinTool, BuiltinToolFn } from "./tool-system/builtin/index.js";
@@ -38,18 +38,18 @@ export type { HookEventName, HookContext, HookResult } from "./hooks/events.js";
38
38
  export { wrapHookMessages } from "./hooks/inject.js";
39
39
  export { AgentServer, type AgentServerOptions } from "./protocol/server.js";
40
40
  export { AgentClient, type BackgroundAgentCompletedHandler } from "./protocol/client.js";
41
- export { createInProcessTransport, StdioTransport, type Transport, } from "./protocol/transport.js";
42
- export { SocketTransport, listenTcp, type TcpListenResult, } from "./protocol/tcp-transport.js";
41
+ export { createInProcessTransport, StdioTransport, type Transport } from "./protocol/transport.js";
42
+ export { SocketTransport, listenTcp, type TcpListenResult } from "./protocol/tcp-transport.js";
43
43
  export { createServer, createClient, type CreateServerOptions, type CreateClientOptions, type ServerHandle, } from "./protocol/factories.js";
44
- export { Methods, ErrorCodes, type RpcMessage, type RunResult, } from "./protocol/types.js";
44
+ export { Methods, ErrorCodes, type RpcMessage, type RunResult } from "./protocol/types.js";
45
45
  export { Transcript } from "./session/transcript.js";
46
46
  export { SessionManager } from "./session/session-manager.js";
47
47
  export { FileHistory } from "./session/file-history.js";
48
- export { createWorktree, currentBranch, findMainWorktreeRoot, listWorktrees, removeWorktree, validateWorktreeSlug, worktreeHasUncommittedOrAheadChanges, worktreeHasUncommittedChanges, type ListWorktreesOptions, type RemoveWorktreeResult, type WorktreeDiffSummary, type WorktreeInfo, type WorktreeWorkspaceOwner, } from "./git/worktree.js";
48
+ export { createWorktree, currentBranch, DEFAULT_WORKTREE_BRANCH_PREFIX, getWorktreeDiff, isManagedWorktreeBranch, isValidWorktreeBranchPrefix, findMainWorktreeRoot, listWorktrees, listWorktreesFast, normalizeWorktreeBranchPrefix, removeWorktree, validateWorktreeSlug, worktreeHasUncommittedOrAheadChanges, worktreeHasUncommittedChanges, type CreateWorktreeOptions, type ListWorktreesOptions, type ListWorktreesFastOptions, type RemoveWorktreeResult, type RemoveWorktreeOptions, type WorktreeDiffSummary, type WorktreeInfo, type WorktreeWorkspaceOwner, } from "./git/worktree.js";
49
49
  export { latestUndoTarget, earliestSnapshotsPerFile, latestTurnUndoTargets, latestRedoTargets, } from "./session/undo-target.js";
50
50
  export { diffLines, renderDiffPreview, type DiffLine } from "./session/simple-diff.js";
51
51
  export { MemoryManager } from "./session/memory.js";
52
- export type { MemoryEntry, MemoryScope } from "./session/memory.js";
52
+ export type { MemoryEntry, MemoryOrigin, MemoryScope } from "./session/memory.js";
53
53
  export { runDreamConsolidation, type DreamConsolidationInput, type DreamConsolidationResult, } from "./services/dream-consolidation.js";
54
54
  export type { FileSnapshot, RedoRecord } from "./session/file-history.js";
55
55
  export { PromptComposer } from "./prompt/composer.js";
@@ -57,7 +57,7 @@ export { SectionCache } from "./prompt/section-cache.js";
57
57
  export { scanInstructions, combineInstructions } from "./prompt/instruction-scanner.js";
58
58
  export { BUILTIN_AGENT_PRESETS, DEFAULT_AGENT_PRESET, DEFAULT_CLI_PRESET, resolveAgentPreset, resolveBuiltinToolNames, buildPresetSystemPrompt, registerPreset, listPresetNames, } from "./preset/index.js";
59
59
  export type { AgentPreset, AgentPresetName } from "./preset/index.js";
60
- export { loadSection, loadSections, availableSections, registerSection } from "./prompt/section-loader.js";
60
+ export { loadSection, loadSections, availableSections, registerSection, } from "./prompt/section-loader.js";
61
61
  export { ContextManager } from "./context/manager.js";
62
62
  export { estimateTokens, microcompact, windowCompact, truncateToolResult, buildSummarizationPrompt, applySummaryCompaction, COMPACTABLE_TOOL_NAMES, } from "./context/compaction.js";
63
63
  export type { MicrocompactOptions } from "./context/compaction.js";
@@ -76,7 +76,7 @@ export { installPluginFromSource } from "./plugins/installer/installFromSource.j
76
76
  export { installLocalPlugin, installPluginFromArchive, } from "./plugins/installer/installFromArchive.js";
77
77
  export { parseSource, type ParsedSource } from "./plugins/installer/parseSource.js";
78
78
  export { detectPluginFormat } from "./plugins/installer/detectFormat.js";
79
- export { CodexPluginManifest, CSMeta, PluginInstallError, } from "./plugins/installer/types.js";
79
+ export { CodexPluginManifest, CSMeta, PluginInstallError } from "./plugins/installer/types.js";
80
80
  export { mergePluginMcpServers } from "./plugins/installer/loadPluginMcp.js";
81
81
  export { listPluginHooks, pluginHookKey, type PluginHookEntry } from "./plugins/loadPluginHooks.js";
82
82
  export { describePluginContent, type PluginContentInventory } from "./plugins/pluginContent.js";
@@ -90,14 +90,14 @@ export { Arena } from "./arena/arena.js";
90
90
  export { MODEL_PRESETS, getMaxOutputTokens } from "./arena/model-presets.js";
91
91
  export type { ModelPreset } from "./arena/model-presets.js";
92
92
  export { detectArenaMode } from "./arena/detect-mode.js";
93
- export { getStrategy, getStrategyForPlan, ReviewStrategy, DiscussionStrategy, PlanningStrategy } from "./arena/strategies/index.js";
93
+ export { getStrategy, getStrategyForPlan, ReviewStrategy, DiscussionStrategy, PlanningStrategy, } from "./arena/strategies/index.js";
94
94
  export { planArena } from "./arena/planner.js";
95
95
  export { collectEvidence } from "./arena/providers/index.js";
96
96
  export { selectTools, hasTools } from "./arena/tools/selector.js";
97
97
  export { ArenaLedger } from "./arena/ledger.js";
98
98
  export { registerClaims, selectClaimsForReview } from "./arena/phases/claim-registry.js";
99
99
  export { buildDigest, formatDigest } from "./arena/digest-builder.js";
100
- export { transitionClaim, resolveClaimStatus, markUnderReview, applyReviewResult, markUnresolved, isTerminal, validTransitions } from "./arena/transitions.js";
100
+ export { transitionClaim, resolveClaimStatus, markUnderReview, applyReviewResult, markUnresolved, isTerminal, validTransitions, } from "./arena/transitions.js";
101
101
  export type { ArenaConfig, ArenaMode, ArenaResultV2, ArenaStrategy, ArenaParticipant, ArenaBaseContext, ArenaFinding, FindingReview, ParticipantReport, ArenaConsensus, ArenaConsensusItem, ArenaRoadmapPhase, ArenaProgressEvent, ArenaPlan, ArenaLens, ArenaLensName, ArenaSourceKind, ArenaArtifact, ArenaQuickFact, FindingKind, PeerVerdict, ToolTrace, EvidencePacket, FindingEvidenceLink, ResearchDossier, ClaimStatus, ClaimRecord, ClaimChallenge, ClaimAdjudication, RequestedCheck, DebateRound, DebateTurn, TargetedCheckTask, SharedResearchLedger, RoundResearchDigest, ArenaExecutionLimits, } from "./arena/types.js";
102
102
  export { IterativeArena, defaultIterateConvergence, iterateDiffRatio, iterateCodeFormat, iterateDocumentFormat, getIterateFormat, } from "./arena/index.js";
103
103
  export type { IterateConfig, IterateResult, IterateSubject, IterateFormat, IterateProgressEvent, IterateFormatPack, Draft, DraftCandidate, Critique, CritiqueCategory, CritiqueEvidence, CritiqueSeverity, ConvergenceSignal, Round, AuthorRotation, StoppedReason, CheckpointFn, CheckpointContext, CheckpointAction, } from "./arena/index.js";
@@ -126,7 +126,7 @@ export { startCapturingEarlyInput, stopCapturingEarlyInput, consumeEarlyInput, h
126
126
  export { formatBytes, formatToolArgs, singleLine, MAX_LINE_WIDTH, TOOL_DOT_COLORS, } from "./utils/toolDisplay.js";
127
127
  export { classifyBashLines, type BashLineKind, type ClassifiedBashLine, } from "./tool-system/builtin/bash-output-style.js";
128
128
  export { formatDuration, formatTokens } from "./utils/format.js";
129
- export { getTheme, type Theme, type ThemeName, type ThemeSetting, } from "./utils/theme.js";
129
+ export { getTheme, type Theme, type ThemeName, type ThemeSetting } from "./utils/theme.js";
130
130
  export { resolveThemeSetting, type SystemTheme } from "./utils/systemTheme.js";
131
131
  /** @internal Host-lifecycle logging hooks for the in-repo TUI/desktop hosts; not stable SDK surface. */
132
132
  export { rotateLogs } from "./logging/logger.js";
@@ -144,7 +144,7 @@ export { buildReviewPrompt, parseDimensions, ALL_DIMENSIONS, type ReviewDimensio
144
144
  * primary Engine/Protocol API above.
145
145
  */
146
146
  export { getInteractiveApprovalBackend } from "./tool-system/permission.js";
147
- export { defaultSandboxConfig, type SandboxConfig, } from "./tool-system/sandbox/index.js";
147
+ export { defaultSandboxConfig, type SandboxConfig } from "./tool-system/sandbox/index.js";
148
148
  export { buildNotificationMessage, buildNotificationSummary, notificationQueue, agentNotificationBus, notificationItemToStreamEvent, type NotificationItem, } from "./tool-system/builtin/agent-notifications.js";
149
149
  export type { BackgroundAgentCompletedEvent } from "./types.js";
150
150
  export { startAutomation, type StartAutomationDeps, type AutomationHandle, CronScheduler, cronScheduler, type CronJob, type CronPermissionLevel, type CreateJobOptions, type UpdateJobPatch, CronStore, defaultCronStorePath, bindCronToEngine, bindCronToRunManager, type CronRunner, type CronRunRequest, type CronRunResult, type RunSubmitter, isCronExpression, parseCronExpression, nextCronTime, type ParsedCron, resolveWritePolicy, wrapUntrustedInput, type WritePolicy, runWriteJobInWorktree, type WriteJobGitOps, type RunWriteJobInput, type RunWriteJobResult, } from "./automation/index.js";
@@ -152,7 +152,7 @@ export * from "./cc-orchestrator/index.js";
152
152
  export { checkQuota, formatQuota } from "./quota/index.js";
153
153
  export { resolveQuotaCredentials } from "./quota/credentials.js";
154
154
  export type { QuotaResult, ProviderQuota, QuotaWindow, QuotaCredentials } from "./quota/types.js";
155
- export { asyncAgentRegistry, type AsyncAgentEntry, } from "./tool-system/builtin/agent-registry.js";
155
+ export { asyncAgentRegistry, type AsyncAgentEntry } from "./tool-system/builtin/agent-registry.js";
156
156
  export { backgroundShellManager, BackgroundShellManager, type BgShell, type BgShellStatus, } from "./runtime/background-shell.js";
157
157
  export { ENV_DENY_REGEX, ENV_ALLOWLIST } from "./runtime/spawn-common.js";
158
158
  export { getImageProvider, DEFAULT_IMAGE_MODEL, type ImageProvider, type ImageProviderCreds, type ImageGenerateRequest, type ImageGenerateResult, } from "./tool-system/builtin/image-providers.js";
@@ -165,23 +165,24 @@ export type { ProtocolModelEntry } from "./protocol/types.js";
165
165
  /** @internal Extended Arena surface for the in-repo TUI/desktop hosts; not stable SDK surface. */
166
166
  export { formatArenaResult, printArenaResult, renderProgress, createProgressRenderer, type OutputSink, } from "./arena/render/terminal.js";
167
167
  export { formatArenaResultForSession } from "./arena/render/session.js";
168
- export { installPlugin, uninstallPlugin, listInstalled, } from "./plugins/pluginInstaller.js";
168
+ export { installPlugin, uninstallPlugin, listInstalled } from "./plugins/pluginInstaller.js";
169
169
  export { addMarketplace, refreshMarketplace, removeMarketplace, listMarketplaces, loadMarketplace, } from "./plugins/marketplaceManager.js";
170
- export { parseMarketplaceInput, deriveMarketplaceName, } from "./plugins/parseMarketplaceInput.js";
171
- export { scanPluginCommands, type PluginCommand, } from "./plugins/pluginCommandsLoader.js";
170
+ export { parseMarketplaceInput, deriveMarketplaceName } from "./plugins/parseMarketplaceInput.js";
171
+ export { scanPluginCommands, type PluginCommand } from "./plugins/pluginCommandsLoader.js";
172
172
  /** @internal Extended LLM surface for the in-repo TUI/desktop hosts; not stable SDK surface. */
173
- export { type CachedModel, defaultCacheDir, } from "./llm/model-cache.js";
174
- export { fetchModelList, type FetchResult, } from "./llm/model-fetcher.js";
175
- export { sanitizeApiKey, hasNonAsciiPrintable, } from "./llm/api-key-sanitize.js";
176
- export { PROVIDER_KINDS, type ProviderKindName, } from "./llm/provider-kinds.js";
177
- export { capabilitiesFor, type Capability, } from "./llm/capabilities/index.js";
173
+ export { type CachedModel, defaultCacheDir } from "./llm/model-cache.js";
174
+ export { fetchModelList, type FetchResult } from "./llm/model-fetcher.js";
175
+ export { sanitizeApiKey, hasNonAsciiPrintable } from "./llm/api-key-sanitize.js";
176
+ export { PROVIDER_KINDS, type ProviderKindName } from "./llm/provider-kinds.js";
177
+ export { capabilitiesFor, type Capability } from "./llm/capabilities/index.js";
178
178
  export { reasoningControlFor, type ReasoningControl, } from "./llm/capabilities/reasoning-control.js";
179
- export { REASONING_EFFORTS, type ReasoningSetting, } from "./llm/reasoning-setting.js";
179
+ export { REASONING_EFFORTS, type ReasoningSetting } from "./llm/reasoning-setting.js";
180
180
  export { type ProviderConfig } from "./llm/provider-catalog.js";
181
- export { syncOpenRouterCatalog, getOpenRouterSnapshot, } from "./data/openrouter-sync.js";
181
+ export { syncOpenRouterCatalog, getOpenRouterSnapshot } from "./data/openrouter-sync.js";
182
182
  /** @internal Extended type surface for the in-repo TUI/desktop hosts; not stable SDK surface. */
183
- export type { ApprovalRequest, ApprovalResult, ApprovalScope, TaskInfo, } from "./types.js";
183
+ export type { ApprovalRequest, ApprovalResult, ApprovalScope, TaskInfo } from "./types.js";
184
184
  export { resolveExternalAgentConfig } from "./external-agents/config.js";
185
185
  export type { ExternalAgentMode, ExternalAgentsSettings, ResolvedExternalAgentsConfig, ResolvedClaudeCodeSettings, ResolvedCodexSettings, } from "./external-agents/types.js";
186
186
  export { flattenAxTree, renderElementList, cleanPageText, CONTENT_CHAR_CAP, buildExtractLinksScript, EXTRACT_LINK_CAP, } from "./tool-system/browser-bridge.js";
187
187
  export type { BrowserBridge, BrowserElement, BrowserSnapshot, BrowserResult, BrowserContent, BrowserExtract, BrowserLink, BrowserImage, BrowserVideo, BrowserImageData, BrowserTab, AXNode, } from "./tool-system/browser-bridge.js";
188
+ export type { WorkspaceBridge } from "./tool-system/workspace-bridge.js";