@gajae-code/coding-agent 0.11.6 → 0.11.7

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 (131) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/types/capability/index.d.ts +10 -20
  3. package/dist/types/capability/types.d.ts +3 -0
  4. package/dist/types/commands/daemon.d.ts +2 -2
  5. package/dist/types/commands/sdk.d.ts +20 -2
  6. package/dist/types/config/keybindings.d.ts +1 -1
  7. package/dist/types/config/settings-schema.d.ts +56 -6
  8. package/dist/types/eval/py/runner-artifact.d.ts +8 -0
  9. package/dist/types/gjc-runtime/ultragoal-guard.d.ts +5 -5
  10. package/dist/types/gjc-runtime/ultragoal-receipt-freshness.d.ts +20 -0
  11. package/dist/types/gjc-runtime/ultragoal-runtime.d.ts +19 -5
  12. package/dist/types/main.d.ts +24 -1
  13. package/dist/types/modes/components/btw-panel.d.ts +1 -0
  14. package/dist/types/modes/components/model-selector.d.ts +2 -0
  15. package/dist/types/modes/components/tool-status-header.d.ts +1 -0
  16. package/dist/types/modes/controllers/btw-controller.d.ts +5 -0
  17. package/dist/types/modes/interactive-mode.d.ts +2 -0
  18. package/dist/types/modes/types.d.ts +1 -0
  19. package/dist/types/runtime-mcp/content-limits.d.ts +7 -0
  20. package/dist/types/sdk/bus/chat-daemon-control.d.ts +2 -1
  21. package/dist/types/sdk/bus/index.d.ts +1 -1
  22. package/dist/types/sdk/bus/lifecycle-commands.d.ts +5 -4
  23. package/dist/types/sdk/bus/notification-service.d.ts +34 -0
  24. package/dist/types/sdk/bus/telegram-daemon-contract.d.ts +8 -3
  25. package/dist/types/sdk/bus/telegram-daemon.d.ts +61 -3
  26. package/dist/types/sdk/bus/topic-registry.d.ts +88 -2
  27. package/dist/types/sdk/client/discovery.d.ts +2 -0
  28. package/dist/types/sdk/client/liveness.d.ts +7 -0
  29. package/dist/types/sdk/transport/auth-preface.d.ts +9 -0
  30. package/dist/types/sdk/transport/index.d.ts +12 -0
  31. package/dist/types/sdk/transport/relay.d.ts +43 -0
  32. package/dist/types/sdk/transport/serve-cli.d.ts +4 -0
  33. package/dist/types/sdk/transport/socket.d.ts +7 -0
  34. package/dist/types/sdk/transport/stdio.d.ts +3 -0
  35. package/dist/types/session/agent-session.d.ts +28 -5
  36. package/dist/types/session/btw-contract.d.ts +16 -0
  37. package/dist/types/session/internal/managed-session-scope.d.ts +21 -7
  38. package/dist/types/session/internal/managed-session-storage.d.ts +10 -8
  39. package/dist/types/session/session-manager.d.ts +25 -4
  40. package/dist/types/setup/credential-import.d.ts +5 -1
  41. package/dist/types/setup/provider-onboarding.d.ts +2 -0
  42. package/dist/types/ssh/utils.d.ts +1 -0
  43. package/dist/types/task/discovery.d.ts +3 -1
  44. package/dist/types/tools/fetch.d.ts +5 -8
  45. package/dist/types/tools/image-gen.d.ts +16 -0
  46. package/dist/types/tools/skill-discovery.d.ts +7 -0
  47. package/dist/types/tools/sqlite-reader.d.ts +7 -0
  48. package/dist/types/utils/shell-snapshot.d.ts +12 -0
  49. package/dist/types/web/insane/bridge.d.ts +1 -0
  50. package/dist/types/web/insane/url-guard.d.ts +17 -0
  51. package/package.json +8 -8
  52. package/scripts/generate-sdk-operation-inventory.ts +2 -0
  53. package/src/capability/index.ts +50 -42
  54. package/src/capability/types.ts +3 -0
  55. package/src/cli/setup-cli.ts +10 -4
  56. package/src/cli.ts +34 -9
  57. package/src/commands/daemon.ts +22 -5
  58. package/src/commands/sdk.ts +42 -9
  59. package/src/config/keybindings.ts +1 -1
  60. package/src/config/model-profiles.ts +18 -0
  61. package/src/config/settings-schema.ts +57 -6
  62. package/src/defaults/gjc/skills/ultragoal/SKILL.md +42 -1
  63. package/src/discovery/ssh.ts +12 -1
  64. package/src/eval/py/kernel.ts +1 -21
  65. package/src/eval/py/runner-artifact.ts +84 -0
  66. package/src/extensibility/plugins/marketplace/fetcher.ts +191 -7
  67. package/src/gjc-runtime/ultragoal-guard.ts +88 -10
  68. package/src/gjc-runtime/ultragoal-receipt-freshness.ts +103 -0
  69. package/src/gjc-runtime/ultragoal-runtime.ts +275 -12
  70. package/src/gjc-runtime/workflow-manifest.generated.json +58 -0
  71. package/src/gjc-runtime/workflow-manifest.ts +23 -0
  72. package/src/internal-urls/docs-index.generated.ts +8 -7
  73. package/src/internal-urls/local-protocol.ts +32 -6
  74. package/src/main.ts +86 -27
  75. package/src/modes/action-registry.ts +1 -1
  76. package/src/modes/components/btw-panel.ts +82 -16
  77. package/src/modes/components/model-selector.ts +31 -3
  78. package/src/modes/components/tool-status-header.ts +6 -1
  79. package/src/modes/controllers/btw-controller.ts +119 -36
  80. package/src/modes/controllers/input-controller.ts +31 -0
  81. package/src/modes/controllers/selector-controller.ts +106 -12
  82. package/src/modes/interactive-mode.ts +16 -7
  83. package/src/modes/types.ts +1 -0
  84. package/src/prompts/system/btw-user.md +3 -8
  85. package/src/prompts/tools/skill-discovery.md +1 -0
  86. package/src/runtime-mcp/client.ts +41 -55
  87. package/src/runtime-mcp/content-limits.ts +71 -0
  88. package/src/runtime-mcp/json-rpc.ts +23 -9
  89. package/src/runtime-mcp/transports/http.ts +50 -16
  90. package/src/sdk/bus/chat-daemon-control.ts +4 -3
  91. package/src/sdk/bus/index.ts +4 -5
  92. package/src/sdk/bus/lifecycle-commands.ts +16 -7
  93. package/src/sdk/bus/notification-service.ts +41 -18
  94. package/src/sdk/bus/telegram-daemon-contract.ts +8 -3
  95. package/src/sdk/bus/telegram-daemon-control.ts +2 -2
  96. package/src/sdk/bus/telegram-daemon.ts +1663 -375
  97. package/src/sdk/bus/topic-registry.ts +451 -12
  98. package/src/sdk/client/discovery.ts +19 -3
  99. package/src/sdk/client/liveness.ts +49 -0
  100. package/src/sdk/protocol/operation-inventory.generated.json +11 -0
  101. package/src/sdk/session.ts +29 -5
  102. package/src/sdk/transport/auth-preface.ts +82 -0
  103. package/src/sdk/transport/index.ts +18 -0
  104. package/src/sdk/transport/relay.ts +252 -0
  105. package/src/sdk/transport/serve-cli.ts +105 -0
  106. package/src/sdk/transport/socket.ts +197 -0
  107. package/src/sdk/transport/stdio.ts +17 -0
  108. package/src/session/agent-session.ts +240 -149
  109. package/src/session/blob-store.ts +19 -6
  110. package/src/session/btw-contract.ts +59 -0
  111. package/src/session/internal/managed-session-scope.ts +313 -57
  112. package/src/session/internal/managed-session-storage.ts +146 -35
  113. package/src/session/session-manager.ts +319 -85
  114. package/src/setup/credential-import.ts +28 -3
  115. package/src/setup/provider-onboarding.ts +30 -1
  116. package/src/setup/provider-presets.json +2 -1
  117. package/src/slash-commands/builtin-registry.ts +1 -1
  118. package/src/ssh/utils.ts +14 -0
  119. package/src/task/discovery.ts +8 -2
  120. package/src/tools/ask.ts +1 -1
  121. package/src/tools/fetch.ts +13 -131
  122. package/src/tools/image-gen.ts +301 -20
  123. package/src/tools/read.ts +2 -0
  124. package/src/tools/skill-discovery.ts +39 -3
  125. package/src/tools/sqlite-reader.ts +63 -5
  126. package/src/utils/pasted-image-path.ts +15 -6
  127. package/src/utils/shell-snapshot.ts +173 -63
  128. package/src/web/insane/bridge.ts +5 -1
  129. package/src/web/insane/url-guard.ts +138 -27
  130. package/src/web/scrapers/types.ts +19 -49
  131. package/src/web/scrapers/utils.ts +12 -26
@@ -5,13 +5,15 @@
5
5
  * .bashrc/.zshrc, which can be sourced before each command to provide a familiar
6
6
  * shell experience.
7
7
  */
8
- import * as fs from "node:fs";
8
+ import * as fs from "node:fs/promises";
9
9
  import * as os from "node:os";
10
10
  import * as path from "node:path";
11
11
  import { postmortem } from "@gajae-code/utils";
12
12
 
13
- const cachedSnapshotPaths = new Map<string, string>();
14
13
  const SNAPSHOT_TIMEOUT_MS = 2_000;
14
+ const SNAPSHOT_ROOT_PREFIX = "gjc-shell-snapshots-";
15
+ const PRIVATE_DIRECTORY_MODE = 0o700;
16
+ const PRIVATE_FILE_MODE = 0o600;
15
17
 
16
18
  function sanitizeSnapshotEnv(env: Record<string, string | undefined>): Record<string, string | undefined> {
17
19
  const sanitized = { ...env };
@@ -23,8 +25,7 @@ function sanitizeSnapshotEnv(env: Record<string, string | undefined>): Record<st
23
25
  /**
24
26
  * Get the user's shell config file path.
25
27
  */
26
- function getShellConfigFile(shell: string): string {
27
- const home = os.homedir();
28
+ function getShellConfigFile(shell: string, home: string): string {
28
29
  if (shell.includes("zsh")) return path.join(home, ".zshrc");
29
30
  if (shell.includes("bash")) return path.join(home, ".bashrc");
30
31
  return path.join(home, ".profile");
@@ -35,8 +36,7 @@ function getShellConfigFile(shell: string): string {
35
36
  * This script sources the user's rc file and extracts functions, aliases, and options.
36
37
  * Matches Anthropic Code's snapshot generation logic.
37
38
  */
38
- function generateSnapshotScript(shell: string, snapshotPath: string, rcFile: string): string {
39
- const hasRcFile = fs.existsSync(rcFile);
39
+ function generateSnapshotScript(shell: string, snapshotPath: string, rcFile: string, hasRcFile: boolean): string {
40
40
  const isZsh = shell.includes("zsh");
41
41
  const commonToolsRegex =
42
42
  "^(ls|dir|vdir|cat|head|tail|less|more|grep|egrep|fgrep|rg|find|fd|locate|sed|awk|perl|cp|mv|rm|mkdir|rmdir|touch|chmod|chown|ln|pwd|readlink|stat|cut|sort|uniq|xargs|tee|tr|basename|dirname)$";
@@ -79,6 +79,7 @@ echo "shopt -s expand_aliases" >> "$SNAPSHOT_FILE"
79
79
  `;
80
80
 
81
81
  return `
82
+ umask 077
82
83
  SNAPSHOT_FILE='${escapedPath}'
83
84
 
84
85
  # Source user's rc file if it exists
@@ -114,74 +115,183 @@ fi
114
115
  `.trim();
115
116
  }
116
117
 
117
- /**
118
- * Create a shell snapshot, caching the result.
119
- * Returns the path to the snapshot file, or null if creation failed.
120
- */
121
- export async function getOrCreateSnapshot(
122
- shell: string,
123
- env: Record<string, string | undefined>,
124
- ): Promise<string | null> {
125
- const cacheKey = shell;
126
- // Return cached snapshot if valid
127
- const cached = cachedSnapshotPaths.get(cacheKey);
128
- if (cached && fs.existsSync(cached)) {
129
- return cached;
130
- }
131
- if (cached) {
132
- cachedSnapshotPaths.delete(cacheKey);
133
- }
118
+ interface ShellSnapshotCacheOptions {
119
+ tempRoot: string;
120
+ home: string | (() => string);
121
+ platform: NodeJS.Platform;
122
+ }
134
123
 
135
- // Skip on Windows (no .bashrc in standard location)
136
- if (process.platform === "win32") {
137
- return null;
124
+ function ownedByCurrentUser(uid: number): boolean {
125
+ return typeof process.getuid !== "function" || uid === process.getuid();
126
+ }
127
+
128
+ async function isTrustedSnapshot(snapshotPath: string): Promise<boolean> {
129
+ try {
130
+ const stat = await fs.lstat(snapshotPath);
131
+ return stat.isFile() && !stat.isSymbolicLink() && ownedByCurrentUser(stat.uid) && (stat.mode & 0o077) === 0;
132
+ } catch {
133
+ return false;
138
134
  }
135
+ }
139
136
 
140
- const rcFile = getShellConfigFile(shell);
137
+ function createShellSnapshotCache(options: ShellSnapshotCacheOptions) {
138
+ const cachedPaths = new Map<string, string>();
139
+ const inFlight = new Map<string, Promise<string | null>>();
140
+ let rootPath: string | null = null;
141
+ let rootInitialization: Promise<string> | null = null;
142
+ let cleanupAttempt: Promise<void> | null = null;
143
+ let cleaningUp = false;
144
+ let lifecycle = 0;
141
145
 
142
- // Create snapshot directory
143
- const snapshotDir = path.join(os.tmpdir(), "gjc-shell-snapshots");
144
- fs.mkdirSync(snapshotDir, { recursive: true });
146
+ async function initializeRoot(): Promise<string> {
147
+ const root = await fs.mkdtemp(path.join(options.tempRoot, SNAPSHOT_ROOT_PREFIX));
148
+ try {
149
+ await fs.chmod(root, PRIVATE_DIRECTORY_MODE);
150
+ const stat = await fs.lstat(root);
151
+ if (
152
+ !stat.isDirectory() ||
153
+ stat.isSymbolicLink() ||
154
+ !ownedByCurrentUser(stat.uid) ||
155
+ (stat.mode & 0o777) !== 0o700
156
+ ) {
157
+ throw new Error("Shell snapshot root is not owner-private");
158
+ }
159
+ return root;
160
+ } catch (error) {
161
+ await fs.rm(root, { recursive: true, force: true }).catch(() => {});
162
+ throw error;
163
+ }
164
+ }
165
+
166
+ async function getRoot(): Promise<string> {
167
+ if (rootPath) return rootPath;
168
+ if (rootInitialization) return await rootInitialization;
169
+ const attempt = initializeRoot();
170
+ rootInitialization = attempt;
171
+ try {
172
+ rootPath = await attempt;
173
+ return rootPath;
174
+ } catch (error) {
175
+ if (rootInitialization === attempt) rootInitialization = null;
176
+ throw error;
177
+ }
178
+ }
145
179
 
146
- // Generate unique snapshot path
147
- const shellName = shell.includes("zsh") ? "zsh" : shell.includes("bash") ? "bash" : "sh";
148
- const snapshotPath = path.join(snapshotDir, `snapshot-${shellName}-${crypto.randomUUID()}.sh`);
180
+ async function createSnapshot(shell: string, env: Record<string, string | undefined>): Promise<string | null> {
181
+ const root = await getRoot();
182
+ const shellName = shell.includes("zsh") ? "zsh" : shell.includes("bash") ? "bash" : "sh";
183
+ const snapshotPath = path.join(root, `snapshot-${shellName}-${crypto.randomUUID()}.sh`);
184
+ let keep = false;
185
+ try {
186
+ const handle = await fs.open(snapshotPath, "wx", PRIVATE_FILE_MODE);
187
+ try {
188
+ await handle.chmod(PRIVATE_FILE_MODE);
189
+ } finally {
190
+ await handle.close();
191
+ }
149
192
 
150
- // Generate and execute snapshot script
151
- const script = generateSnapshotScript(shell, snapshotPath, rcFile);
193
+ const home = typeof options.home === "function" ? options.home() : options.home;
194
+ const rcFile = getShellConfigFile(shell, home);
195
+ const script = generateSnapshotScript(shell, snapshotPath, rcFile, await Bun.file(rcFile).exists());
196
+ const snapshotEnv = sanitizeSnapshotEnv(env);
197
+ const spawnEnv: Record<string, string> = {};
198
+ for (const [key, value] of Object.entries(snapshotEnv)) {
199
+ if (value !== undefined) spawnEnv[key] = value;
200
+ }
201
+ const child = Bun.spawn([shell, "-c", script], {
202
+ env: spawnEnv,
203
+ stdin: "ignore",
204
+ stdout: "ignore",
205
+ stderr: "ignore",
206
+ timeout: SNAPSHOT_TIMEOUT_MS,
207
+ killSignal: "SIGKILL",
208
+ });
152
209
 
153
- try {
154
- const snapshotEnv = sanitizeSnapshotEnv(env);
155
- const spawnEnv: Record<string, string> = {};
156
- for (const [key, value] of Object.entries(snapshotEnv)) {
157
- if (value !== undefined) {
158
- spawnEnv[key] = value;
210
+ await child.exited;
211
+ if (child.exitCode === 0 && (await isTrustedSnapshot(snapshotPath))) {
212
+ cachedPaths.set(shell, snapshotPath);
213
+ keep = true;
214
+ return snapshotPath;
159
215
  }
216
+ } catch {
217
+ // Snapshot creation failed, proceed without it.
218
+ } finally {
219
+ if (!keep) await fs.unlink(snapshotPath).catch(() => {});
160
220
  }
161
- const child = Bun.spawn([shell, "-c", script], {
162
- env: spawnEnv,
163
- stdin: "ignore",
164
- stdout: "ignore",
165
- stderr: "ignore",
166
- timeout: SNAPSHOT_TIMEOUT_MS,
167
- killSignal: "SIGKILL",
168
- });
169
-
170
- await child.exited;
171
- if (child.exitCode === 0 && fs.existsSync(snapshotPath)) {
172
- cachedSnapshotPaths.set(cacheKey, snapshotPath);
173
- return snapshotPath;
174
- }
175
- } catch {
176
- // Snapshot creation failed, proceed without it
221
+ return null;
177
222
  }
178
223
 
179
- return null;
224
+ return {
225
+ async getOrCreateSnapshot(shell: string, env: Record<string, string | undefined>) {
226
+ if (options.platform === "win32" || cleaningUp) return null;
227
+ const currentLifecycle = lifecycle;
228
+ const cached = cachedPaths.get(shell);
229
+ if (cached && (await isTrustedSnapshot(cached))) {
230
+ return cleaningUp || lifecycle !== currentLifecycle ? null : cached;
231
+ }
232
+ if (cleaningUp || lifecycle !== currentLifecycle) return null;
233
+ if (cached) cachedPaths.delete(shell);
234
+ const pending = inFlight.get(shell);
235
+ if (pending) {
236
+ const snapshot = await pending;
237
+ return cleaningUp || lifecycle !== currentLifecycle ? null : snapshot;
238
+ }
239
+ const attempt = createSnapshot(shell, env);
240
+ inFlight.set(shell, attempt);
241
+ try {
242
+ const snapshot = await attempt;
243
+ return cleaningUp || lifecycle !== currentLifecycle ? null : snapshot;
244
+ } finally {
245
+ if (inFlight.get(shell) === attempt) inFlight.delete(shell);
246
+ }
247
+ },
248
+ async cleanup() {
249
+ if (cleanupAttempt) return await cleanupAttempt;
250
+ const attempt = (async () => {
251
+ cleaningUp = true;
252
+ lifecycle += 1;
253
+ try {
254
+ const pending: Promise<unknown>[] = [...inFlight.values()];
255
+ if (rootInitialization) pending.push(rootInitialization);
256
+ await Promise.allSettled(pending);
257
+ const root = rootPath ?? (await rootInitialization?.catch(() => null)) ?? null;
258
+ cachedPaths.clear();
259
+ inFlight.clear();
260
+ rootPath = null;
261
+ rootInitialization = null;
262
+ if (root) await fs.rm(root, { recursive: true, force: true });
263
+ } finally {
264
+ cleaningUp = false;
265
+ }
266
+ })();
267
+ cleanupAttempt = attempt;
268
+ try {
269
+ await attempt;
270
+ } finally {
271
+ if (cleanupAttempt === attempt) cleanupAttempt = null;
272
+ }
273
+ },
274
+ };
180
275
  }
181
276
 
182
- postmortem.register("shell-snapshot", () => {
183
- for (const snapshotPath of cachedSnapshotPaths.values()) {
184
- fs.unlinkSync(snapshotPath);
185
- }
186
- cachedSnapshotPaths.clear();
277
+ /** @internal Test-only factory for isolated filesystem and platform assertions. */
278
+ export const createShellSnapshotCacheForTesting = createShellSnapshotCache;
279
+
280
+ const processSnapshotCache = createShellSnapshotCache({
281
+ tempRoot: os.tmpdir(),
282
+ home: () => os.homedir(),
283
+ platform: process.platform,
187
284
  });
285
+
286
+ /**
287
+ * Create a shell snapshot, caching the result.
288
+ * Returns the path to the snapshot file, or null if creation failed.
289
+ */
290
+ export async function getOrCreateSnapshot(
291
+ shell: string,
292
+ env: Record<string, string | undefined>,
293
+ ): Promise<string | null> {
294
+ return await processSnapshotCache.getOrCreateSnapshot(shell, env);
295
+ }
296
+
297
+ postmortem.register("shell-snapshot", () => processSnapshotCache.cleanup());
@@ -31,6 +31,7 @@ const KILL_GRACE_MS = 2_000;
31
31
 
32
32
  /** Stable note prefixes — tests assert on these without depending on full stderr. */
33
33
  export const INSANE_NOTES = {
34
+ securityDisabled: `insane fallback disabled: remote renderer cannot preserve validated network routing`,
34
35
  guardBlocked: (reason: string) => `insane fallback blocked: target URL is not public HTTP(S): ${reason}`,
35
36
  vendorMissing: `insane fallback unavailable: vendor engine missing at packages/coding-agent/vendor/insane-search`,
36
37
  noPython: `insane fallback unavailable: python3 not found; install python3 and curl_cffi, then retry with web.insaneFallback=true`,
@@ -325,8 +326,11 @@ function mapEngineOutput(raw: EngineRawOutput, timeoutMs: number): InsaneBridgeR
325
326
  * (which MUST run before this is called). Never throws; always returns a result.
326
327
  */
327
328
  export async function tryInsaneFetch(url: string, options: TryInsaneFetchOptions = {}): Promise<InsaneBridgeResult> {
329
+ if (!options.runner) {
330
+ return { ok: false, reason: "disabled-security", notes: [INSANE_NOTES.securityDisabled] };
331
+ }
328
332
  const prober = options.prober ?? probeInsaneDependencies;
329
- const runner = options.runner ?? (inv => runEngineSubprocess(inv));
333
+ const runner = options.runner;
330
334
  const limit = options.concurrencyLimit ?? DEFAULT_CONCURRENCY;
331
335
 
332
336
  const deps = await prober();
@@ -28,12 +28,36 @@ export type PublicUrlResult = PublicUrlAccepted | PublicUrlRejected;
28
28
  /** Resolver seam so tests can inject DNS results without real lookups. */
29
29
  export type AddressResolver = (hostname: string) => Promise<string[]>;
30
30
 
31
+ type ProxyEnvironment = Record<string, string | undefined>;
32
+
33
+ export type GuardedPublicFetchResult =
34
+ | { ok: true; response: Response; logicalUrl: URL; wireUrl: URL }
35
+ | { ok: false; reason: string; logicalUrl: string };
36
+
31
37
  const defaultResolver: AddressResolver = async hostname => {
32
38
  const records = await dns.lookup(hostname, { all: true, verbatim: true });
33
39
  return records.map(record => record.address);
34
40
  };
35
41
 
36
42
  const BLOCKED_HOSTNAMES = new Set(["localhost", "localhost.localdomain", "0.0.0.0", ""]);
43
+ const PROXY_ENV_KEYS = ["HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"] as const;
44
+
45
+ export function hasConfiguredProxy(env: ProxyEnvironment): boolean {
46
+ return PROXY_ENV_KEYS.some(key => Boolean(env[key]));
47
+ }
48
+
49
+ async function resolveWithSignal(resolver: AddressResolver, hostname: string, signal?: AbortSignal): Promise<string[]> {
50
+ if (!signal) return resolver(hostname);
51
+ if (signal.aborted) throw signal.reason;
52
+ const { promise, reject } = Promise.withResolvers<never>();
53
+ const onAbort = () => reject(signal.reason);
54
+ signal.addEventListener("abort", onAbort, { once: true });
55
+ try {
56
+ return await Promise.race([resolver(hostname), promise]);
57
+ } finally {
58
+ signal.removeEventListener("abort", onAbort);
59
+ }
60
+ }
37
61
 
38
62
  function isBlockedHostname(hostname: string): boolean {
39
63
  const normalized = hostname.toLowerCase().replace(/\.$/, "");
@@ -67,37 +91,81 @@ function isPrivateIPv4(address: string): boolean {
67
91
  );
68
92
  }
69
93
 
70
- function normalizeIPv4MappedIPv6(address: string): string {
71
- return address.toLowerCase().startsWith("::ffff:") ? address.slice(7) : address;
94
+ function parseIPv6Bytes(address: string): Uint8Array | undefined {
95
+ let normalized = address.toLowerCase();
96
+ const ipv4Tail = normalized.slice(normalized.lastIndexOf(":") + 1);
97
+ if (ipv4Tail.includes(".")) {
98
+ const parts = ipv4Tail.split(".").map(part => Number.parseInt(part, 10));
99
+ if (parts.length !== 4 || parts.some(part => !Number.isInteger(part) || part < 0 || part > 255)) return;
100
+ normalized = `${normalized.slice(0, normalized.lastIndexOf(":") + 1)}${((parts[0] << 8) | parts[1]).toString(16)}:${((parts[2] << 8) | parts[3]).toString(16)}`;
101
+ }
102
+
103
+ const halves = normalized.split("::");
104
+ if (halves.length > 2) return;
105
+ const left = halves[0] ? halves[0].split(":") : [];
106
+ const right = halves[1] ? halves[1].split(":") : [];
107
+ const omitted = 8 - left.length - right.length;
108
+ if ((halves.length === 1 && omitted !== 0) || (halves.length === 2 && omitted < 1)) return;
109
+ const words = [...left, ...Array.from({ length: omitted }, () => "0"), ...right];
110
+ if (words.length !== 8 || words.some(word => !/^[0-9a-f]{1,4}$/.test(word))) return;
111
+
112
+ const bytes = new Uint8Array(16);
113
+ for (let index = 0; index < words.length; index++) {
114
+ const word = Number.parseInt(words[index], 16);
115
+ bytes[index * 2] = word >> 8;
116
+ bytes[index * 2 + 1] = word & 0xff;
117
+ }
118
+ return bytes;
119
+ }
120
+
121
+ interface IPv6Cidr {
122
+ network: Uint8Array;
123
+ prefixLength: number;
124
+ }
125
+
126
+ function ipv6Cidr(network: string, prefixLength: number): IPv6Cidr {
127
+ const bytes = parseIPv6Bytes(network);
128
+ if (!bytes) throw new Error(`Invalid static IPv6 CIDR: ${network}/${prefixLength}`);
129
+ return { network: bytes, prefixLength };
72
130
  }
73
131
 
132
+ function matchesIPv6Cidr(address: Uint8Array, cidr: IPv6Cidr): boolean {
133
+ const wholeBytes = Math.floor(cidr.prefixLength / 8);
134
+ for (let index = 0; index < wholeBytes; index++) {
135
+ if (address[index] !== cidr.network[index]) return false;
136
+ }
137
+ const remainingBits = cidr.prefixLength % 8;
138
+ if (remainingBits === 0) return true;
139
+ const mask = (0xff << (8 - remainingBits)) & 0xff;
140
+ return (address[wholeBytes] & mask) === (cidr.network[wholeBytes] & mask);
141
+ }
142
+
143
+ const IPV6_GLOBAL_UNICAST = ipv6Cidr("2000::", 3);
144
+ const BLOCKED_GLOBAL_IPV6_RANGES = [
145
+ ipv6Cidr("2001::", 23), // IETF protocol assignments
146
+ ipv6Cidr("2001:db8::", 32), // documentation
147
+ ipv6Cidr("2002::", 16), // 6to4
148
+ ipv6Cidr("2620:4f:8000::", 48), // AS112 service
149
+ ipv6Cidr("3ffe::", 16), // returned 6bone range
150
+ ipv6Cidr("3fff::", 20), // documentation
151
+ ] as const;
152
+
74
153
  function isPrivateIPv6(address: string): boolean {
75
- const normalized = address.toLowerCase();
76
- const mapped = normalizeIPv4MappedIPv6(normalized);
77
- if (mapped !== normalized && net.isIP(mapped) === 4) return isPrivateIPv4(mapped);
154
+ const bytes = parseIPv6Bytes(address);
155
+ if (!bytes) return true;
156
+ const isIPv4Mapped = bytes.subarray(0, 10).every(byte => byte === 0) && bytes[10] === 0xff && bytes[11] === 0xff;
157
+ if (isIPv4Mapped) return isPrivateIPv4(`${bytes[12]}.${bytes[13]}.${bytes[14]}.${bytes[15]}`);
78
158
  return (
79
- normalized === "::" || // unspecified
80
- normalized === "::1" || // loopback
81
- normalized.startsWith("fc") || // ULA fc00::/7
82
- normalized.startsWith("fd") || // ULA
83
- normalized.startsWith("fe8") || // link-local fe80::/10
84
- normalized.startsWith("fe9") ||
85
- normalized.startsWith("fea") ||
86
- normalized.startsWith("feb") ||
87
- normalized.startsWith("ff") || // multicast ff00::/8
88
- normalized.startsWith("2001:db8") || // documentation
89
- normalized.startsWith("::ffff:") // any remaining IPv4-mapped form we could not classify
159
+ !matchesIPv6Cidr(bytes, IPV6_GLOBAL_UNICAST) ||
160
+ BLOCKED_GLOBAL_IPV6_RANGES.some(cidr => matchesIPv6Cidr(bytes, cidr))
90
161
  );
91
162
  }
92
163
 
93
164
  /** True for any address that is not a routable public unicast address. */
94
165
  export function isPrivateOrSpecialAddress(address: string): boolean {
95
- const normalized = normalizeIPv4MappedIPv6(address);
96
- const family = net.isIP(normalized);
97
- if (family === 4) return isPrivateIPv4(normalized);
98
- if (family === 6) return isPrivateIPv6(normalized);
99
- // Re-check the raw value in case it was an IPv4-mapped IPv6 literal.
100
- if (net.isIP(address) === 6) return isPrivateIPv6(address);
166
+ const family = net.isIP(address);
167
+ if (family === 4) return isPrivateIPv4(address);
168
+ if (family === 6) return isPrivateIPv6(address);
101
169
  return true; // not a recognizable IP -> treat as unsafe
102
170
  }
103
171
 
@@ -108,7 +176,7 @@ export function isPrivateOrSpecialAddress(address: string): boolean {
108
176
  */
109
177
  export async function validatePublicHttpUrl(
110
178
  rawUrl: string,
111
- options: { resolver?: AddressResolver } = {},
179
+ options: { resolver?: AddressResolver; signal?: AbortSignal } = {},
112
180
  ): Promise<PublicUrlResult> {
113
181
  const resolver = options.resolver ?? defaultResolver;
114
182
 
@@ -128,18 +196,20 @@ export async function validatePublicHttpUrl(
128
196
  return { ok: false, reason: "localhost or internal host" };
129
197
  }
130
198
 
131
- const literalFamily = net.isIP(url.hostname);
199
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
200
+ const literalFamily = net.isIP(hostname);
132
201
  if (literalFamily !== 0) {
133
- if (isPrivateOrSpecialAddress(url.hostname)) {
202
+ if (isPrivateOrSpecialAddress(hostname)) {
134
203
  return { ok: false, reason: "private, loopback, link-local, or reserved IP literal" };
135
204
  }
136
- return { ok: true, url, addresses: [url.hostname] };
205
+ return { ok: true, url, addresses: [hostname] };
137
206
  }
138
207
 
139
208
  let addresses: string[];
140
209
  try {
141
- addresses = await resolver(url.hostname);
210
+ addresses = await resolveWithSignal(resolver, hostname, options.signal);
142
211
  } catch {
212
+ if (options.signal?.aborted) return { ok: false, reason: "host resolution aborted" };
143
213
  return { ok: false, reason: "host could not be resolved" };
144
214
  }
145
215
  if (addresses.length === 0) {
@@ -151,6 +221,47 @@ export async function validatePublicHttpUrl(
151
221
  return { ok: true, url, addresses };
152
222
  }
153
223
 
224
+ export async function guardedPublicFetch(
225
+ rawUrl: string,
226
+ init: BunFetchRequestInit = {},
227
+ options: { resolver?: AddressResolver } = {},
228
+ ): Promise<GuardedPublicFetchResult> {
229
+ if (Object.hasOwn(init, "proxy") || Object.hasOwn(init, "unix") || hasConfiguredProxy(process.env)) {
230
+ return { ok: false, reason: "proxy or Unix-socket routing is not allowed", logicalUrl: rawUrl };
231
+ }
232
+
233
+ const signal = init.signal ?? undefined;
234
+ const guard = await validatePublicHttpUrl(rawUrl, { resolver: options.resolver, signal });
235
+ if (signal?.aborted) throw signal.reason;
236
+ if (!guard.ok) return { ok: false, reason: guard.reason, logicalUrl: rawUrl };
237
+
238
+ const logicalUrl = guard.url;
239
+ const headers = new Headers(init.headers);
240
+ headers.delete("host");
241
+ headers.set("Host", logicalUrl.host);
242
+ const hostname = logicalUrl.hostname.replace(/^\[|\]$/g, "");
243
+ const tls =
244
+ logicalUrl.protocol === "https:"
245
+ ? { rejectUnauthorized: true, ...(net.isIP(hostname) === 0 ? { serverName: hostname } : {}) }
246
+ : undefined;
247
+ let lastError: unknown;
248
+ for (const address of guard.addresses) {
249
+ if (hasConfiguredProxy(process.env)) {
250
+ return { ok: false, reason: "proxy routing appeared during resolution", logicalUrl: rawUrl };
251
+ }
252
+ const wireUrl = new URL(logicalUrl);
253
+ wireUrl.hostname = net.isIP(address) === 6 ? `[${address}]` : address;
254
+ try {
255
+ const response = await fetch(wireUrl, { ...init, headers, redirect: "manual", keepalive: false, tls });
256
+ return { ok: true, response, logicalUrl, wireUrl };
257
+ } catch (error) {
258
+ if (signal?.aborted) throw signal.reason;
259
+ lastError = error;
260
+ }
261
+ }
262
+ throw lastError;
263
+ }
264
+
154
265
  export async function validatePublicHttpUrlForInsane(
155
266
  rawUrl: string,
156
267
  options: { resolver?: AddressResolver } = {},
@@ -5,7 +5,7 @@ import { ptree } from "@gajae-code/utils";
5
5
  import type { AgentStorage } from "../../session/agent-storage";
6
6
  import { ToolAbortError } from "../../tools/tool-errors";
7
7
  import type { AddressResolver } from "../insane/url-guard";
8
- import { validatePublicHttpUrl } from "../insane/url-guard";
8
+ import { guardedPublicFetch } from "../insane/url-guard";
9
9
 
10
10
  export { formatNumber } from "@gajae-code/utils";
11
11
 
@@ -85,20 +85,6 @@ export interface LoadPageResult {
85
85
  error?: string;
86
86
  }
87
87
 
88
- async function guardPublicFetchUrl(
89
- rawUrl: string,
90
- resolver: AddressResolver | undefined,
91
- context: string,
92
- ): Promise<{ ok: true; url: string } | { ok: false; error: string; finalUrl: string }> {
93
- const guard = await validatePublicHttpUrl(rawUrl, { resolver });
94
- if (guard.ok) return { ok: true, url: guard.url.toString() };
95
- return {
96
- ok: false,
97
- error: `${context}: target URL is not public HTTP(S): ${guard.reason}`,
98
- finalUrl: rawUrl,
99
- };
100
- }
101
-
102
88
  function shouldRewriteRedirectMethod(status: number, method: string): boolean {
103
89
  const normalized = method.toUpperCase();
104
90
  return status === 303 || ((status === 301 || status === 302) && normalized === "POST");
@@ -120,20 +106,7 @@ export async function loadPage(url: string, options: LoadPageOptions = {}): Prom
120
106
  maxRedirects = 10,
121
107
  } = options;
122
108
 
123
- let initialUrl = url;
124
- if (publicUrlGuard) {
125
- const guarded = await guardPublicFetchUrl(url, resolver, "Blocked URL fetch");
126
- if (!guarded.ok) {
127
- return {
128
- content: "",
129
- contentType: "",
130
- finalUrl: guarded.finalUrl,
131
- ok: false,
132
- error: guarded.error,
133
- };
134
- }
135
- initialUrl = guarded.url;
136
- }
109
+ const initialUrl = url;
137
110
 
138
111
  attempts: for (let attempt = 0; attempt < USER_AGENTS.length; attempt++) {
139
112
  if (signal?.aborted) {
@@ -165,36 +138,33 @@ export async function loadPage(url: string, options: LoadPageOptions = {}): Prom
165
138
  requestInit.body = currentBody;
166
139
  }
167
140
 
168
- const response = await fetch(currentUrl, requestInit);
141
+ const dial = publicUrlGuard
142
+ ? await guardedPublicFetch(currentUrl, requestInit, { resolver })
143
+ : { ok: true as const, response: await fetch(currentUrl, requestInit), logicalUrl: new URL(currentUrl) };
144
+ if (!dial.ok) {
145
+ return {
146
+ content: "",
147
+ contentType: "",
148
+ finalUrl: dial.logicalUrl,
149
+ ok: false,
150
+ error: `Blocked URL fetch: target URL is not public HTTP(S): ${dial.reason}`,
151
+ };
152
+ }
153
+ const { response } = dial;
154
+ const logicalUrl = dial.logicalUrl.toString();
169
155
  if (REDIRECT_STATUSES.has(response.status)) {
170
156
  const location = response.headers.get("location");
171
157
  if (!location) {
172
158
  return {
173
159
  content: "",
174
160
  contentType: "",
175
- finalUrl: currentUrl,
161
+ finalUrl: logicalUrl,
176
162
  ok: false,
177
163
  status: response.status,
178
164
  error: "Redirect response missing Location header",
179
165
  };
180
166
  }
181
- const redirectUrl = new URL(location, currentUrl).toString();
182
- if (publicUrlGuard) {
183
- const guarded = await guardPublicFetchUrl(redirectUrl, resolver, "Blocked URL redirect");
184
- if (!guarded.ok) {
185
- return {
186
- content: "",
187
- contentType: "",
188
- finalUrl: guarded.finalUrl,
189
- ok: false,
190
- status: response.status,
191
- error: guarded.error,
192
- };
193
- }
194
- currentUrl = guarded.url;
195
- } else {
196
- currentUrl = redirectUrl;
197
- }
167
+ currentUrl = new URL(location, logicalUrl).toString();
198
168
  if (shouldRewriteRedirectMethod(response.status, currentMethod)) {
199
169
  currentMethod = "GET";
200
170
  currentBody = undefined;
@@ -203,7 +173,7 @@ export async function loadPage(url: string, options: LoadPageOptions = {}): Prom
203
173
  }
204
174
 
205
175
  const contentType = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() ?? "";
206
- const finalUrl = response.url || currentUrl;
176
+ const finalUrl = logicalUrl;
207
177
 
208
178
  const reader = response.body?.getReader();
209
179
  if (!reader) {