@arhan-w/ibex 0.0.0-stage → 3.6.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 (167) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +295 -2
  3. package/npm-package/LICENSE +21 -0
  4. package/npm-package/README.md +176 -0
  5. package/npm-package/bin/goat.js +3 -0
  6. package/npm-package/bin/ibex.js +77 -0
  7. package/npm-package/package.json +58 -0
  8. package/npm-package/scripts/install-binary.js +168 -0
  9. package/package.json +69 -6
  10. package/src/agent.ts +695 -0
  11. package/src/agents/loader.ts +110 -0
  12. package/src/ambient.d.ts +2 -0
  13. package/src/code/extract.ts +292 -0
  14. package/src/code/find.ts +244 -0
  15. package/src/code/grammars.ts +88 -0
  16. package/src/code/indexer.ts +242 -0
  17. package/src/code/semantic.ts +253 -0
  18. package/src/code/slash.ts +88 -0
  19. package/src/code/tool.ts +40 -0
  20. package/src/collab/client.ts +141 -0
  21. package/src/collab/handlers.ts +141 -0
  22. package/src/collab/invite.ts +39 -0
  23. package/src/collab/relay.ts +106 -0
  24. package/src/collab/sync.ts +131 -0
  25. package/src/commands.tsx +943 -0
  26. package/src/computer.ts +629 -0
  27. package/src/config.ts +318 -0
  28. package/src/constants.ts +18 -0
  29. package/src/context.ts +73 -0
  30. package/src/data/providers.json +2342 -0
  31. package/src/diff.ts +50 -0
  32. package/src/doctor.ts +443 -0
  33. package/src/errors.ts +139 -0
  34. package/src/gflash.ts +170 -0
  35. package/src/hooks.ts +133 -0
  36. package/src/ide/assets.gen.ts +3 -0
  37. package/src/ide/index.html +844 -0
  38. package/src/ide/server.ts +506 -0
  39. package/src/ide/vendor/marked.umd.js +80 -0
  40. package/src/ide/vendor/vs/base/browser/ui/codicons/codicon/codicon.ttf +0 -0
  41. package/src/ide/vendor/vs/base/worker/workerMain.js +31 -0
  42. package/src/ide/vendor/vs/basic-languages/abap/abap.js +10 -0
  43. package/src/ide/vendor/vs/basic-languages/apex/apex.js +10 -0
  44. package/src/ide/vendor/vs/basic-languages/azcli/azcli.js +10 -0
  45. package/src/ide/vendor/vs/basic-languages/bat/bat.js +10 -0
  46. package/src/ide/vendor/vs/basic-languages/bicep/bicep.js +11 -0
  47. package/src/ide/vendor/vs/basic-languages/cameligo/cameligo.js +10 -0
  48. package/src/ide/vendor/vs/basic-languages/clojure/clojure.js +10 -0
  49. package/src/ide/vendor/vs/basic-languages/coffee/coffee.js +10 -0
  50. package/src/ide/vendor/vs/basic-languages/cpp/cpp.js +10 -0
  51. package/src/ide/vendor/vs/basic-languages/csharp/csharp.js +10 -0
  52. package/src/ide/vendor/vs/basic-languages/csp/csp.js +10 -0
  53. package/src/ide/vendor/vs/basic-languages/css/css.js +12 -0
  54. package/src/ide/vendor/vs/basic-languages/cypher/cypher.js +10 -0
  55. package/src/ide/vendor/vs/basic-languages/dart/dart.js +10 -0
  56. package/src/ide/vendor/vs/basic-languages/dockerfile/dockerfile.js +10 -0
  57. package/src/ide/vendor/vs/basic-languages/ecl/ecl.js +10 -0
  58. package/src/ide/vendor/vs/basic-languages/elixir/elixir.js +10 -0
  59. package/src/ide/vendor/vs/basic-languages/flow9/flow9.js +10 -0
  60. package/src/ide/vendor/vs/basic-languages/freemarker2/freemarker2.js +12 -0
  61. package/src/ide/vendor/vs/basic-languages/fsharp/fsharp.js +10 -0
  62. package/src/ide/vendor/vs/basic-languages/go/go.js +10 -0
  63. package/src/ide/vendor/vs/basic-languages/graphql/graphql.js +10 -0
  64. package/src/ide/vendor/vs/basic-languages/handlebars/handlebars.js +10 -0
  65. package/src/ide/vendor/vs/basic-languages/hcl/hcl.js +10 -0
  66. package/src/ide/vendor/vs/basic-languages/html/html.js +10 -0
  67. package/src/ide/vendor/vs/basic-languages/ini/ini.js +10 -0
  68. package/src/ide/vendor/vs/basic-languages/java/java.js +10 -0
  69. package/src/ide/vendor/vs/basic-languages/javascript/javascript.js +10 -0
  70. package/src/ide/vendor/vs/basic-languages/julia/julia.js +10 -0
  71. package/src/ide/vendor/vs/basic-languages/kotlin/kotlin.js +10 -0
  72. package/src/ide/vendor/vs/basic-languages/less/less.js +11 -0
  73. package/src/ide/vendor/vs/basic-languages/lexon/lexon.js +10 -0
  74. package/src/ide/vendor/vs/basic-languages/liquid/liquid.js +10 -0
  75. package/src/ide/vendor/vs/basic-languages/lua/lua.js +10 -0
  76. package/src/ide/vendor/vs/basic-languages/m3/m3.js +10 -0
  77. package/src/ide/vendor/vs/basic-languages/markdown/markdown.js +10 -0
  78. package/src/ide/vendor/vs/basic-languages/mdx/mdx.js +10 -0
  79. package/src/ide/vendor/vs/basic-languages/mips/mips.js +10 -0
  80. package/src/ide/vendor/vs/basic-languages/msdax/msdax.js +10 -0
  81. package/src/ide/vendor/vs/basic-languages/mysql/mysql.js +10 -0
  82. package/src/ide/vendor/vs/basic-languages/objective-c/objective-c.js +10 -0
  83. package/src/ide/vendor/vs/basic-languages/pascal/pascal.js +10 -0
  84. package/src/ide/vendor/vs/basic-languages/pascaligo/pascaligo.js +10 -0
  85. package/src/ide/vendor/vs/basic-languages/perl/perl.js +10 -0
  86. package/src/ide/vendor/vs/basic-languages/pgsql/pgsql.js +10 -0
  87. package/src/ide/vendor/vs/basic-languages/php/php.js +10 -0
  88. package/src/ide/vendor/vs/basic-languages/pla/pla.js +10 -0
  89. package/src/ide/vendor/vs/basic-languages/postiats/postiats.js +10 -0
  90. package/src/ide/vendor/vs/basic-languages/powerquery/powerquery.js +10 -0
  91. package/src/ide/vendor/vs/basic-languages/powershell/powershell.js +10 -0
  92. package/src/ide/vendor/vs/basic-languages/protobuf/protobuf.js +11 -0
  93. package/src/ide/vendor/vs/basic-languages/pug/pug.js +10 -0
  94. package/src/ide/vendor/vs/basic-languages/python/python.js +10 -0
  95. package/src/ide/vendor/vs/basic-languages/qsharp/qsharp.js +10 -0
  96. package/src/ide/vendor/vs/basic-languages/r/r.js +10 -0
  97. package/src/ide/vendor/vs/basic-languages/razor/razor.js +10 -0
  98. package/src/ide/vendor/vs/basic-languages/redis/redis.js +10 -0
  99. package/src/ide/vendor/vs/basic-languages/redshift/redshift.js +10 -0
  100. package/src/ide/vendor/vs/basic-languages/restructuredtext/restructuredtext.js +10 -0
  101. package/src/ide/vendor/vs/basic-languages/ruby/ruby.js +10 -0
  102. package/src/ide/vendor/vs/basic-languages/rust/rust.js +10 -0
  103. package/src/ide/vendor/vs/basic-languages/sb/sb.js +10 -0
  104. package/src/ide/vendor/vs/basic-languages/scala/scala.js +10 -0
  105. package/src/ide/vendor/vs/basic-languages/scheme/scheme.js +10 -0
  106. package/src/ide/vendor/vs/basic-languages/scss/scss.js +12 -0
  107. package/src/ide/vendor/vs/basic-languages/shell/shell.js +10 -0
  108. package/src/ide/vendor/vs/basic-languages/solidity/solidity.js +10 -0
  109. package/src/ide/vendor/vs/basic-languages/sophia/sophia.js +10 -0
  110. package/src/ide/vendor/vs/basic-languages/sparql/sparql.js +10 -0
  111. package/src/ide/vendor/vs/basic-languages/sql/sql.js +10 -0
  112. package/src/ide/vendor/vs/basic-languages/st/st.js +10 -0
  113. package/src/ide/vendor/vs/basic-languages/swift/swift.js +13 -0
  114. package/src/ide/vendor/vs/basic-languages/systemverilog/systemverilog.js +10 -0
  115. package/src/ide/vendor/vs/basic-languages/tcl/tcl.js +10 -0
  116. package/src/ide/vendor/vs/basic-languages/twig/twig.js +10 -0
  117. package/src/ide/vendor/vs/basic-languages/typescript/typescript.js +10 -0
  118. package/src/ide/vendor/vs/basic-languages/typespec/typespec.js +10 -0
  119. package/src/ide/vendor/vs/basic-languages/vb/vb.js +10 -0
  120. package/src/ide/vendor/vs/basic-languages/wgsl/wgsl.js +307 -0
  121. package/src/ide/vendor/vs/basic-languages/xml/xml.js +10 -0
  122. package/src/ide/vendor/vs/basic-languages/yaml/yaml.js +10 -0
  123. package/src/ide/vendor/vs/editor/editor.main.css +8 -0
  124. package/src/ide/vendor/vs/editor/editor.main.js +798 -0
  125. package/src/ide/vendor/vs/language/css/cssMode.js +13 -0
  126. package/src/ide/vendor/vs/language/css/cssWorker.js +77 -0
  127. package/src/ide/vendor/vs/language/html/htmlMode.js +13 -0
  128. package/src/ide/vendor/vs/language/html/htmlWorker.js +454 -0
  129. package/src/ide/vendor/vs/language/json/jsonMode.js +19 -0
  130. package/src/ide/vendor/vs/language/json/jsonWorker.js +42 -0
  131. package/src/ide/vendor/vs/language/typescript/tsMode.js +20 -0
  132. package/src/ide/vendor/vs/language/typescript/tsWorker.js +51328 -0
  133. package/src/ide/vendor/vs/loader.js +11 -0
  134. package/src/index-shared.ts +117 -0
  135. package/src/index.ts +586 -0
  136. package/src/llm.ts +721 -0
  137. package/src/logger.ts +39 -0
  138. package/src/mcp/client.ts +121 -0
  139. package/src/mcp/types.ts +27 -0
  140. package/src/oauth.ts +205 -0
  141. package/src/onboarding.ts +140 -0
  142. package/src/palette.tsx +199 -0
  143. package/src/permissions.ts +123 -0
  144. package/src/plugins/loader.ts +120 -0
  145. package/src/plugins/marketplace.ts +252 -0
  146. package/src/plugins/sandbox.ts +303 -0
  147. package/src/plugins/tar.ts +241 -0
  148. package/src/pricing.ts +78 -0
  149. package/src/protocol/client.ts +102 -0
  150. package/src/protocol/rpc.ts +43 -0
  151. package/src/protocol/serve.ts +136 -0
  152. package/src/providers.ts +402 -0
  153. package/src/rate-limiter.ts +101 -0
  154. package/src/refs.ts +97 -0
  155. package/src/runtime.ts +144 -0
  156. package/src/session.ts +401 -0
  157. package/src/skills/loader.ts +136 -0
  158. package/src/statusline.ts +70 -0
  159. package/src/system-prompt.ts +28 -0
  160. package/src/tools.ts +1280 -0
  161. package/src/tui.tsx +1355 -0
  162. package/src/update.ts +236 -0
  163. package/src/vendor/flashServer.ts +2 -0
  164. package/src/vendor/gemini-web2api/gemini_web2api.py +1136 -0
  165. package/src/virtual-list.tsx +125 -0
  166. package/src/window.ts +31 -0
  167. package/tsconfig.json +16 -0
@@ -0,0 +1,303 @@
1
+ /**
2
+ * Plugin Sandbox — isolated execution environment for untrusted plugins.
3
+ * Provides process-level isolation with resource limits, filesystem sandbox,
4
+ * network restrictions, and a timeout guard.
5
+ *
6
+ * Plugins run in a child process with:
7
+ * - Limited memory (512MB default)
8
+ * - Filesystem scoped to plugin dir + temp
9
+ * - No network access by default
10
+ * - Timeout protection (30s default)
11
+ * - Exit code reporting
12
+ */
13
+ import { spawn, type ChildProcess } from "node:child_process";
14
+ import { join, dirname } from "node:path";
15
+ import { randomUUID } from "node:crypto";
16
+ import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
17
+ import { appDir } from "../config.ts";
18
+
19
+ export interface SandboxConfig {
20
+ /** Plugin entry point script */
21
+ entryPoint: string;
22
+ /** Working directory for the plugin */
23
+ workDir?: string;
24
+ /** Max memory in MB (default 512) */
25
+ maxMemoryMb?: number;
26
+ /** Timeout in ms (default 30000) */
27
+ timeoutMs?: number;
28
+ /** Allow network access (default false) */
29
+ allowNetwork?: boolean;
30
+ /** Additional environment variables */
31
+ env?: Record<string, string>;
32
+ /** Stdout handler */
33
+ onStdout?: (data: string) => void;
34
+ /** Stderr handler */
35
+ onStderr?: (data: string) => void;
36
+ /** Exit handler */
37
+ onExit?: (code: number | null, signal: string | null) => void;
38
+ }
39
+
40
+ export interface SandboxResult {
41
+ ok: boolean;
42
+ output: string;
43
+ exitCode: number | null;
44
+ signal: string | null;
45
+ durationMs: number;
46
+ timedOut: boolean;
47
+ }
48
+
49
+ export class SandboxError extends Error {
50
+ constructor(
51
+ public message: string,
52
+ public exitCode: number | null,
53
+ public signal: string | null,
54
+ ) {
55
+ super(message);
56
+ }
57
+ }
58
+
59
+ /** Sandbox session tracking */
60
+ export interface SandboxSession {
61
+ id: string;
62
+ pluginName: string;
63
+ process: ChildProcess;
64
+ startTime: number;
65
+ stdout: string;
66
+ stderr: string;
67
+ terminated: boolean;
68
+ }
69
+
70
+ const sandboxSessions = new Map<string, SandboxSession>();
71
+ const MAX_SANDBOX_SESSIONS = 10;
72
+ const DEFAULT_MAX_MEMORY_MB = 512;
73
+ const DEFAULT_TIMEOUT_MS = 30_000;
74
+ const PLUGIN_SANDBOX_DIR = "sandbox";
75
+
76
+ /** Get or create sandbox directory */
77
+ function getSandboxDir(): string {
78
+ const dir = join(appDir(), PLUGIN_SANDBOX_DIR);
79
+ mkdirSync(dir, { recursive: true });
80
+ return dir;
81
+ }
82
+
83
+ /**
84
+ * Create a sandboxed execution environment for a plugin.
85
+ * Returns a SandboxSession that can be used to monitor/kill the process.
86
+ */
87
+ export function createSandbox(config: SandboxConfig): SandboxSession {
88
+ // Limit concurrent sessions
89
+ if (sandboxSessions.size >= MAX_SANDBOX_SESSIONS) {
90
+ throw new SandboxError(
91
+ "Maximum sandbox sessions reached",
92
+ null,
93
+ null,
94
+ );
95
+ }
96
+
97
+ const id = `sandbox-${randomUUID().slice(0, 8)}`;
98
+ const workDir = config.workDir ?? join(getSandboxDir(), id);
99
+ mkdirSync(workDir, { recursive: true });
100
+
101
+ // Prepare environment
102
+ const env: Record<string, string> = {
103
+ ...process.env,
104
+ GOAT_SANDBOX: "1",
105
+ GOAT_SANDBOX_ID: id,
106
+ GOAT_SANDBOX_DIR: workDir,
107
+ NODE_ENV: "production",
108
+ ...(config.env ?? {}),
109
+ };
110
+
111
+ // Build command
112
+ const args = ["--max-old-space-size=" + (config.maxMemoryMb ?? DEFAULT_MAX_MEMORY_MB)];
113
+ if (!config.allowNetwork) {
114
+ // Node.js doesn't have built-in network blocking, but we can set environment flag
115
+ env.GOAT_SANDBOX_NO_NETWORK = "1";
116
+ }
117
+
118
+ // Spawn child process
119
+ const sandboxProcess = spawn("bun", [...args, config.entryPoint], {
120
+ cwd: workDir,
121
+ env,
122
+ stdio: ["pipe", "pipe", "pipe"],
123
+ detached: false,
124
+ });
125
+
126
+ const session: SandboxSession = {
127
+ id,
128
+ pluginName: config.entryPoint.split("/").pop()?.replace(".ts", "") ?? id,
129
+ process: sandboxProcess,
130
+ startTime: Date.now(),
131
+ stdout: "",
132
+ stderr: "",
133
+ terminated: false,
134
+ };
135
+
136
+ // Collect stdout
137
+ sandboxProcess.stdout?.on("data", (data: Buffer) => {
138
+ const text = data.toString("utf8");
139
+ session.stdout += text;
140
+ config.onStdout?.(text);
141
+ });
142
+
143
+ // Collect stderr
144
+ sandboxProcess.stderr?.on("data", (data: Buffer) => {
145
+ const text = data.toString("utf8");
146
+ session.stderr += text;
147
+ config.onStderr?.(text);
148
+ });
149
+
150
+ // Handle exit
151
+ sandboxProcess.on("exit", (code, signal) => {
152
+ session.terminated = true;
153
+ config.onExit?.(code, signal);
154
+ sandboxSessions.delete(id);
155
+ });
156
+
157
+ sandboxProcess.on("error", (err) => {
158
+ session.terminated = true;
159
+ config.onStderr?.(`Sandbox error: ${err.message}\n`);
160
+ sandboxSessions.delete(id);
161
+ });
162
+
163
+ // Set timeout
164
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
165
+ const timer = setTimeout(() => {
166
+ if (!session.terminated) {
167
+ killSession(id);
168
+ config.onStderr?.(`Sandbox timeout after ${timeoutMs}ms\n`);
169
+ }
170
+ }, timeoutMs);
171
+
172
+ // Store session
173
+ sandboxSessions.set(id, session);
174
+
175
+ return session;
176
+ }
177
+
178
+ /**
179
+ * Execute a plugin command in the sandbox and return result.
180
+ */
181
+ export async function executeSandbox(config: SandboxConfig): Promise<SandboxResult> {
182
+ return new Promise((resolve, reject) => {
183
+ let finished = false;
184
+ const result: SandboxResult = {
185
+ ok: false,
186
+ output: "",
187
+ exitCode: null,
188
+ signal: null,
189
+ durationMs: 0,
190
+ timedOut: false,
191
+ };
192
+
193
+ const session = createSandbox({
194
+ ...config,
195
+ onStdout: (data) => {
196
+ if (!finished) {
197
+ result.output += data;
198
+ }
199
+ config.onStdout?.(data);
200
+ },
201
+ onStderr: (data) => {
202
+ if (!finished) {
203
+ result.output += data;
204
+ }
205
+ config.onStderr?.(data);
206
+ },
207
+ onExit: (code, signal) => {
208
+ if (finished) return;
209
+ finished = true;
210
+ result.exitCode = code;
211
+ result.signal = signal;
212
+ result.durationMs = Date.now() - session.startTime;
213
+ result.timedOut = code === null && signal !== null && signal.startsWith("SIG");
214
+
215
+ if (code === 0) {
216
+ result.ok = true;
217
+ } else if (signal && signal.startsWith("SIGTERM")) {
218
+ result.ok = false;
219
+ result.timedOut = true;
220
+ } else {
221
+ result.ok = false;
222
+ }
223
+ resolve(result);
224
+ },
225
+ });
226
+ });
227
+ }
228
+
229
+ /**
230
+ * Kill a sandbox session by ID.
231
+ */
232
+ export function killSession(id: string): void {
233
+ const session = sandboxSessions.get(id);
234
+ if (!session || session.terminated) return;
235
+ try {
236
+ session.process.kill("SIGTERM");
237
+ // Force kill after 5s
238
+ setTimeout(() => {
239
+ if (!session.terminated) {
240
+ session.process.kill("SIGKILL");
241
+ }
242
+ }, 5000);
243
+ } catch {
244
+ /* already dead */
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Kill all sandbox sessions.
250
+ */
251
+ export function killAllSessions(): void {
252
+ for (const id of sandboxSessions.keys()) {
253
+ killSession(id);
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Get active sandbox sessions.
259
+ */
260
+ export function listSessions(): Array<{
261
+ id: string;
262
+ pluginName: string;
263
+ durationMs: number;
264
+ terminated: boolean;
265
+ }> {
266
+ const now = Date.now();
267
+ return [...sandboxSessions.values()].map((s) => ({
268
+ id: s.id,
269
+ pluginName: s.pluginName,
270
+ durationMs: now - s.startTime,
271
+ terminated: s.terminated,
272
+ }));
273
+ }
274
+
275
+ /**
276
+ * Check if a file is within allowed sandbox paths.
277
+ */
278
+ export function isPathAllowed(filePath: string, sandboxDir: string): boolean {
279
+ const resolved = require("node:path").resolve(sandboxDir, filePath);
280
+ return resolved.startsWith(sandboxDir);
281
+ }
282
+
283
+ /**
284
+ * Write a fixture file to the sandbox for testing.
285
+ */
286
+ export function writeSandboxFixture(name: string, content: string): string {
287
+ const sandboxDir = getSandboxDir();
288
+ const fixtureDir = join(sandboxDir, "fixtures");
289
+ mkdirSync(fixtureDir, { recursive: true });
290
+ const filePath = join(fixtureDir, name);
291
+ writeFileSync(filePath, content, "utf8");
292
+ return filePath;
293
+ }
294
+
295
+ /**
296
+ * Read a fixture file from the sandbox.
297
+ */
298
+ export function readSandboxFixture(name: string): string {
299
+ const sandboxDir = getSandboxDir();
300
+ const filePath = join(sandboxDir, "fixtures", name);
301
+ if (!existsSync(filePath)) throw new Error(`Fixture not found: ${name}`);
302
+ return readFileSync(filePath, "utf8");
303
+ }
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Tar archive utilities — pure ustar/GNU tar parser and writer, gzip
3
+ * via Bun.gunzipSync (fallback node:zlib). Used by the plugin marketplace
4
+ * for installing .tgz packages with pinned ed25519 signatures.
5
+ *
6
+ * NOTE: NO wasmtime — the v2 plugin directory bundle IS the plugin system;
7
+ * tgz installation is the extension mechanism only.
8
+ */
9
+ import { mkdirSync, rmSync, readFileSync, writeFileSync, existsSync } from "node:fs";
10
+ import { join, dirname, resolve, relative, isAbsolute, sep } from "node:path";
11
+ import { randomUUID } from "node:crypto";
12
+
13
+ export class TarError extends Error {
14
+ constructor(reason: string) { super(reason); this.name = "TarError"; }
15
+ }
16
+
17
+ /** Max decompressed bytes before rejecting a gzip bomb. */
18
+ export const MAX_DECOMPRESSED = 50_000_000;
19
+
20
+ /** Parse a ustar/GNU tar header at offset 0 into fields, or null. */
21
+ function parseHeader(buf: Buffer, off: number): Record<string, string | number> | null {
22
+ if (off + 512 > buf.length) return null;
23
+ const h = buf.subarray(off, off + 512);
24
+ const magic = h.subarray(257, 263).toString("ascii").replace(/\0/g, "").trim();
25
+ if (magic !== "ustar" && magic !== "") return null;
26
+ // All-zero block = end of archive
27
+ if (h.every((b) => b === 0)) return null;
28
+ const name = h.subarray(0, 100).toString("ascii").replace(/\0/g, "");
29
+ const mode = h.subarray(100, 108).toString("ascii").replace(/\0/g, "").trim();
30
+ const sizeRaw = h.subarray(124, 136).toString("ascii").replace(/\0/g, "").trim();
31
+ const typeflag = h.subarray(156, 157).toString("ascii");
32
+ const prefix = h.subarray(345, 500).toString("ascii").replace(/\0/g, "");
33
+ return { name: prefix ? `${prefix}${name}` : name, mode, size: sizeRaw, typeflag, magic };
34
+ }
35
+
36
+ /** Parse an octal string (including base-256 high-bit variant) to a number. */
37
+ function parseOctal(s: string): number {
38
+ if (!s) return 0;
39
+ // GNU high-bit variant: first char is 0o200 (128) | digits
40
+ if (s.charCodeAt(0) >= 128) {
41
+ let n = s.charCodeAt(0) & 0x7f;
42
+ for (let i = 1; i < s.length; i++) {
43
+ const d = s.charCodeAt(i) - 48;
44
+ if (d < 0 || d > 7) break;
45
+ n = n * 8 + d;
46
+ }
47
+ return n;
48
+ }
49
+ const v = parseInt(s, 8);
50
+ return Number.isNaN(v) ? 0 : v;
51
+ }
52
+
53
+ /** Read PAX (POSIX) extended header entries preceding the real header. */
54
+ function readPaxEntries(buf: Buffer, off: number): Map<string, string> {
55
+ const m = new Map<string, string>();
56
+ for (;;) {
57
+ if (off + 512 > buf.length) return m;
58
+ const h = buf.subarray(off, off + 512);
59
+ if (h.every((b) => b === 0)) return m; // zero block = end
60
+ const typeflag = h.subarray(156, 157).toString("ascii");
61
+ if (typeflag !== "x" && typeflag !== "g") return m;
62
+ const s = h.subarray(124, 136).toString("ascii").replace(/\0/g, "").trim();
63
+ const sz = parseInt(s, 8) || 0;
64
+ const end = off + 512 + sz;
65
+ const content = buf.subarray(off + 512, Math.min(end, buf.length)).toString("utf8");
66
+ for (const line of content.split("\n")) {
67
+ const i = line.indexOf("=");
68
+ if (i > 0) {
69
+ const k = line.slice(0, i).trim();
70
+ const v = line.slice(i + 1).trim();
71
+ if (k === "path") m.set("path", v);
72
+ }
73
+ }
74
+ off = Math.ceil(end / 512) * 512;
75
+ }
76
+ }
77
+
78
+ /** Read the next entry's long name (GNU typeflag 'L'). */
79
+ function readLongName(buf: Buffer, off: number): string {
80
+ if (off + 512 > buf.length) return "";
81
+ const h = buf.subarray(off, off + 512);
82
+ if (h.every((b) => b === 0)) return "";
83
+ const typeflag = h.subarray(156, 157).toString("ascii");
84
+ if (typeflag !== "L") return "";
85
+ const s = h.subarray(124, 136).toString("ascii").replace(/\0/g, "").trim();
86
+ const sz = parseOctal(s);
87
+ return buf.subarray(off + 512, off + 512 + sz).toString("utf8").replace(/\0/g, "");
88
+ }
89
+
90
+ /** Read the data blocks for a header of given size. Returns exact [data, alignedNextOff]. */
91
+ function readData(buf: Buffer, off: number, size: number): { data: Buffer; off: number } {
92
+ const actualLen = Math.min(size, Math.max(0, buf.length - off));
93
+ const data = buf.subarray(off, off + actualLen);
94
+ const alignedOff = Math.ceil((off + size) / 512) * 512;
95
+ return { data, off: alignedOff };
96
+ }
97
+
98
+ /** Decompress gzip bytes. Bun.gunzipSync first, node:zlib fallback. */
99
+ export function gunzipToU8(u8: Uint8Array): Uint8Array {
100
+ try {
101
+ return new Uint8Array(Bun.gunzipSync(Buffer.from(u8)));
102
+ } catch {
103
+ const { gunzipSync } = require("node:zlib");
104
+ return new Uint8Array(gunzipSync(Buffer.from(u8)));
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Extract a tar (gzipped or raw) buffer into destDir.
110
+ * Returns the list of extracted entry names + sizes.
111
+ * Every guard listed in the spec is enforced; throws TarError on violation.
112
+ */
113
+ export function extractTar(buffer: Buffer, destDir: string): { name: string; size: number }[] {
114
+ const raw = Buffer.from(buffer.length > 2 && buffer[0] === 0x1f && buffer[1] === 0x8b ? gunzipToU8(buffer) : buffer);
115
+ if (raw.length > MAX_DECOMPRESSED) throw new TarError("decompressed payload exceeds 50MB");
116
+
117
+ const destRoot = resolve(destDir);
118
+ mkdirSync(destRoot, { recursive: true });
119
+ const out: { name: string; size: number }[] = [];
120
+ let off = 0;
121
+ let longName = "";
122
+ let paxPath = "";
123
+ let entryCount = 0;
124
+ const writtenPaths = new Set<string>();
125
+ const lowerPaths = new Set<string>(); // case-collision guard on Windows
126
+
127
+ while (off + 512 <= raw.length) {
128
+ const h = parseHeader(raw, off);
129
+ if (!h) break; // zero block = end
130
+ off += 512;
131
+ entryCount++;
132
+ if (entryCount > 10000) throw new TarError("too many entries (>10000)");
133
+
134
+ const name = paxPath || longName || (h.name as string);
135
+ paxPath = "";
136
+ longName = "";
137
+ const typeflag = h.typeflag as string;
138
+ const size = parseOctal(h.size as string);
139
+
140
+ // PAX "x" / "g" entries: capture path override for the next entry
141
+ if (typeflag === "x" || typeflag === "g") {
142
+ const pax = readPaxEntries(raw, off - 512);
143
+ off = Math.ceil((off + size) / 512) * 512;
144
+ if (typeflag === "x" && pax.has("path")) paxPath = pax.get("path")!;
145
+ continue;
146
+ }
147
+
148
+ // GNU long name entry: capture, then skip data
149
+ if (typeflag === "L") {
150
+ longName = readLongName(raw, off - 512);
151
+ const lz = parseOctal(h.size as string);
152
+ off = Math.ceil((off + lz) / 512) * 512;
153
+ continue;
154
+ }
155
+
156
+ // Resolve final name
157
+ const entryName = name;
158
+ // Guard: absolute path or Windows drive letter
159
+ if (entryName.startsWith("/") || entryName.startsWith("\\")) throw new TarError("absolute entry name rejected");
160
+ if (/^[A-Za-z]:[\\/]/.test(entryName)) throw new TarError("drive-letter name rejected");
161
+ // Guard: links & special device nodes
162
+ if (typeflag === "1" || typeflag === "2") throw new TarError("symlinks and hardlinks not allowed");
163
+ if (typeflag === "3" || typeflag === "4" || typeflag === "6") throw new TarError("special device entries not allowed");
164
+
165
+ const normalizedEntry = entryName.replaceAll("\\", "/");
166
+ const destPath = resolve(destRoot, normalizedEntry);
167
+ const rel = relative(destRoot, destPath);
168
+ // Guard: dot-dot escape via cross-platform relative containment check
169
+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
170
+ throw new TarError("path escapes target (dot-dot)");
171
+ }
172
+
173
+ // Read data
174
+ const { data, off: newOff } = readData(raw, off, size);
175
+ off = newOff; // pad to 512 boundary
176
+
177
+ if (typeflag === "S" || typeflag === "K") {
178
+ // sparse: treat as normal file if header size sane, else skip
179
+ if (size > MAX_DECOMPRESSED) { out.push({ name: entryName, size: 0 }); continue; }
180
+ }
181
+
182
+ const relPath = rel.replaceAll("\\", "/");
183
+ if (!relPath || relPath === ".") continue;
184
+ const lowerRel = relPath.toLowerCase();
185
+
186
+ // Case-collision guard
187
+ if (lowerPaths.has(lowerRel)) {
188
+ throw new TarError(`case collision: ${relPath}`);
189
+ }
190
+ lowerPaths.add(lowerRel);
191
+ writtenPaths.add(relPath);
192
+
193
+ const fullPath = destPath;
194
+ if (typeflag === "5") {
195
+ mkdirSync(fullPath, { recursive: true });
196
+ } else {
197
+ mkdirSync(dirname(fullPath), { recursive: true });
198
+ writeFileSync(fullPath, data);
199
+ }
200
+ out.push({ name: relPath, size });
201
+ }
202
+ return out;
203
+ }
204
+
205
+ /** Minimal ustar writer: 512-byte headers, octal fields, zero padding. */
206
+ export function writeTarFixtures(entries: { name: string; content: string | Buffer }[]): Buffer {
207
+ const blocks: Buffer[] = [];
208
+ for (const e of entries) {
209
+ const content = typeof e.content === "string" ? Buffer.from(e.content, "utf8") : e.content;
210
+ const size = content.length;
211
+ const sizeOct = size.toString(8).padStart(11, "0").slice(0, 11) + "\0";
212
+ const name = e.name.slice(0, 99);
213
+ const hdr = Buffer.alloc(512);
214
+ // name (0-99)
215
+ Buffer.from(name).copy(hdr, 0);
216
+ // mode (100-107)
217
+ hdr.write("0000644\0", 100);
218
+ // uid/gid (108-135)
219
+ hdr.write("0000000\0", 108);
220
+ hdr.write("0000000\0", 116);
221
+ // size (124-135)
222
+ Buffer.from(sizeOct).copy(hdr, 124);
223
+ // mtime (136-147)
224
+ hdr.write("00000000000\0", 136);
225
+ // typeflag (156)
226
+ hdr.write("0", 156);
227
+ // magic (257-262)
228
+ hdr.write("ustar\0", 257);
229
+ // version (263-264)
230
+ hdr.write("00", 263);
231
+ // prefix (345-500) — empty for simple names
232
+ blocks.push(hdr);
233
+ blocks.push(content);
234
+ // pad to 512
235
+ const pad = (512 - (content.length % 512)) % 512;
236
+ if (pad) blocks.push(Buffer.alloc(pad));
237
+ }
238
+ // Two zero blocks = end
239
+ blocks.push(Buffer.alloc(1024));
240
+ return Buffer.concat(blocks);
241
+ }
package/src/pricing.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Model price table — USD per 1M tokens (input, output).
3
+ * Patterns match against the model id, case-insensitive; first match wins,
4
+ * so put the most specific patterns first. Unknown models cost $0 with an
5
+ * "(no price known)" note rather than a made-up number.
6
+ */
7
+ export interface Price {
8
+ in: number;
9
+ out: number;
10
+ }
11
+
12
+ const PRICE_PATTERNS: [RegExp, Price][] = [
13
+ // Anthropic
14
+ [/opus/, { in: 15, out: 75 }],
15
+ [/sonnet/, { in: 3, out: 15 }],
16
+ [/haiku/, { in: 0.8, out: 4 }],
17
+ // OpenAI
18
+ [/gpt-4\.1\b/, { in: 2, out: 8 }],
19
+ [/gpt-5\b/, { in: 1.25, out: 10 }],
20
+ [/o[134]-?mini/, { in: 1.1, out: 4.4 }],
21
+ [/gpt-4o/, { in: 2.5, out: 10 }],
22
+ [/gpt-4o-mini|gpt-4\.1-nano/, { in: 0.15, out: 0.6 }],
23
+ // Google
24
+ [/gemini.*flash/, { in: 0.3, out: 2.5 }],
25
+ [/gemini.*pro/, { in: 1.25, out: 10 }],
26
+ // DeepSeek
27
+ [/deepseek.*(chat|v3)/, { in: 0.27, out: 1.1 }],
28
+ [/deepseek.*reasoner|deepseek-r1/, { in: 0.55, out: 2.19 }],
29
+ // Meta / Llama
30
+ [/llama-?3\.3-70b|llama-3\.1-70b/, { in: 0.59, out: 0.79 }],
31
+ [/llama-?4|llama-3\.[12]-405b/, { in: 2, out: 5 }],
32
+ // Mistral
33
+ [/mistral-large/, { in: 2, out: 6 }],
34
+ [/mistral|devstral/, { in: 0.4, out: 2 }],
35
+ // Qwen
36
+ [/qwen.*(235b|max)/, { in: 1.6, out: 6.4 }],
37
+ [/qwen/, { in: 0.23, out: 0.92 }],
38
+ ];
39
+
40
+ export function priceFor(model: string): Price | null {
41
+ const m = model.toLowerCase();
42
+ for (const [re, p] of PRICE_PATTERNS) if (re.test(m)) return p;
43
+ return null;
44
+ }
45
+
46
+ /** Estimated USD spend for token counts, e.g. costUsd("anthropic/claude-sonnet-4-5", 120000, 3400). */
47
+ export interface TokenUsage {
48
+ in: number; out: number; cacheRead?: number; cacheWrite?: number;
49
+ }
50
+
51
+ /**
52
+ * Estimated USD spend. Anthropic bills cache reads at 0.1x and cache writes at
53
+ * 1.25x the input price; `inTok` from the API EXCLUDES cached tokens, so the
54
+ * cache blocks are priced on top. Legacy (in, out) call shape still works.
55
+ */
56
+ export function costUsd(model: string, inTok: number | TokenUsage, outTok?: number): number | null {
57
+ const p = priceFor(model);
58
+ if (!p) return null;
59
+ const u: TokenUsage = typeof inTok === "number"
60
+ ? { in: inTok, out: outTok ?? 0 }
61
+ : inTok;
62
+ const M = 1_000_000;
63
+ return (u.in / M) * p.in
64
+ + ((u.cacheRead ?? 0) / M) * p.in * 0.1
65
+ + ((u.cacheWrite ?? 0) / M) * p.in * 1.25
66
+ + (u.out / M) * p.out;
67
+ }
68
+
69
+ /** USD saved by cache hits vs uncached input price (0 when nothing cached). */
70
+ export function cacheSavings(model: string, u: TokenUsage): number | null {
71
+ const p = priceFor(model);
72
+ if (!p || !u.cacheRead) return null;
73
+ return (u.cacheRead / 1_000_000) * p.in * 0.9;
74
+ }
75
+
76
+ export function fmtUsd(n: number): string {
77
+ return n < 0.01 ? `$${n.toFixed(4)}` : `$${n.toFixed(2)}`;
78
+ }