omp-superagent 0.1.8 → 0.1.9

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 (104) hide show
  1. package/DESIGN.md +6 -2
  2. package/README.ko.md +12 -9
  3. package/README.md +13 -9
  4. package/THIRD_PARTY_NOTICES.md +8 -8
  5. package/docs/OPERATIONS.md +62 -20
  6. package/docs/design/execution.md +79 -14
  7. package/docs/design/messaging.md +66 -15
  8. package/docs/releases/0.1.9.md +18 -0
  9. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  10. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  11. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  12. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  13. package/host-owner/bin/notices/darwin-arm64/Cargo-LICENSES.txt +2 -0
  14. package/host-owner/bin/notices/darwin-arm64/Cargo-SOURCES.txt +2 -0
  15. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  16. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  17. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  18. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  19. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  20. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  21. package/host-owner/bin/notices/darwin-x64/Cargo-LICENSES.txt +2 -0
  22. package/host-owner/bin/notices/darwin-x64/Cargo-SOURCES.txt +2 -0
  23. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  24. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  25. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  26. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  27. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  28. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  29. package/host-owner/bin/notices/linux-arm64/Cargo-LICENSES.txt +3 -0
  30. package/host-owner/bin/notices/linux-arm64/Cargo-SOURCES.txt +3 -0
  31. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  32. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  33. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  34. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  35. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  36. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  37. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  38. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  39. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  40. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  41. package/host-owner/bin/notices/linux-x64/Cargo-LICENSES.txt +3 -0
  42. package/host-owner/bin/notices/linux-x64/Cargo-SOURCES.txt +3 -0
  43. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  44. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  45. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  46. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  47. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  48. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  49. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  50. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  51. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  52. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  53. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  54. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  55. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  56. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  57. package/package.json +10 -8
  58. package/skills/head/SKILL.md +3 -11
  59. package/skills/head/references/routing.md +23 -17
  60. package/skills/head/references/supervision.md +13 -1
  61. package/skills/lane/references/workflow.md +8 -8
  62. package/src/cli.ts +4 -4
  63. package/src/contracts.ts +71 -7
  64. package/src/discord-command-registration.ts +34 -186
  65. package/src/extension.ts +22 -2
  66. package/src/gateway-client.ts +11 -59
  67. package/src/gateway-protocol.ts +35 -1
  68. package/src/head-recovery.ts +226 -17
  69. package/src/host-extension.ts +82 -9
  70. package/src/host-protocol.ts +5 -9
  71. package/src/lane-models.ts +8 -0
  72. package/src/managed-ulw-probe.ts +22 -20
  73. package/src/messenger-command-catalog.json +6 -3
  74. package/src/messenger-commands.ts +9 -2
  75. package/src/operator.ts +77 -0
  76. package/src/pr-github-schema.ts +2 -0
  77. package/src/pr-intake-automation.ts +1 -2
  78. package/src/pr-intake-comment.ts +1 -2
  79. package/src/pr-intake-fix.ts +1 -2
  80. package/src/pr-intake-github.ts +1 -2
  81. package/src/pr-intake-material.ts +1 -2
  82. package/src/pr-intake-tree.ts +1 -2
  83. package/src/pr-review-models.ts +28 -0
  84. package/src/result-attachment.ts +60 -79
  85. package/src/runtime.ts +1461 -254
  86. package/src/setup-profiles.ts +26 -65
  87. package/src/slack-command-registration.ts +48 -197
  88. package/src/store.ts +265 -45
  89. package/src/superkit-skills.ts +22 -0
  90. package/src/telegram-command-languages.json +17 -0
  91. package/src/telegram-command-registration.ts +32 -134
  92. package/src/worker-bridge.ts +21 -0
  93. package/src/worker-enrollment.ts +2 -1
  94. package/src/worker-host.ts +0 -24
  95. package/src/worker-serve-prepare.ts +19 -0
  96. package/src/worker-service.ts +51 -47
  97. package/scripts/ci.ts +0 -44
  98. package/scripts/release.ts +0 -112
  99. package/scripts/test-omp.sh +0 -44
  100. package/src/discord-commands.ts +0 -29
  101. package/src/discord-markdown.ts +0 -399
  102. package/src/slack-commands.ts +0 -18
  103. package/src/telegram-signal.ts +0 -14
  104. package/src/worker-stdio.ts +0 -61
@@ -0,0 +1,77 @@
1
+ import { addAbortListener } from "node:events";
2
+ import { requireGateway } from "./gateway-native";
3
+ import { readCredentialFile, validateCredential } from "./credentials";
4
+
5
+ type Credentials = { readonly bot: string; readonly manifest?: string };
6
+ export type OperatorRun = <T>(operation: string, request: unknown, credentials: Credentials, signal?: AbortSignal) => Promise<T>;
7
+
8
+ export class OperatorStartError extends Error {
9
+ constructor() { super("Could not start the native operator; no mutation was attempted."); }
10
+ }
11
+
12
+ export function operatorBotToken(platform: "Discord" | "Telegram", configPath: string, tokenEnv: string): string {
13
+ const explicit = process.env[tokenEnv];
14
+ let stored: string | undefined;
15
+ try {
16
+ // Validate the sibling's ownership even when an explicit environment value wins.
17
+ stored = readCredentialFile(configPath)?.values[tokenEnv];
18
+ if (!explicit && stored) validateCredential(stored);
19
+ } catch { throw new Error(`Cannot safely load the configured ${platform} credential; details suppressed`); }
20
+ if (explicit) {
21
+ try { validateCredential(explicit); }
22
+ catch { throw new Error(`Configured ${platform} credential is invalid; value suppressed`); }
23
+ return explicit;
24
+ }
25
+ if (!stored) throw new Error(`Configured ${platform} credential is missing`);
26
+ return stored;
27
+ }
28
+
29
+ /** Run only the selected operation's credentials through the child's private environment. */
30
+ export async function invokeOperator<T>(argv: string[], request: unknown, credentials: Credentials, signal?: AbortSignal): Promise<T> {
31
+ let child: Bun.Subprocess<"pipe", "pipe", "ignore">;
32
+ let frame: string;
33
+ try {
34
+ if (signal?.aborted) throw new OperatorStartError();
35
+ frame = `${JSON.stringify(request)}\n`;
36
+ if (signal?.aborted) throw new OperatorStartError();
37
+ child = Bun.spawn(argv, {
38
+ env: { OMP_SA_OPERATOR_PARENT: String(process.pid), OMP_SA_OPERATOR_BOT: credentials.bot,
39
+ ...(credentials.manifest !== undefined && { OMP_SA_OPERATOR_MANIFEST: credentials.manifest }) },
40
+ stdin: "pipe", stdout: "pipe", stderr: "ignore",
41
+ });
42
+ } catch {
43
+ throw new OperatorStartError();
44
+ }
45
+ const uncertain = "No authoritative operator receipt. A requested change may have reached the platform; inspect before retrying.";
46
+ const stop = () => {
47
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
48
+ };
49
+ using abortListener = signal && addAbortListener(signal, stop);
50
+ if (signal?.aborted) stop();
51
+ const send = async () => {
52
+ // Keep the writer open after this frame. EOF is a parent-lifetime fence,
53
+ // including when a supervisor kills only the CLI and no JS handlers run.
54
+ await child.stdin.write(frame);
55
+ await child.stdin.flush();
56
+ };
57
+ try {
58
+ const [code, output] = await Promise.all([child.exited, new Response(child.stdout).text(), send()])
59
+ .catch(() => { throw new Error(uncertain); });
60
+ if (signal?.aborted) throw new Error(uncertain);
61
+ let reply: { ok?: boolean; error?: string; value?: T };
62
+ try { reply = JSON.parse(output); }
63
+ catch { throw new Error(uncertain); }
64
+ if (reply?.ok === false && typeof reply.error === "string") throw new Error(reply.error);
65
+ if (code !== 0 || reply?.ok !== true || reply.value === undefined) throw new Error(uncertain);
66
+ return reply.value;
67
+ } finally {
68
+ stop();
69
+ await child.exited.catch(() => undefined);
70
+ }
71
+ }
72
+
73
+ export const runOperator: OperatorRun = async (operation, request, credentials, signal) => {
74
+ if (signal?.aborted) throw new OperatorStartError();
75
+ const gateway = await requireGateway().catch(() => { throw new OperatorStartError(); });
76
+ return invokeOperator([gateway, "operator", operation], request, credentials, signal);
77
+ };
@@ -17,6 +17,8 @@ export class PrReadError extends Error {
17
17
 
18
18
  const id = Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });
19
19
  export const sha = Type.String({ pattern: "^(?:[0-9a-f]{40}|[0-9a-f]{64})$" });
20
+ // PR intake accepts SHA-1 only; general GitHub reads also accept SHA-256.
21
+ export const sha40 = Type.String({ pattern: "^[0-9a-f]{40}$" });
20
22
  const nullableText = Type.Union([Type.String(), Type.Null()]);
21
23
  const user = Type.Union([Type.Object({
22
24
  login: Type.String({ pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*(\\[bot\\])?$", maxLength: 100 }),
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { Type, type Static } from "@sinclair/typebox/type";
3
3
  import type { StorePort } from "./contracts";
4
- import { PrReadError, parseWire } from "./pr-github-schema";
4
+ import { PrReadError, parseWire, sha40 as sha } from "./pr-github-schema";
5
5
  import { inspectIntakeComment, publishIntakeComment } from "./pr-intake-comment";
6
6
  import { applyIntakeFix, parseIntakeFix, reconcileIntakeFix } from "./pr-intake-fix";
7
7
  import { inspectIntakeMerge, mergeIntakePull } from "./pr-intake-github";
@@ -12,7 +12,6 @@ import type { ReviewRound } from "./pr-intake-review";
12
12
  // allow: SIZE_OK - This state machine owns the PR-wide ledger and its single write fence.
13
13
  const maxHeads = 3;
14
14
  const rank = { review: 0, fix: 1, merge: 2 } as const;
15
- const sha = Type.String({ pattern: "^[a-f0-9]{40}$" });
16
15
  const hash = Type.String({ pattern: "^[a-f0-9]{64}$" });
17
16
  const nonempty = Type.String({ minLength: 1 });
18
17
  const materialSchema = Type.Object({ digest: hash, baseRef: nonempty, baseSha: sha, headRef: nonempty });
@@ -1,12 +1,11 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { Type, type Static, type TSchema } from "@sinclair/typebox/type";
3
3
  import { parsePrRef } from "./pr-github";
4
- import { loginSchema, parseWire, PrReadError } from "./pr-github-schema";
4
+ import { loginSchema, parseWire, PrReadError, sha40 as sha } from "./pr-github-schema";
5
5
  import { openIntakeGitHubSession, queryIntakeGitHub, type IntakeMergeIdentity } from "./pr-intake-github";
6
6
  import { intakeEvidenceDeadlineMs } from "./pr-intake-material";
7
7
 
8
8
  const id = Type.String({ pattern: "^[A-Za-z0-9_+/=-]{1,256}$" });
9
- const sha = Type.String({ pattern: "^[0-9a-f]{40}$" });
10
9
  const databaseId = Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });
11
10
  const user = Type.Object({ login: loginSchema.properties.login, databaseId });
12
11
  const actor = Type.Object({ login: Type.String(), databaseId: Type.Optional(Type.Union([databaseId, Type.Null()])) });
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { Type, type Static } from "@sinclair/typebox/type";
3
- import { parseWire, PrReadError } from "./pr-github-schema";
3
+ import { parseWire, PrReadError, sha40 as oid } from "./pr-github-schema";
4
4
  import { openIntakeGitHubSession, queryIntakeGitHub, type IntakeRepositoryIdentity } from "./pr-intake-github";
5
5
  import {
6
6
  intakeEvidenceDeadlineMs, IntakeMaterialError, readIntakeDiff, readIntakePullIdentity, serializeIntakeDiff,
@@ -10,7 +10,6 @@ import { openIntakeTree, readIntakeBlob } from "./pr-intake-tree";
10
10
 
11
11
  const maxSnippet = 8 * 1024;
12
12
  const maxSource = 96 * 1024;
13
- const oid = Type.String({ pattern: "^[0-9a-f]{40}$" });
14
13
  const id = Type.String({ minLength: 1, maxLength: 256, pattern: "^[A-Za-z0-9_+=/-]+$" });
15
14
  const fix = Type.Object({
16
15
  path: Type.String({ minLength: 1, maxLength: 256 }),
@@ -1,11 +1,10 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { Type, type Static, type TSchema } from "@sinclair/typebox/type";
3
3
  import { parsePrRef, readGitHubApi } from "./pr-github";
4
- import { PrReadError, checkPageSchema, loginSchema, pages, parseWire, statusSchema } from "./pr-github-schema";
4
+ import { PrReadError, checkPageSchema, loginSchema, pages, parseWire, sha40 as sha, statusSchema } from "./pr-github-schema";
5
5
 
6
6
  // allow: SIZE_OK — One wire adapter; preflight and the single mutation share the authenticated session.
7
7
  const id = Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });
8
- const sha = Type.String({ pattern: "^[0-9a-f]{40}$" });
9
8
  const nodeId = Type.String({ pattern: "^[A-Za-z0-9_+/=-]{1,256}$" });
10
9
  const utcTimestamp = Type.String({ pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{3})?Z$" });
11
10
  const actor = Type.Object({ id, login: loginSchema.properties.login, type: Type.Literal("User") });
@@ -1,6 +1,6 @@
1
1
  import { Type, type Static } from "@sinclair/typebox/type";
2
2
  import { parsePrRef } from "./pr-github";
3
- import { loginSchema, parseWire, PrReadError } from "./pr-github-schema";
3
+ import { loginSchema, parseWire, PrReadError, sha40 as sha } from "./pr-github-schema";
4
4
  import { openIntakeGitHubSession, type IntakeRepositoryIdentity } from "./pr-intake-github";
5
5
  import { openIntakeTree, readIntakeBlob } from "./pr-intake-tree";
6
6
 
@@ -11,7 +11,6 @@ const maxReviewBlobBytes = 96 * 1024;
11
11
  export const intakeEvidenceDeadlineMs = 90_000;
12
12
  const count = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });
13
13
  const id = Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });
14
- const sha = Type.String({ pattern: "^[0-9a-f]{40}$" });
15
14
  const login = loginSchema.properties.login;
16
15
  const actor = Type.Object({ id, login, type: Type.Literal("User") });
17
16
  const repo = Type.Object({ id, full_name: Type.String({ minLength: 3, maxLength: 140 }), owner: Type.Object({ id, login }) });
@@ -1,10 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { Type, type Static } from "@sinclair/typebox/type";
3
- import { PrReadError } from "./pr-github-schema";
3
+ import { PrReadError, sha40 as sha } from "./pr-github-schema";
4
4
  import type { openIntakeGitHubSession } from "./pr-intake-github";
5
5
 
6
6
  type Session = Awaited<ReturnType<typeof openIntakeGitHubSession>>;
7
- const sha = Type.String({ pattern: "^[0-9a-f]{40}$" });
8
7
  const entry = Type.Object({ mode: Type.String(), type: Type.String(), sha, path: Type.String() });
9
8
  const commit = Type.Object({ sha, tree: Type.Object({ sha }) });
10
9
  const tree = Type.Object({ sha, truncated: Type.Literal(false), tree: Type.Array(entry) });
@@ -0,0 +1,28 @@
1
+ import type { LaneModel } from "./contracts";
2
+ import { acceptsRestrictedModelSelector, isLaneModel } from "./lane-models";
3
+
4
+ const inferenceApis = new Set(["openai-completions", "openai-responses", "openai-codex-responses",
5
+ "azure-openai-responses", "anthropic-messages"]);
6
+
7
+ /** A tool-free inference API, not an external agent harness. */
8
+ export function isPrReviewInferenceModel(model: unknown): boolean {
9
+ return typeof model === "object" && model !== null
10
+ && "api" in model && typeof model.api === "string" && inferenceApis.has(model.api)
11
+ && "provider" in model && typeof model.provider === "string" && model.provider !== "gitlab-duo"
12
+ && (!("transport" in model) || model.transport !== "pi-native");
13
+ }
14
+
15
+ /** New selections must be exact, unique chat models in the native available catalogue. */
16
+ export function prReviewModelChoices<T>(catalog: readonly T[]): (T & LaneModel)[] {
17
+ const choices = new Map<string, (T & LaneModel) | undefined>();
18
+ for (const model of catalog) {
19
+ if (!isLaneModel(model)) continue;
20
+ const key = JSON.stringify([model.provider, model.id]);
21
+ // Track rejected entries too: another row with this identity is ambiguous.
22
+ const allowed = !choices.has(key) && isPrReviewInferenceModel(model)
23
+ && acceptsRestrictedModelSelector(model)
24
+ && (!("kind" in model) || model.kind === undefined || model.kind === "chat");
25
+ choices.set(key, allowed ? model : undefined);
26
+ }
27
+ return [...choices.values()].filter(model => model !== undefined);
28
+ }
@@ -1,5 +1,5 @@
1
- import { constants, fstatSync, lstatSync, openSync, closeSync, readSync, realpathSync } from "node:fs";
2
- import { basename, isAbsolute, relative, resolve, sep } from "node:path";
1
+ import { isAbsolute } from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
3
  import type { ExtensionAPI } from "@oh-my-pi/pi-coding-agent";
4
4
  import { Type } from "@sinclair/typebox";
5
5
  import type { Inbound } from "./contracts";
@@ -7,11 +7,17 @@ import type { Inbound } from "./contracts";
7
7
  const MAX_RESULT_ATTACHMENT_BYTES = 8 * 1024 * 1024;
8
8
  export const RESULT_ATTACH_TOOL = "result_attach";
9
9
 
10
- export interface ResultAttachmentPayload {
10
+ export interface ResultAttachmentSnapshot {
11
11
  readonly name: string;
12
- readonly data: string;
12
+ readonly size: number;
13
+ readonly sha256: string;
14
+ readonly snapshotId: string;
15
+ readonly fileIdentity: string;
13
16
  }
14
17
 
18
+ // Read-only compatibility with output rows persisted before the native spool.
19
+ export type ResultAttachmentPayload = ResultAttachmentSnapshot | { readonly name: string; readonly data: string };
20
+
15
21
  interface NativeSession {
16
22
  readonly sessionId: string;
17
23
  readonly sessionFile: string;
@@ -59,89 +65,64 @@ export function isOriginalAttachmentMessage({ id, messageId, route }: Inbound):
59
65
  : `${route.platform}:${route.accountId}:${route.channelId}:${messageId}:original`);
60
66
  }
61
67
 
62
- function inside(root: string, file: string): boolean {
63
- const delta = relative(root, file);
64
- return delta === "" || delta !== ".." && !delta.startsWith(`..${sep}`) && !isAbsolute(delta);
65
- }
68
+ const binary = fileURLToPath(new URL(`../gateway/bin/omp-gateway-${process.platform}-${process.arch}`, import.meta.url));
66
69
 
67
- /** Store the bytes, not a mutable file path to be opened later by the Gateway. */
68
- export function stageResultAttachment(path: string, scope: {
69
- readonly cwd: string;
70
- readonly privatePaths: readonly string[];
71
- }): ResultAttachmentPayload {
70
+ type StageCommand =
71
+ | { readonly action: "stage"; readonly stateDir: string; readonly cwd: string; readonly path: string; readonly privatePaths: readonly string[] }
72
+ | { readonly action: "discard"; readonly stateDir: string; readonly snapshotId: string }
73
+ | { readonly action: "prune"; readonly stateDir: string };
74
+
75
+ function runStage(command: StageCommand): unknown {
72
76
  try {
73
- if (!validPath(path)) throw new ResultAttachmentError("Use a literal, non-hidden workspace-relative file path");
74
- const root = resolve(scope.cwd);
75
- if (realpathSync(root) !== root) throw new ResultAttachmentError("The canonical workspace root has changed");
76
- const originalRoot = lstatSync(root, { bigint: true });
77
- const file = resolve(root, path);
78
- const name = basename(file);
79
- if (Buffer.byteLength(name) > 180 || !/^[\p{L}\p{N}\p{M}_. -]+$/u.test(name))
80
- throw new ResultAttachmentError("The result attachment has an unsupported filename");
81
- const privateEntries = scope.privatePaths.map(privatePath => {
82
- let canonical = resolve(privatePath);
83
- try {
84
- canonical = realpathSync(canonical);
85
- return { canonical, stat: lstatSync(canonical, { bigint: true }) };
86
- } catch (error) {
87
- if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
88
- return { canonical };
89
- }
77
+ const child = Bun.spawnSync([binary, "__stage-result-attachment"], {
78
+ env: {}, stdin: Buffer.from(JSON.stringify(command)), stdout: "pipe", stderr: "ignore", timeout: 5_000,
90
79
  });
91
- const checkPrivate = () => {
92
- if (realpathSync(root) !== root) throw new ResultAttachmentError("The canonical workspace root has changed");
93
- const rootStat = lstatSync(root, { bigint: true });
94
- if (rootStat.dev !== originalRoot.dev || rootStat.ino !== originalRoot.ino)
95
- throw new ResultAttachmentError("The canonical workspace root has changed");
96
- if (privateEntries.some(entry => inside(entry.canonical, file)))
97
- throw new ResultAttachmentError("Private state cannot be sent as a result attachment");
98
- // Also compare filesystem identities (e.g. case-insensitive volumes).
99
- let current = root;
100
- for (const part of ["", ...path.split("/")]) {
101
- current = resolve(current, part);
102
- const stat = lstatSync(current, { bigint: true });
103
- if (stat.isSymbolicLink()) throw new ResultAttachmentError("Result attachment paths cannot follow links");
104
- if (privateEntries.some(entry => entry.stat?.dev === stat.dev && entry.stat.ino === stat.ino))
105
- throw new ResultAttachmentError("Private state cannot be sent as a result attachment");
106
- }
107
- };
108
- checkPrivate();
109
- if (realpathSync(file) !== file) throw new ResultAttachmentError("Result attachment paths cannot follow links");
110
- // lstat and the identity checks pin the observed directory entry to the
111
- // descriptor. Nonblocking open cannot hang if it is replaced with a FIFO.
112
- const initial = lstatSync(file, { bigint: true });
113
- if (!initial.isFile() || initial.nlink !== 1n)
114
- throw new ResultAttachmentError("A result attachment must be a regular file without hard links");
115
- const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
116
- try {
117
- const same = (stat: typeof initial) => stat.isFile() && stat.nlink === 1n
118
- && stat.dev === initial.dev && stat.ino === initial.ino && stat.size === initial.size
119
- && stat.mtimeNs === initial.mtimeNs && stat.ctimeNs === initial.ctimeNs;
120
- if (!same(fstatSync(fd, { bigint: true }))) throw new ResultAttachmentError("The attachment changed before staging");
121
- if (initial.size < 1n || initial.size > MAX_RESULT_ATTACHMENT_BYTES)
122
- throw new ResultAttachmentError("Result attachments must be nonempty and at most 8 MiB");
123
- const bytes = Buffer.allocUnsafe(Number(initial.size));
124
- let offset = 0;
125
- while (offset < bytes.length) {
126
- const count = readSync(fd, bytes, offset, bytes.length - offset, offset);
127
- if (!count) break;
128
- offset += count;
129
- }
130
- if (offset !== bytes.length || !same(fstatSync(fd, { bigint: true }))
131
- || realpathSync(file) !== file || !same(lstatSync(file, { bigint: true }))) {
132
- throw new ResultAttachmentError("The attachment changed during staging");
133
- }
134
- checkPrivate();
135
- return { name, data: bytes.toString("base64") };
136
- } finally {
137
- closeSync(fd);
138
- }
80
+ if (child.exitCode !== 0 || child.stdout.length > 4_096)
81
+ throw new ResultAttachmentError("The native result attachment helper did not complete");
82
+ const response = asRecord(JSON.parse(child.stdout.toString("utf8")));
83
+ if (response?.ok === true) return response.value;
84
+ if (response?.ok === false && typeof response.error === "string") throw new ResultAttachmentError(response.error);
85
+ throw new ResultAttachmentError("The native result attachment helper returned no receipt");
139
86
  } catch (error) {
140
87
  if (error instanceof ResultAttachmentError) throw error;
141
- throw new ResultAttachmentError("The requested result attachment could not be read safely", { cause: error });
88
+ // Do not attach an exception that could include the command's private paths.
89
+ throw new ResultAttachmentError("The native result attachment helper is unavailable");
142
90
  }
143
91
  }
144
92
 
93
+ export function isResultAttachmentSnapshot(value: unknown): value is ResultAttachmentSnapshot {
94
+ const snapshot = asRecord(value);
95
+ return snapshot !== null && Object.keys(snapshot).length === 5 &&
96
+ typeof snapshot.name === "string" && validPath(snapshot.name) && Buffer.byteLength(snapshot.name) <= 180 &&
97
+ /^[\p{L}\p{N}\p{M}_. -]+$/u.test(snapshot.name) &&
98
+ typeof snapshot.size === "number" && Number.isSafeInteger(snapshot.size) &&
99
+ snapshot.size > 0 && snapshot.size <= MAX_RESULT_ATTACHMENT_BYTES &&
100
+ typeof snapshot.sha256 === "string" && /^[a-f0-9]{64}$/.test(snapshot.sha256) &&
101
+ typeof snapshot.snapshotId === "string" && /^[a-f0-9]{32}$/.test(snapshot.snapshotId) &&
102
+ typeof snapshot.fileIdentity === "string" && /^\d+:\d+$/.test(snapshot.fileIdentity);
103
+ }
104
+
105
+ /** The helper publishes a private immutable snapshot before queue admission. */
106
+ export function stageResultAttachment(path: string, scope: {
107
+ readonly stateDir: string;
108
+ readonly cwd: string;
109
+ readonly privatePaths: readonly string[];
110
+ }): ResultAttachmentSnapshot {
111
+ if (!validPath(path)) throw new ResultAttachmentError("Use a literal, non-hidden workspace-relative file path");
112
+ const receipt = runStage({ action: "stage", ...scope, path });
113
+ if (!isResultAttachmentSnapshot(receipt) || receipt.name !== path.split("/").at(-1))
114
+ throw new ResultAttachmentError("The native result attachment receipt does not match the request");
115
+ return receipt;
116
+ }
117
+
118
+ export function discardResultAttachment(stateDir: string, snapshotId: string): void {
119
+ runStage({ action: "discard", stateDir, snapshotId });
120
+ }
121
+
122
+ export function pruneResultAttachments(stateDir: string): void {
123
+ runStage({ action: "prune", stateDir });
124
+ }
125
+
145
126
  export function registerResultAttach(pi: ExtensionAPI, submit?: (intent: ResultAttachmentIntent) => string): void {
146
127
  pi.on("tool_call", (event, ctx) => {
147
128
  if (event.toolName === RESULT_ATTACH_TOOL && ctx.agent.kind !== "main")