@opengeni/runtime 4.0.3 → 4.1.0-canary.36239117573001

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 (38) hide show
  1. package/dist/assets/codemode-client.json +1 -1
  2. package/dist/{chunk-GBVN7WSK.js → chunk-ORTF5RRC.js} +371 -28
  3. package/dist/chunk-ORTF5RRC.js.map +1 -0
  4. package/dist/{chunk-LL2YQO5H.js → chunk-YAA7WDNO.js} +638 -71
  5. package/dist/chunk-YAA7WDNO.js.map +1 -0
  6. package/dist/codex-tool-search.d.ts +12 -0
  7. package/dist/context-compaction.d.ts +4 -2
  8. package/dist/index.d.ts +27 -8
  9. package/dist/index.js +18 -2
  10. package/dist/knowledge-model-projection.d.ts +28 -0
  11. package/dist/metrics.d.ts +17 -0
  12. package/dist/model-provider-routing.d.ts +14 -0
  13. package/dist/operational-instructions.d.ts +1 -1
  14. package/dist/provider-quota.d.ts +76 -0
  15. package/dist/sandbox/channel-a.d.ts +43 -0
  16. package/dist/sandbox/index.d.ts +1 -1
  17. package/dist/sandbox/index.js +5 -1
  18. package/dist/tool-result-spill.d.ts +11 -3
  19. package/dist/workspace-tool-gateway.js +2 -2
  20. package/package.json +11 -11
  21. package/src/codex-tool-search.ts +54 -6
  22. package/src/context-compaction.ts +19 -3
  23. package/src/index.ts +277 -56
  24. package/src/knowledge-model-projection.ts +169 -0
  25. package/src/lazy-tool-transport.ts +4 -0
  26. package/src/metrics.ts +26 -0
  27. package/src/model-context-inspector.ts +1 -0
  28. package/src/model-provider-client.ts +37 -16
  29. package/src/model-provider-routing.ts +32 -6
  30. package/src/operational-instructions.ts +1 -1
  31. package/src/provider-quota.ts +412 -0
  32. package/src/sandbox/browser-control-client.ts +70 -25
  33. package/src/sandbox/channel-a.ts +370 -0
  34. package/src/sandbox/index.ts +3 -0
  35. package/src/sandbox/routing/routing-session.ts +25 -4
  36. package/src/tool-result-spill.ts +17 -5
  37. package/dist/chunk-GBVN7WSK.js.map +0 -1
  38. package/dist/chunk-LL2YQO5H.js.map +0 -1
@@ -20,6 +20,7 @@
20
20
  // apply-patch-only path which cannot do binary, C4), falling back to
21
21
  // `createEditor` for text when `exec` is absent.
22
22
 
23
+ import { constants as zlibConstants, createGunzip } from "node:zlib";
23
24
  import type {
24
25
  FileSystemRouteIdentity,
25
26
  FsChangedPayload,
@@ -331,6 +332,140 @@ export type RepositoryDiscoveryResult = {
331
332
  };
332
333
 
333
334
  const REPOSITORY_DISCOVERY_TRUNCATED_SENTINEL = "__OPENGENI_REPOSITORY_DISCOVERY_TRUNCATED__";
335
+
336
+ /** Raw ripgrep stdout kept on the box before encoding. */
337
+ export const CODE_SEARCH_RG_MAX_BYTES = 64 * 1024 * 1024;
338
+ // Providers retain about 1 MiB per output stream. Like Git capture, compressed
339
+ // ripgrep output travels as 512 KiB chunks (~683 KiB base64) with room to spare.
340
+ const CODE_SEARCH_RG_CHUNK_BYTES = 512 * 1024;
341
+ const CODE_SEARCH_RG_FRAME_CHARS = 768 * 1024;
342
+ /** Compressed bytes fetched per call at most; the rest is reported as a cut. */
343
+ const CODE_SEARCH_RG_MAX_TRANSFER_BYTES = 8 * 1024 * 1024;
344
+ const CODE_SEARCH_RG_TOKEN = /^opengeni-code-search\.[A-Za-z0-9]+$/;
345
+ const CODE_SEARCH_RG_BEGIN = "__OPENGENI_CODE_SEARCH_RG_BEGIN__";
346
+ const CODE_SEARCH_RG_END = "__OPENGENI_CODE_SEARCH_RG_END__";
347
+ // Search: status:timedOut:compressedSize:token:rawSize:stored. A box without
348
+ // ripgrep sends only `127:0`, and a chunk fetch sends `0:0:0:-` or `0:0:0:missing`.
349
+ const CODE_SEARCH_RG_TRAILER = new RegExp(
350
+ `${CODE_SEARCH_RG_END}(\\d+):([01])(?::(\\d+):([A-Za-z0-9._-]+)(?::(\\d+):([01]))?)?__`,
351
+ );
352
+ const CODE_SEARCH_RG_STORE_FAILED =
353
+ "code search could not store its output on this machine; its temporary directory may be full";
354
+ const CODE_SEARCH_KINDS_BEGIN = "__OPENGENI_CODE_SEARCH_KINDS_BEGIN__";
355
+ const CODE_SEARCH_KINDS_END = "__OPENGENI_CODE_SEARCH_KINDS_END__";
356
+
357
+ export type CodeSearchRipgrepOutcome = {
358
+ /** False when ripgrep is not installed on the box. */
359
+ available: boolean;
360
+ stdout: string;
361
+ /** rg exit status (0 matches, 1 none, 2 error); null after a timeout. */
362
+ exitCode: number | null;
363
+ /** Output hit the byte cap and was cut at a line boundary. */
364
+ truncated: boolean;
365
+ timedOut: boolean;
366
+ };
367
+
368
+ const CODE_SEARCH_RG_FLAGS: ReadonlySet<string> = new Set([
369
+ "--files",
370
+ "--null",
371
+ "--line-number",
372
+ "--with-filename",
373
+ "--no-heading",
374
+ "-i",
375
+ "-w",
376
+ "--no-require-git",
377
+ "--hidden",
378
+ ]);
379
+ const CODE_SEARCH_RG_VALUE_FLAGS: ReadonlyMap<string, (value: string) => boolean> = new Map([
380
+ ["--color", (value: string) => value === "never"],
381
+ ["-m", (value: string) => /^[1-9]\d{0,5}$/.test(value)],
382
+ ["--max-columns", (value: string) => /^[1-9]\d{0,6}$/.test(value)],
383
+ ["--max-filesize", (value: string) => /^[1-9]\d{0,9}$/.test(value)],
384
+ ["-g", (value: string) => value.length > 0 && value.length <= 512],
385
+ ["-e", (value: string) => value.length > 0 && value.length <= 16_384],
386
+ ]);
387
+
388
+ /**
389
+ * Accept only the ripgrep arguments `code_search` needs. Flags that run a
390
+ * program (`--pre`, `-z`) or read other files, and paths that leave the
391
+ * workspace, are rejected before a command is built. `--no-config` stops a
392
+ * `RIPGREP_CONFIG_PATH` on the box from adding flags.
393
+ */
394
+ export function validateCodeSearchRipgrepArgs(
395
+ args: readonly string[],
396
+ workspaceRoot = "",
397
+ ): string[] {
398
+ const out: string[] = [];
399
+ let index = 0;
400
+ for (; index < args.length; index++) {
401
+ const arg = args[index]!;
402
+ if (arg.includes(NUL)) throw new ChannelAValidationError("ripgrep argument contains NUL");
403
+ if (arg === "--") break;
404
+ if (CODE_SEARCH_RG_FLAGS.has(arg)) {
405
+ out.push(arg);
406
+ continue;
407
+ }
408
+ const valid = CODE_SEARCH_RG_VALUE_FLAGS.get(arg);
409
+ const value = args[index + 1];
410
+ if (!valid || value === undefined || value.includes(NUL) || !valid(value)) {
411
+ throw new ChannelAValidationError(`ripgrep argument is not allowed: ${arg}`);
412
+ }
413
+ out.push(arg, value);
414
+ index++;
415
+ }
416
+ const paths = args.slice(index + 1);
417
+ if (index >= args.length || paths.length === 0) {
418
+ throw new ChannelAValidationError("ripgrep arguments must end with -- and paths");
419
+ }
420
+ out.push("--");
421
+ for (const path of paths) {
422
+ if (path.includes(NUL) || path.startsWith("-") || path.startsWith("/")) {
423
+ throw new ChannelAValidationError(`ripgrep path is not allowed: ${path}`);
424
+ }
425
+ out.push(assertSafeRelPathOrRoot(path, workspaceRoot) || ".");
426
+ }
427
+ return ["--no-config", ...out];
428
+ }
429
+
430
+ /** The base64 body between the begin marker and the trailer at `trailerIndex`. */
431
+ function decodeCodeSearchChunk(stdout: string, trailerIndex: number): Buffer {
432
+ const begin = stdout.indexOf(CODE_SEARCH_RG_BEGIN);
433
+ if (begin < 0 || begin > trailerIndex) {
434
+ throw new ChannelAUnavailableError("code search output frame is missing");
435
+ }
436
+ const encoded = stdout
437
+ .slice(begin + CODE_SEARCH_RG_BEGIN.length, trailerIndex)
438
+ .replace(/\s+/g, "");
439
+ // A frame longer than one chunk can only come from a broken or hostile box.
440
+ if (encoded.length > Math.ceil(CODE_SEARCH_RG_CHUNK_BYTES / 3) * 4) {
441
+ throw new ChannelAUnavailableError("code search output frame is malformed");
442
+ }
443
+ return Buffer.from(encoded, "base64");
444
+ }
445
+
446
+ /**
447
+ * Inflate at most `limit` bytes of box-controlled gzip. A sync flush decodes a
448
+ * cut stream as a prefix, and reading stops once `limit` is reached, so a
449
+ * small hostile frame cannot inflate to hundreds of megabytes in the worker.
450
+ */
451
+ async function gunzipCodeSearchPrefix(input: Buffer, limit: number): Promise<Buffer> {
452
+ const gunzip = createGunzip({ finishFlush: zlibConstants.Z_SYNC_FLUSH, chunkSize: 64 * 1024 });
453
+ gunzip.end(input);
454
+ const chunks: Buffer[] = [];
455
+ let size = 0;
456
+ try {
457
+ for await (const chunk of gunzip as AsyncIterable<Buffer>) {
458
+ chunks.push(chunk);
459
+ size += chunk.length;
460
+ // Leaving the loop destroys the stream before it inflates further.
461
+ if (size >= limit) break;
462
+ }
463
+ } catch {
464
+ throw new ChannelAUnavailableError("code search output could not be decoded");
465
+ }
466
+ return Buffer.concat(chunks, size).subarray(0, limit);
467
+ }
468
+
334
469
  const REPOSITORY_DISCOVERY_STATUS_PREFIX = "__OPENGENI_REPOSITORY_DISCOVERY_STATUS__:";
335
470
 
336
471
  const NUL = String.fromCharCode(0); // \0 NUL — find/porcelain/numstat -z separator
@@ -2278,6 +2413,241 @@ export class SandboxChannelAService {
2278
2413
  return (await this.detectReposDetailed()).repos;
2279
2414
  }
2280
2415
 
2416
+ // ═════════════════════════ Code search (worker-only) ═══════════════════════
2417
+
2418
+ /**
2419
+ * Run ripgrep read-only in the workspace root for the Jev `code_search` tool.
2420
+ * Arguments are checked against a closed allowlist (no `--pre`, `-z` or other
2421
+ * flags that run programs), so the command is provably read-only and skips
2422
+ * durable mutation admission. stdout is capped at `maxBytes`, gzip+base64
2423
+ * framed so providers that drop newlines or retain limited output cannot
2424
+ * corrupt it, and bounded by a wall-clock watchdog (not GNU `timeout`, which
2425
+ * stock macOS lacks). Resolves `available: false` when `rg` is not installed,
2426
+ * and throws when the box could not store the output whole (a full
2427
+ * temporary directory) rather than returning a prefix as complete.
2428
+ */
2429
+ async codeSearchRipgrep(
2430
+ args: readonly string[],
2431
+ options: { timeoutMs: number; maxBytes: number; maxTransferBytes?: number },
2432
+ ): Promise<CodeSearchRipgrepOutcome> {
2433
+ const argv = validateCodeSearchRipgrepArgs(args, this.workspaceRoot);
2434
+ const maxBytes = Math.max(1, Math.min(CODE_SEARCH_RG_MAX_BYTES, Math.floor(options.maxBytes)));
2435
+ const maxTransferBytes = Math.max(
2436
+ CODE_SEARCH_RG_CHUNK_BYTES,
2437
+ Math.min(
2438
+ CODE_SEARCH_RG_MAX_TRANSFER_BYTES,
2439
+ Math.floor(options.maxTransferBytes ?? CODE_SEARCH_RG_MAX_TRANSFER_BYTES),
2440
+ ),
2441
+ );
2442
+ const seconds = Math.max(1, Math.min(120, Math.ceil(options.timeoutMs / 1_000)));
2443
+ const script = [
2444
+ // Remove output a previous call could not fetch (worker gone mid-transfer).
2445
+ // The trailing slash makes find enter a symlinked /tmp, as on macOS.
2446
+ `find "\${TMPDIR:-/tmp}/" -maxdepth 1 -name 'opengeni-code-search.*' -mmin +15 -exec rm -f {} + 2>/dev/null`,
2447
+ 'gz_file=$(mktemp "${TMPDIR:-/tmp}/opengeni-code-search.XXXXXX") || exit 70',
2448
+ 'status_file="${gz_file}.status"',
2449
+ 'timeout_file="${gz_file}.timed-out"',
2450
+ "keep_gz=",
2451
+ "search_pid=",
2452
+ "watchdog_pid=",
2453
+ 'cleanup() { if [ -n "$search_pid" ]; then kill -TERM -- "-$search_pid" 2>/dev/null || kill "$search_pid" 2>/dev/null || true; fi; if [ -n "$watchdog_pid" ]; then kill "$watchdog_pid" 2>/dev/null || true; fi; rm -f "$status_file" "$timeout_file"; [ -n "$keep_gz" ] || rm -f "$gz_file"; }',
2454
+ "abort() { trap - EXIT; keep_gz=; cleanup; exit 143; }",
2455
+ "trap cleanup EXIT",
2456
+ "trap abort HUP INT TERM",
2457
+ `if ! command -v rg >/dev/null 2>&1; then printf '${CODE_SEARCH_RG_END}127:0__'; exit 0; fi`,
2458
+ // Job control gives the pipeline its own process group, so the watchdog
2459
+ // and cleanup stop ripgrep itself rather than only the subshell. Output is
2460
+ // compressed once, straight into the kept file: providers retain only
2461
+ // about 1 MiB per output stream, and later chunks are fetched by name.
2462
+ // That TERM stops only ripgrep and head. The subshell and gzip ignore it
2463
+ // (bash 3.2 runs a trap before the pipeline ends), so a stopped search
2464
+ // still stores a whole member and records every stage's status.
2465
+ "set -m",
2466
+ `( trap '' TERM; ( trap - TERM; exec rg ${argv.map(shellQuote).join(" ")} ) 2>/dev/null | ( trap - TERM; exec head -c ${maxBytes + 1} ) | gzip -c > "$gz_file"; printf '%s %s %s' "\${PIPESTATUS[0]}" "\${PIPESTATUS[1]}" "\${PIPESTATUS[2]}" > "$status_file" ) </dev/null >/dev/null 2>&1 &`,
2467
+ "search_pid=$!",
2468
+ `(sleeper_pid=; stop_watchdog() { if [ -n "$sleeper_pid" ]; then kill "$sleeper_pid" 2>/dev/null || true; wait "$sleeper_pid" 2>/dev/null || true; fi; exit 0; }; trap stop_watchdog HUP INT TERM; sleep ${seconds} & sleeper_pid=$!; wait "$sleeper_pid"; sleeper_pid=; if kill -TERM -- "-$search_pid" 2>/dev/null; then : > "$timeout_file"; fi) </dev/null >/dev/null 2>&1 &`,
2469
+ "watchdog_pid=$!",
2470
+ 'wait "$search_pid" 2>/dev/null',
2471
+ "search_pid=",
2472
+ 'kill "$watchdog_pid" 2>/dev/null || true',
2473
+ 'wait "$watchdog_pid" 2>/dev/null || true',
2474
+ "watchdog_pid=",
2475
+ "set +m",
2476
+ "rg_status= head_status= gzip_status=",
2477
+ 'if [ -f "$status_file" ]; then read -r rg_status head_status gzip_status < "$status_file"; fi',
2478
+ '[ -n "$rg_status" ] || rg_status=125',
2479
+ "timed_out=0",
2480
+ 'if [ -f "$timeout_file" ]; then timed_out=1; fi',
2481
+ // A full temporary directory cuts the member without a word, so decode it
2482
+ // end to end: that yields the raw size and fails on a cut or corrupt member.
2483
+ "stored=0",
2484
+ 'if raw_size=$(set -o pipefail; gzip -dc < "$gz_file" 2>/dev/null | wc -c | tr -d \' \') && [ "$head_status" = 0 ] && [ "$gzip_status" = 0 ]; then stored=1; fi',
2485
+ '[ -n "$raw_size" ] || raw_size=0',
2486
+ "gz_size=$(wc -c < \"$gz_file\" | tr -d ' ')",
2487
+ '[ -n "$gz_size" ] || gz_size=0',
2488
+ "token=-",
2489
+ // The worker fails an unstored search that did not time out, so only
2490
+ // keep output it will fetch.
2491
+ `if [ "$gz_size" -gt ${CODE_SEARCH_RG_CHUNK_BYTES} ] && { [ "$stored" = 1 ] || [ "$timed_out" = 1 ]; }; then keep_gz=1; token=$(basename "$gz_file"); fi`,
2492
+ `printf '${CODE_SEARCH_RG_BEGIN}'`,
2493
+ `head -c ${CODE_SEARCH_RG_CHUNK_BYTES} "$gz_file" | base64 | tr -d '\\r\\n'`,
2494
+ `printf '${CODE_SEARCH_RG_END}%s:%s:%s:%s:%s:%s__' "$rg_status" "$timed_out" "$gz_size" "$token" "$raw_size" "$stored"`,
2495
+ ].join("\n");
2496
+ const { stdout } = await this.runReadOnly({
2497
+ cmd: internalBashCommand(script),
2498
+ workdir: this.providerWorkspaceRoot(),
2499
+ yieldTimeMs: (seconds + 15) * 1_000,
2500
+ maxOutputTokens: CODE_SEARCH_RG_FRAME_CHARS,
2501
+ });
2502
+ const trailer = CODE_SEARCH_RG_TRAILER.exec(stdout);
2503
+ if (!trailer) {
2504
+ throw new ChannelAUnavailableError("code search did not complete in this workspace");
2505
+ }
2506
+ const exitCode = Number.parseInt(trailer[1]!, 10);
2507
+ if (exitCode === 127) {
2508
+ return { available: false, stdout: "", exitCode: null, truncated: false, timedOut: false };
2509
+ }
2510
+ if (trailer[3] === undefined || trailer[5] === undefined) {
2511
+ throw new ChannelAUnavailableError("code search output trailer is malformed");
2512
+ }
2513
+ const timedOut = trailer[2] === "1";
2514
+ // A stopped search keeps the whole lines it stored. Otherwise a lost
2515
+ // status or a failed or corrupt store must not pass as complete output.
2516
+ if (!timedOut && exitCode === 125) {
2517
+ throw new ChannelAUnavailableError(
2518
+ "code search did not record its status on this machine; its temporary directory may be full",
2519
+ );
2520
+ }
2521
+ if (!timedOut && trailer[6] !== "1") {
2522
+ throw new ChannelAUnavailableError(CODE_SEARCH_RG_STORE_FAILED);
2523
+ }
2524
+ const first = decodeCodeSearchChunk(stdout, trailer.index);
2525
+ const reportedSize = Number.parseInt(trailer[3], 10);
2526
+ const rawSize = Number.parseInt(trailer[5], 10);
2527
+ const token = trailer[4] === "-" ? null : trailer[4]!;
2528
+ const parts = [first];
2529
+ let fetched = first.length;
2530
+ if (token !== null && reportedSize > fetched) {
2531
+ if (!CODE_SEARCH_RG_TOKEN.test(token)) {
2532
+ throw new ChannelAUnavailableError("code search output frame is malformed");
2533
+ }
2534
+ // A box that lies about its size never gets more than the transfer cap
2535
+ // fetched from it, nor more calls than that cap needs.
2536
+ const target = Math.min(reportedSize, maxTransferBytes);
2537
+ const maxCalls = Math.ceil(maxTransferBytes / CODE_SEARCH_RG_CHUNK_BYTES);
2538
+ for (let call = 0; call < maxCalls && fetched < target; call++) {
2539
+ const length = Math.min(CODE_SEARCH_RG_CHUNK_BYTES, target - fetched);
2540
+ const chunk = await this.codeSearchRipgrepChunk(
2541
+ token,
2542
+ fetched,
2543
+ length,
2544
+ fetched + length >= target,
2545
+ );
2546
+ if (chunk === null) break;
2547
+ parts.push(chunk);
2548
+ fetched += chunk.length;
2549
+ // A real box returns every byte asked for; a short chunk ends the
2550
+ // transfer and is reported as a cut.
2551
+ if (chunk.length < length) break;
2552
+ }
2553
+ }
2554
+ const transferCut = fetched < reportedSize;
2555
+ // The box already cut stdout at maxBytes + 1, so more decoded bytes than
2556
+ // that come from a broken or hostile box and are dropped as a cut.
2557
+ const compressed = Buffer.concat(parts);
2558
+ const raw = compressed.length
2559
+ ? await gunzipCodeSearchPrefix(compressed, maxBytes + 1)
2560
+ : Buffer.alloc(0);
2561
+ const rawCut = raw.length > maxBytes;
2562
+ // With nothing cut, the output must be exactly what the box verified.
2563
+ const sizeMismatch = !rawCut && !transferCut && !timedOut && raw.length !== rawSize;
2564
+ const truncated = rawCut || transferCut || sizeMismatch;
2565
+ let text = (rawCut ? raw.subarray(0, maxBytes) : raw).toString("utf8");
2566
+ if (truncated || timedOut) {
2567
+ // Drop the last partial line so every returned record is whole.
2568
+ const lastNewline = text.lastIndexOf("\n");
2569
+ text = lastNewline >= 0 ? text.slice(0, lastNewline + 1) : "";
2570
+ }
2571
+ return {
2572
+ available: true,
2573
+ stdout: text,
2574
+ exitCode: timedOut ? null : exitCode,
2575
+ truncated,
2576
+ timedOut,
2577
+ };
2578
+ }
2579
+
2580
+ /**
2581
+ * Fetch one chunk of compressed ripgrep output kept on the box by a previous
2582
+ * codeSearchRipgrep call. The last fetch deletes the file. Null when the
2583
+ * file is gone.
2584
+ */
2585
+ private async codeSearchRipgrepChunk(
2586
+ token: string,
2587
+ offset: number,
2588
+ length: number,
2589
+ last: boolean,
2590
+ ): Promise<Buffer | null> {
2591
+ const script = [
2592
+ 'f="${TMPDIR:-/tmp}/$1"',
2593
+ `if [ ! -f "$f" ]; then printf '${CODE_SEARCH_RG_END}0:0:0:missing__'; exit 0; fi`,
2594
+ `printf '${CODE_SEARCH_RG_BEGIN}'`,
2595
+ 'tail -c +"$2" "$f" | head -c "$3" | base64 | tr -d \'\\r\\n\'',
2596
+ `printf '${CODE_SEARCH_RG_END}0:0:0:-__'`,
2597
+ 'if [ "$4" = 1 ]; then rm -f "$f"; fi',
2598
+ ].join("\n");
2599
+ const { stdout } = await this.runReadOnly({
2600
+ cmd: `${internalBashCommand(script)} opengeni-code-search ${shellQuote(token)} ${offset + 1} ${length} ${last ? 1 : 0}`,
2601
+ workdir: this.providerWorkspaceRoot(),
2602
+ yieldTimeMs: 30_000,
2603
+ maxOutputTokens: CODE_SEARCH_RG_FRAME_CHARS,
2604
+ });
2605
+ const trailer = CODE_SEARCH_RG_TRAILER.exec(stdout);
2606
+ if (!trailer) {
2607
+ throw new ChannelAUnavailableError("code search did not complete in this workspace");
2608
+ }
2609
+ if (trailer[4] === "missing") return null;
2610
+ const chunk = decodeCodeSearchChunk(stdout, trailer.index);
2611
+ if (chunk.length > length) {
2612
+ throw new ChannelAUnavailableError("code search output frame is malformed");
2613
+ }
2614
+ return chunk;
2615
+ }
2616
+
2617
+ /** Classify workspace-relative paths for `code_search` path filters. */
2618
+ async codeSearchPathKinds(
2619
+ paths: readonly string[],
2620
+ ): Promise<Record<string, "file" | "directory" | "missing">> {
2621
+ const checked = paths.map((path) => {
2622
+ if (path.startsWith("-")) throw new ChannelAValidationError(`invalid path: ${path}`);
2623
+ return assertSafeRelPathOrRoot(path, this.workspaceRoot) || ".";
2624
+ });
2625
+ if (checked.length === 0) return {};
2626
+ const script = [
2627
+ `printf '${CODE_SEARCH_KINDS_BEGIN}'`,
2628
+ 'for p in "$@"; do if [ -d "$p" ]; then printf d; elif [ -e "$p" ]; then printf f; else printf m; fi; done',
2629
+ `printf '${CODE_SEARCH_KINDS_END}'`,
2630
+ ].join("\n");
2631
+ const { stdout } = await this.runReadOnly({
2632
+ cmd: `${internalBashCommand(script)} opengeni-code-search ${checked.map(shellQuote).join(" ")}`,
2633
+ workdir: this.providerWorkspaceRoot(),
2634
+ yieldTimeMs: 20_000,
2635
+ maxOutputTokens: 4_096,
2636
+ });
2637
+ const match = new RegExp(`${CODE_SEARCH_KINDS_BEGIN}([dfm]*)${CODE_SEARCH_KINDS_END}`).exec(
2638
+ stdout,
2639
+ );
2640
+ if (!match || match[1]!.length !== checked.length) {
2641
+ throw new ChannelAUnavailableError("code search path check did not complete");
2642
+ }
2643
+ const kinds: Record<string, "file" | "directory" | "missing"> = {};
2644
+ paths.forEach((path, index) => {
2645
+ const code = match[1]![index];
2646
+ kinds[path] = code === "d" ? "directory" : code === "f" ? "file" : "missing";
2647
+ });
2648
+ return kinds;
2649
+ }
2650
+
2281
2651
  // ════════════════════════ Terminal exec + PTY (A2) ════════════════════════
2282
2652
 
2283
2653
  /** Run a bounded command to physical completion and return buffered output.
@@ -431,6 +431,9 @@ export {
431
431
  parseNumstatZ,
432
432
  parseUnifiedPatch,
433
433
  REPOSITORY_DISCOVERY_LIMIT,
434
+ CODE_SEARCH_RG_MAX_BYTES,
435
+ validateCodeSearchRipgrepArgs,
436
+ type CodeSearchRipgrepOutcome,
434
437
  type ChannelASession,
435
438
  type ChannelAExecArgs,
436
439
  type ChannelAExecResult,
@@ -27,6 +27,8 @@
27
27
  // real `readActiveSandbox` DAO + a backend resolver without coupling the leaf to
28
28
  // `@opengeni/db`.
29
29
 
30
+ import { SandboxWorkspaceReadNotFoundError } from "@openai/agents/sandbox";
31
+ import { SandboxFilesystemNotFoundError } from "modal";
30
32
  import type { ExposedPortEndpoint } from "../stream-port";
31
33
  import { ModalCommandStartPreDispatchUnavailableError } from "../providers/modal-command-router-wire";
32
34
  import { isDeepStrictEqual } from "node:util";
@@ -374,6 +376,22 @@ export type RoutingSandboxFirstOperationObserver = (
374
376
 
375
377
  type RoutingSandboxFirstOperationTiming = Pick<RoutingSandboxFirstOperationObservation, "phases">;
376
378
 
379
+ const READ_ONLY_PATH_PROBE_OPERATIONS = new Set(["readFile", "listDir", "pathExists", "viewImage"]);
380
+
381
+ /** A definite path miss is the provider's authoritative answer to a read-only
382
+ * probe (repository skill discovery lists absent `.agents/skills` on almost
383
+ * every turn), not a failed provider operation. Writes never qualify. Only
384
+ * typed misses count, the same set skill discovery treats as absent: generic
385
+ * 404 statuses or "not found" text never do. */
386
+ function isReadOnlyPathProbeMiss(op: string, error: unknown): boolean {
387
+ return (
388
+ READ_ONLY_PATH_PROBE_OPERATIONS.has(op) &&
389
+ (isDefinitePathNotFoundError(error) ||
390
+ error instanceof SandboxWorkspaceReadNotFoundError ||
391
+ error instanceof SandboxFilesystemNotFoundError)
392
+ );
393
+ }
394
+
377
395
  function recordFirstOperationPhase(
378
396
  timing: RoutingSandboxFirstOperationTiming | undefined,
379
397
  phase: RoutingSandboxFirstOperationPhase,
@@ -1485,6 +1503,9 @@ export class RoutingSandboxSession implements RoutableBackendSession {
1485
1503
  );
1486
1504
  outcome = "completed";
1487
1505
  return result;
1506
+ } catch (error) {
1507
+ if (isReadOnlyPathProbeMiss(op, error)) outcome = "completed";
1508
+ throw error;
1488
1509
  } finally {
1489
1510
  try {
1490
1511
  firstOperationObserver({
@@ -1677,6 +1698,9 @@ export class RoutingSandboxSession implements RoutableBackendSession {
1677
1698
  },
1678
1699
  );
1679
1700
  providerOutcome = "completed";
1701
+ } catch (error) {
1702
+ if (isReadOnlyPathProbeMiss(op, error)) providerOutcome = "completed";
1703
+ throw error;
1680
1704
  } finally {
1681
1705
  recordFirstOperationPhase(
1682
1706
  firstOperationTiming,
@@ -1944,10 +1968,7 @@ export class RoutingSandboxSession implements RoutableBackendSession {
1944
1968
  return result;
1945
1969
  } catch (error) {
1946
1970
  materializationFailureReason = materializationVerificationDiagnostic(error)?.reason;
1947
- if (
1948
- (op === "readFile" || op === "listDir" || op === "pathExists" || op === "viewImage") &&
1949
- isDefinitePathNotFoundError(error)
1950
- ) {
1971
+ if (isReadOnlyPathProbeMiss(op, error)) {
1951
1972
  outcome = "not_found";
1952
1973
  }
1953
1974
  throw error;
@@ -2,9 +2,11 @@ import type { AttemptToolDefinition, AttemptToolExecutionContext } from "@openge
2
2
  import {
3
3
  ToolResultSpilledReceipt,
4
4
  sandboxShellPath,
5
+ type AttemptToolIdentity,
5
6
  type AttemptToolResult as AttemptToolResultValue,
6
7
  type ToolResultSpilledReceipt as ToolResultSpilledReceiptValue,
7
8
  } from "@opengeni/contracts";
9
+ import { projectKnowledgeToolResultForModel } from "./knowledge-model-projection";
8
10
  import { MCP_MAX_TOOL_RESULT_BYTES, mcpSerializedSizeBytes } from "./mcp-network";
9
11
 
10
12
  export type SpillOversizedModelToolResult = (input: {
@@ -44,23 +46,32 @@ export function spilledModelToolResult(
44
46
  };
45
47
  }
46
48
 
49
+ /**
50
+ * The single per-caller seam over one executor result. Codemode receives the
51
+ * exact result. The model receives its model-visible projection (compact
52
+ * Knowledge discovery output for the exact tool identity) when that fits in
53
+ * 1 MiB; otherwise the exact result is spilled to a file, as for any tool.
54
+ * MCP-backed tools are already bounded on their exact result by the MCP
55
+ * transport cap before this seam runs.
56
+ */
47
57
  export async function projectAttemptToolResultForCaller(
48
58
  result: AttemptToolResultValue,
49
59
  context: AttemptToolExecutionContext,
50
60
  spill?: SpillOversizedModelToolResult,
61
+ identity?: AttemptToolIdentity,
51
62
  ): Promise<AttemptToolResultValue> {
52
63
  switch (context.caller.kind) {
53
64
  case "codemode":
54
65
  return result;
55
66
  case "model": {
56
- const serializedBytes = mcpSerializedSizeBytes(result);
57
- if (serializedBytes <= MCP_MAX_TOOL_RESULT_BYTES) return result;
67
+ const visible = identity ? projectKnowledgeToolResultForModel(identity, result) : result;
68
+ if (mcpSerializedSizeBytes(visible) <= MCP_MAX_TOOL_RESULT_BYTES) return visible;
58
69
  if (!spill) return modelToolResultOverflowError();
59
70
  try {
60
71
  return await spill({
61
72
  operationId: context.operationId,
62
73
  result,
63
- serializedBytes,
74
+ serializedBytes: mcpSerializedSizeBytes(result),
64
75
  });
65
76
  } catch {
66
77
  return modelToolResultOverflowError();
@@ -76,9 +87,10 @@ export async function projectAttemptToolResultForCaller(
76
87
  export function wrapAttemptToolExecute(
77
88
  execute: AttemptToolDefinition["execute"],
78
89
  spill?: SpillOversizedModelToolResult,
90
+ identity?: AttemptToolIdentity,
79
91
  ): AttemptToolDefinition["execute"] {
80
92
  return async (args, context) =>
81
- await projectAttemptToolResultForCaller(await execute(args, context), context, spill);
93
+ await projectAttemptToolResultForCaller(await execute(args, context), context, spill, identity);
82
94
  }
83
95
 
84
96
  export function wrapAttemptToolDefinitions(
@@ -87,6 +99,6 @@ export function wrapAttemptToolDefinitions(
87
99
  ): AttemptToolDefinition[] {
88
100
  return definitions.map((definition) => ({
89
101
  ...definition,
90
- execute: wrapAttemptToolExecute(definition.execute, spill),
102
+ execute: wrapAttemptToolExecute(definition.execute, spill, definition.identity),
91
103
  }));
92
104
  }