omp-superagent 0.1.10 → 0.1.13

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 (154) hide show
  1. package/DESIGN.md +71 -15
  2. package/README.ko.md +10 -1
  3. package/README.md +10 -1
  4. package/THIRD_PARTY_NOTICES.md +35 -436
  5. package/assets/architecture-dark.svg +7 -12
  6. package/assets/architecture.ko-dark.svg +7 -12
  7. package/assets/architecture.ko.svg +7 -12
  8. package/assets/architecture.mmd +5 -13
  9. package/assets/architecture.svg +7 -12
  10. package/config.example.json +1 -0
  11. package/docs/OPERATIONS.en.md +282 -53
  12. package/docs/OPERATIONS.md +264 -45
  13. package/docs/design/execution.md +80 -52
  14. package/docs/design/messaging.md +113 -32
  15. package/docs/releases/0.1.11.md +20 -0
  16. package/docs/releases/0.1.13.md +13 -0
  17. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  18. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  19. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  20. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  21. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  22. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  23. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  24. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  25. package/package.json +13 -11
  26. package/scripts/{prepare-ulw.ts → prepare-super.ts} +1 -1
  27. package/scripts/upgrade-evidence-files.mjs +100 -0
  28. package/scripts/upgrade-evidence.mjs +192 -0
  29. package/scripts/upgrade-host-wire.mjs +162 -0
  30. package/skills/head/SKILL.md +12 -3
  31. package/skills/head/references/routing.md +1 -1
  32. package/skills/head/references/supervision.md +23 -26
  33. package/skills/lane/SKILL.md +28 -21
  34. package/skills/lane/references/workflow.md +15 -17
  35. package/src/cli.ts +33 -53
  36. package/src/{config.ts → config/config.ts} +7 -3
  37. package/src/config/wake-config.ts +36 -0
  38. package/src/contracts.ts +61 -12
  39. package/src/{cron-jobs.ts → cron/cron-jobs.ts} +21 -13
  40. package/src/{cron-pr-intake.ts → cron/cron-pr-intake.ts} +4 -4
  41. package/src/{cron-schedule.ts → cron/cron-schedule.ts} +3 -3
  42. package/src/extension.ts +43 -25
  43. package/src/{gateway-client.ts → gateway/gateway-client.ts} +89 -32
  44. package/src/{gateway-native.ts → gateway/gateway-native.ts} +4 -4
  45. package/src/{gateway-protocol.ts → gateway/gateway-protocol.ts} +69 -14
  46. package/src/{gateway-wire.ts → gateway/gateway-wire.ts} +12 -7
  47. package/src/gateway-config.ts +1 -1
  48. package/src/gateway-restart-env.ts +3 -3
  49. package/src/{group-access.ts → group/group-access.ts} +8 -3
  50. package/src/{group-policy.ts → group/group-policy.ts} +2 -2
  51. package/src/{group-runner.ts → group/group-runner.ts} +11 -6
  52. package/src/host-extension.ts +164 -36
  53. package/src/host-sdk-helper.ts +66 -65
  54. package/src/{decision-tool.ts → lane/decision-tool.ts} +12 -4
  55. package/src/{decisions.ts → lane/decisions.ts} +12 -10
  56. package/src/{lane-models.ts → lane/lane-models.ts} +1 -1
  57. package/src/{lane-rows.ts → lane/lane-rows.ts} +2 -2
  58. package/src/{lane-watch.ts → lane/lane-watch.ts} +6 -2
  59. package/src/{workflow.ts → lane/workflow.ts} +1 -1
  60. package/src/lane-extension.ts +25 -7
  61. package/src/managed-memory-helper.ts +2 -2
  62. package/src/{managed-ulw-probe.ts → managed-super-probe.ts} +3 -3
  63. package/src/{delivery.ts → messaging/delivery.ts} +1 -1
  64. package/src/{discord-command-registration.ts → messaging/discord-command-registration.ts} +3 -2
  65. package/src/{discord-context.ts → messaging/discord-context.ts} +1 -1
  66. package/src/{messenger-command-catalog.json → messaging/messenger-command-catalog.json} +1 -0
  67. package/src/messaging/messenger-commands.ts +55 -0
  68. package/src/{result-attachment.ts → messaging/result-attachment.ts} +3 -3
  69. package/src/{slack-command-registration.ts → messaging/slack-command-registration.ts} +3 -3
  70. package/src/{telegram-command-registration.ts → messaging/telegram-command-registration.ts} +2 -2
  71. package/src/omp/head-resume.ts +123 -0
  72. package/src/{host-owner-path.ts → omp/host-owner-path.ts} +1 -1
  73. package/src/{host-protocol.ts → omp/host-protocol.ts} +10 -2
  74. package/src/{host-superkit.ts → omp/host-superkit.ts} +1 -1
  75. package/src/{host.ts → omp/host.ts} +26 -17
  76. package/src/{installed-omp.ts → omp/installed-omp.ts} +1 -1
  77. package/src/{managed-memory.ts → omp/managed-memory.ts} +2 -2
  78. package/src/{managed-ulw.ts → omp/managed-super.ts} +42 -16
  79. package/src/omp/native-journal.ts +124 -0
  80. package/src/{native-launch-profile.ts → omp/native-launch-profile.ts} +6 -2
  81. package/src/{native-presets.ts → omp/native-presets.ts} +2 -2
  82. package/src/omp/native-sessions.ts +124 -0
  83. package/src/{omp-usage.ts → omp/omp-usage.ts} +1 -1
  84. package/src/{soul.ts → omp/soul.ts} +2 -2
  85. package/src/omp/stock-head-launch.ts +31 -0
  86. package/src/{autostart.ts → operator/autostart.ts} +3 -3
  87. package/src/{operator.ts → operator/operator.ts} +2 -2
  88. package/src/{setup-judge.ts → operator/setup-judge.ts} +1 -1
  89. package/src/{setup-profiles.ts → operator/setup-profiles.ts} +2 -2
  90. package/src/{setup.ts → operator/setup.ts} +5 -5
  91. package/src/operator/stop-lane.ts +25 -0
  92. package/src/{pr-intake-automation.ts → pr/pr-intake-automation.ts} +1 -1
  93. package/src/{pr-intake-mode.ts → pr/pr-intake-mode.ts} +3 -3
  94. package/src/{pr-intake-review.ts → pr/pr-intake-review.ts} +5 -5
  95. package/src/{pr-intake-work.ts → pr/pr-intake-work.ts} +1 -1
  96. package/src/{pr-review-models.ts → pr/pr-review-models.ts} +2 -2
  97. package/src/{pr-watch.ts → pr/pr-watch.ts} +36 -26
  98. package/src/{message-order.ts → routing/message-order.ts} +1 -1
  99. package/src/{topic-history.ts → routing/topic-history.ts} +2 -2
  100. package/src/{topic-request.ts → routing/topic-request.ts} +4 -2
  101. package/src/{runtime.ts → runtime/controller.ts} +867 -1213
  102. package/src/runtime/deferred-routing.ts +106 -0
  103. package/src/runtime/dm-timeline.ts +194 -0
  104. package/src/{head-recovery.ts → runtime/head-recovery.ts} +1 -1
  105. package/src/{head-rotation.ts → runtime/head-rotation.ts} +32 -5
  106. package/src/runtime/model-journal.ts +119 -0
  107. package/src/runtime/native-frames.ts +131 -0
  108. package/src/{observation-request.ts → runtime/observation-request.ts} +1 -1
  109. package/src/runtime/preset-sync.ts +232 -0
  110. package/src/runtime/preset-watch-paths.ts +137 -0
  111. package/src/runtime/result-attachments.ts +146 -0
  112. package/src/storage/deferred-routing.ts +149 -0
  113. package/src/{store.ts → storage/store.ts} +75 -42
  114. package/src/{worker-bridge.ts → worker/worker-bridge.ts} +2 -2
  115. package/src/{worker-enrollment.ts → worker/worker-enrollment.ts} +2 -2
  116. package/src/{worker-host.ts → worker/worker-host.ts} +7 -3
  117. package/src/{worker-placement.ts → worker/worker-placement.ts} +1 -1
  118. package/src/{worker-profile.ts → worker/worker-profile.ts} +1 -1
  119. package/src/{worker-registration.ts → worker/worker-registration.ts} +2 -2
  120. package/src/{worker-request.ts → worker/worker-request.ts} +5 -5
  121. package/src/{worker-service.ts → worker/worker-service.ts} +2 -2
  122. package/src/{worker-trust.ts → worker/worker-trust.ts} +1 -1
  123. package/src/{worker-wire.ts → worker/worker-wire.ts} +3 -3
  124. package/src/worker-serve-prepare.ts +4 -4
  125. package/src/board-extension.ts +0 -217
  126. package/src/board.ts +0 -467
  127. package/src/gateway-host-helper.ts +0 -13
  128. package/src/messenger-commands.ts +0 -15
  129. package/src/native-sessions.ts +0 -34
  130. /package/src/{credentials.ts → config/credentials.ts} +0 -0
  131. /package/src/{lane-report.ts → lane/lane-report.ts} +0 -0
  132. /package/src/{dialog.ts → messaging/dialog.ts} +0 -0
  133. /package/src/{telegram-command-languages.json → messaging/telegram-command-languages.json} +0 -0
  134. /package/src/{host-broker-services.ts → omp/host-broker-services.ts} +0 -0
  135. /package/src/{host-inventory-manifest.ts → omp/host-inventory-manifest.ts} +0 -0
  136. /package/src/{host-reply-voice.ts → omp/host-reply-voice.ts} +0 -0
  137. /package/src/{host-services.ts → omp/host-services.ts} +0 -0
  138. /package/src/{native-settings.ts → omp/native-settings.ts} +0 -0
  139. /package/src/{superkit-skills.ts → omp/superkit-skills.ts} +0 -0
  140. /package/src/{repository.ts → operator/repository.ts} +0 -0
  141. /package/src/{pr-github-schema.ts → pr/pr-github-schema.ts} +0 -0
  142. /package/src/{pr-github.ts → pr/pr-github.ts} +0 -0
  143. /package/src/{pr-intake-comment.ts → pr/pr-intake-comment.ts} +0 -0
  144. /package/src/{pr-intake-fix.ts → pr/pr-intake-fix.ts} +0 -0
  145. /package/src/{pr-intake-github.ts → pr/pr-intake-github.ts} +0 -0
  146. /package/src/{pr-intake-material.ts → pr/pr-intake-material.ts} +0 -0
  147. /package/src/{pr-intake-tree.ts → pr/pr-intake-tree.ts} +0 -0
  148. /package/src/{head-quota.ts → runtime/head-quota.ts} +0 -0
  149. /package/src/{worker-checkout.ts → worker/worker-checkout.ts} +0 -0
  150. /package/src/{worker-destination.ts → worker/worker-destination.ts} +0 -0
  151. /package/src/{worker-doctor.ts → worker/worker-doctor.ts} +0 -0
  152. /package/src/{worker-ledger.ts → worker/worker-ledger.ts} +0 -0
  153. /package/src/{worker-repository.ts → worker/worker-repository.ts} +0 -0
  154. /package/upstream/{ulw.json → super.json} +0 -0
@@ -0,0 +1,232 @@
1
+ import { statSync, watch, type FSWatcher } from "node:fs";
2
+ import type { PresetSyncOutcome } from "../omp/native-presets";
3
+ import { presetWatchState } from "./preset-watch-paths";
4
+
5
+ const presetSyncFallbackIntervalMs = 120_000;
6
+ const presetSyncDebounceMs = 150;
7
+ const presetSyncRetryBaseMs = 100;
8
+ const presetSyncRetryMaxMs = 1_600;
9
+ const presetSyncMaxRetries = 5;
10
+
11
+ export interface PresetRoleSyncAdapters {
12
+ readonly syncPresetRoles?: (canWrite: () => boolean) => Promise<void | PresetSyncOutcome>;
13
+ readonly presetRolePaths?: () => Promise<readonly string[]> | readonly string[];
14
+ }
15
+
16
+ export class PresetRoleSync {
17
+ private presetSync?: Promise<void>;
18
+ private stopped = false;
19
+ private nextPresetSync = 0;
20
+ private nextDeferredPresetSync?: number;
21
+ private presetSyncDirty = false;
22
+ private presetWatchFallback = false;
23
+ private presetWatchDebounce?: NodeJS.Timeout;
24
+ private presetSyncRetryTimer?: NodeJS.Timeout;
25
+ private presetSyncRetryCount = 0;
26
+ private presetWatchPaths: readonly string[] = [];
27
+ private presetWatchSnapshot = "";
28
+ private readonly presetWatchers: FSWatcher[] = [];
29
+ private presetWatchFingerprint?: string;
30
+
31
+ constructor(private readonly adapters: PresetRoleSyncAdapters, private readonly lifecycle: {
32
+ readonly canWrite: () => boolean;
33
+ readonly report: (error: unknown) => void;
34
+ }) {}
35
+
36
+ get pending(): Promise<void> | undefined { return this.presetSync; }
37
+ get pendingWork(): boolean {
38
+ return !!this.adapters.syncPresetRoles && (this.presetSyncDirty || this.presetSync !== undefined
39
+ || this.presetWatchDebounce !== undefined || this.presetSyncRetryTimer !== undefined || this.nextDeferredPresetSync !== undefined);
40
+ }
41
+
42
+ initialize(preserveSelection: boolean, gate: {
43
+ readonly canStart: () => boolean;
44
+ readonly canWrite: () => boolean;
45
+ }): Promise<void | PresetSyncOutcome> | undefined {
46
+ if (preserveSelection) {
47
+ this.nextPresetSync = Date.now() + presetSyncFallbackIntervalMs;
48
+ return;
49
+ }
50
+ if (!this.adapters.syncPresetRoles || !gate.canStart()) return;
51
+ this.nextPresetSync = Date.now() + presetSyncFallbackIntervalMs;
52
+ return this.adapters.syncPresetRoles(gate.canWrite).catch(this.lifecycle.report);
53
+ }
54
+
55
+ async start(): Promise<void> {
56
+ await this.startPresetWatcher();
57
+ // Reconcile changes between the initial startup sync and watch registration.
58
+ this.presetSyncDirty = true;
59
+ this.observe();
60
+ await this.presetSync;
61
+ }
62
+
63
+ tick(): void {
64
+ if (this.presetWatchFingerprint !== undefined && !this.presetWatchDebounce
65
+ && this.readPresetWatchFingerprint() !== this.presetWatchFingerprint) this.queuePresetWatchSync();
66
+ this.observe();
67
+ }
68
+
69
+ stop(): void {
70
+ this.stopped = true;
71
+ this.stopPresetWatcher();
72
+ }
73
+
74
+ private clearPresetSyncRetry(): void {
75
+ if (this.presetSyncRetryTimer) {
76
+ clearTimeout(this.presetSyncRetryTimer);
77
+ this.presetSyncRetryTimer = undefined;
78
+ }
79
+ }
80
+
81
+ private readPresetWatchFingerprint(): string {
82
+ // Bun registers Darwin FSEvents streams asynchronously without replay. Stat
83
+ // the configured files (following links), not every directory in the watch tree.
84
+ return this.presetWatchPaths.map(path => {
85
+ try {
86
+ const info = statSync(path, { bigint: true, throwIfNoEntry: false });
87
+ return info ? `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}` : "missing";
88
+ } catch (error) {
89
+ if (error instanceof Error && "code" in error) return "unavailable";
90
+ throw error;
91
+ }
92
+ }).join("\n");
93
+ }
94
+
95
+ private queuePresetWatchSync(): void {
96
+ if (this.presetWatchDebounce) clearTimeout(this.presetWatchDebounce);
97
+ this.presetWatchDebounce = setTimeout(() => {
98
+ this.presetWatchDebounce = undefined;
99
+ void (async () => {
100
+ if (this.stopped) return;
101
+ if (this.presetWatchFingerprint !== undefined) this.presetWatchFingerprint = this.readPresetWatchFingerprint();
102
+ if (this.presetWatchPaths.length
103
+ && presetWatchState(this.presetWatchPaths).snapshot !== this.presetWatchSnapshot) {
104
+ await this.startPresetWatcher();
105
+ }
106
+ if (this.stopped) return;
107
+ this.presetSyncRetryCount = 0;
108
+ this.clearPresetSyncRetry();
109
+ this.presetSyncDirty = true;
110
+ this.observe();
111
+ })().catch(this.lifecycle.report);
112
+ }, presetSyncDebounceMs);
113
+ this.presetWatchDebounce.unref?.();
114
+ }
115
+
116
+ private async startPresetWatcher(): Promise<void> {
117
+ this.stopPresetWatcher(false);
118
+ this.presetWatchFallback = false;
119
+ if (!this.adapters.syncPresetRoles) return;
120
+ if (!this.adapters.presetRolePaths) {
121
+ this.presetWatchFallback = true;
122
+ return;
123
+ }
124
+ let paths: readonly string[];
125
+ try { paths = await this.adapters.presetRolePaths(); }
126
+ catch (error) {
127
+ this.presetWatchFallback = true;
128
+ this.lifecycle.report(error);
129
+ return;
130
+ }
131
+ if (this.stopped || !paths.length) {
132
+ this.presetWatchFallback = true;
133
+ return;
134
+ }
135
+ this.presetWatchPaths = paths;
136
+ if (process.platform === "darwin") this.presetWatchFingerprint = this.readPresetWatchFingerprint();
137
+ const state = presetWatchState(paths);
138
+ this.presetWatchSnapshot = state.snapshot;
139
+ let uncovered = state.uncovered;
140
+ const directories = new Set([...state.direct.keys(), ...state.ancestors.keys()]);
141
+ for (const directory of directories) {
142
+ const directNames = state.direct.get(directory);
143
+ const ancestorNames = state.ancestors.get(directory);
144
+ try {
145
+ const watcher = watch(directory, { persistent: false }, (_event, filename) => {
146
+ if (this.stopped) return;
147
+ if (filename !== null) {
148
+ const name = String(filename);
149
+ if (!directNames?.has(name) && !ancestorNames?.has(name)) return;
150
+ } else if (!directNames?.size && ancestorNames?.size
151
+ && (!this.presetWatchPaths.length
152
+ || presetWatchState(this.presetWatchPaths).snapshot === this.presetWatchSnapshot)) {
153
+ return;
154
+ }
155
+ this.queuePresetWatchSync();
156
+ });
157
+ watcher.unref?.();
158
+ watcher.on("error", error => {
159
+ this.presetWatchFallback = true;
160
+ const next = Date.now() + presetSyncFallbackIntervalMs;
161
+ if (!this.nextPresetSync || next < this.nextPresetSync) this.nextPresetSync = next;
162
+ this.lifecycle.report(error);
163
+ watcher.close();
164
+ });
165
+ this.presetWatchers.push(watcher);
166
+ } catch (error) {
167
+ uncovered = true;
168
+ this.lifecycle.report(error);
169
+ }
170
+ }
171
+ if (uncovered || !this.presetWatchers.length) this.presetWatchFallback = true;
172
+ }
173
+
174
+ private stopPresetWatcher(clearRetry = true): void {
175
+ if (clearRetry) this.clearPresetSyncRetry();
176
+ this.presetWatchFingerprint = undefined;
177
+ if (this.presetWatchDebounce) {
178
+ clearTimeout(this.presetWatchDebounce);
179
+ this.presetWatchDebounce = undefined;
180
+ }
181
+ while (this.presetWatchers.length) {
182
+ try { this.presetWatchers.pop()?.close(); }
183
+ catch {}
184
+ }
185
+ }
186
+
187
+ observe(): void {
188
+ const sync = this.adapters.syncPresetRoles;
189
+ const canWrite = this.lifecycle.canWrite;
190
+ if (!sync || this.presetSync || !canWrite()) return;
191
+ const now = Date.now();
192
+ const dueFallback = this.presetWatchFallback && now >= this.nextPresetSync;
193
+ const dueDeferred = this.nextDeferredPresetSync !== undefined && now >= this.nextDeferredPresetSync;
194
+ if (!this.presetSyncDirty && !dueFallback && !dueDeferred) return;
195
+ this.presetSyncDirty = false;
196
+ this.clearPresetSyncRetry();
197
+ if (this.presetWatchFallback) this.nextPresetSync = now + presetSyncFallbackIntervalMs;
198
+ if (this.nextDeferredPresetSync !== undefined) this.nextDeferredPresetSync = now + presetSyncFallbackIntervalMs;
199
+ let retryable = false;
200
+ this.presetSync = sync(canWrite)
201
+ .then(outcome => {
202
+ if (outcome === "deferred") {
203
+ retryable = true;
204
+ // Model availability can recover without changing any watched configuration.
205
+ this.nextDeferredPresetSync = Date.now() + presetSyncFallbackIntervalMs;
206
+ } else {
207
+ this.presetSyncRetryCount = 0;
208
+ this.nextDeferredPresetSync = undefined;
209
+ }
210
+ })
211
+ .catch(error => {
212
+ retryable = true;
213
+ this.lifecycle.report(error);
214
+ })
215
+ .finally(() => {
216
+ this.presetSync = undefined;
217
+ if (this.stopped) return;
218
+ if (this.presetSyncDirty) {
219
+ this.observe();
220
+ } else if (retryable && this.presetSyncRetryCount < presetSyncMaxRetries) {
221
+ const delay = Math.min(presetSyncRetryBaseMs * 2 ** this.presetSyncRetryCount, presetSyncRetryMaxMs);
222
+ this.presetSyncRetryCount++;
223
+ this.presetSyncRetryTimer = setTimeout(() => {
224
+ this.presetSyncRetryTimer = undefined;
225
+ this.presetSyncDirty = true;
226
+ this.observe();
227
+ }, delay);
228
+ this.presetSyncRetryTimer.unref?.();
229
+ }
230
+ });
231
+ }
232
+ }
@@ -0,0 +1,137 @@
1
+ import { existsSync, lstatSync, readlinkSync, realpathSync, statSync } from "node:fs";
2
+ import { basename, dirname, join, parse, resolve, sep } from "node:path";
3
+
4
+ export function presetWatchState(paths: readonly string[]): {
5
+ direct: Map<string, Set<string>>;
6
+ ancestors: Map<string, Set<string>>;
7
+ uncovered: boolean;
8
+ snapshot: string;
9
+ } {
10
+ const direct = new Map<string, Set<string>>();
11
+ const ancestors = new Map<string, Set<string>>();
12
+ const add = (map: Map<string, Set<string>>, dir: string, name: string) => {
13
+ let names = map.get(dir);
14
+ if (!names) { names = new Set(); map.set(dir, names); }
15
+ names.add(name);
16
+ };
17
+ const addAncestor = (missingDir: string): boolean => {
18
+ let child = missingDir;
19
+ let parent = dirname(child);
20
+ while (parent !== child && !existsSync(parent)) {
21
+ child = parent;
22
+ parent = dirname(child);
23
+ }
24
+ if (parent !== child && existsSync(parent)) {
25
+ add(ancestors, parent, basename(child));
26
+ return true;
27
+ }
28
+ return false;
29
+ };
30
+ const statIdentity = (filePath: string, follow: boolean): string => {
31
+ try {
32
+ const info = (follow ? statSync : lstatSync)(filePath, { bigint: true });
33
+ const kind = !follow && info.isSymbolicLink() ? "l" : info.isDirectory() ? "d" : "f";
34
+ return `${info.dev}:${info.ino}:${kind}`;
35
+ } catch {
36
+ return "missing";
37
+ }
38
+ };
39
+ let uncovered = false;
40
+ const entries: string[] = [];
41
+ const watchLinks = (target: string) => {
42
+ const absolute = resolve(target);
43
+ let dir = parse(absolute).root;
44
+ let parts = absolute.slice(dir.length).split(sep);
45
+ let followed = 0;
46
+ for (let name = parts.shift(); name !== undefined; name = parts.shift()) {
47
+ if (!name || name === ".") continue;
48
+ if (name === "..") { dir = dirname(dir); continue; }
49
+ const path = join(dir, name);
50
+ let info;
51
+ try { info = lstatSync(path, { bigint: true }); }
52
+ catch (error) {
53
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") uncovered = true;
54
+ else add(ancestors, dir, name);
55
+ return;
56
+ }
57
+ if (!info.isSymbolicLink()) {
58
+ if (parts.length && !info.isDirectory()) { uncovered = true; return; }
59
+ dir = path;
60
+ continue;
61
+ }
62
+ // Subscribe to every physical hop, not just the input path and the final realpath.
63
+ add(ancestors, dir, name);
64
+ const parent = dirname(dir);
65
+ if (parent !== dir) add(ancestors, parent, basename(dir));
66
+ try {
67
+ const link = readlinkSync(path);
68
+ entries.push(`link:${path}|${info.dev}:${info.ino}|${link}`);
69
+ // Linux stops resolving paths after this many symlinks, including cycles.
70
+ if (++followed > 40) { uncovered = true; return; }
71
+ const root = parse(link).root;
72
+ if (root) dir = root;
73
+ parts = [...link.slice(root.length).split(sep), ...parts];
74
+ } catch { uncovered = true; return; }
75
+ }
76
+ };
77
+ for (const target of paths) {
78
+ const directory = dirname(target);
79
+ const name = basename(target);
80
+ watchLinks(target);
81
+ if (!existsSync(directory)) {
82
+ uncovered = true;
83
+ const watched = addAncestor(directory);
84
+ entries.push(`${target}|missing|${watched}`);
85
+ continue;
86
+ }
87
+ add(direct, directory, name);
88
+ const parentDir = dirname(directory);
89
+ if (parentDir !== directory && existsSync(parentDir)) add(ancestors, parentDir, basename(directory));
90
+ let realDir = "";
91
+ try {
92
+ realDir = realpathSync(directory);
93
+ if (realDir !== directory) {
94
+ add(direct, realDir, name);
95
+ const realParent = dirname(realDir);
96
+ if (realParent !== realDir && existsSync(realParent)) add(ancestors, realParent, basename(realDir));
97
+ }
98
+ } catch {
99
+ uncovered = true;
100
+ }
101
+ let resolved: string | null = null;
102
+ let covered = true;
103
+ try {
104
+ lstatSync(target);
105
+ try {
106
+ const real = realpathSync(target);
107
+ resolved = real;
108
+ if (real !== target) {
109
+ const realTargetDir = dirname(real);
110
+ if (existsSync(realTargetDir)) {
111
+ add(direct, realTargetDir, basename(real));
112
+ const realTargetParent = dirname(realTargetDir);
113
+ if (realTargetParent !== realTargetDir && existsSync(realTargetParent)) {
114
+ add(ancestors, realTargetParent, basename(realTargetDir));
115
+ }
116
+ } else {
117
+ covered = false;
118
+ }
119
+ }
120
+ } catch {
121
+ // Dangling symlink or unresolvable target: watch link target's parent/ancestor if possible and keep fallback active.
122
+ covered = false;
123
+ try {
124
+ const linkDest = resolve(directory, readlinkSync(target));
125
+ const linkDir = dirname(linkDest);
126
+ if (existsSync(linkDir)) add(direct, linkDir, basename(linkDest));
127
+ else addAncestor(linkDir);
128
+ } catch {}
129
+ }
130
+ } catch {
131
+ // File does not exist yet inside an existing directory: directory watch covers creation.
132
+ }
133
+ if (!covered) uncovered = true;
134
+ entries.push(`${target}|exists|${statIdentity(directory, true)}|${realDir}|${statIdentity(realDir, true)}|${resolved ?? ""}|${statIdentity(target, false)}|${statIdentity(target, true)}|${covered}`);
135
+ }
136
+ return { direct, ancestors, uncovered, snapshot: entries.join("\n") };
137
+ }
@@ -0,0 +1,146 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { getAgentDir } from "@oh-my-pi/pi-utils";
4
+ import { getAgentDbPath } from "@oh-my-pi/pi-utils/dirs";
5
+ import { authorizeRoute, type Config } from "../config/config";
6
+ import type { InputRecord, Route, StorePort } from "../contracts";
7
+ import { messengerCommandText, telegramCommandBlocked } from "../messaging/messenger-commands";
8
+ import { discardResultAttachment, isOriginalAttachmentMessage, pruneResultAttachments, readResultAttachmentIntent,
9
+ readResultAttachmentStart, requestedResultPath, ResultAttachmentError, stageResultAttachment,
10
+ type ResultAttachmentIntent, type ResultAttachmentPayload } from "../messaging/result-attachment";
11
+
12
+ type AttachmentRun = {
13
+ readonly id: string;
14
+ readonly generation: number;
15
+ readonly sessionId: string;
16
+ readonly input?: Pick<InputRecord, "requestId">;
17
+ readonly running: boolean;
18
+ readonly ownedRuns: number;
19
+ readonly result?: object;
20
+ readonly recovery?: object;
21
+ readonly admitted: ReadonlyMap<string, { readonly input: Pick<InputRecord, "id"> }>;
22
+ };
23
+
24
+ type AttachmentStart = NonNullable<ReturnType<typeof readResultAttachmentStart>> & {
25
+ readonly ownerRequestId: string;
26
+ readonly toolName: unknown;
27
+ };
28
+
29
+ type AttachmentBinding = {
30
+ readonly source: InputRecord;
31
+ readonly input: InputRecord;
32
+ readonly outputSourceId: string;
33
+ readonly route: Route;
34
+ };
35
+
36
+ export class ResultAttachments {
37
+ private readonly starts = new WeakMap<AttachmentRun, Map<string, AttachmentStart>>();
38
+
39
+ constructor(private readonly config: Config,
40
+ private readonly store: Pick<StorePort, "lane" | "input" | "topicDelivery" | "getMeta" | "output" | "queueOutput">,
41
+ private readonly delivery: {
42
+ readonly headSessionFile: () => string;
43
+ readonly wakeOutputs: (route: Route) => void;
44
+ readonly report: (error: unknown) => void;
45
+ }) {}
46
+
47
+ prune(): void {
48
+ if (!existsSync(join(this.config.stateDir, "result-attachments"))) return;
49
+ try { pruneResultAttachments(this.config.stateDir); }
50
+ catch (error) { this.delivery.report(error); }
51
+ }
52
+
53
+ authorizeOwner(route: Route): void {
54
+ // Route eligibility can include restricted group members. Only the
55
+ // configured platform owner can disclose files from the local filesystem.
56
+ if (route.authorityId !== this.config[route.platform]?.ownerId) {
57
+ throw new ResultAttachmentError("Result attachments require the configured messenger owner");
58
+ }
59
+ if (!authorizeRoute(this.config, route)) throw new Error("Unauthorized messenger route");
60
+ }
61
+
62
+ queue(run: AttachmentRun, intent: ResultAttachmentIntent, admission: {
63
+ readonly binding: AttachmentBinding;
64
+ readonly canPublish: () => boolean;
65
+ }): string {
66
+ const { source, input, outputSourceId, route } = admission.binding;
67
+ const lane = run.id === "main" ? null : this.store.lane(run.id);
68
+ if (run.id !== "main" && !lane) throw new Error(`Unknown lane: ${run.id}`);
69
+ if (lane?.remote) throw new ResultAttachmentError("Remote result files cannot be staged on the head");
70
+ const sessionFile = lane?.sessionFile ?? this.delivery.headSessionFile();
71
+ if (!admission.canPublish() || !run.running || run.ownedRuns !== 1 || run.result || run.recovery
72
+ || (lane && lane.workState !== "open") || intent.sessionFile !== sessionFile || intent.sessionId !== run.sessionId
73
+ || input.state !== "submitted" || input.generation !== run.generation || input.target !== run.id || !input.requestId
74
+ || run.admitted.get(input.requestId)?.input.id !== input.id || source.state === "cancelled" || source.state === "uncertain"
75
+ || this.store.getMeta(`user-source:${source.id}`) !== "true" || !isOriginalAttachmentMessage(source)) {
76
+ throw new ResultAttachmentError("Result attachments require the original owner input in the current native run");
77
+ }
78
+ this.authorizeOwner(source.route);
79
+ this.authorizeOwner(route);
80
+ if (telegramCommandBlocked(source) || requestedResultPath(messengerCommandText(source)) !== intent.path)
81
+ throw new ResultAttachmentError("The owner did not explicitly request this exact result file in the current message");
82
+ const id = `result-attachment:${source.id}`;
83
+ const existing = this.store.output(id);
84
+ if (existing) return `Result attachment ${id} is ${existing.state}; no new attempt was made.`;
85
+ const agentDb = getAgentDbPath();
86
+ const payload = stageResultAttachment(intent.path, {
87
+ stateDir: this.config.stateDir,
88
+ cwd: lane?.cwd ?? this.config.headCwd,
89
+ privatePaths: [this.config.stateDir, this.config.path, `${this.config.path}.env`, getAgentDir(), sessionFile,
90
+ agentDb, `${agentDb}-wal`, `${agentDb}-shm`, `${agentDb}-journal`].map(path => resolve(path)),
91
+ });
92
+ try {
93
+ this.store.queueOutput({
94
+ id, sourceId: outputSourceId, route, text: "",
95
+ resultAttachment: {
96
+ payload, sourceId: source.id, inputId: input.id, requestId: input.requestId,
97
+ generation: run.generation, sessionId: run.sessionId, sessionFile, toolCallId: intent.toolCallId,
98
+ },
99
+ });
100
+ } catch (error) {
101
+ this.discard(payload);
102
+ throw error;
103
+ }
104
+ this.delivery.wakeOutputs(route);
105
+ return `Result attachment ${id} was durably queued to the original topic, not yet confirmed delivered.`;
106
+ }
107
+
108
+ clearStarts(run: AttachmentRun): void { this.starts.delete(run); }
109
+
110
+ observe(run: AttachmentRun, frame: Record<string, unknown>, canPublish: () => boolean): void {
111
+ const ownerRequestId = run.input?.requestId;
112
+ if (run.id === "main" || !ownerRequestId || !run.running || run.ownedRuns !== 1 || run.recovery
113
+ || typeof frame.toolCallId !== "string") return;
114
+ if (frame.type === "tool_execution_start") {
115
+ const args = readResultAttachmentStart(frame);
116
+ if (args) {
117
+ let starts = this.starts.get(run);
118
+ if (!starts) this.starts.set(run, starts = new Map());
119
+ starts.set(frame.toolCallId, { ...args, ownerRequestId, toolName: frame.toolName });
120
+ }
121
+ return;
122
+ }
123
+ const starts = this.starts.get(run);
124
+ const start = starts?.get(frame.toolCallId);
125
+ starts?.delete(frame.toolCallId);
126
+ if (!start || start.ownerRequestId !== ownerRequestId || start.toolName !== frame.toolName) return;
127
+ const intent = readResultAttachmentIntent(frame);
128
+ if (!intent || intent.sourceId !== start.sourceId || intent.path !== start.path) return;
129
+ // Only matched live execution events may introduce a file effect. The
130
+ // journal is not permission to reopen a path or replay after disconnect.
131
+ for (const { input } of run.admitted.values()) {
132
+ const native = this.store.input(input.id);
133
+ const topic = native && this.store.topicDelivery(native.id);
134
+ if (!native || topic?.source.id !== intent.sourceId) continue;
135
+ try { this.queue(run, intent, { binding: { ...topic, input: native }, canPublish }); }
136
+ catch (error) { this.delivery.report(error); }
137
+ return;
138
+ }
139
+ }
140
+
141
+ discard(payload: ResultAttachmentPayload | undefined): void {
142
+ if (!payload || !("snapshotId" in payload)) return;
143
+ try { discardResultAttachment(this.config.stateDir, payload.snapshotId); }
144
+ catch (error) { this.delivery.report(error); }
145
+ }
146
+ }
@@ -0,0 +1,149 @@
1
+ import type { Database } from "bun:sqlite";
2
+ import { deferredRecoveryCandidate, physicalRouteKey, routingConversation, type DeferredRoutingPort, type Inbound, type Lane, type Route } from "../contracts";
3
+
4
+ const LEGACY_QUEUE = "intake:deferred-routing";
5
+ const SCHEMA = `
6
+ CREATE TABLE IF NOT EXISTS deferred_routing (
7
+ sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE,
8
+ conversation TEXT NOT NULL, physical_route TEXT NOT NULL, message_id TEXT,
9
+ priority TEXT, stop_lane TEXT, choice_at INTEGER, data TEXT NOT NULL
10
+ );
11
+ CREATE INDEX IF NOT EXISTS deferred_routing_conversation
12
+ ON deferred_routing(conversation, sequence, id);
13
+ CREATE INDEX IF NOT EXISTS deferred_routing_priority
14
+ ON deferred_routing(conversation, sequence, priority) WHERE priority IS NOT NULL;
15
+ CREATE INDEX IF NOT EXISTS deferred_routing_named_stop
16
+ ON deferred_routing(stop_lane, sequence) WHERE stop_lane IS NOT NULL;
17
+ CREATE INDEX IF NOT EXISTS deferred_routing_bare_stop
18
+ ON deferred_routing(physical_route, sequence) WHERE priority = 'bare-stop';
19
+ CREATE INDEX IF NOT EXISTS deferred_routing_message
20
+ ON deferred_routing(physical_route, message_id, sequence, id);
21
+ CREATE INDEX IF NOT EXISTS deferred_routing_choice
22
+ ON deferred_routing(physical_route, choice_at) WHERE choice_at IS NOT NULL;
23
+ `;
24
+
25
+ // A missing queue ID is a new direct receipt. In that case the snapshot
26
+ // includes every row already queued, regardless of its conversation.
27
+ const EARLIER = `sequence <= COALESCE(
28
+ (SELECT sequence - 1 FROM deferred_routing WHERE id = ?1),
29
+ (SELECT max(sequence) FROM deferred_routing))`;
30
+
31
+ interface DataRow { readonly data: string }
32
+ interface IdRow { readonly id: string }
33
+
34
+ export interface DeferredChoiceRow {
35
+ readonly id: string;
36
+ readonly text: string;
37
+ readonly messageId: string | null;
38
+ readonly replyId: string | null;
39
+ readonly authoredAt: number;
40
+ }
41
+
42
+ export class DeferredRoutingQueue implements DeferredRoutingPort {
43
+ constructor(private readonly db: Database,
44
+ private readonly reconcileInbound: (existing: Inbound, incoming: Inbound) => Inbound | null) {
45
+ this.db.transaction(() => {
46
+ this.db.run(SCHEMA);
47
+ const legacy = this.db.query<{ value: string }, [string]>("SELECT value FROM metadata WHERE key = ?").get(LEGACY_QUEUE);
48
+ if (!legacy) return;
49
+ const queue: readonly Inbound[] = JSON.parse(legacy.value);
50
+ if (!Array.isArray(queue)) throw new TypeError("Invalid legacy deferred routing queue");
51
+ for (const input of queue) this.enqueue(input);
52
+ this.db.query("DELETE FROM metadata WHERE key = ?").run(LEGACY_QUEUE);
53
+ }).immediate();
54
+ }
55
+
56
+ enqueue(input: Inbound): void {
57
+ const candidate = deferredRecoveryCandidate(input.text);
58
+ const choiceAt = !input.pickerSelection && (typeof input.messageId === "string" || typeof input.interactionId === "string")
59
+ && Number.isSafeInteger(input.receivedAt) ? input.receivedAt : null;
60
+ this.db.query(`INSERT INTO deferred_routing
61
+ (id, conversation, physical_route, message_id, priority, stop_lane, choice_at, data)
62
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(
63
+ input.id, routingConversation(input.route), physicalRouteKey(input.route), input.messageId,
64
+ candidate?.kind ?? null, candidate?.kind === "lane-stop" ? candidate.laneId : null,
65
+ choiceAt, JSON.stringify(input),
66
+ );
67
+ }
68
+
69
+ reconcile(incoming: Inbound): boolean {
70
+ const existing = this.input(incoming.id);
71
+ if (!existing) return false;
72
+ const refreshed = this.reconcileInbound(existing, incoming);
73
+ if (refreshed) this.db.query("UPDATE deferred_routing SET data = ? WHERE id = ?").run(JSON.stringify(refreshed), incoming.id);
74
+ return true;
75
+ }
76
+
77
+ input(id: string): Inbound | null {
78
+ const row = this.db.query<DataRow, [string]>("SELECT data FROM deferred_routing WHERE id = ?").get(id);
79
+ return row ? JSON.parse(row.data) : null;
80
+ }
81
+
82
+ has(id: string): boolean {
83
+ return this.db.query("SELECT 1 FROM deferred_routing WHERE id = ?").get(id) !== null;
84
+ }
85
+
86
+ head(conversation: string): string | null {
87
+ return this.db.query<IdRow, [string]>(`
88
+ SELECT id FROM deferred_routing WHERE conversation = ? ORDER BY sequence LIMIT 1
89
+ `).get(conversation)?.id ?? null;
90
+ }
91
+
92
+ conversations(): readonly string[] {
93
+ return this.db.query<{ conversation: string }, []>(`
94
+ SELECT conversation FROM deferred_routing GROUP BY conversation ORDER BY min(sequence)
95
+ `).all().map(row => row.conversation);
96
+ }
97
+
98
+ *priority(conversation: string, includeBare: boolean): Iterable<Inbound> {
99
+ const rows = this.db.query<DataRow, [string, number]>(`
100
+ SELECT data FROM deferred_routing INDEXED BY deferred_routing_priority WHERE conversation = ? AND priority IS NOT NULL
101
+ AND (? OR priority <> 'bare-stop') ORDER BY sequence
102
+ `).iterate(conversation, Number(includeBare));
103
+ for (const row of rows) yield JSON.parse(row.data);
104
+ }
105
+
106
+ *earlierLaneStops(lane: Pick<Lane, "id" | "route">, beforeId: string): Iterable<Inbound> {
107
+ // A bare stop binds only by its exact Discord thread route. Named stops
108
+ // can come from any conversation but need not read other lanes' candidates.
109
+ const rows = this.db.query<DataRow, [string, string, string]>(`
110
+ SELECT data, sequence FROM deferred_routing INDEXED BY deferred_routing_named_stop WHERE stop_lane = ?2 AND ${EARLIER}
111
+ UNION ALL
112
+ SELECT data, sequence FROM deferred_routing INDEXED BY deferred_routing_bare_stop
113
+ WHERE physical_route = ?3 AND priority = 'bare-stop' AND ${EARLIER}
114
+ ORDER BY sequence
115
+ `).iterate(beforeId, lane.id, physicalRouteKey(lane.route));
116
+ for (const row of rows) yield JSON.parse(row.data);
117
+ }
118
+
119
+ hasEarlierMessage(input: Pick<Inbound, "id" | "route">, messageId: string): boolean {
120
+ return this.db.query(`
121
+ SELECT 1 FROM deferred_routing WHERE physical_route = ?2 AND message_id = ?3 AND ${EARLIER} LIMIT 1
122
+ `).get(input.id, physicalRouteKey(input.route), messageId) !== null;
123
+ }
124
+
125
+ idsBefore(id: string): readonly string[] {
126
+ return this.db.query<IdRow, [string]>(`
127
+ SELECT id FROM deferred_routing WHERE ${EARLIER} ORDER BY sequence
128
+ `).all(id).map(row => row.id);
129
+ }
130
+
131
+ remove(id: string): void {
132
+ this.db.query("DELETE FROM deferred_routing WHERE id = ?").run(id);
133
+ }
134
+
135
+ hasOnRoute(route: Route, exceptId: string): boolean {
136
+ return this.db.query(`
137
+ SELECT 1 FROM deferred_routing WHERE physical_route = ? AND id <> ? LIMIT 1
138
+ `).get(physicalRouteKey(route), exceptId) !== null;
139
+ }
140
+
141
+ choices(input: Pick<Inbound, "id" | "route" | "receivedAt">, deadline: number): Iterable<DeferredChoiceRow> {
142
+ return this.db.query<DeferredChoiceRow, [string, number, number, string]>(`
143
+ SELECT id, json_extract(data, '$.text') AS text, message_id AS messageId,
144
+ json_extract(data, '$.reply.messageId') AS replyId, choice_at AS authoredAt
145
+ FROM deferred_routing INDEXED BY deferred_routing_choice
146
+ WHERE physical_route = ? AND choice_at BETWEEN ? AND ? AND id <> ?
147
+ `).iterate(physicalRouteKey(input.route), input.receivedAt, deadline, input.id);
148
+ }
149
+ }