coding-agents-sdk 0.13.0 → 0.14.1

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 (61) hide show
  1. package/README.md +19 -2
  2. package/dist/Agent-YQZmTatB.mjs +4 -0
  3. package/dist/{SdkAgent-p0nJ6dWV.mjs → SdkAgent-Dv3I0OW2.mjs} +1 -1
  4. package/dist/adapters/claude-code-cli/index.d.mts +1 -1
  5. package/dist/adapters/claude-code-cli/index.mjs +1 -1
  6. package/dist/adapters/claude-code-cli-pty/index.d.mts +2 -2
  7. package/dist/adapters/claude-code-cli-pty/index.mjs +5 -5
  8. package/dist/adapters/claude-code-sdk/index.d.mts +1 -1
  9. package/dist/adapters/claude-code-sdk/index.mjs +4 -4
  10. package/dist/adapters/codex-cli/index.d.mts +1 -1
  11. package/dist/adapters/codex-cli/index.mjs +2 -2
  12. package/dist/adapters/codex-sdk/index.d.mts +1 -1
  13. package/dist/adapters/codex-sdk/index.mjs +1 -1
  14. package/dist/adapters/cursor-cli/index.d.mts +2 -2
  15. package/dist/adapters/cursor-cli/index.mjs +1 -1
  16. package/dist/adapters/cursor-sdk/index.d.mts +2 -2
  17. package/dist/adapters/cursor-sdk/index.mjs +1 -1
  18. package/dist/adapters/gemini-cli/index.d.mts +1 -1
  19. package/dist/adapters/gemini-cli/index.mjs +1 -1
  20. package/dist/adapters/opencode-cli/index.d.mts +1 -1
  21. package/dist/adapters/opencode-cli/index.mjs +1 -1
  22. package/dist/adapters/pi-cli/index.d.mts +1 -1
  23. package/dist/adapters/pi-cli/index.mjs +1 -1
  24. package/dist/{classify-error-BPQtzEVV.mjs → classify-error-UZrj89Yi.mjs} +3 -3
  25. package/dist/container/index.d.mts +2 -2
  26. package/dist/container/index.mjs +1 -1
  27. package/dist/{container-46QA1d3v.mjs → container-B3SrSQYp.mjs} +1 -1
  28. package/dist/{container-DBXaA-Iv.mjs → container-B5suwmUQ.mjs} +1 -1
  29. package/dist/{container-DRj7xq5x.mjs → container-BH5So6E_.mjs} +1 -1
  30. package/dist/{container-gJ8B-Z5B.mjs → container-BPllAKd8.mjs} +1 -1
  31. package/dist/{container-Dg68bfte.mjs → container-DQzVZjLd.mjs} +1 -1
  32. package/dist/diff-Bh8JPwVM.mjs +1 -0
  33. package/dist/{events-B0BpIsW2.d.mts → events-BxEB6zHt.d.mts} +7 -10
  34. package/dist/{index-C9XD71QR.d.mts → index-BQwDFirP.d.mts} +2 -25
  35. package/dist/{index-CG2m7pFJ.d.mts → index-BXgvYZSv.d.mts} +10 -1
  36. package/dist/{index-DdyD2ji1.d.mts → index-CGGPY1qE.d.mts} +3 -2
  37. package/dist/{index-BKK-3gye.d.mts → index-CSfb-Q3A.d.mts} +29 -16
  38. package/dist/{index-BQ8cUo2i.d.mts → index-CSty5NNW.d.mts} +39 -29
  39. package/dist/{index-B5NFoNlS.d.mts → index-C_WwuF3E.d.mts} +3 -4
  40. package/dist/{index-XWqpUSBc.d.mts → index-Cxegh1Rs.d.mts} +27 -17
  41. package/dist/{index-DPP4zoiJ.d.mts → index-D1IlwEGE.d.mts} +23 -14
  42. package/dist/{index-B9ze9hTN.d.mts → index-Dm9HCmWK.d.mts} +3 -2
  43. package/dist/{index-CG5DS_NB.d.mts → index-TzOW2t1h.d.mts} +20 -12
  44. package/dist/{index-DzFF15zC.d.mts → index-f1x-Ugwa.d.mts} +26 -16
  45. package/dist/{index-5bx9TIY_.d.mts → index-tmvnx5wp.d.mts} +22 -13
  46. package/dist/index.d.mts +16 -15
  47. package/dist/index.mjs +1 -1
  48. package/dist/{oci-DmEG3Ia3.mjs → oci-C5y_whHx.mjs} +1 -1
  49. package/dist/{parser-DNYBLV_4.mjs → parser-CTagqQyR.mjs} +2 -2
  50. package/dist/sandbox/index.d.mts +2 -2
  51. package/dist/sandbox/index.mjs +1 -1
  52. package/dist/{sandbox-C5vzNxZR.mjs → sandbox-DQWTg5YL.mjs} +1 -1
  53. package/dist/schemas/index.d.mts +2 -2
  54. package/dist/spawner-BE2hAC0w.mjs +1 -0
  55. package/dist/structured-output-Bfzi3RU4.mjs +1 -0
  56. package/dist/{types-CGzSzwfB.d.mts → types-CeIQCAFV.d.mts} +24 -9
  57. package/package.json +29 -16
  58. package/dist/Agent-4TZ8JK66.mjs +0 -4
  59. package/dist/diff-BJWXJsjx.mjs +0 -1
  60. package/dist/spawner-BB6W3FVi.mjs +0 -1
  61. package/dist/structured-output-DsMPRckW.mjs +0 -1
@@ -1,6 +1,5 @@
1
- import { t as AgentEvent, v as AgentCapabilities, x as JsonSchema, y as ContentPart } from "./events-B0BpIsW2.mjs";
1
+ import { t as AgentEvent, v as AgentCapabilities, x as JsonSchema, y as ContentPart } from "./events-BxEB6zHt.mjs";
2
2
  import { ZodType } from "zod/v4";
3
-
4
3
  //#region src/core/process/types.d.ts
5
4
  type StdioOption = "ignore" | "inherit" | "pipe" | number;
6
5
  /** POSIX signal name (re-export of `NodeJS.Signals`). */
@@ -41,7 +40,6 @@ interface AgentProcess {
41
40
  write?: (chunk: Uint8Array | string) => void;
42
41
  end: () => void;
43
42
  } | null;
44
- /** Send a signal to the process. Defaults to `"SIGTERM"`. Idempotent after exit. */
45
43
  kill: (signal?: ProcessSignal | number) => void;
46
44
  /** Resolve with the {@link ProcessResult} once the process exits. */
47
45
  wait: () => Promise<ProcessResult>;
@@ -92,10 +90,14 @@ interface PermissionRequest {
92
90
  * model as the rejection reason.
93
91
  */
94
92
  type PermissionDecision = {
95
- /** Approve the tool call. */decision: "allow"; /** Optional rewritten tool input; overrides {@link PermissionRequest.input}. */
93
+ /** Approve the tool call. */
94
+ decision: "allow";
95
+ /** Optional rewritten tool input; overrides {@link PermissionRequest.input}. */
96
96
  updatedInput?: Record<string, unknown>;
97
97
  } | {
98
- /** Reject the tool call. */decision: "deny"; /** Rejection reason sent back to the model. */
98
+ /** Reject the tool call. */
99
+ decision: "deny";
100
+ /** Rejection reason sent back to the model. */
99
101
  message?: string;
100
102
  };
101
103
  /**
@@ -136,6 +138,17 @@ type StopReason = "abort" | "timeout" | "user";
136
138
  * optional because providers differ — Claude reports caching tokens, Codex
137
139
  * reports reasoning tokens, others may report nothing beyond `turns` and
138
140
  * `costUsd`.
141
+ *
142
+ * The token classes are disjoint: a token counted in `inputTokens` is never also counted in
143
+ * `cacheCreationInputTokens` or `cacheReadInputTokens`, so
144
+ * `inputTokens + cacheCreationInputTokens + cacheReadInputTokens + outputTokens` equals
145
+ * `totalTokens` for every adapter that reports them. Providers disagree upstream — Anthropic bills
146
+ * the cache classes separately from `input_tokens` while OpenAI nests them inside it — so adapters
147
+ * normalize to this layout rather than passing provider fields through.
148
+ *
149
+ * `reasoningOutputTokens` is the one exception: it is a breakdown of `outputTokens` rather than a
150
+ * class of its own, so it is already counted in both `outputTokens` and `totalTokens` and must not
151
+ * be added to either.
139
152
  */
140
153
  interface RunStats {
141
154
  /** Wall-clock duration of the run as reported by the provider, in milliseconds. */
@@ -146,7 +159,7 @@ interface RunStats {
146
159
  turns: number;
147
160
  /** Provider-reported cost in USD; `0` if the provider does not report cost. */
148
161
  costUsd: number;
149
- /** Input tokens billed (excluding cache-hit tokens, when distinguished). */
162
+ /** Input tokens billed at the full rate, excluding both cache-read and cache-write tokens. */
150
163
  inputTokens?: number;
151
164
  /** Tokens written to the provider's prompt cache during this run. */
152
165
  cacheCreationInputTokens?: number;
@@ -154,7 +167,9 @@ interface RunStats {
154
167
  cacheReadInputTokens?: number;
155
168
  /** Output tokens generated by the model. */
156
169
  outputTokens?: number;
157
- /** Sum of all token classes for convenience; provider definitions vary. */
170
+ /** Reasoning/thinking tokens spent producing the output; already included in `outputTokens`. */
171
+ reasoningOutputTokens?: number;
172
+ /** Sum of the disjoint token classes above. */
158
173
  totalTokens?: number;
159
174
  }
160
175
  /**
@@ -352,7 +367,7 @@ interface AgentMetrics {
352
367
  /** Timestamp of the most recent emitted event (not updated on plain method calls like `reset`/`dispose`). */
353
368
  lastActivityAt: Date;
354
369
  }
355
- type EffectiveKeys<T> = keyof { [K in keyof T as Required<T>[K] extends never ? never : K]: unknown };
370
+ type EffectiveKeys<T> = keyof { [K in keyof T as Required<T>[K] extends never ? never : K]: unknown; };
356
371
  /**
357
372
  * Compile-time assertion that an adapter's `*RunOptions` shape does not
358
373
  * collide with the keys of {@link RunRequest}. Resolves to `T` when disjoint,
@@ -473,4 +488,4 @@ interface BaseAgent<TRunOptions extends object = {}> {
473
488
  onPermissionRequest: (handler: PermissionHandler) => () => void;
474
489
  }
475
490
  //#endregion
476
- export { ProcessSpawner as A, RunTiming as C, PermissionDecision as D, ZodRunRequest as E, PermissionHandler as O, RunStatus as S, StructuredRunRequest as T, RunProcessInfo as _, AgentValidationError as a, RunResultBase as b, AnyRunResult as c, CompletedRunResult as d, EnsureDisjoint as f, RunError as g, JsonSchemaRunRequest as h, AgentType as i, PermissionRequest as k, BaseAgent as l, FailedRunResult as m, AgentMetrics as n, AnyCompletedRunResult as o, ExclusiveExecutionTargetOptions as p, AgentRunError as r, AnyRunRequest as s, AgentEventHandler as t, CancelledRunResult as u, RunRequest as v, StopReason as w, RunStats as x, RunResult as y };
491
+ export { StopReason as C, PermissionHandler as D, PermissionDecision as E, PermissionRequest as O, RunTiming as S, ZodRunRequest as T, RunProcessInfo as _, AgentValidationError as a, RunStats as b, AnyRunResult as c, CompletedRunResult as d, EnsureDisjoint as f, RunError as g, JsonSchemaRunRequest as h, AgentType as i, ProcessSpawner as k, BaseAgent as l, FailedRunResult as m, AgentMetrics as n, AnyCompletedRunResult as o, ExclusiveExecutionTargetOptions as p, AgentRunError as r, AnyRunRequest as s, AgentEventHandler as t, CancelledRunResult as u, RunRequest as v, StructuredRunRequest as w, RunStatus as x, RunResult as y };
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "coding-agents-sdk",
3
- "version": "0.13.0",
3
+ "version": "0.14.1",
4
+ "description": "Run coding agents (Claude Code, Codex, Cursor, Gemini, OpenCode, Pi — CLI and SDK) behind one uniform TypeScript interface, with optional container and sandbox execution.",
5
+ "keywords": [
6
+ "coding-agent",
7
+ "ai-agent",
8
+ "claude-code",
9
+ "codex",
10
+ "cursor",
11
+ "gemini",
12
+ "opencode",
13
+ "sandbox",
14
+ "container",
15
+ "agent-sdk"
16
+ ],
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/3rd/coding-agents-sdk.git"
20
+ },
4
21
  "type": "module",
5
22
  "types": "./dist/index.d.mts",
6
23
  "exports": {
@@ -89,24 +106,23 @@
89
106
  "typecheck": "bun run tsc"
90
107
  },
91
108
  "devDependencies": {
92
- "@anthropic-ai/claude-agent-sdk": "^0.3.170",
93
- "@cursor/sdk": "^1.0.18",
94
- "@openai/codex-sdk": "^0.139.0",
109
+ "@anthropic-ai/claude-agent-sdk": "^0.3.226",
110
+ "@cursor/sdk": "^1.0.27",
111
+ "@openai/codex-sdk": "^0.147.0",
95
112
  "@types/bun": "^1.3.14",
96
- "@types/node": "^25.9.2",
97
- "e2b": "^2.28.2",
98
- "knip": "^6.16.1",
99
- "picoprint": "^2.0.0",
100
- "tsdown": "^0.22.2",
101
- "@opencode-ai/sdk": "^1.17.7"
113
+ "@types/node": "^26.2.0",
114
+ "e2b": "^2.38.3",
115
+ "knip": "^6.32.1",
116
+ "picoprint": "^2.2.2",
117
+ "tsdown": "^0.22.14",
118
+ "typescript": "^7.0.2"
102
119
  },
103
120
  "peerDependencies": {
104
121
  "@anthropic-ai/claude-agent-sdk": "^0.3.170",
105
122
  "@cursor/sdk": "^1.0.12",
106
- "@openai/codex-sdk": "^0.139.0",
123
+ "@openai/codex-sdk": "^0.145.0",
107
124
  "e2b": "^2.19.4",
108
- "typescript": "^6.0.3",
109
- "@opencode-ai/sdk": "^1.17.7"
125
+ "typescript": "^6.0.3 || ^7.0.0"
110
126
  },
111
127
  "peerDependenciesMeta": {
112
128
  "@anthropic-ai/claude-agent-sdk": {
@@ -120,9 +136,6 @@
120
136
  },
121
137
  "e2b": {
122
138
  "optional": true
123
- },
124
- "@opencode-ai/sdk": {
125
- "optional": true
126
139
  }
127
140
  },
128
141
  "dependencies": {
@@ -1,4 +0,0 @@
1
- import{t as e}from"./util-DcPzh_0u.mjs";import{t}from"./env-Cb8MIvH7.mjs";import{t as n}from"./spawner-BB6W3FVi.mjs";import{a as r,i,n as a,o,t as s}from"./classify-error-BPQtzEVV.mjs";import{dirname as c}from"node:path";import{createWriteStream as l,mkdirSync as u}from"node:fs";async function*d(e){let t=new TextDecoder,n=``;for await(let r of e){let e=t.decode(r,{stream:!0});n+=e;let i=n.split(`
2
- `);n=i.pop()??``;for(let e of i){let t=e.trim();t&&(yield t)}}let r=t.decode();r&&(n+=r);let i=n.trim();i&&(yield i)}const f=t=>t.status===`rejected`?e(t.reason):void 0,p=(e,t)=>{if(e.stopReason)return;let n=f(t.processResult);if(n)return{kind:`spawn`,message:n};let i=f(t.stdoutResult);if(i)return{kind:`process`,message:i};let a=f(t.stderrResult);if(a)return{kind:`process`,message:a};if(!e.status&&!e.error){let t=e.processResult,n=e.stderrLines.join(`
3
- `);if(t&&t.exitCode!==null&&t.exitCode!==0)return{kind:`process`,message:n||`Process exited with code ${t.exitCode}.`};if(!r(e)&&e.stderrLines.length>0)return{kind:`process`,message:n}}},m=e=>{let t=s(e);return t.kind===`provider`?{kind:`process`,message:t.message}:t};var h=class extends a{spawner;defaults;executionTargetRef;autoStartExecutionTarget;autoStopExecutionTarget;executionTargetStopPromise;logStream;sigkillTimer;constructor(e){super({type:e.type,capabilities:e.capabilities,sessionId:e.defaults?.sessionId,onEvent:e.onEvent}),this.spawner=e.spawner??n,this.defaults=e.defaults??{},this.executionTargetRef=e.executionTarget,this.autoStartExecutionTarget=e.autoStartExecutionTarget??!0,this.autoStopExecutionTarget=e.autoStopExecutionTarget??!1,e.logPath&&this.initLogStream(e.logPath)}onParseError(t,n){this.appendRawLog(`[parse-error] ${e(n)} ${t.slice(0,200)}`)}buildDefaultEnv(e){let n=t({propagateEnv:e});return n.CI=n.CI??`true`,this.defaults.env&&Object.assign(n,this.defaults.env),n}async executeRunCore(t,n){let r=this.setupRunLifecycle(t);try{if(r.abortedBeforeStart)return this.buildResult(t,new Date);try{await this.onBeforeRun(t);let e={...n,...t.normalizedRequest},r=this.buildArgs(e,t),i=this.buildEnv(e,t),a=this.defaults.command?.[0]??`claude`,o=[...this.defaults.command?.slice(1)??[],...r];if(t.stopReason)return this.buildResult(t,new Date);t.sessionId&&this.emitSessionStart(t),t.process=this.spawner.spawn(a,o,{cwd:t.normalizedRequest.cwd,env:i,stdio:[`pipe`,`pipe`,`pipe`]}),t.process.stdin?.end();let[s,c,l]=await Promise.allSettled([this.watchStdout(t),this.watchStderr(t),t.process.wait()]);l.status===`fulfilled`&&(t.processResult=l.value);let u=p(t,{stdoutResult:s,stderrResult:c,processResult:l});u&&(t.error=u)}catch(e){!t.stopReason&&!t.error&&(t.error=m(e))}return this.buildResult(t,new Date)}finally{r.cleanup(),this.sigkillTimer&&=(clearTimeout(this.sigkillTimer),void 0);try{await this.onRunFinished(t)}catch(t){this.appendRawLog(`[cleanup-error] ${e(t)}`)}}}async watchStdout(e){let t=e.process?.stdout;if(t)for await(let n of d(t))this.appendLog(`stdout`,n),this.processLine(e,n)}async watchStderr(e){let t=e.process?.stderr;if(t)for await(let n of d(t))this.appendLog(`stderr`,n),e.stderrLines.push(n),this.emit(e,o(e.runId,`stderr`,{sessionId:e.sessionId,text:n}))}processLine(e,t){let n;try{n=JSON.parse(t)}catch(e){this.onParseError(t,e);return}let r;try{r=this.mapRawEvent(n,i(e))}catch(e){this.onParseError(t,e);return}this.applyBatch(e,r)}get runRequestDefaults(){return this.defaults}onHandlerError(t){this.appendRawLog(`[handler-error] ${e(t)}`)}async onDispose(){let e=this.logStream;this.logStream=void 0,e&&await new Promise(t=>{e.end(t)})}onStopRequested(e){e.process?.kill(),this.sigkillTimer=setTimeout(()=>{e.process?.kill(`SIGKILL`)},5e3),this.sigkillTimer.unref?.()}onBeforeRun(e){return this.ensureExecutionTarget()}async onRunFinished(t){this.autoStopExecutionTarget&&this.executionTargetRef&&this.executionTargetRef.status===`running`&&(this.executionTargetStopPromise=this.executionTargetRef.stop().catch(t=>{this.appendRawLog(`[auto-stop-error] ${e(t)}`)}),await this.executionTargetStopPromise)}appendRawLog(e){if(!this.logStream)return;let t=typeof e==`string`?e:JSON.stringify(e);this.logStream.write(`${t}\n`)}initLogStream(e){try{u(c(e),{recursive:!0}),this.logStream=l(e,{flags:`a`}),this.logStream.write(`\n--- ${new Date().toISOString()} ---\n`)}catch{this.logStream=void 0}}appendLog(e,t){if(!this.logStream||!t)return;let n=e===`stderr`?`STDERR`:`STDOUT`,r=new Date().toISOString();for(let e of t.split(`
4
- `))e&&this.logStream.write(`[${r}] ${n} ${e}\n`)}async ensureExecutionTarget(){this.executionTargetStopPromise&&=(await this.executionTargetStopPromise,void 0),this.autoStartExecutionTarget&&this.executionTargetRef&&this.executionTargetRef.status!==`running`&&await this.executionTargetRef.start()}};export{h as t};
@@ -1 +0,0 @@
1
- import{t as e}from"./util-DcPzh_0u.mjs";import{i as t,r as n,s as r}from"./container-DBXaA-Iv.mjs";import{execFile as i}from"node:child_process";import{dirname as a,isAbsolute as o,join as s,posix as c,relative as l,sep as u}from"node:path";import{promisify as d}from"node:util";import{createReadStream as f}from"node:fs";import{tmpdir as p}from"node:os";import{copyFile as m,lstat as h,mkdir as g,mkdtemp as _,readdir as v,readlink as y,rm as b,stat as x,symlink as S}from"node:fs/promises";import{createHash as C}from"node:crypto";import{pipeline as w}from"node:stream/promises";const T=e=>e instanceof Error&&`code`in e&&(`stdout`in e||`stderr`in e),E=d(i),D=e=>e!==`..`&&!e.startsWith(`..${u}`)&&!o(e),O=(e,t)=>{let n=l(e,t);if(D(n))return n.split(u).join(c.sep)},k=(e,t,r)=>{let i=O(t,e);if(i!==void 0)return i;let a=O(r,e);if(a!==void 0)return a;throw new n(`Git diff produced a path outside the materialized trees: ${e}`)},A=e=>e.sort((e,t)=>e.path===t.path?(e.previousPath??``).localeCompare(t.previousPath??``):e.path.localeCompare(t.path)),j=async e=>{let t=await v(e,{withFileTypes:!0});for(let n of t){let t=s(e,n.name);if(n.name===`.git`){await b(t,{recursive:!0,force:!0});continue}n.isDirectory()&&await j(t)}},M=()=>_(s(p(),`cw-workdir-diff-`)),N=async e=>{e&&await b(e,{recursive:!0,force:!0}).catch(()=>{})},P=(e,t)=>{let n={cwd:e.cwd,createdAt:new Date};return t.set(n,e),n},F=(e,t,r)=>{if(typeof t!=`object`||!t)throw new n(`Invalid workdir snapshot.`);let i=r.get(t);if(!i)throw new n(`Invalid workdir snapshot.`);if(i.owner!==e)throw new n(`Workdir snapshot was created by a different container instance.`);return i},I=(e,t)=>{if(!t.has(e))throw new n(`Workdir snapshot has been released.`)},L=e=>C(`sha256`).update(e).digest(`hex`),R=e=>Buffer.isBuffer(e)?e:Buffer.from(e,`utf8`),z=async e=>{let t=C(`sha256`);return await w(f(e),t),t.digest(`hex`)},B=async(e,t,r)=>{let i=`${e}:${t}`;if(r.has(i))return r.get(i);let a=s(e,...t.split(c.sep));try{let e=await h(a),t,o;if(e.isSymbolicLink()){let e=Buffer.from(await y(a));t=L(e),o=e.byteLength}else if(e.isFile())t=await z(a),o=e.size;else throw new n(`Unsupported filesystem entry in diff metadata: ${a}`);let s={hash:t,size:o};return r.set(i,s),s}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`){r.set(i,void 0);return}throw e}},V=(e,t,r)=>{if(e.byteLength===0)return[];let i=e.toString(`utf8`).split(`\0`);i[i.length-1]===``&&i.pop();let a=[];for(let e=0;e<i.length;){let o=i[e++];if(!o)continue;if(o.startsWith(`R`)){let o=i[e++],s=i[e++];if(!o||!s)throw new n(`Failed to parse git rename entry.`);a.push({kind:`renamed`,previousPath:k(o,t,r),path:k(s,t,r)});continue}let s=i[e++];if(!s)throw new n(`Failed to parse git diff entry.`);switch(o){case`A`:a.push({kind:`added`,path:k(s,t,r)});break;case`D`:a.push({kind:`deleted`,path:k(s,t,r)});break;case`M`:a.push({kind:`modified`,path:k(s,t,r)});break;case`T`:a.push({kind:`modified`,path:k(s,t,r)});break;default:throw new n(`Unsupported git diff change kind: ${o}`)}}return a},H=async(t,r)=>{try{return V(R((await E(`git`,[`diff`,`--no-index`,`-z`,`--name-status`,`-M`,`--find-renames=100%`,t,r],{cwd:p(),encoding:`buffer`,maxBuffer:50*1024*1024})).stdout),t,r)}catch(i){if(!T(i))throw new n(`Failed to run git diff: ${e(i)}`);let a=i.code??1,o=Buffer.isBuffer(i.stdout)?i.stdout:Buffer.from(String(i.stdout??``),`utf8`),s=Buffer.isBuffer(i.stderr)?i.stderr:Buffer.from(String(i.stderr??``),`utf8`);if(a===0||a===1)return V(o,t,r);throw new n(`Failed to run git diff: ${s.toString(`utf8`).trim()||o.toString(`utf8`).trim()||`exit code ${a}`}`)}},U=async(e,t,n)=>{let r=new Map;return A(await Promise.all(e.map(async e=>{let i;i=e.kind===`added`?void 0:e.kind===`renamed`?e.previousPath:e.path;let a=e.kind===`deleted`?void 0:e.path,[o,s]=await Promise.all([i===void 0?void 0:B(t,i,r),a===void 0?void 0:B(n,a,r)]);return{path:e.path,previousPath:e.previousPath,kind:e.kind,beforeHash:o?.hash,afterHash:s?.hash,beforeSize:o?.size,afterSize:s?.size}})))},W=e=>{let t=new Set;for(let n of e)t.add(n.path),n.kind===`renamed`&&n.previousPath&&t.add(n.previousPath);return[...t].sort((e,t)=>e.localeCompare(t))},G=(i,a)=>{throw a instanceof n||a instanceof t||a instanceof r?a:new n(`${i}: ${e(a)}`)},K=async(e,t)=>{if(!(await x(e)).isDirectory())throw new n(`Target path is not a directory: ${e}`);await g(t,{recursive:!0});let r=await v(e,{withFileTypes:!0});await Promise.all(r.filter(e=>e.name!==`.git`).map(async r=>{let i=s(e,r.name),o=s(t,r.name);if(r.isDirectory()){await K(i,o);return}if(r.isSymbolicLink()){await g(a(o),{recursive:!0}),await S(await y(i),o);return}if(r.isFile()){await g(a(o),{recursive:!0}),await m(i,o);return}throw new n(`Unsupported filesystem entry in workdir diff: ${i}`)}))},q=e=>{let t=new Set,n=new WeakMap,r=async(r={})=>{let i=r.cwd??e.workdir,a;try{a=await M(),await e.materialize(i,a),await j(a);let r={owner:e.owner,tempDir:a,cwd:i,inFlightDiffs:0,released:!1};return t.add(r),a=void 0,P(r,n)}catch(e){return await N(a),G(`Failed to materialize workdir snapshot`,e)}},i=async r=>{let i=Date.now(),a=F(e.owner,r,n);I(a,t),a.inFlightDiffs++;let o;try{o=await M(),await e.materialize(a.cwd,o),await j(o);let t=await U(await H(a.tempDir,o),a.tempDir,o),n=W(t);return{cwd:a.cwd,changedFiles:n,fileChanges:t,stats:{durationMs:Date.now()-i,filesCompared:n.length}}}catch(e){return G(`Failed to diff workdir snapshot`,e)}finally{a.inFlightDiffs--,a.inFlightDiffs===0&&(a.resolveIdle?.(),a.resolveIdle=void 0),await N(o)}},a=e=>{let n=e;return n.releasePromise?n.releasePromise:(n.released=!0,t.delete(n),n.releasePromise=(async()=>{n.inFlightDiffs>0&&await new Promise(e=>{n.resolveIdle=e}),await N(n.tempDir)})(),n.releasePromise)};return{snapshotWorkdir:r,diffWorkdir:i,releaseWorkdirSnapshot:async t=>{await a(F(e.owner,t,n))},disposeSnapshots:async()=>{await Promise.all(Array.from(t).map(a))}}};export{q as n,T as r,K as t};
@@ -1 +0,0 @@
1
- import{spawn as e}from"node:child_process";const t=e=>({async*[Symbol.asyncIterator](){for await(let t of e){if(t instanceof Buffer){yield new Uint8Array(t);continue}if(typeof t==`string`){yield new TextEncoder().encode(t);continue}if(t instanceof Uint8Array){yield t;continue}throw Error(`Unsupported stdout/stderr chunk type: ${typeof t}`)}}}),n={spawn:(n,r,i={})=>{let a=e(n,r,{cwd:i.cwd,env:i.env,stdio:i.stdio});a.stdin?.on(`error`,()=>{});let o=new Promise((e,t)=>{let n=(t,n)=>{a.removeListener(`error`,r),e({exitCode:t,signal:n})},r=e=>{a.removeListener(`close`,n),t(e)};a.once(`error`,r),a.once(`close`,n)});return{stdout:a.stdout?t(a.stdout):null,stderr:a.stderr?t(a.stderr):null,stdin:a.stdin?{write:e=>a.stdin?.write(e),end:()=>a.stdin?.end()}:null,kill:e=>a.kill(e),wait:()=>o}}};export{n as t};
@@ -1 +0,0 @@
1
- const e=e=>{let t;for(let[,n]of e)n.toolName===`StructuredOutput`&&n.input!==void 0&&(t=n.input);return t},t=(t,n,r,i)=>{if(t!=null)return{value:t};if(!n.schemaRequested)return{};if(n.allowToolCallFallback??!0){let t=e(n.toolCalls);if(t!==void 0)return{value:t}}return r.isSuccess?{error:{kind:`parse`,message:i}}:{}};export{t};