omp-superagent 0.1.17 → 0.1.19

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 (82) hide show
  1. package/DESIGN.md +15 -12
  2. package/config.example.json +4 -1
  3. package/docs/OPERATIONS.en.md +205 -59
  4. package/docs/OPERATIONS.md +173 -47
  5. package/docs/design/execution.md +119 -37
  6. package/docs/design/messaging.md +160 -45
  7. package/docs/releases/0.1.18.md +10 -0
  8. package/docs/releases/0.1.19.md +10 -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/omp-host-owner-darwin-arm64 +0 -0
  14. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  15. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  16. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  17. package/package.json +1 -1
  18. package/skills/head/SKILL.md +6 -5
  19. package/skills/head/references/model-selection.md +8 -22
  20. package/skills/head/references/routing.md +36 -17
  21. package/skills/lane/SKILL.md +24 -76
  22. package/skills/lane/references/workflow.md +7 -94
  23. package/src/cli.ts +36 -16
  24. package/src/config/config.ts +21 -2
  25. package/src/contracts.ts +66 -7
  26. package/src/cron/cron-jobs.ts +135 -92
  27. package/src/cron/cron-pr-intake.ts +18 -11
  28. package/src/extension.ts +25 -10
  29. package/src/gateway/gateway-client.ts +3 -1
  30. package/src/host-extension.ts +76 -8
  31. package/src/lane/lane-report.ts +1 -1
  32. package/src/lane/lane-rows.ts +2 -1
  33. package/src/lane/workflow.ts +12 -6
  34. package/src/lane-extension.ts +4 -21
  35. package/src/managed-super-probe.ts +21 -15
  36. package/src/messaging/messenger-command-catalog.json +1 -1
  37. package/src/messaging/messenger-commands.ts +8 -3
  38. package/src/messaging/result-attachment.ts +77 -19
  39. package/src/messaging/slack-context.ts +50 -0
  40. package/src/messaging/written-directives.ts +56 -0
  41. package/src/omp/exit-record.ts +27 -0
  42. package/src/omp/host-protocol.ts +20 -0
  43. package/src/omp/host.ts +73 -20
  44. package/src/omp/installed-omp.ts +15 -12
  45. package/src/omp/managed-super.ts +135 -65
  46. package/src/omp/superkit-skills.ts +15 -2
  47. package/src/pr/pr-intake-order.ts +62 -0
  48. package/src/pr/pr-intake-review.ts +49 -31
  49. package/src/pr/pr-intake-work.ts +3 -2
  50. package/src/routing/message-order.ts +22 -1
  51. package/src/routing/topic-request.ts +48 -4
  52. package/src/runtime/controller.ts +968 -338
  53. package/src/runtime/deferred-routing.ts +12 -4
  54. package/src/runtime/dm-timeline.ts +3 -3
  55. package/src/runtime/inbound-attachments.ts +70 -0
  56. package/src/runtime/local-host-fence.ts +85 -0
  57. package/src/runtime/model-journal.ts +14 -9
  58. package/src/runtime/native-frames.ts +5 -1
  59. package/src/runtime/result-attachments.ts +151 -24
  60. package/src/runtime/worker-result-download.ts +36 -0
  61. package/src/storage/deferred-routing.ts +25 -4
  62. package/src/storage/store.ts +445 -75
  63. package/src/worker/worker-checkout.ts +89 -9
  64. package/src/worker/worker-destination.ts +8 -7
  65. package/src/worker/worker-doctor.ts +29 -9
  66. package/src/worker/worker-enrollment.ts +44 -12
  67. package/src/worker/worker-git-startup.ts +157 -0
  68. package/src/worker/worker-host.ts +16 -26
  69. package/src/worker/worker-ledger.ts +42 -18
  70. package/src/worker/worker-placement-intent.ts +13 -0
  71. package/src/worker/worker-placement.ts +204 -28
  72. package/src/worker/worker-profile.ts +18 -65
  73. package/src/worker/worker-project-startup.ts +106 -0
  74. package/src/worker/worker-registration.ts +85 -30
  75. package/src/worker/worker-repository.ts +55 -6
  76. package/src/worker/worker-request.ts +13 -6
  77. package/src/worker/worker-result-attachments.ts +185 -0
  78. package/src/worker/worker-result-wire.ts +12 -0
  79. package/src/worker/worker-service.ts +51 -23
  80. package/src/worker/worker-trust.ts +19 -4
  81. package/src/worker/worker-wire.ts +47 -14
  82. package/upstream/super.json +2 -3
@@ -10,6 +10,7 @@ interface DrainActions {
10
10
  readonly stopped: () => boolean;
11
11
  readonly fenced: () => boolean;
12
12
  readonly recovery: (input: Inbound) => RecoveryControl | null;
13
+ readonly awaitingReceipt: (input: Inbound) => boolean;
13
14
  readonly admit: (id: string) => Promise<void>;
14
15
  readonly report: (error: unknown) => void;
15
16
  readonly background: (task: Promise<void>) => void;
@@ -32,8 +33,9 @@ export class DeferredRoutingDrain {
32
33
  this.drain(conversation);
33
34
  }
34
35
 
35
- retrying(conversation: string): boolean {
36
- return this.retry.has(conversation);
36
+ blocked(conversation: string): boolean {
37
+ const head = this.queue.head(conversation);
38
+ return this.retry.has(conversation) || head !== null && this.awaitingReceipt(head);
37
39
  }
38
40
 
39
41
  resume(): void {
@@ -49,10 +51,16 @@ export class DeferredRoutingDrain {
49
51
  return this.actions.stopped() || this.actions.fenced();
50
52
  }
51
53
 
54
+ private awaitingReceipt(id: string): boolean {
55
+ const input = this.queue.input(id);
56
+ return input !== null && this.actions.awaitingReceipt(input);
57
+ }
58
+
52
59
  private next(conversation: string, head: string, failed: ReadonlySet<string>): string | null {
53
60
  const retry = this.retry.get(conversation);
54
- const headReady = (!retry || retry.at <= Date.now()) && !failed.has(head);
55
- const includeBare = !headReady && retry !== undefined;
61
+ const awaitingReceipt = this.awaitingReceipt(head);
62
+ const headReady = !awaitingReceipt && (!retry || retry.at <= Date.now()) && !failed.has(head);
63
+ const includeBare = !headReady && (awaitingReceipt || retry !== undefined);
56
64
  // A persisted exact stop can bypass a blocked history read so work from
57
65
  // another conversation cannot resume the target lane out of order.
58
66
  for (const input of this.queue.priority(conversation, includeBare)) {
@@ -37,7 +37,7 @@ export class DmTimeline {
37
37
  constructor(private readonly store: Pick<StorePort, "getMeta" | "admittedMessageIds" | "input">) {}
38
38
 
39
39
  admit(input: Inbound, eventId: string | null, commandBlocked: boolean): { input: Inbound; metadata: Record<string, string> } {
40
- if (input.route.platform === "slack") return this.slackDmAdmission(input);
40
+ if (input.route.platform === "slack") return this.slackDmAdmission(input, commandBlocked);
41
41
  let metadata: Record<string, string> = {};
42
42
  if (eventId === null) throw new Error("Cannot order this DM input");
43
43
  const physical = physicalRoute(input.route);
@@ -118,9 +118,9 @@ export class DmTimeline {
118
118
  return latest;
119
119
  }
120
120
 
121
- private slackDmAdmission(input: Inbound): { input: Inbound; metadata: Record<string, string> } {
121
+ private slackDmAdmission(input: Inbound, commandBlocked: boolean): { input: Inbound; metadata: Record<string, string> } {
122
122
  const physical = physicalRoute(input.route);
123
- const command = input.text.trim();
123
+ const command = commandBlocked ? "" : input.text.trim();
124
124
  const control = /^\/new(?:\s|$)/.test(command) || command === "/main";
125
125
  const anchorMessageId = input.messageId === null ? this.slackAnchor(input) : undefined;
126
126
  let metadata: Record<string, string> = {};
@@ -0,0 +1,70 @@
1
+ import { createHash } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { open, realpath } from "node:fs/promises";
4
+ import type { InboundAttachmentReceipt } from "../contracts";
5
+ import type { RuntimeHost } from "./native-frames";
6
+ import { successful } from "./native-frames";
7
+
8
+ type SpoolFile = InboundAttachmentReceipt["files"][number];
9
+ const chunkBytes = 1024 * 1024;
10
+ const command = "stage_worker_attachments";
11
+
12
+ /** The Gateway receipt describes a private snapshot, not a live pathname to trust. */
13
+ export async function readAttachmentBytes({ path, size, sha256 }: SpoolFile): Promise<Buffer> {
14
+ if (await realpath(path) !== path) throw new Error("Attachment spool path changed");
15
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
16
+ try {
17
+ const stat = await file.stat();
18
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600
19
+ || stat.nlink !== 1 || stat.size !== size) throw new Error("Attachment spool file changed");
20
+ const data = Buffer.alloc(size);
21
+ for (let offset = 0; offset < size;) {
22
+ const { bytesRead } = await file.read(data, offset, size - offset, offset);
23
+ if (!bytesRead) throw new Error("Attachment spool file was truncated");
24
+ offset += bytesRead;
25
+ }
26
+ if (createHash("sha256").update(data).digest("hex") !== sha256)
27
+ throw new Error("Attachment changed after the Gateway published its receipt");
28
+ return data;
29
+ } finally { await file.close(); }
30
+ }
31
+
32
+ /** Upload only verified bytes to the same attested connection that will submit this prompt. */
33
+ export async function stageWorkerAttachments(host: RuntimeHost, requestId: string,
34
+ files: readonly SpoolFile[], signal: AbortSignal): Promise<AsyncDisposable> {
35
+ signal.throwIfAborted();
36
+ const interrupted = Promise.withResolvers<never>();
37
+ const abort = () => interrupted.reject(signal.reason);
38
+ signal.addEventListener("abort", abort, { once: true });
39
+ const send = async (params: Record<string, unknown>) => {
40
+ signal.throwIfAborted();
41
+ const response = host.request({ type: command, requestId, ...params });
42
+ successful(await Promise.race([response, interrupted.promise]), command);
43
+ };
44
+ const transfer = {
45
+ async [Symbol.asyncDispose]() {
46
+ // Upload commands are ordered on this peer. Discard follows any write
47
+ // already sent, even when we stop waiting for that write's receipt.
48
+ // A consumed upload is gone; disconnect also clears the peer's batch.
49
+ await host.request({ type: command, op: "discard", requestId }).catch(() => {});
50
+ },
51
+ };
52
+ try {
53
+ await send({ op: "begin", files: files.map(({ size, mimeType }) => ({ size, mimeType })) });
54
+ let transferred = 0;
55
+ for (const file of files) {
56
+ signal.throwIfAborted();
57
+ const bytes = await readAttachmentBytes(file);
58
+ for (let offset = 0; offset < bytes.length; offset += chunkBytes) {
59
+ await send({ op: "write", offset: transferred + offset,
60
+ data: bytes.subarray(offset, offset + chunkBytes).toString("base64") });
61
+ }
62
+ transferred += bytes.length;
63
+ }
64
+ signal.throwIfAborted();
65
+ return transfer;
66
+ } catch (error) {
67
+ await transfer[Symbol.asyncDispose]();
68
+ throw error;
69
+ } finally { signal.removeEventListener("abort", abort); }
70
+ }
@@ -0,0 +1,85 @@
1
+ import { lstatSync, type Stats } from "node:fs";
2
+ import { createConnection } from "node:net";
3
+ import { dirname } from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { hostPaths, type Config } from "../config/config";
6
+ import type { Lane, LocalHostIdentity } from "../contracts";
7
+ import { readExitRecord } from "../omp/exit-record";
8
+
9
+ function endpoint(config: Config, lane: Lane): Stats | undefined {
10
+ const paths = hostPaths(config, lane.id);
11
+ if (lane.remote || paths.socketPath !== lane.socketPath || paths.sessionFile !== lane.sessionFile)
12
+ throw new Error("Not the recorded local Host path");
13
+ const dir = lstatSync(dirname(paths.socketPath));
14
+ if (!dir.isDirectory() || dir.uid !== process.getuid?.() || (dir.mode & 0o777) !== 0o700)
15
+ throw new Error("Not a private Host socket directory");
16
+ const socket = lstatSync(paths.socketPath, { throwIfNoEntry: false });
17
+ if (socket && (!socket.isSocket() || socket.uid !== dir.uid || (socket.mode & 0o777) !== 0o600
18
+ || !Number.isSafeInteger(socket.dev) || !Number.isSafeInteger(socket.ino)))
19
+ throw new Error("Not an identifiable private Host socket");
20
+ return socket;
21
+ }
22
+
23
+ function sameSocket(socket: Stats, owner: LocalHostIdentity): boolean {
24
+ return socket.dev === owner.dev && socket.ino === owner.ino && socket.ctimeMs === owner.ctimeMs;
25
+ }
26
+
27
+ /** Only the exact proven residue (or its absence) is exempt, never a replacement. */
28
+ export function quarantinedSlotFree(config: Config, lane: Lane): boolean {
29
+ if (!lane.localOwner?.journalHeld) return false;
30
+ try {
31
+ const socket = endpoint(config, lane);
32
+ return !socket || sameSocket(socket, lane.localOwner);
33
+ } catch { return false; } // Uninspectable paths count against the budget.
34
+ }
35
+
36
+ function validPid(value: unknown): value is number {
37
+ return typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 0x7fffffff;
38
+ }
39
+
40
+ function exited(pid: number): boolean {
41
+ try { process.kill(pid, 0); return false; }
42
+ catch (error) { return error instanceof Error && "code" in error && error.code === "ESRCH"; }
43
+ }
44
+
45
+ function deadOwner(config: Config, lane: Lane): LocalHostIdentity | undefined {
46
+ const { pid, sessionId, sessionFile, localOwner } = lane;
47
+ if (lane.remote || !sessionId || !validPid(pid) || !exited(pid)) return;
48
+ const socket = endpoint(config, lane);
49
+ if (!socket) return;
50
+ let ownerPid: unknown;
51
+ if (localOwner) {
52
+ if (localOwner.pid !== pid || localOwner.sessionId !== sessionId || localOwner.sessionFile !== sessionFile
53
+ || !sameSocket(socket, localOwner)) return;
54
+ ownerPid = localOwner.ownerPid;
55
+ } else {
56
+ // Legacy local launches retained the native PID but not the adapter identity.
57
+ // A receipt from an earlier use of the journal cannot identify this owner.
58
+ const path = `${lane.socketPath}.exit.json`;
59
+ const stat = lstatSync(path, { throwIfNoEntry: false });
60
+ if (!stat || stat.mtimeMs <= socket.ctimeMs) return;
61
+ const receipt = readExitRecord(path, stat);
62
+ if (!receipt || typeof receipt !== "object" || "workerAttempt" in receipt
63
+ || !("pid" in receipt) || receipt.pid !== pid || !("sessionId" in receipt) || receipt.sessionId !== sessionId
64
+ || !("sessionFile" in receipt) || receipt.sessionFile !== sessionFile || !("ownerPid" in receipt)
65
+ || !("observationsFlushed" in receipt) || typeof receipt.observationsFlushed !== "boolean"
66
+ || !("persisted" in receipt) || typeof receipt.persisted !== "boolean") return;
67
+ ownerPid = receipt.ownerPid;
68
+ }
69
+ if (!validPid(ownerPid) || ownerPid === pid || !exited(ownerPid)) return;
70
+ return { pid, ownerPid, sessionFile, sessionId, dev: socket.dev, ino: socket.ino, ctimeMs: socket.ctimeMs };
71
+ }
72
+
73
+ /** Send no RPC. A timeout, successful connection, or anything but refusal is not proof. */
74
+ export async function inspectLocalOrphan(config: Config, lane: Lane): Promise<LocalHostIdentity | undefined> {
75
+ try {
76
+ const before = deadOwner(config, lane);
77
+ if (!before) return;
78
+ const refused = await new Promise<boolean>(resolve => {
79
+ const socket = createConnection({ path: lane.socketPath, signal: AbortSignal.timeout(500) });
80
+ socket.once("connect", () => { socket.destroy(); resolve(false); });
81
+ socket.once("error", (error: NodeJS.ErrnoException) => resolve(error.code === "ECONNREFUSED"));
82
+ });
83
+ if (refused && isDeepStrictEqual(before, deadOwner(config, lane))) return before;
84
+ } catch { /* Unavailable or changing ownership is not proof. */ }
85
+ }
@@ -3,7 +3,7 @@ import { resolveRoutedModelSelector } from "@oh-my-pi/pi-coding-agent/config/mod
3
3
  import { EPHEMERAL_MODEL_CHANGE_ROLE } from "@oh-my-pi/pi-coding-agent/session/session-entries";
4
4
  import type { LaneModel } from "../contracts";
5
5
  import { LANE_MODEL_PROMOTION_RECEIPT } from "../omp/host-protocol";
6
- import { isLaneModel, laneModelArgument, sameLaneModel } from "../lane/lane-models";
6
+ import { codingModels, isLaneModel, laneModelArgument, sameLaneModel } from "../lane/lane-models";
7
7
  import { record } from "./native-frames";
8
8
 
9
9
  type JournaledModelChange = {
@@ -59,8 +59,8 @@ function activeModelJournal(entries: unknown, leafId: string, after?: string):
59
59
  }
60
60
 
61
61
  /** Read the configured default; the caller still fences against a moving native leaf. */
62
- export function nativeDefaultModelEvidence(result: Record<string, unknown>, catalog: unknown[], laneId: string):
63
- { readonly leaf: string | null; readonly selected?: LaneModel } {
62
+ export async function nativeDefaultModelEvidence(result: Record<string, unknown>, readCatalog: () => Promise<unknown[]>, laneId: string):
63
+ Promise<{ readonly leaf: string | null; readonly selected?: LaneModel }> {
64
64
  const leaf = result.leafId;
65
65
  if (leaf === null && Array.isArray(result.entries) && result.entries.length === 0) return { leaf };
66
66
  const journal = typeof leaf === "string" && leaf ? activeModelJournal(result.entries, leaf) : null;
@@ -80,6 +80,7 @@ export function nativeDefaultModelEvidence(result: Record<string, unknown>, cata
80
80
  throw new Error(`Lane ${laneId} native model promotion receipt does not match its default journal entry`);
81
81
  selected = exact;
82
82
  } else {
83
+ const catalog = await readCatalog();
83
84
  const legacy = recordedModel(saved.model, catalog);
84
85
  if (!legacy || catalog.some(candidate => isLaneModel(candidate) && !sameLaneModel(candidate, legacy)
85
86
  && laneModelArgument(candidate) === laneModelArgument(legacy))) {
@@ -92,11 +93,11 @@ export function nativeDefaultModelEvidence(result: Record<string, unknown>, cata
92
93
  }
93
94
 
94
95
  /** Check the fallback chain on the exact active branch, not unrelated journal rows. */
95
- export function recordedFallbackEvidence(evidence: Record<string, unknown>, models: {
96
+ export async function recordedFallbackEvidence(evidence: Record<string, unknown>, models: {
96
97
  readonly configured: LaneModel;
97
98
  readonly actual: LaneModel;
98
- readonly catalog: unknown[];
99
- }, after?: string): { readonly leaf: string; readonly entryId: string } | null {
99
+ readonly readCatalog: () => Promise<unknown[]>;
100
+ }, after?: string): Promise<{ readonly leaf: string; readonly entryId: string } | null> {
100
101
  const leaf = evidence.leafId;
101
102
  if (typeof leaf !== "string" || !leaf) return null;
102
103
  const changes = activeModelJournal(evidence.entries, leaf, after)?.changes;
@@ -111,9 +112,13 @@ export function recordedFallbackEvidence(evidence: Record<string, unknown>, mode
111
112
  // model after cooldown. That row is only the source, never the evidence
112
113
  // that another model is permitted now.
113
114
  if ((configured.role !== undefined && configured.role !== "default" && configured.role !== EPHEMERAL_MODEL_CHANGE_ROLE)
114
- || configured.resolvedModelIsFallback === true
115
- || !sameLaneModel(recordedModel(configured.model, models.catalog), models.configured)) return null;
115
+ || configured.resolvedModelIsFallback === true) return null;
116
+ const catalog = await models.readCatalog();
117
+ const available = codingModels(catalog);
118
+ if (!available.some(candidate => sameLaneModel(candidate, models.configured))
119
+ || !available.some(candidate => sameLaneModel(candidate, models.actual))
120
+ || !sameLaneModel(recordedModel(configured.model, catalog), models.configured)) return null;
116
121
  const latest = changes[0];
117
- if (!sameLaneModel(recordedModel(latest.model, models.catalog), models.actual)) return null;
122
+ if (!sameLaneModel(recordedModel(latest.model, catalog), models.actual)) return null;
118
123
  return { leaf, entryId: latest.id };
119
124
  }
@@ -1,4 +1,4 @@
1
- import type { DialogResponse, LaneModel, LanePresetSnapshot } from "../contracts";
1
+ import type { DialogResponse, LaneModel, LanePresetSnapshot, LocalHostIdentity } from "../contracts";
2
2
  import type { FastModeState } from "../omp/host-protocol";
3
3
  import { laneQuotaExhausted } from "./head-recovery";
4
4
 
@@ -7,8 +7,11 @@ export interface RuntimeState {
7
7
  sessionId: string;
8
8
  readonly journalCursorVersion?: 1;
9
9
  readonly replyVoiceVersion?: 1 | 2;
10
+ readonly workerResultVersion?: 1;
10
11
  readonly fastMode?: FastModeState;
11
12
  model?: LaneModel | null;
13
+ /** Exact active identity eligible on the owned lane Host; null is a refusal, omission is legacy. */
14
+ readonly laneModelAvailable?: LaneModel | null;
12
15
  thinkingLevel?: string;
13
16
  configuredThinkingLevel?: string | null;
14
17
  thinkingLevels?: readonly string[];
@@ -30,6 +33,7 @@ export interface RuntimeState {
30
33
  }
31
34
  /** The production adapter is HostConnection; tests inject only its transport boundary. */
32
35
  export interface RuntimeHost {
36
+ readonly localIdentity?: LocalHostIdentity;
33
37
  assertPrReviewOnly?(cwd: string): Promise<void>;
34
38
  client: {
35
39
  getState(): Promise<RuntimeState>;
@@ -3,28 +3,34 @@ import { join, resolve } from "node:path";
3
3
  import { getAgentDir } from "@oh-my-pi/pi-utils";
4
4
  import { getAgentDbPath } from "@oh-my-pi/pi-utils/dirs";
5
5
  import { authorizeRoute, type Config } from "../config/config";
6
- import type { InputRecord, Route, StorePort } from "../contracts";
7
- import { messengerCommandText, telegramCommandBlocked } from "../messaging/messenger-commands";
6
+ import { routeKey, type InputRecord, type Route, type StorePort } from "../contracts";
7
+ import { hasWorkerCurrentHeader } from "../messaging/written-directives";
8
8
  import { discordWorkThreadSource } from "../messaging/discord-work-thread";
9
- import { discardResultAttachment, isOriginalAttachmentMessage, pruneResultAttachments, readResultAttachmentIntent,
10
- readResultAttachmentStart, requestedResultPath, ResultAttachmentError, stageResultAttachment,
9
+ import { discardResultAttachment, importWorkerResult, isOriginalAttachmentMessage, pruneResultAttachments, readResultAttachmentDirective,
10
+ readResultAttachmentIntent, readResultAttachmentStart, ResultAttachmentError, stageResultAttachment,
11
11
  type ResultAttachmentIntent, type ResultAttachmentPayload } from "../messaging/result-attachment";
12
+ import { successful, type NativePromptResult, type RuntimeHost } from "./native-frames";
13
+ import { WORKER_RESULT_LIMIT, type WorkerResultSource } from "../worker/worker-result-wire";
14
+ import { downloadWorkerResult } from "./worker-result-download";
12
15
 
13
16
  type AttachmentRun = {
14
17
  readonly id: string;
15
18
  readonly generation: number;
16
19
  readonly sessionId: string;
20
+ readonly connection: Pick<RuntimeHost, "request">;
17
21
  readonly input?: Pick<InputRecord, "requestId">;
18
22
  readonly running: boolean;
19
23
  readonly ownedRuns: number;
20
- readonly result?: object;
24
+ readonly result?: NativePromptResult;
21
25
  readonly recovery?: object;
22
- readonly admitted: ReadonlyMap<string, { readonly input: Pick<InputRecord, "id"> }>;
26
+ readonly admitted: ReadonlyMap<string, { readonly input: Pick<InputRecord, "id">; readonly result?: NativePromptResult;
27
+ readonly workerResult?: WorkerResultSource }>;
23
28
  };
24
29
 
25
30
  type AttachmentStart = NonNullable<ReturnType<typeof readResultAttachmentStart>> & {
26
31
  readonly ownerRequestId: string;
27
32
  readonly toolName: unknown;
33
+ readonly workerRequestId?: string;
28
34
  };
29
35
 
30
36
  type AttachmentBinding = {
@@ -34,11 +40,20 @@ type AttachmentBinding = {
34
40
  readonly route: Route;
35
41
  };
36
42
 
43
+ type AttachmentAdmission = {
44
+ readonly binding: AttachmentBinding;
45
+ readonly canPublish: () => boolean;
46
+ };
47
+
48
+ type TransferQueue = { readonly ownerRequestId: InputRecord["requestId"] | undefined; tail: Promise<void>; pending: number;
49
+ readonly attempted: Set<string> };
50
+
37
51
  export class ResultAttachments {
38
52
  private readonly starts = new WeakMap<AttachmentRun, Map<string, AttachmentStart>>();
53
+ private readonly workerQueues = new WeakMap<AttachmentRun, TransferQueue>();
39
54
 
40
55
  constructor(private readonly config: Config,
41
- private readonly store: Pick<StorePort, "lane" | "input" | "topicDelivery" | "getMeta" | "output" | "queueOutput">,
56
+ private readonly store: Pick<StorePort, "lane" | "input" | "resultAttachmentDelivery" | "getMeta" | "output" | "queueOutput">,
42
57
  private readonly delivery: {
43
58
  readonly headSessionFile: () => string;
44
59
  readonly wakeOutputs: (route: Route) => void;
@@ -61,27 +76,50 @@ export class ResultAttachments {
61
76
  throw new Error("Unauthorized messenger route");
62
77
  }
63
78
 
64
- queue(run: AttachmentRun, intent: ResultAttachmentIntent, admission: {
65
- readonly binding: AttachmentBinding;
66
- readonly canPublish: () => boolean;
67
- }): string {
68
- const { source, input, outputSourceId, route } = admission.binding;
79
+ workerSource(inputId: string): WorkerResultSource | undefined {
80
+ const binding = this.store.resultAttachmentDelivery(inputId);
81
+ if (!binding || this.store.getMeta(`user-source:${binding.source.id}`) !== "true") return;
82
+ const { source, route } = binding;
83
+ const directive = readResultAttachmentDirective(source, "worker");
84
+ if (!directive || source.state === "cancelled" || source.state === "uncertain") return;
85
+ try {
86
+ this.authorizeOwner(source.route);
87
+ this.authorizeOwner(route);
88
+ } catch (error) {
89
+ if (error instanceof Error) return;
90
+ throw error;
91
+ }
92
+ return { sourceId: source.id, path: directive.path };
93
+ }
94
+
95
+ private authorize(run: AttachmentRun, intent: ResultAttachmentIntent, admission: AttachmentAdmission, afterCopy = false) {
96
+ const { source, input, route } = admission.binding;
69
97
  const lane = run.id === "main" ? null : this.store.lane(run.id);
70
98
  if (run.id !== "main" && !lane) throw new Error(`Unknown lane: ${run.id}`);
71
- if (lane?.remote) throw new ResultAttachmentError("Remote result files cannot be staged on the head");
72
99
  const sessionFile = lane?.sessionFile ?? this.delivery.headSessionFile();
73
- if (!admission.canPublish() || !run.running || run.ownedRuns !== 1 || run.result || run.recovery
100
+ const native = input.requestId && run.admitted.get(input.requestId);
101
+ const stopped = (result: NativePromptResult | undefined) => result &&
102
+ (result.status !== "completed" || !result.agentInvoked);
103
+ if (!admission.canPublish() || run.ownedRuns !== 1 || run.recovery
104
+ || (afterCopy ? stopped(run.result) || stopped(native ? native.result : undefined) : !run.running || run.result)
74
105
  || (lane && lane.workState !== "open") || intent.sessionFile !== sessionFile || intent.sessionId !== run.sessionId
75
106
  || input.state !== "submitted" || input.generation !== run.generation || input.target !== run.id || !input.requestId
76
- || run.admitted.get(input.requestId)?.input.id !== input.id || source.state === "cancelled" || source.state === "uncertain"
107
+ || !native || native.input.id !== input.id || source.state === "cancelled" || source.state === "uncertain"
77
108
  || this.store.getMeta(`user-source:${source.id}`) !== "true" || !isOriginalAttachmentMessage(source)) {
78
109
  throw new ResultAttachmentError("Result attachments require the original owner input in the current native run");
79
110
  }
80
111
  this.authorizeOwner(source.route);
81
112
  this.authorizeOwner(route);
82
- if (telegramCommandBlocked(source) || requestedResultPath(messengerCommandText(source)) !== intent.path)
113
+ if (run.id === "main" && hasWorkerCurrentHeader(source.text))
114
+ throw new ResultAttachmentError("Worker-current result attachments require the original request on its selected worker lane");
115
+ if (readResultAttachmentDirective(source, lane?.remote ? "worker" : "local")?.path !== intent.path)
83
116
  throw new ResultAttachmentError("The owner did not explicitly request this exact result file in the current message");
84
- const id = `result-attachment:${source.id}`;
117
+ return { id: `result-attachment:${source.id}`, lane, sessionFile, requestId: input.requestId };
118
+ }
119
+
120
+ queue(run: AttachmentRun, intent: ResultAttachmentIntent, admission: AttachmentAdmission): string {
121
+ const { id, lane, sessionFile, requestId } = this.authorize(run, intent, admission);
122
+ if (lane?.remote) throw new ResultAttachmentError("Worker results require a mediated copy");
85
123
  const existing = this.store.output(id);
86
124
  if (existing) return `Result attachment ${id} is ${existing.state}; no new attempt was made.`;
87
125
  const agentDb = getAgentDbPath();
@@ -91,12 +129,18 @@ export class ResultAttachments {
91
129
  privatePaths: [this.config.stateDir, this.config.path, `${this.config.path}.env`, getAgentDir(), sessionFile,
92
130
  agentDb, `${agentDb}-wal`, `${agentDb}-shm`, `${agentDb}-journal`].map(path => resolve(path)),
93
131
  });
132
+ return this.publish(id, run, intent, admission.binding, requestId, payload);
133
+ }
134
+
135
+ private publish(id: string, run: AttachmentRun, intent: ResultAttachmentIntent, binding: AttachmentBinding,
136
+ requestId: string, payload: ResultAttachmentPayload): string {
137
+ const { source, input, outputSourceId, route } = binding;
94
138
  try {
95
139
  this.store.queueOutput({
96
140
  id, sourceId: outputSourceId, route, text: "",
97
141
  resultAttachment: {
98
- payload, sourceId: source.id, inputId: input.id, requestId: input.requestId,
99
- generation: run.generation, sessionId: run.sessionId, sessionFile, toolCallId: intent.toolCallId,
142
+ payload, sourceId: source.id, inputId: input.id, requestId,
143
+ generation: run.generation, sessionId: run.sessionId, sessionFile: intent.sessionFile, toolCallId: intent.toolCallId,
100
144
  },
101
145
  });
102
146
  } catch (error) {
@@ -107,18 +151,96 @@ export class ResultAttachments {
107
151
  return `Result attachment ${id} was durably queued to the original topic, not yet confirmed delivered.`;
108
152
  }
109
153
 
154
+ private queueWorker(run: AttachmentRun, intent: ResultAttachmentIntent, admission: AttachmentAdmission): Promise<void> | undefined {
155
+ const { id, lane, requestId } = this.authorize(run, intent, admission);
156
+ if (!lane?.remote || this.store.output(id)) return;
157
+ const workerId = lane.remote.workerId;
158
+ const ownerRequestId = run.input?.requestId;
159
+ const existing = this.workerQueues.get(run);
160
+ const queue = existing && existing.ownerRequestId === ownerRequestId ? existing
161
+ : { ownerRequestId, tail: Promise.resolve(), pending: 0, attempted: new Set<string>() };
162
+ if (queue !== existing) this.workerQueues.set(run, queue);
163
+ if (queue.attempted.has(id) || queue.attempted.size >= WORKER_RESULT_LIMIT) return;
164
+ queue.attempted.add(id);
165
+ queue.pending++;
166
+ const copy = (op: "reserve" | "discard" | "begin" | "read", offset?: number) => run.connection.request({
167
+ type: "copy_worker_result_attachment", sourceId: intent.sourceId, toolCallId: intent.toolCallId, requestId, op,
168
+ ...(offset === undefined ? {} : { offset }),
169
+ });
170
+ const currentBinding = () => {
171
+ const { binding, canPublish } = admission;
172
+ const input = this.store.input(binding.input.id);
173
+ const topic = input && this.store.resultAttachmentDelivery(input.id);
174
+ if (!input || !topic || run.input?.requestId !== ownerRequestId || input.requestId !== requestId
175
+ || topic.source.id !== binding.source.id || topic.outputSourceId !== binding.outputSourceId
176
+ || routeKey(topic.route) !== routeKey(binding.route) || routeKey(topic.source.route) !== routeKey(binding.source.route))
177
+ throw new ResultAttachmentError("Worker result attachment ownership changed before staging");
178
+ const refreshed = { ...topic, input };
179
+ const current = this.authorize(run, intent, { binding: refreshed, canPublish }, true);
180
+ if (current.lane?.remote?.workerId !== workerId || current.lane?.generation !== lane.generation)
181
+ throw new ResultAttachmentError("Worker result attachment lane changed before staging");
182
+ return refreshed;
183
+ };
184
+ // Claim immediately within native grace, even while an earlier source's
185
+ // bytes are in flight. The FIFO orders the actual copies and publication.
186
+ // A lost reservation or transfer acknowledgement is never retried.
187
+ const reservation = Promise.resolve().then(() => copy("reserve")).then(response => {
188
+ successful(response, "Worker result attachment reservation");
189
+ return { ok: true } as const;
190
+ }).catch((error: unknown) => ({ ok: false, error }) as const);
191
+ const transfer = async () => {
192
+ const receipt = await reservation;
193
+ if (!receipt.ok) throw receipt.error;
194
+ let finished = false;
195
+ try {
196
+ if (this.store.output(id)) return;
197
+ const snapshot = await downloadWorkerResult(copy, currentBinding);
198
+ finished = true;
199
+ // Never import bytes from a superseded generation, connection, source or topic.
200
+ const binding = currentBinding();
201
+ if (this.store.output(id)) return;
202
+ const payload = importWorkerResult(this.config.stateDir, intent.path, snapshot);
203
+ this.publish(id, run, intent, binding, requestId, payload);
204
+ } finally {
205
+ if (!finished && admission.canPublish()) {
206
+ // A scoped release is not a retry. The worker also expires orphaned copies.
207
+ try { await copy("discard"); }
208
+ catch (error) { this.delivery.report(error); }
209
+ }
210
+ }
211
+ };
212
+ const done = queue.tail.then(transfer).catch((error: unknown) => this.delivery.report(error)).finally(() => queue.pending--);
213
+ queue.tail = done;
214
+ return done;
215
+ }
216
+
110
217
  clearStarts(run: AttachmentRun): void { this.starts.delete(run); }
111
218
 
112
- observe(run: AttachmentRun, frame: Record<string, unknown>, canPublish: () => boolean): void {
219
+ copyPending(run: AttachmentRun): boolean {
220
+ return (this.workerQueues.get(run)?.pending ?? 0) > 0;
221
+ }
222
+
223
+ observe(run: AttachmentRun, frame: Record<string, unknown>, canPublish: () => boolean): void | Promise<void> {
113
224
  const ownerRequestId = run.input?.requestId;
114
225
  if (run.id === "main" || !ownerRequestId || !run.running || run.ownedRuns !== 1 || run.recovery
115
226
  || typeof frame.toolCallId !== "string") return;
116
227
  if (frame.type === "tool_execution_start") {
117
228
  const args = readResultAttachmentStart(frame);
118
229
  if (args) {
230
+ let workerRequestId: string | undefined;
231
+ if (this.store.lane(run.id)?.remote) {
232
+ for (const [requestId, { workerResult }] of run.admitted) {
233
+ if (workerResult?.sourceId === args.sourceId && workerResult.path === args.path) {
234
+ workerRequestId = requestId;
235
+ break;
236
+ }
237
+ }
238
+ if (!workerRequestId) return;
239
+ }
119
240
  let starts = this.starts.get(run);
120
241
  if (!starts) this.starts.set(run, starts = new Map());
121
- starts.set(frame.toolCallId, { ...args, ownerRequestId, toolName: frame.toolName });
242
+ if (!starts.has(frame.toolCallId)) starts.set(frame.toolCallId,
243
+ { ...args, ownerRequestId, toolName: frame.toolName, workerRequestId });
122
244
  }
123
245
  return;
124
246
  }
@@ -130,11 +252,16 @@ export class ResultAttachments {
130
252
  if (!intent || intent.sourceId !== start.sourceId || intent.path !== start.path) return;
131
253
  // Only matched live execution events may introduce a file effect. The
132
254
  // journal is not permission to reopen a path or replay after disconnect.
133
- for (const { input } of run.admitted.values()) {
255
+ for (const [requestId, { input }] of run.admitted) {
256
+ if (start.workerRequestId && start.workerRequestId !== requestId) continue;
134
257
  const native = this.store.input(input.id);
135
- const topic = native && this.store.topicDelivery(native.id);
258
+ const topic = native && this.store.resultAttachmentDelivery(native.id);
136
259
  if (!native || topic?.source.id !== intent.sourceId) continue;
137
- try { this.queue(run, intent, { binding: { ...topic, input: native }, canPublish }); }
260
+ const admission = { binding: { ...topic, input: native }, canPublish };
261
+ try {
262
+ if (start.workerRequestId) return this.queueWorker(run, intent, admission);
263
+ else this.queue(run, intent, admission);
264
+ }
138
265
  catch (error) { this.delivery.report(error); }
139
266
  return;
140
267
  }
@@ -0,0 +1,36 @@
1
+ import { ResultAttachmentError } from "../messaging/result-attachment";
2
+ import { WORKER_RESULT_CHUNK, WORKER_RESULT_MAX_ENCODED, WORKER_RESULT_TRANSFER_MS } from "../worker/worker-result-wire";
3
+ import { successful } from "./native-frames";
4
+
5
+ /** A reserved snapshot is drained once, under a single end-to-end deadline. */
6
+ export async function downloadWorkerResult(
7
+ request: (op: "begin" | "read", offset?: number) => Promise<unknown>,
8
+ assertCurrent: () => void,
9
+ ): Promise<{ readonly name: string; readonly data: string }> {
10
+ const deadline = performance.now() + WORKER_RESULT_TRANSFER_MS;
11
+ const expired = Promise.withResolvers<never>();
12
+ const timer = setTimeout(() => expired.reject(new ResultAttachmentError("Worker result transfer expired")), WORKER_RESULT_TRANSFER_MS);
13
+ timer.unref();
14
+ try {
15
+ const chunks: string[] = [];
16
+ let total = 0, name = "", offset = 0;
17
+ do {
18
+ if (performance.now() >= deadline) throw new ResultAttachmentError("Worker result transfer expired");
19
+ assertCurrent();
20
+ const received = await Promise.race([expired.promise, offset === 0 ? request("begin") : request("read", offset)]);
21
+ const chunk = successful(received, "Worker result attachment copy");
22
+ if (offset === 0 && typeof chunk.total === "number" && typeof chunk.name === "string") {
23
+ total = chunk.total;
24
+ name = chunk.name;
25
+ }
26
+ if (!Number.isSafeInteger(total) || total <= offset || total > WORKER_RESULT_MAX_ENCODED || total % 4 !== 0 ||
27
+ chunk.total !== total || !name || chunk.name !== name || typeof chunk.data !== "string" ||
28
+ chunk.data.length !== Math.min(WORKER_RESULT_CHUNK, total - offset))
29
+ throw new ResultAttachmentError("Invalid worker result attachment chunk");
30
+ chunks.push(chunk.data);
31
+ offset += chunk.data.length;
32
+ } while (offset < total);
33
+ if (performance.now() >= deadline) throw new ResultAttachmentError("Worker result transfer expired");
34
+ return { name, data: chunks.join("") };
35
+ } finally { clearTimeout(timer); }
36
+ }