hiveagents-runtime 0.0.0-stage → 0.1.0-beta.3
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.
- package/LICENSE +202 -0
- package/README.md +89 -2
- package/dist/adapter-kit.d.ts +37 -0
- package/dist/adapter-kit.js +34 -0
- package/dist/adapter-kit.js.map +1 -0
- package/dist/agent-Bj5YPrO7.d.ts +169 -0
- package/dist/agent-D6OXR7UF.js +24 -0
- package/dist/agent-D6OXR7UF.js.map +1 -0
- package/dist/agent-readiness-KSGNKTGK.js +19 -0
- package/dist/agent-readiness-KSGNKTGK.js.map +1 -0
- package/dist/capture-runtime-GP6NZ2ee.d.ts +54 -0
- package/dist/chunk-2RK74GCA.js +2397 -0
- package/dist/chunk-2RK74GCA.js.map +1 -0
- package/dist/chunk-3TIYA3K5.js +55 -0
- package/dist/chunk-3TIYA3K5.js.map +1 -0
- package/dist/chunk-6FIXXWNM.js +1 -0
- package/dist/chunk-6FIXXWNM.js.map +1 -0
- package/dist/chunk-6XIJW65Q.js +52 -0
- package/dist/chunk-6XIJW65Q.js.map +1 -0
- package/dist/chunk-7LDQKJKI.js +248 -0
- package/dist/chunk-7LDQKJKI.js.map +1 -0
- package/dist/chunk-CPN4DOXH.js +115 -0
- package/dist/chunk-CPN4DOXH.js.map +1 -0
- package/dist/chunk-DAXPAV2L.js +810 -0
- package/dist/chunk-DAXPAV2L.js.map +1 -0
- package/dist/chunk-DQEMIGKC.js +291 -0
- package/dist/chunk-DQEMIGKC.js.map +1 -0
- package/dist/chunk-DZFFGUIA.js +81 -0
- package/dist/chunk-DZFFGUIA.js.map +1 -0
- package/dist/chunk-EEUYQFCP.js +106 -0
- package/dist/chunk-EEUYQFCP.js.map +1 -0
- package/dist/chunk-G6JV7WV6.js +521 -0
- package/dist/chunk-G6JV7WV6.js.map +1 -0
- package/dist/chunk-GFVYNPLS.js +118 -0
- package/dist/chunk-GFVYNPLS.js.map +1 -0
- package/dist/chunk-GS5U3KUN.js +201 -0
- package/dist/chunk-GS5U3KUN.js.map +1 -0
- package/dist/chunk-HB7FBSH2.js +960 -0
- package/dist/chunk-HB7FBSH2.js.map +1 -0
- package/dist/chunk-HZFZX5A3.js +21 -0
- package/dist/chunk-HZFZX5A3.js.map +1 -0
- package/dist/chunk-J7VAYJKM.js +595 -0
- package/dist/chunk-J7VAYJKM.js.map +1 -0
- package/dist/chunk-NCNSHOF7.js +52 -0
- package/dist/chunk-NCNSHOF7.js.map +1 -0
- package/dist/chunk-RH5A5U7G.js +202 -0
- package/dist/chunk-RH5A5U7G.js.map +1 -0
- package/dist/chunk-RX3XZENU.js +385 -0
- package/dist/chunk-RX3XZENU.js.map +1 -0
- package/dist/chunk-RXU2Q2HF.js +49 -0
- package/dist/chunk-RXU2Q2HF.js.map +1 -0
- package/dist/chunk-TG7NTMTR.js +208 -0
- package/dist/chunk-TG7NTMTR.js.map +1 -0
- package/dist/chunk-TWGEYWMO.js +1217 -0
- package/dist/chunk-TWGEYWMO.js.map +1 -0
- package/dist/chunk-UZPDDQVJ.js +2910 -0
- package/dist/chunk-UZPDDQVJ.js.map +1 -0
- package/dist/chunk-WMKO5XOE.js +601 -0
- package/dist/chunk-WMKO5XOE.js.map +1 -0
- package/dist/chunk-WOQBVJH5.js +175 -0
- package/dist/chunk-WOQBVJH5.js.map +1 -0
- package/dist/chunk-WVT5SEKC.js +581 -0
- package/dist/chunk-WVT5SEKC.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +26 -0
- package/dist/cli.js.map +1 -0
- package/dist/errors-BNHvvjn9.d.ts +98 -0
- package/dist/execution-halt-B8G0fOKS.d.ts +12 -0
- package/dist/execution-types-ClYYqPQP.d.ts +239 -0
- package/dist/host-ledger-VPRWVVOS.js +25 -0
- package/dist/host-ledger-VPRWVVOS.js.map +1 -0
- package/dist/hosted-runtime.d.ts +168 -0
- package/dist/hosted-runtime.js +858 -0
- package/dist/hosted-runtime.js.map +1 -0
- package/dist/index-B86C6VAD.d.ts +41 -0
- package/dist/index.d.ts +344 -0
- package/dist/index.js +8825 -0
- package/dist/index.js.map +1 -0
- package/dist/memory-items-BSTC0_R0.d.ts +28 -0
- package/dist/memory-tools.d.ts +222 -0
- package/dist/memory-tools.js +923 -0
- package/dist/memory-tools.js.map +1 -0
- package/dist/orchestration/dynamic.d.ts +854 -0
- package/dist/orchestration/dynamic.js +3150 -0
- package/dist/orchestration/dynamic.js.map +1 -0
- package/dist/orchestration/graph.d.ts +11 -0
- package/dist/orchestration/graph.js +9 -0
- package/dist/orchestration/graph.js.map +1 -0
- package/dist/orchestration/index.d.ts +2385 -0
- package/dist/orchestration/index.js +6409 -0
- package/dist/orchestration/index.js.map +1 -0
- package/dist/orchestration/log.d.ts +301 -0
- package/dist/orchestration/log.js +3058 -0
- package/dist/orchestration/log.js.map +1 -0
- package/dist/orchestration/memory.d.ts +711 -0
- package/dist/orchestration/memory.js +27 -0
- package/dist/orchestration/memory.js.map +1 -0
- package/dist/provider-DX5Mf0uq.d.ts +151 -0
- package/dist/routing/index.d.ts +29 -0
- package/dist/routing/index.js +386 -0
- package/dist/routing/index.js.map +1 -0
- package/dist/routing/learning/index.d.ts +433 -0
- package/dist/routing/learning/index.js +2502 -0
- package/dist/routing/learning/index.js.map +1 -0
- package/dist/runtime-BSjrnxeF.d.ts +283 -0
- package/dist/runtime-OISPXS4I.js +19 -0
- package/dist/runtime-OISPXS4I.js.map +1 -0
- package/dist/store-types-2YdceOMy.d.ts +78 -0
- package/dist/types-BB7KqceP.d.ts +52 -0
- package/dist/types-CIqkKXix.d.ts +86 -0
- package/dist/types-DTFc1qO6.d.ts +1065 -0
- package/dist/types-DYex3p7_.d.ts +88 -0
- package/docs/licenses/ruflo-memory-MIT.txt +21 -0
- package/docs/releases/0.1.0-beta.3.md +13 -0
- package/package.json +114 -4
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AbortError,
|
|
3
|
+
AgentRuntimeError,
|
|
4
|
+
OutputLimitError,
|
|
5
|
+
ProtocolError,
|
|
6
|
+
ProviderUnavailableError,
|
|
7
|
+
TimeoutError
|
|
8
|
+
} from "./chunk-TG7NTMTR.js";
|
|
9
|
+
|
|
10
|
+
// src/process/run-process.ts
|
|
11
|
+
import { spawn } from "node:child_process";
|
|
12
|
+
function signalProcessTree(child, signal, parentClosed = false) {
|
|
13
|
+
if (parentClosed || child.exitCode !== null || child.signalCode !== null) return;
|
|
14
|
+
if (process.platform !== "win32" && child.pid !== void 0) {
|
|
15
|
+
try {
|
|
16
|
+
process.kill(-child.pid, signal);
|
|
17
|
+
return;
|
|
18
|
+
} catch {
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
child.kill(signal);
|
|
23
|
+
} catch {
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function forceKillWindowsTree(child) {
|
|
27
|
+
if (process.platform !== "win32" || child.pid === void 0 || child.exitCode !== null || child.signalCode !== null) return;
|
|
28
|
+
const killer = spawn("taskkill.exe", ["/pid", String(child.pid), "/t", "/f"], {
|
|
29
|
+
shell: false,
|
|
30
|
+
windowsHide: true,
|
|
31
|
+
stdio: "ignore"
|
|
32
|
+
});
|
|
33
|
+
killer.unref();
|
|
34
|
+
}
|
|
35
|
+
var MAX_TIMEOUT_MS = 2 ** 31 - 1;
|
|
36
|
+
function validateTimeoutMs(timeoutMs) {
|
|
37
|
+
const value = timeoutMs ?? 6e5;
|
|
38
|
+
if (!Number.isInteger(value) || value < 1 || value > MAX_TIMEOUT_MS) {
|
|
39
|
+
throw new RangeError(`timeoutMs must be an integer between 1 and ${MAX_TIMEOUT_MS}`);
|
|
40
|
+
}
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
async function runProcess(request) {
|
|
44
|
+
validateTimeoutMs(request.timeoutMs);
|
|
45
|
+
if (request.signal?.aborted) {
|
|
46
|
+
throw new AbortError({ retryable: true }, "Turn aborted before process start");
|
|
47
|
+
}
|
|
48
|
+
const startedAt = Date.now();
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
let stdoutBytes = 0;
|
|
51
|
+
let stderrBytes = 0;
|
|
52
|
+
const stdout = request.captureStdout === false ? void 0 : [];
|
|
53
|
+
const stderr = [];
|
|
54
|
+
let terminalError;
|
|
55
|
+
let settled = false;
|
|
56
|
+
let parentClosed = false;
|
|
57
|
+
let closeOutcome;
|
|
58
|
+
let pendingDelivery;
|
|
59
|
+
let deferredStdout;
|
|
60
|
+
const deliveryController = new AbortController();
|
|
61
|
+
let escalationTimer;
|
|
62
|
+
const child = spawn(request.command, request.args, {
|
|
63
|
+
cwd: request.cwd,
|
|
64
|
+
env: request.env,
|
|
65
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
66
|
+
shell: false,
|
|
67
|
+
windowsHide: true,
|
|
68
|
+
detached: process.platform !== "win32"
|
|
69
|
+
});
|
|
70
|
+
const startTermination = () => {
|
|
71
|
+
if (parentClosed || settled || child.exitCode !== null || child.signalCode !== null) return;
|
|
72
|
+
signalProcessTree(child, "SIGTERM", parentClosed);
|
|
73
|
+
if (escalationTimer !== void 0) clearTimeout(escalationTimer);
|
|
74
|
+
escalationTimer = setTimeout(() => {
|
|
75
|
+
escalationTimer = void 0;
|
|
76
|
+
if (process.platform === "win32") {
|
|
77
|
+
if (!parentClosed) forceKillWindowsTree(child);
|
|
78
|
+
} else signalProcessTree(child, "SIGKILL", parentClosed);
|
|
79
|
+
finishProcess();
|
|
80
|
+
}, request.killGraceMs ?? 100);
|
|
81
|
+
escalationTimer.unref();
|
|
82
|
+
};
|
|
83
|
+
const notifyFailure = (error) => {
|
|
84
|
+
try {
|
|
85
|
+
void Promise.resolve(request.onFailure?.(error)).catch(() => void 0);
|
|
86
|
+
} catch {
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
const terminate = () => {
|
|
90
|
+
if (parentClosed || settled) return;
|
|
91
|
+
startTermination();
|
|
92
|
+
};
|
|
93
|
+
const fail = (error) => {
|
|
94
|
+
if (terminalError) return;
|
|
95
|
+
terminalError = error;
|
|
96
|
+
notifyFailure(error);
|
|
97
|
+
deferredStdout = void 0;
|
|
98
|
+
deliveryController.abort(error);
|
|
99
|
+
child.stdout?.resume();
|
|
100
|
+
terminate();
|
|
101
|
+
finishProcess();
|
|
102
|
+
};
|
|
103
|
+
const exceedLimit = () => {
|
|
104
|
+
fail(new OutputLimitError(
|
|
105
|
+
{
|
|
106
|
+
retryable: false,
|
|
107
|
+
sanitizedDiagnostics: {
|
|
108
|
+
maxOutputBytes: request.maxOutputBytes,
|
|
109
|
+
observedOutputBytes: stdoutBytes + stderrBytes
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
));
|
|
113
|
+
};
|
|
114
|
+
const deliver = (sink, callback, value) => {
|
|
115
|
+
if (terminalError) return;
|
|
116
|
+
if (stdoutBytes + stderrBytes > request.maxOutputBytes) {
|
|
117
|
+
exceedLimit();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
sink?.push(value);
|
|
121
|
+
try {
|
|
122
|
+
callback?.(value);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
fail(error instanceof AgentRuntimeError ? error : new ProtocolError(
|
|
125
|
+
{
|
|
126
|
+
retryable: false,
|
|
127
|
+
sanitizedDiagnostics: { message: error instanceof Error ? error.message : String(error) }
|
|
128
|
+
},
|
|
129
|
+
"Provider output consumer failed"
|
|
130
|
+
));
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
const deliverAsync = (value) => {
|
|
134
|
+
deliver(stdout, void 0, value);
|
|
135
|
+
if (terminalError) {
|
|
136
|
+
child.stdout.resume();
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
timeoutTimer.ref();
|
|
140
|
+
pendingDelivery = Promise.resolve().then(async () => {
|
|
141
|
+
if (!terminalError) await request.onStdoutAsync(value, deliveryController.signal);
|
|
142
|
+
});
|
|
143
|
+
void pendingDelivery.then(() => {
|
|
144
|
+
pendingDelivery = void 0;
|
|
145
|
+
const deferred = deferredStdout;
|
|
146
|
+
deferredStdout = void 0;
|
|
147
|
+
if (!terminalError && !settled) {
|
|
148
|
+
if (deferred) deliverAsync(deferred);
|
|
149
|
+
else child.stdout.resume();
|
|
150
|
+
}
|
|
151
|
+
finishProcess();
|
|
152
|
+
}, (error) => {
|
|
153
|
+
pendingDelivery = void 0;
|
|
154
|
+
fail(error instanceof AgentRuntimeError ? error : new ProtocolError(
|
|
155
|
+
{ retryable: false, sanitizedDiagnostics: { message: error instanceof Error ? error.message : String(error) } },
|
|
156
|
+
"Provider output consumer failed"
|
|
157
|
+
));
|
|
158
|
+
});
|
|
159
|
+
};
|
|
160
|
+
child.stdout?.on("data", (value) => {
|
|
161
|
+
stdoutBytes += value.byteLength;
|
|
162
|
+
if (!request.onStdoutAsync) {
|
|
163
|
+
deliver(stdout, request.onStdout, value);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (terminalError) return;
|
|
167
|
+
if (stdoutBytes + stderrBytes > request.maxOutputBytes) {
|
|
168
|
+
exceedLimit();
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
child.stdout.pause();
|
|
172
|
+
if (pendingDelivery !== void 0) {
|
|
173
|
+
if (deferredStdout !== void 0) {
|
|
174
|
+
fail(new OutputLimitError({ retryable: false }, "Provider stdout exceeded its pending delivery buffer"));
|
|
175
|
+
} else deferredStdout = value;
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
deliverAsync(value);
|
|
179
|
+
});
|
|
180
|
+
child.stderr?.on("data", (value) => {
|
|
181
|
+
stderrBytes += value.byteLength;
|
|
182
|
+
deliver(stderr, request.onStderr, value);
|
|
183
|
+
});
|
|
184
|
+
const timeoutTimer = setTimeout(() => fail(new TimeoutError(
|
|
185
|
+
{ retryable: true, sanitizedDiagnostics: { timeoutMs: request.timeoutMs } }
|
|
186
|
+
)), request.timeoutMs);
|
|
187
|
+
timeoutTimer.unref();
|
|
188
|
+
const onAbort = () => fail(new AbortError({ retryable: true }));
|
|
189
|
+
request.signal?.addEventListener("abort", onAbort, { once: true });
|
|
190
|
+
const cleanup = () => {
|
|
191
|
+
clearTimeout(timeoutTimer);
|
|
192
|
+
if (escalationTimer !== void 0) clearTimeout(escalationTimer);
|
|
193
|
+
request.signal?.removeEventListener("abort", onAbort);
|
|
194
|
+
};
|
|
195
|
+
child.once("error", (cause) => {
|
|
196
|
+
if (settled) return;
|
|
197
|
+
settled = true;
|
|
198
|
+
const hadFailure = terminalError !== void 0;
|
|
199
|
+
const failure = terminalError ?? new ProviderUnavailableError(
|
|
200
|
+
{ retryable: true, sanitizedDiagnostics: { command: request.command } },
|
|
201
|
+
`Unable to start provider process: ${cause.message}`
|
|
202
|
+
);
|
|
203
|
+
terminalError = failure;
|
|
204
|
+
if (!hadFailure) notifyFailure(failure);
|
|
205
|
+
deliveryController.abort(cause);
|
|
206
|
+
cleanup();
|
|
207
|
+
reject(failure);
|
|
208
|
+
});
|
|
209
|
+
function finishProcess() {
|
|
210
|
+
if (settled || closeOutcome === void 0) return;
|
|
211
|
+
if (!terminalError && pendingDelivery !== void 0) {
|
|
212
|
+
timeoutTimer.ref();
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
if (terminalError && escalationTimer !== void 0) {
|
|
216
|
+
escalationTimer.ref();
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
settled = true;
|
|
220
|
+
cleanup();
|
|
221
|
+
if (terminalError) {
|
|
222
|
+
reject(terminalError);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
resolve({
|
|
226
|
+
...closeOutcome,
|
|
227
|
+
stdout: stdout === void 0 ? "" : Buffer.concat(stdout).toString("utf8"),
|
|
228
|
+
stderr: Buffer.concat(stderr).toString("utf8"),
|
|
229
|
+
durationMs: Date.now() - startedAt
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
child.once("close", (code, signal) => {
|
|
233
|
+
if (settled) return;
|
|
234
|
+
parentClosed = true;
|
|
235
|
+
closeOutcome = { code, signal };
|
|
236
|
+
finishProcess();
|
|
237
|
+
});
|
|
238
|
+
child.stdin?.once("error", () => {
|
|
239
|
+
});
|
|
240
|
+
child.stdin?.end(request.stdin);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export {
|
|
245
|
+
validateTimeoutMs,
|
|
246
|
+
runProcess
|
|
247
|
+
};
|
|
248
|
+
//# sourceMappingURL=chunk-7LDQKJKI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/process/run-process.ts"],"sourcesContent":["import { spawn, type ChildProcess } from 'node:child_process';\n\nimport {\n AbortError as RuntimeAbortError,\n AgentRuntimeError,\n OutputLimitError,\n ProtocolError,\n ProviderUnavailableError,\n TimeoutError,\n} from '../public/errors.js';\n\nexport interface ProcessRequest {\n command: string;\n args: string[];\n cwd: string;\n env: NodeJS.ProcessEnv;\n stdin: string | Uint8Array;\n timeoutMs: number;\n maxOutputBytes: number;\n /** Defaults to true. False returns empty stdout without changing delivery or byte limits. */\n captureStdout?: boolean;\n signal?: AbortSignal;\n onStdout?: (chunk: Uint8Array) => void;\n /** Cooperative bounded delivery; preferred over onStdout when supplied. */\n onStdoutAsync?: (chunk: Uint8Array, deliverySignal: AbortSignal) => Promise<void>;\n onStderr?: (chunk: Uint8Array) => void;\n /** Synchronous notification of the first native failure, before bounded cleanup. */\n onFailure?: (error: AgentRuntimeError) => void | Promise<void>;\n killGraceMs?: number;\n}\n\nexport interface ProcessOutcome {\n code: number | null;\n signal: NodeJS.Signals | null;\n stdout: string;\n stderr: string;\n durationMs: number;\n}\n\nfunction signalProcessTree(child: ChildProcess, signal: NodeJS.Signals, parentClosed = false): void {\n // A saved PID/PGID loses its identity when the leader exits. Inherited\n // pipes do not establish ownership; only a surviving guardian can do that.\n if (parentClosed || child.exitCode !== null || child.signalCode !== null) return;\n if (process.platform !== 'win32' && child.pid !== undefined) {\n try {\n process.kill(-child.pid, signal);\n return;\n } catch {\n // The group can already be gone; fall through to the direct child.\n }\n }\n try {\n child.kill(signal);\n } catch {\n // The process already exited.\n }\n}\n\nfunction forceKillWindowsTree(child: ChildProcess): void {\n if (process.platform !== 'win32' || child.pid === undefined\n || child.exitCode !== null || child.signalCode !== null) return;\n const killer = spawn('taskkill.exe', ['/pid', String(child.pid), '/t', '/f'], {\n shell: false,\n windowsHide: true,\n stdio: 'ignore',\n });\n killer.unref();\n}\n\n/** Node timers silently clamp anything outside this range to 1 ms. */\nconst MAX_TIMEOUT_MS = 2 ** 31 - 1;\n\nexport function validateTimeoutMs(timeoutMs: number | undefined): number {\n const value = timeoutMs ?? 600_000;\n if (!Number.isInteger(value) || value < 1 || value > MAX_TIMEOUT_MS) {\n throw new RangeError(`timeoutMs must be an integer between 1 and ${MAX_TIMEOUT_MS}`);\n }\n return value;\n}\n\nexport async function runProcess(request: ProcessRequest): Promise<ProcessOutcome> {\n validateTimeoutMs(request.timeoutMs);\n if (request.signal?.aborted) {\n throw new RuntimeAbortError({ retryable: true }, 'Turn aborted before process start');\n }\n\n const startedAt = Date.now();\n return new Promise<ProcessOutcome>((resolve, reject) => {\n let stdoutBytes = 0;\n let stderrBytes = 0;\n const stdout: Buffer[] | undefined = request.captureStdout === false ? undefined : [];\n const stderr: Buffer[] = [];\n let terminalError: AgentRuntimeError | undefined;\n let settled = false;\n let parentClosed = false;\n let closeOutcome: { code: number | null; signal: NodeJS.Signals | null } | undefined;\n let pendingDelivery: Promise<void> | undefined;\n let deferredStdout: Buffer | undefined;\n const deliveryController = new AbortController();\n let escalationTimer: NodeJS.Timeout | undefined;\n\n const child = spawn(request.command, request.args, {\n cwd: request.cwd,\n env: request.env,\n stdio: ['pipe', 'pipe', 'pipe'],\n shell: false,\n windowsHide: true,\n detached: process.platform !== 'win32',\n });\n\n const startTermination = (): void => {\n if (parentClosed || settled || child.exitCode !== null || child.signalCode !== null) return;\n signalProcessTree(child, 'SIGTERM', parentClosed);\n if (escalationTimer !== undefined) clearTimeout(escalationTimer);\n escalationTimer = setTimeout(() => {\n escalationTimer = undefined;\n if (process.platform === 'win32') {\n if (!parentClosed) forceKillWindowsTree(child);\n }\n else signalProcessTree(child, 'SIGKILL', parentClosed);\n finishProcess();\n }, request.killGraceMs ?? 100);\n escalationTimer.unref();\n };\n\n const notifyFailure = (error: AgentRuntimeError): void => {\n try { void Promise.resolve(request.onFailure?.(error)).catch(() => undefined); }\n catch { /* Observation cannot replace the native first cause. */ }\n };\n const terminate = (): void => {\n if (parentClosed || settled) return;\n // If the leader has exited, keep observing actual pipe settlement.\n // Do not guess ownership of its numeric group or destroy pipes as proof.\n startTermination();\n };\n\n const fail = (error: AgentRuntimeError): void => {\n if (terminalError) return;\n terminalError = error;\n notifyFailure(error);\n deferredStdout = undefined;\n deliveryController.abort(error);\n // Stop waiting for an abandoned/noncooperative sink. Drain the pipe so\n // child close and group cleanup remain observable; discard later bytes.\n child.stdout?.resume();\n terminate();\n finishProcess();\n };\n\n const exceedLimit = (): void => {\n fail(new OutputLimitError(\n {\n retryable: false,\n sanitizedDiagnostics: {\n maxOutputBytes: request.maxOutputBytes,\n observedOutputBytes: stdoutBytes + stderrBytes,\n },\n },\n ));\n };\n\n // A consumer callback runs inside the stream 'data' handler: anything it\n // throws would otherwise escape as an uncaughtException in the host while\n // the child keeps running. Its failure is terminal for the turn instead.\n const deliver = (\n sink: Buffer[] | undefined,\n callback: ((chunk: Uint8Array) => void) | undefined,\n value: Buffer,\n ): void => {\n if (terminalError) return;\n if (stdoutBytes + stderrBytes > request.maxOutputBytes) {\n exceedLimit();\n return;\n }\n sink?.push(value);\n try {\n callback?.(value);\n } catch (error) {\n fail(error instanceof AgentRuntimeError ? error : new ProtocolError(\n {\n retryable: false,\n sanitizedDiagnostics: { message: error instanceof Error ? error.message : String(error) },\n },\n 'Provider output consumer failed',\n ));\n }\n };\n\n const deliverAsync = (value: Buffer): void => {\n deliver(stdout, undefined, value);\n if (terminalError) { child.stdout.resume(); return; }\n // Pausing before invoking the sink leaves exactly one outstanding\n // delivery, with Node/OS pipe buffers providing bounded upstream storage.\n timeoutTimer.ref();\n pendingDelivery = Promise.resolve().then(async () => {\n if (!terminalError) await request.onStdoutAsync!(value, deliveryController.signal);\n });\n void pendingDelivery.then(() => {\n pendingDelivery = undefined;\n const deferred = deferredStdout; deferredStdout = undefined;\n if (!terminalError && !settled) {\n if (deferred) deliverAsync(deferred);\n else child.stdout.resume();\n }\n finishProcess();\n }, (error: unknown) => {\n pendingDelivery = undefined;\n fail(error instanceof AgentRuntimeError ? error : new ProtocolError(\n { retryable: false, sanitizedDiagnostics: { message: error instanceof Error ? error.message : String(error) } },\n 'Provider output consumer failed',\n ));\n });\n };\n child.stdout?.on('data', (value: Buffer) => {\n stdoutBytes += value.byteLength;\n if (!request.onStdoutAsync) { deliver(stdout, request.onStdout, value); return; }\n if (terminalError) return;\n if (stdoutBytes + stderrBytes > request.maxOutputBytes) { exceedLimit(); return; }\n child.stdout.pause();\n if (pendingDelivery !== undefined) {\n // Node's child-exit flush resumes stdio independently of our pause.\n // Retain at most that one read chunk, counted by the output fuse now,\n // and deliver it only after the current sink acknowledges.\n if (deferredStdout !== undefined) {\n fail(new OutputLimitError({ retryable: false }, 'Provider stdout exceeded its pending delivery buffer'));\n } else deferredStdout = value;\n return;\n }\n deliverAsync(value);\n });\n child.stderr?.on('data', (value: Buffer) => {\n stderrBytes += value.byteLength;\n deliver(stderr, request.onStderr, value);\n });\n\n // Both go through fail(): the first terminal error wins. A timer or abort\n // landing while the child is still closing after an OUTPUT_LIMIT must not\n // relabel it as a retryable TIMEOUT/ABORTED.\n const timeoutTimer = setTimeout(() => fail(new TimeoutError(\n { retryable: true, sanitizedDiagnostics: { timeoutMs: request.timeoutMs } },\n )), request.timeoutMs);\n timeoutTimer.unref();\n\n const onAbort = (): void => fail(new RuntimeAbortError({ retryable: true }));\n request.signal?.addEventListener('abort', onAbort, { once: true });\n\n const cleanup = (): void => {\n clearTimeout(timeoutTimer);\n if (escalationTimer !== undefined) clearTimeout(escalationTimer);\n request.signal?.removeEventListener('abort', onAbort);\n };\n\n child.once('error', (cause) => {\n if (settled) return;\n settled = true;\n const hadFailure = terminalError !== undefined;\n const failure = terminalError ?? new ProviderUnavailableError(\n { retryable: true, sanitizedDiagnostics: { command: request.command } },\n `Unable to start provider process: ${cause.message}`,\n );\n terminalError = failure;\n if (!hadFailure) notifyFailure(failure);\n deliveryController.abort(cause);\n cleanup();\n reject(failure);\n });\n\n function finishProcess(): void {\n if (settled || closeOutcome === undefined) return;\n // A clean close never cancels delivery. Keep the deadline alive until\n // every read byte is acknowledged, even after the child has exited.\n if (!terminalError && pendingDelivery !== undefined) { timeoutTimer.ref(); return; }\n if (terminalError && escalationTimer !== undefined) { escalationTimer.ref(); return; }\n settled = true;\n cleanup();\n if (terminalError) { reject(terminalError); return; }\n resolve({ ...closeOutcome, stdout: stdout === undefined ? '' : Buffer.concat(stdout).toString('utf8'),\n stderr: Buffer.concat(stderr).toString('utf8'), durationMs: Date.now() - startedAt });\n }\n\n child.once('close', (code, signal) => {\n if (settled) return;\n parentClosed = true;\n closeOutcome = { code, signal };\n // Escalation rechecks the live leader before every native signal.\n finishProcess();\n });\n\n child.stdin?.once('error', () => {\n // A provider may exit before consuming stdin; close/exit classification is authoritative.\n });\n child.stdin?.end(request.stdin);\n });\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,aAAgC;AAuCzC,SAAS,kBAAkB,OAAqB,QAAwB,eAAe,OAAa;AAGlG,MAAI,gBAAgB,MAAM,aAAa,QAAQ,MAAM,eAAe,KAAM;AAC1E,MAAI,QAAQ,aAAa,WAAW,MAAM,QAAQ,QAAW;AAC3D,QAAI;AACF,cAAQ,KAAK,CAAC,MAAM,KAAK,MAAM;AAC/B;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AACA,MAAI;AACF,UAAM,KAAK,MAAM;AAAA,EACnB,QAAQ;AAAA,EAER;AACF;AAEA,SAAS,qBAAqB,OA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nF,UAAI,iBAAiB,oBAAoB,QAAW;AAAE,wBAAgB,IAAI;AAAG;AAAA,MAAQ;AACrF,gBAAU;AACV,cAAQ;AACR,UAAI,eAAe;AAAE,eAAO,aAAa;AAAG;AAAA,MAAQ;AACpD,cAAQ;AAAA,QAAE,GAAG;AAAA,QAAc,QAAQ,WAAW,SAAY,KAAK,OAAO,OAAO,MAAM,EAAE,SAAS,MAAM;AAAA,QAClG,QAAQ,OAAO,OAAO,MAAM,EAAE,SAAS,MAAM;AAAA,QAAG,YAAY,KAAK,IAAI,IAAI;AAAA,MAAU,CAAC;AAAA,IACxF;AAEA,UAAM,KAAK,SAAS,CAAC,MAAM,WAAW;AACpC,UAAI,QAAS;AACb,qBAAe;AACf,qBAAe,EAAE,MAAM,OAAO;AAE9B,oBAAc;AAAA,IAChB,CAAC;AAED,UAAM,OAAO,KAAK,SAAS,MAAM;AAAA,IAEjC,CAAC;AACD,UAAM,OAAO,IAAI,QAAQ,KAAK;AAAA,EAChC,CAAC;AACH;","names":[]}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import {
|
|
2
|
+
checksum
|
|
3
|
+
} from "./chunk-EEUYQFCP.js";
|
|
4
|
+
|
|
5
|
+
// src/orchestration/workflow/checkpoint.ts
|
|
6
|
+
function nonempty(value, field) {
|
|
7
|
+
if (typeof value !== "string" || !value.trim()) throw new Error(`${field} must be a nonempty string`);
|
|
8
|
+
}
|
|
9
|
+
function jsonClone(value) {
|
|
10
|
+
const seen = /* @__PURE__ */ new Set();
|
|
11
|
+
const visit = (item) => {
|
|
12
|
+
if (item === null || typeof item === "string" || typeof item === "boolean") return;
|
|
13
|
+
if (typeof item === "number" && Number.isFinite(item)) return;
|
|
14
|
+
if (typeof item !== "object" || item === null) throw new Error("Workflow output must be JSON-compatible");
|
|
15
|
+
if (seen.has(item)) throw new Error("Workflow output must be JSON-compatible (cycle)");
|
|
16
|
+
const prototype = Object.getPrototypeOf(item);
|
|
17
|
+
if (Array.isArray(item) ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) {
|
|
18
|
+
throw new Error("Workflow output must be JSON-compatible (plain objects only)");
|
|
19
|
+
}
|
|
20
|
+
if (Object.getOwnPropertySymbols(item).length) throw new Error("Workflow output must be JSON-compatible");
|
|
21
|
+
for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(item))) {
|
|
22
|
+
if (Array.isArray(item) && key === "length") continue;
|
|
23
|
+
if (!Object.hasOwn(descriptor, "value") || !descriptor.enumerable) {
|
|
24
|
+
throw new Error("Workflow output must be JSON-compatible (enumerable data properties only)");
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
seen.add(item);
|
|
28
|
+
if (Array.isArray(item)) {
|
|
29
|
+
if (Object.keys(item).length !== item.length) throw new Error("Workflow output must be JSON-compatible (array holes/properties)");
|
|
30
|
+
for (let index = 0; index < item.length; index++) {
|
|
31
|
+
if (!Object.hasOwn(item, index)) throw new Error("Workflow output must be JSON-compatible (array hole)");
|
|
32
|
+
visit(item[index]);
|
|
33
|
+
}
|
|
34
|
+
} else {
|
|
35
|
+
for (const child of Object.values(item)) visit(child);
|
|
36
|
+
}
|
|
37
|
+
seen.delete(item);
|
|
38
|
+
};
|
|
39
|
+
visit(value);
|
|
40
|
+
return JSON.parse(JSON.stringify(value));
|
|
41
|
+
}
|
|
42
|
+
function identity(definition) {
|
|
43
|
+
nonempty(definition.id, "Workflow id");
|
|
44
|
+
nonempty(definition.version, "Workflow version");
|
|
45
|
+
for (const step of definition.steps) {
|
|
46
|
+
const attempts = step.maxAttempts ?? 1;
|
|
47
|
+
if (!Number.isSafeInteger(attempts) || attempts < 1) throw new Error(`Invalid maxAttempts for ${step.id}`);
|
|
48
|
+
if (step.replaySafe !== void 0 && typeof step.replaySafe !== "boolean") throw new Error(`Invalid replaySafe for ${step.id}`);
|
|
49
|
+
if (typeof step.execute !== "function") throw new Error(`Missing execute callback for ${step.id}`);
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
id: definition.id,
|
|
53
|
+
version: definition.version,
|
|
54
|
+
fingerprint: checksum(JSON.stringify({
|
|
55
|
+
id: definition.id,
|
|
56
|
+
version: definition.version,
|
|
57
|
+
steps: definition.steps.map((step) => ({
|
|
58
|
+
id: step.id,
|
|
59
|
+
dependencies: [...step.dependencies ?? []].sort(),
|
|
60
|
+
maxAttempts: step.maxAttempts ?? 1,
|
|
61
|
+
replaySafe: step.replaySafe ?? false
|
|
62
|
+
}))
|
|
63
|
+
}))
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function object(value) {
|
|
67
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
68
|
+
}
|
|
69
|
+
function validateCheckpoint(value, definition, runId) {
|
|
70
|
+
const fail = () => {
|
|
71
|
+
throw new Error("Corrupt workflow checkpoint");
|
|
72
|
+
};
|
|
73
|
+
if (!object(value) || value.format !== 1 || value.runId !== runId || !object(value.workflow)) return fail();
|
|
74
|
+
const wanted = identity(definition);
|
|
75
|
+
if (value.workflow.id !== wanted.id || value.workflow.version !== wanted.version || value.workflow.fingerprint !== wanted.fingerprint) throw new Error("Workflow definition does not match checkpoint");
|
|
76
|
+
if (typeof value.status !== "string" || !["running", "completed", "failed", "cancelled", "halted"].includes(value.status) || !object(value.steps)) return fail();
|
|
77
|
+
if (Object.keys(value.steps).length !== definition.steps.length) return fail();
|
|
78
|
+
for (const step of definition.steps) {
|
|
79
|
+
if (!Object.hasOwn(value.steps, step.id)) return fail();
|
|
80
|
+
const state = value.steps[step.id];
|
|
81
|
+
if (!object(state) || !Number.isSafeInteger(state.attempts)) return fail();
|
|
82
|
+
const attempts = state.attempts;
|
|
83
|
+
const max = step.maxAttempts ?? 1;
|
|
84
|
+
if (attempts < 0 || attempts > max) return fail();
|
|
85
|
+
if (typeof state.status !== "string" || !["pending", "running", "completed", "failed", "interrupted", "blocked"].includes(state.status)) return fail();
|
|
86
|
+
if (state.status === "pending" && attempts >= max) return fail();
|
|
87
|
+
if (state.status === "blocked" ? attempts !== 0 : state.status !== "pending" && attempts === 0) return fail();
|
|
88
|
+
if (state.status === "failed" && attempts !== max) return fail();
|
|
89
|
+
if (state.error !== void 0 && typeof state.error !== "string") return fail();
|
|
90
|
+
if (state.status === "completed" !== Object.hasOwn(state, "output")) return fail();
|
|
91
|
+
if (state.status === "completed") jsonClone(state.output);
|
|
92
|
+
if (attempts > 0) {
|
|
93
|
+
for (const dependency of step.dependencies ?? []) {
|
|
94
|
+
const parent = value.steps[dependency];
|
|
95
|
+
if (!object(parent) || parent.status !== "completed") return fail();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const states = Object.values(value.steps);
|
|
100
|
+
if (value.status === "completed" && !states.every((state) => state.status === "completed")) return fail();
|
|
101
|
+
if (value.status === "failed" && (states.some((state) => ["pending", "running", "interrupted"].includes(state.status)) || !states.some((state) => state.status === "failed"))) return fail();
|
|
102
|
+
return jsonClone(value);
|
|
103
|
+
}
|
|
104
|
+
function cloneSteps(steps) {
|
|
105
|
+
return steps.map((step) => ({ ...step, ...step.dependencies === void 0 ? {} : { dependencies: [...step.dependencies] } }));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export {
|
|
109
|
+
nonempty,
|
|
110
|
+
jsonClone,
|
|
111
|
+
identity,
|
|
112
|
+
validateCheckpoint,
|
|
113
|
+
cloneSteps
|
|
114
|
+
};
|
|
115
|
+
//# sourceMappingURL=chunk-CPN4DOXH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/orchestration/workflow/checkpoint.ts"],"sourcesContent":["import { checksum } from '../../shared/json.js';\nimport type { JsonValue, WorkflowCheckpoint, WorkflowDefinition, WorkflowStep } from './types.js';\n\nexport { checksum };\n\nexport function nonempty(value: unknown, field: string): asserts value is string {\n if (typeof value !== 'string' || !value.trim()) throw new Error(`${field} must be a nonempty string`);\n}\n\n/** Validates rather than silently dropping undefined, Infinity, holes, cycles or toJSON objects. */\nexport function jsonClone<T>(value: T): T {\n const seen = new Set<object>();\n const visit = (item: unknown): void => {\n if (item === null || typeof item === 'string' || typeof item === 'boolean') return;\n if (typeof item === 'number' && Number.isFinite(item)) return;\n if (typeof item !== 'object' || item === null) throw new Error('Workflow output must be JSON-compatible');\n if (seen.has(item)) throw new Error('Workflow output must be JSON-compatible (cycle)');\n const prototype = Object.getPrototypeOf(item);\n if (Array.isArray(item) ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) {\n throw new Error('Workflow output must be JSON-compatible (plain objects only)');\n }\n if (Object.getOwnPropertySymbols(item).length) throw new Error('Workflow output must be JSON-compatible');\n for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(item))) {\n if (Array.isArray(item) && key === 'length') continue;\n if (!Object.hasOwn(descriptor, 'value') || !descriptor.enumerable) {\n throw new Error('Workflow output must be JSON-compatible (enumerable data properties only)');\n }\n }\n seen.add(item);\n if (Array.isArray(item)) {\n if (Object.keys(item).length !== item.length) throw new Error('Workflow output must be JSON-compatible (array holes/properties)');\n for (let index = 0; index < item.length; index++) {\n if (!Object.hasOwn(item, index)) throw new Error('Workflow output must be JSON-compatible (array hole)');\n visit(item[index]);\n }\n } else {\n for (const child of Object.values(item)) visit(child);\n }\n seen.delete(item);\n };\n visit(value);\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nexport function identity(definition: WorkflowDefinition): WorkflowCheckpoint['workflow'] {\n nonempty(definition.id, 'Workflow id'); nonempty(definition.version, 'Workflow version');\n for (const step of definition.steps) {\n const attempts = step.maxAttempts ?? 1;\n if (!Number.isSafeInteger(attempts) || attempts < 1) throw new Error(`Invalid maxAttempts for ${step.id}`);\n if (step.replaySafe !== undefined && typeof step.replaySafe !== 'boolean') throw new Error(`Invalid replaySafe for ${step.id}`);\n if (typeof step.execute !== 'function') throw new Error(`Missing execute callback for ${step.id}`);\n }\n return {\n id: definition.id, version: definition.version,\n fingerprint: checksum(JSON.stringify({\n id: definition.id, version: definition.version,\n steps: definition.steps.map(step => ({\n id: step.id, dependencies: [...(step.dependencies ?? [])].sort(),\n maxAttempts: step.maxAttempts ?? 1, replaySafe: step.replaySafe ?? false,\n })),\n })),\n };\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function validateCheckpoint(\n value: unknown, definition: WorkflowDefinition, runId: string,\n): WorkflowCheckpoint {\n const fail = (): never => { throw new Error('Corrupt workflow checkpoint'); };\n if (!object(value) || value.format !== 1 || value.runId !== runId || !object(value.workflow)) return fail();\n const wanted = identity(definition);\n if (value.workflow.id !== wanted.id || value.workflow.version !== wanted.version\n || value.workflow.fingerprint !== wanted.fingerprint) throw new Error('Workflow definition does not match checkpoint');\n if (typeof value.status !== 'string' || !['running', 'completed', 'failed', 'cancelled', 'halted'].includes(value.status) || !object(value.steps)) return fail();\n if (Object.keys(value.steps).length !== definition.steps.length) return fail();\n for (const step of definition.steps) {\n if (!Object.hasOwn(value.steps, step.id)) return fail();\n const state = value.steps[step.id];\n if (!object(state) || !Number.isSafeInteger(state.attempts)) return fail();\n const attempts = state.attempts as number; const max = step.maxAttempts ?? 1;\n if (attempts < 0 || attempts > max) return fail();\n if (typeof state.status !== 'string' || !['pending', 'running', 'completed', 'failed', 'interrupted', 'blocked'].includes(state.status)) return fail();\n if (state.status === 'pending' && attempts >= max) return fail();\n if (state.status === 'blocked' ? attempts !== 0 : state.status !== 'pending' && attempts === 0) return fail();\n if (state.status === 'failed' && attempts !== max) return fail();\n if (state.error !== undefined && typeof state.error !== 'string') return fail();\n if ((state.status === 'completed') !== Object.hasOwn(state, 'output')) return fail();\n if (state.status === 'completed') jsonClone(state.output as JsonValue);\n if (attempts > 0) {\n for (const dependency of step.dependencies ?? []) {\n const parent = value.steps[dependency];\n if (!object(parent) || parent.status !== 'completed') return fail();\n }\n }\n }\n const states = Object.values(value.steps) as unknown as WorkflowCheckpoint['steps'][string][];\n if (value.status === 'completed' && !states.every(state => state.status === 'completed')) return fail();\n if (value.status === 'failed' && (states.some(state => ['pending', 'running', 'interrupted'].includes(state.status))\n || !states.some(state => state.status === 'failed'))) return fail();\n return jsonClone(value) as unknown as WorkflowCheckpoint;\n}\n\nexport function cloneSteps(steps: readonly WorkflowStep[]): WorkflowStep[] {\n return steps.map(step => ({ ...step, ...(step.dependencies === undefined ? {} : { dependencies: [...step.dependencies] }) }));\n}\n"],"mappings":";;;;;AAKO,SAAS,SAAS,OAAgB,OAAwC;AAC/E,MAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,EAAG,OAAM,IAAI,MAAM,GAAG,KAAK,4BAA4B;AACtG;AAGO,SAAS,UAAa,OAAa;AACxC,QAAM,OAAO,oBAAI,IAAY;AAC7B,QAAM,QAAQ,CAAC,SAAwB;AACrC,QAAI,SAAS,QAAQ,OAAO,SAAS,YAAY,OAAO,SAAS,UAAW;AAC5E,QAAI,OAAO,SAAS,YAAY,OAAO,SAAS,IAAI,EAAG;AACvD,QAAI,OAAO,SAAS,YAAY,SAAS,KAAM,OAAM,IAAI,MAAM,yCAAyC;AACxG,QAAI,KAAK,IAAI,IAAI,EAAG,OAAM,IAAI,MAAM,iDAAiD;AACrF,UAAM,YAAY,OAAO,eAAe,IAAI;AAC5C,QAAI,MAAM,QAAQ,IAAI,IAAI,cAAc,MAAM,YAAY,cAAc,OAAO,aAAa,cAAc,MAAM;AAC9G,YAAM,IAAI,MAAM,8DAA8D;AAAA,IAChF;AACA,QAAI,OAAO,sBAAsB,IAAI,EAAE,OAAQ,OAAM,IAAI,MAAM,yCAAyC;AACxG,eAAW,CAAC,KAAK,UAAU,KAAK,OAAO,QAAQ,OAAO,0BAA0B,IAAI,CAAC,GAAG;AACtF,UAAI,MAAM,QAAQ,IAAI,KAAK,QAAQ,SAAU;AAC7C,UAAI,CAAC,OAAO,OAAO,YAAY,OAAO,KAAK,CAAC,WAAW,YAAY;AACjE,cAAM,IAAI,MAAM,2EAA2E;AAAA,MAC7F;AAAA,IACF;AACA,S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