@ancientpantheon/khronoton-core 0.11.0 → 0.13.0
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/CHANGELOG.md +36 -0
- package/README.md +114 -0
- package/dist/blockchain/stoachain.d.ts +1 -1
- package/dist/blockchain/stoachain.js +16 -1
- package/dist/{chunk-LX6T2BDL.js → chunk-7H5TM3CS.js} +1 -1
- package/dist/{chunk-GNQ2IVXA.js → chunk-IAK4UEAA.js} +731 -24
- package/dist/{context-89YS4xT3.d.ts → context-P-rCtBbJ.d.ts} +2 -2
- package/dist/handlers/execute.d.ts +12 -4
- package/dist/handlers/execute.js +42 -5
- package/dist/handlers/index.d.ts +4 -2
- package/dist/handlers/index.js +7 -2
- package/dist/handlers/public.d.ts +41 -0
- package/dist/handlers/public.js +78 -0
- package/dist/handlers/read.d.ts +11 -0
- package/dist/handlers/read.js +65 -1
- package/dist/handlers/steps.d.ts +3 -0
- package/dist/handlers/steps.js +115 -0
- package/dist/hooks/index.d.ts +4 -4
- package/dist/hooks/index.js +2 -2
- package/dist/provider/index.d.ts +4 -4
- package/dist/provider/index.js +33 -2
- package/dist/{seams-DUtxDw_U.d.ts → seams-Co8Tq4ka.d.ts} +24 -0
- package/dist/server/executor.d.ts +14 -1
- package/dist/server/executor.js +144 -26
- package/dist/server/index.d.ts +11 -2
- package/dist/server/index.js +29 -1
- package/dist/server/loop.d.ts +17 -13
- package/dist/server/loop.js +19 -12
- package/dist/server/planners/evict.d.ts +20 -0
- package/dist/server/planners/evict.js +143 -0
- package/dist/server/planners/inject.d.ts +22 -0
- package/dist/server/planners/inject.js +120 -0
- package/dist/server/planners/registry.d.ts +80 -0
- package/dist/server/planners/registry.js +50 -0
- package/dist/server/planners/stoa-unwrap.d.ts +23 -0
- package/dist/server/planners/stoa-unwrap.js +204 -0
- package/dist/server/planners/stoa-wrap.d.ts +22 -0
- package/dist/server/planners/stoa-wrap.js +201 -0
- package/dist/server/planners/unstall.d.ts +25 -0
- package/dist/server/planners/unstall.js +135 -0
- package/dist/server/pure/run-advance.d.ts +76 -0
- package/dist/server/pure/run-advance.js +94 -0
- package/dist/server/pure/split-plan.d.ts +144 -0
- package/dist/server/pure/split-plan.js +362 -0
- package/dist/server/resolvers.js +48 -6
- package/dist/server/runs-driver.d.ts +92 -0
- package/dist/server/runs-driver.js +511 -0
- package/dist/server/schema.d.ts +12 -2
- package/dist/server/schema.js +105 -1
- package/dist/server/seams.d.ts +28 -0
- package/dist/server/seams.js +4 -0
- package/dist/server/store/errors.d.ts +38 -0
- package/dist/server/store/errors.js +61 -0
- package/dist/server/store/fires.js +27 -1
- package/dist/server/store/index.d.ts +8 -2
- package/dist/server/store/index.js +8 -2
- package/dist/server/store/mappers.d.ts +11 -0
- package/dist/server/store/mappers.js +20 -0
- package/dist/server/store/public.d.ts +104 -0
- package/dist/server/store/public.js +197 -0
- package/dist/server/store/runs.d.ts +233 -0
- package/dist/server/store/runs.js +341 -0
- package/dist/server/store/steps.d.ts +42 -0
- package/dist/server/store/steps.js +51 -0
- package/dist/server/tick.d.ts +7 -0
- package/dist/server/tick.js +50 -1
- package/dist/server/types.d.ts +55 -3
- package/dist/{types-DnFB1Yz-.d.ts → types-uYSglFrJ.d.ts} +13 -0
- package/dist/ui/index.d.ts +1 -1
- package/dist/ui/index.js +2 -2
- package/package.json +1 -1
|
@@ -2,10 +2,14 @@ import crypto2, { randomUUID } from 'crypto';
|
|
|
2
2
|
import { createContext, useContext } from 'react';
|
|
3
3
|
|
|
4
4
|
// src/server/seams.ts
|
|
5
|
+
var defaultOnAudit = () => {
|
|
6
|
+
};
|
|
5
7
|
var defaultResolveFireMode = () => "live";
|
|
6
8
|
var LISTEN_TIMEOUT_MS = 3e5;
|
|
7
9
|
var AUTO_GAS_CEILING = 2e6;
|
|
8
10
|
var SINGLE_TX_GAS_GUARD = 16e5;
|
|
11
|
+
var RUN_STEP_DEADLINE_MS = 6e5;
|
|
12
|
+
var DEFAULT_MAX_REPLAN_ATTEMPTS = 3;
|
|
9
13
|
|
|
10
14
|
// src/server/pure/capability.ts
|
|
11
15
|
function parseCapabilityLine(line) {
|
|
@@ -87,6 +91,60 @@ function runtimeArgKeysCollide(payload, declaredKeys) {
|
|
|
87
91
|
return declaredKeys.some((k) => Object.prototype.hasOwnProperty.call(payload, k));
|
|
88
92
|
}
|
|
89
93
|
|
|
94
|
+
// src/server/pure/run-advance.ts
|
|
95
|
+
function replanOrFail(run, trigger, policy) {
|
|
96
|
+
if (policy.canReplan && run.attempt < policy.maxReplanAttempts) {
|
|
97
|
+
return [
|
|
98
|
+
{
|
|
99
|
+
kind: "replan-step",
|
|
100
|
+
reason: `step ${run.stepIndex}: ${trigger}; re-planning (attempt ${run.attempt + 1}/${policy.maxReplanAttempts})`
|
|
101
|
+
}
|
|
102
|
+
];
|
|
103
|
+
}
|
|
104
|
+
const why = policy.canReplan ? `replan attempts exhausted (${run.attempt}/${policy.maxReplanAttempts})` : "no re-plan available for a single-mode step";
|
|
105
|
+
return [{ kind: "fail-run", reason: `step ${run.stepIndex}: ${trigger}; ${why}` }];
|
|
106
|
+
}
|
|
107
|
+
function advanceRun(run, legs, now, policy) {
|
|
108
|
+
if (run.status === "succeeded" || run.status === "failed" || run.status === "abandoned") {
|
|
109
|
+
return [{ kind: "wait" }];
|
|
110
|
+
}
|
|
111
|
+
if (legs.length === 0) {
|
|
112
|
+
return [{ kind: "replan-step", reason: `step ${run.stepIndex} has no legs yet` }];
|
|
113
|
+
}
|
|
114
|
+
if (legs.every((l) => l.status === "confirmed")) {
|
|
115
|
+
return [{ kind: "advance-step" }];
|
|
116
|
+
}
|
|
117
|
+
const deadlinePassed = run.deadlineAt != null && now.getTime() > new Date(run.deadlineAt).getTime();
|
|
118
|
+
if (deadlinePassed) {
|
|
119
|
+
return replanOrFail(run, "barrier deadline exceeded", policy);
|
|
120
|
+
}
|
|
121
|
+
if (policy.stepMode === "serial" && legs.some((l) => l.status === "failed")) {
|
|
122
|
+
return replanOrFail(run, "a leg failed", policy);
|
|
123
|
+
}
|
|
124
|
+
if (policy.stepMode === "parallel" && legs.some((l) => l.status === "failed")) {
|
|
125
|
+
const allResolved = legs.every((l) => l.status === "confirmed" || l.status === "failed");
|
|
126
|
+
if (allResolved) {
|
|
127
|
+
return replanOrFail(run, "a leg failed", policy);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (policy.stepMode === "parallel") {
|
|
131
|
+
const pending = legs.filter((l) => l.status === "pending");
|
|
132
|
+
if (pending.length > 0) {
|
|
133
|
+
return pending.map((l) => ({ kind: "submit-leg", legIndex: l.legIndex }));
|
|
134
|
+
}
|
|
135
|
+
return [{ kind: "poll" }];
|
|
136
|
+
}
|
|
137
|
+
if (legs.some((l) => l.status === "submitted")) {
|
|
138
|
+
return [{ kind: "poll" }];
|
|
139
|
+
}
|
|
140
|
+
const pendingLegs = legs.filter((l) => l.status === "pending");
|
|
141
|
+
if (pendingLegs.length > 0) {
|
|
142
|
+
const lowest = pendingLegs.reduce((a, b) => b.legIndex < a.legIndex ? b : a);
|
|
143
|
+
return [{ kind: "submit-leg", legIndex: lowest.legIndex }];
|
|
144
|
+
}
|
|
145
|
+
return [{ kind: "wait" }];
|
|
146
|
+
}
|
|
147
|
+
|
|
90
148
|
// src/server/schema.ts
|
|
91
149
|
var SCHEMA_SQL = `
|
|
92
150
|
CREATE TABLE IF NOT EXISTS codex_cronotons (
|
|
@@ -169,9 +227,87 @@ CREATE INDEX IF NOT EXISTS idx_codex_manual_batches_due
|
|
|
169
227
|
|
|
170
228
|
CREATE INDEX IF NOT EXISTS idx_codex_manual_batches_cronoton
|
|
171
229
|
ON codex_cronoton_manual_batches(codex_cronoton_id);
|
|
230
|
+
|
|
231
|
+
CREATE TABLE IF NOT EXISTS codex_cronoton_steps (
|
|
232
|
+
id TEXT PRIMARY KEY,
|
|
233
|
+
codex_cronoton_id TEXT NOT NULL REFERENCES codex_cronotons(id) ON DELETE CASCADE,
|
|
234
|
+
step_index INTEGER NOT NULL,
|
|
235
|
+
mode TEXT NOT NULL CHECK (mode IN ('single', 'planner')),
|
|
236
|
+
pact_code TEXT,
|
|
237
|
+
config_json TEXT,
|
|
238
|
+
payload_json TEXT,
|
|
239
|
+
gas_payer_json TEXT,
|
|
240
|
+
signers_json TEXT,
|
|
241
|
+
planner_name TEXT,
|
|
242
|
+
planner_params_json TEXT,
|
|
243
|
+
idempotent INTEGER NOT NULL DEFAULT 0,
|
|
244
|
+
created_at TEXT NOT NULL,
|
|
245
|
+
modified_at TEXT NOT NULL,
|
|
246
|
+
CHECK (
|
|
247
|
+
(mode = 'single' AND pact_code IS NOT NULL) OR
|
|
248
|
+
(mode = 'planner' AND planner_name IS NOT NULL)
|
|
249
|
+
)
|
|
250
|
+
);
|
|
251
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_steps_order
|
|
252
|
+
ON codex_cronoton_steps(codex_cronoton_id, step_index);
|
|
253
|
+
|
|
254
|
+
CREATE TABLE IF NOT EXISTS codex_cronoton_runs (
|
|
255
|
+
id TEXT PRIMARY KEY,
|
|
256
|
+
codex_cronoton_id TEXT NOT NULL REFERENCES codex_cronotons(id) ON DELETE CASCADE,
|
|
257
|
+
fire_id TEXT REFERENCES codex_cronoton_fires(id),
|
|
258
|
+
status TEXT NOT NULL DEFAULT 'planning' CHECK (status IN (
|
|
259
|
+
'planning', 'awaiting', 'advancing', 'succeeded', 'failed', 'abandoned'
|
|
260
|
+
)),
|
|
261
|
+
step_index INTEGER NOT NULL DEFAULT 0,
|
|
262
|
+
step_count INTEGER NOT NULL,
|
|
263
|
+
started_at TEXT NOT NULL,
|
|
264
|
+
modified_at TEXT NOT NULL,
|
|
265
|
+
deadline_at TEXT,
|
|
266
|
+
attempt INTEGER NOT NULL DEFAULT 0,
|
|
267
|
+
context_json TEXT
|
|
268
|
+
);
|
|
269
|
+
CREATE INDEX IF NOT EXISTS idx_codex_cronoton_runs_due
|
|
270
|
+
ON codex_cronoton_runs(status, modified_at);
|
|
271
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_runs_self_block
|
|
272
|
+
ON codex_cronoton_runs(codex_cronoton_id)
|
|
273
|
+
WHERE status IN ('planning', 'awaiting', 'advancing');
|
|
274
|
+
|
|
275
|
+
CREATE TABLE IF NOT EXISTS codex_cronoton_run_legs (
|
|
276
|
+
id TEXT PRIMARY KEY,
|
|
277
|
+
run_id TEXT NOT NULL REFERENCES codex_cronoton_runs(id) ON DELETE CASCADE,
|
|
278
|
+
step_index INTEGER NOT NULL,
|
|
279
|
+
leg_index INTEGER NOT NULL,
|
|
280
|
+
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN (
|
|
281
|
+
'pending', 'submitted', 'confirmed', 'failed'
|
|
282
|
+
)),
|
|
283
|
+
request_key TEXT,
|
|
284
|
+
chain_id TEXT,
|
|
285
|
+
definition_json TEXT NOT NULL,
|
|
286
|
+
error_message TEXT,
|
|
287
|
+
submitted_at TEXT,
|
|
288
|
+
confirmed_at TEXT,
|
|
289
|
+
attempt INTEGER NOT NULL DEFAULT 0
|
|
290
|
+
);
|
|
291
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_run_legs_slot
|
|
292
|
+
ON codex_cronoton_run_legs(run_id, step_index, leg_index);
|
|
293
|
+
CREATE INDEX IF NOT EXISTS idx_codex_cronoton_run_legs_barrier
|
|
294
|
+
ON codex_cronoton_run_legs(run_id, step_index, status);
|
|
172
295
|
`;
|
|
296
|
+
function ensureColumn(db, table, column, columnDefSql) {
|
|
297
|
+
const existing = db.prepare(`PRAGMA table_info(${table})`).all();
|
|
298
|
+
const hasColumn = existing.some((c) => c.name === column);
|
|
299
|
+
if (!hasColumn) {
|
|
300
|
+
db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${columnDefSql}`);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
173
303
|
function installSchema(db) {
|
|
174
304
|
db.exec(SCHEMA_SQL);
|
|
305
|
+
ensureColumn(db, "codex_cronotons", "public_token", "TEXT");
|
|
306
|
+
ensureColumn(db, "codex_cronotons", "public_observable", "INTEGER NOT NULL DEFAULT 0");
|
|
307
|
+
db.exec(
|
|
308
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronotons_public_token ON codex_cronotons(public_token)`
|
|
309
|
+
);
|
|
310
|
+
ensureColumn(db, "codex_cronoton_run_legs", "claimed_at", "TEXT");
|
|
175
311
|
}
|
|
176
312
|
|
|
177
313
|
// src/server/executor-signers.ts
|
|
@@ -216,10 +352,17 @@ function effectiveSigners(definition, kadenaNamespace) {
|
|
|
216
352
|
function isSaneCeiling(v) {
|
|
217
353
|
return typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
218
354
|
}
|
|
219
|
-
|
|
355
|
+
var CEILING_CACHE_TTL_MS = 3e4;
|
|
356
|
+
var ceilingCache = /* @__PURE__ */ new Map();
|
|
357
|
+
async function resolveCeiling(ctx, client, chainId) {
|
|
220
358
|
if (isSaneCeiling(ctx.config?.autoGasCeiling)) return ctx.config.autoGasCeiling;
|
|
359
|
+
const now = Date.now();
|
|
360
|
+
const cached = ceilingCache.get(chainId);
|
|
361
|
+
if (cached && cached.expiresAt > now) return cached.value;
|
|
221
362
|
const live = await client.getBlockGasLimit?.();
|
|
222
|
-
|
|
363
|
+
const resolved = isSaneCeiling(live) ? live : AUTO_GAS_CEILING;
|
|
364
|
+
ceilingCache.set(chainId, { value: resolved, expiresAt: now + CEILING_CACHE_TTL_MS });
|
|
365
|
+
return resolved;
|
|
223
366
|
}
|
|
224
367
|
function buildTransaction(runtime, definition, signers, gasLimitOverride) {
|
|
225
368
|
if (signers.length === 0) {
|
|
@@ -297,6 +440,9 @@ async function signTransaction(runtime, resolver, signers, tx) {
|
|
|
297
440
|
function dirtyReadError(result) {
|
|
298
441
|
return result.error?.message || "Transaction simulation failed on-chain.";
|
|
299
442
|
}
|
|
443
|
+
function describeThrown(e, fallbackLabel) {
|
|
444
|
+
return (e instanceof Error ? e.message : String(e)) || (e instanceof Error ? `${e.name} (no message)` : `unknown ${fallbackLabel} error`);
|
|
445
|
+
}
|
|
300
446
|
async function listenWithTimeout(listen, descriptor, timeoutMs) {
|
|
301
447
|
let timeoutId = null;
|
|
302
448
|
try {
|
|
@@ -323,7 +469,7 @@ async function runSimulate(ctx, definition, signers) {
|
|
|
323
469
|
const { runtime, resolver } = ctx;
|
|
324
470
|
const { autoGasLimit } = definition.config;
|
|
325
471
|
const client = runtime.createClient(runtime.getPactUrl(definition.config.chainId));
|
|
326
|
-
const ceiling = await resolveCeiling(ctx, client);
|
|
472
|
+
const ceiling = await resolveCeiling(ctx, client, definition.config.chainId);
|
|
327
473
|
const tx = buildTransaction(
|
|
328
474
|
runtime,
|
|
329
475
|
definition,
|
|
@@ -367,12 +513,9 @@ async function runSimulate(ctx, definition, signers) {
|
|
|
367
513
|
terminalIntent: null
|
|
368
514
|
};
|
|
369
515
|
}
|
|
370
|
-
async function
|
|
516
|
+
async function submitTransaction(ctx, definition, signers, client, ceiling) {
|
|
371
517
|
const { runtime, resolver } = ctx;
|
|
372
|
-
const listenMs = ctx.config?.listenTimeoutMs ?? LISTEN_TIMEOUT_MS;
|
|
373
518
|
const { chainId, autoGasLimit } = definition.config;
|
|
374
|
-
const client = runtime.createClient(runtime.getPactUrl(chainId));
|
|
375
|
-
const ceiling = await resolveCeiling(ctx, client);
|
|
376
519
|
let tx = buildTransaction(
|
|
377
520
|
runtime,
|
|
378
521
|
definition,
|
|
@@ -389,22 +532,19 @@ async function runFire(ctx, definition, signers) {
|
|
|
389
532
|
if (preflight.result.status === "failure") {
|
|
390
533
|
return {
|
|
391
534
|
ok: false,
|
|
392
|
-
mode: "fire",
|
|
393
535
|
chainId,
|
|
394
536
|
error: dirtyReadError(preflight.result),
|
|
395
|
-
rawResult: preflight.result
|
|
396
|
-
terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false)
|
|
537
|
+
rawResult: preflight.result
|
|
397
538
|
};
|
|
398
539
|
}
|
|
399
540
|
const gasUsed = preflight.gas || 0;
|
|
400
541
|
if (gasUsed > ceiling) {
|
|
401
542
|
return {
|
|
402
543
|
ok: false,
|
|
403
|
-
mode: "fire",
|
|
404
544
|
chainId,
|
|
405
545
|
error: `Transaction needs ${gasUsed} gas, over the block limit of ${ceiling} \u2014 no gas setting can mine it. Reduce the transaction's size or complexity.`,
|
|
406
546
|
rawResult: preflight.result,
|
|
407
|
-
|
|
547
|
+
gasUsed
|
|
408
548
|
};
|
|
409
549
|
}
|
|
410
550
|
if (autoGasLimit && gasUsed > 0) {
|
|
@@ -434,15 +574,43 @@ async function runFire(ctx, definition, signers) {
|
|
|
434
574
|
if (derivedNetworkId) descriptor.networkId = derivedNetworkId;
|
|
435
575
|
submitResult = descriptor;
|
|
436
576
|
}
|
|
577
|
+
return {
|
|
578
|
+
ok: true,
|
|
579
|
+
chainId,
|
|
580
|
+
requestKey: submitResult.requestKey,
|
|
581
|
+
networkId: derivedNetworkId
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
async function runFire(ctx, definition, signers) {
|
|
585
|
+
const { runtime } = ctx;
|
|
586
|
+
const listenMs = ctx.config?.listenTimeoutMs ?? LISTEN_TIMEOUT_MS;
|
|
587
|
+
const { chainId } = definition.config;
|
|
588
|
+
const client = runtime.createClient(runtime.getPactUrl(chainId));
|
|
589
|
+
const ceiling = await resolveCeiling(ctx, client, chainId);
|
|
590
|
+
const outcome = await submitTransaction(ctx, definition, signers, client, ceiling);
|
|
591
|
+
if (!outcome.ok) {
|
|
592
|
+
return {
|
|
593
|
+
ok: false,
|
|
594
|
+
mode: "fire",
|
|
595
|
+
chainId: outcome.chainId,
|
|
596
|
+
error: outcome.error,
|
|
597
|
+
rawResult: outcome.rawResult,
|
|
598
|
+
terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false)
|
|
599
|
+
};
|
|
600
|
+
}
|
|
437
601
|
let result;
|
|
438
602
|
try {
|
|
439
|
-
result = await listenWithTimeout(
|
|
603
|
+
result = await listenWithTimeout(
|
|
604
|
+
client.listen,
|
|
605
|
+
{ requestKey: outcome.requestKey, chainId: outcome.chainId, networkId: outcome.networkId },
|
|
606
|
+
listenMs
|
|
607
|
+
);
|
|
440
608
|
} catch (listenErr) {
|
|
441
609
|
return {
|
|
442
610
|
ok: false,
|
|
443
611
|
mode: "fire",
|
|
444
|
-
chainId,
|
|
445
|
-
requestKey:
|
|
612
|
+
chainId: outcome.chainId,
|
|
613
|
+
requestKey: outcome.requestKey,
|
|
446
614
|
error: listenErr instanceof Error ? listenErr.message : "Transaction confirmation could not be observed.",
|
|
447
615
|
terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false)
|
|
448
616
|
};
|
|
@@ -451,8 +619,8 @@ async function runFire(ctx, definition, signers) {
|
|
|
451
619
|
return {
|
|
452
620
|
ok: false,
|
|
453
621
|
mode: "fire",
|
|
454
|
-
chainId,
|
|
455
|
-
requestKey: result.reqKey ||
|
|
622
|
+
chainId: outcome.chainId,
|
|
623
|
+
requestKey: result.reqKey || outcome.requestKey,
|
|
456
624
|
error: result.result.error?.message || "Transaction failed on-chain.",
|
|
457
625
|
rawResult: result.result,
|
|
458
626
|
terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false)
|
|
@@ -461,12 +629,35 @@ async function runFire(ctx, definition, signers) {
|
|
|
461
629
|
return {
|
|
462
630
|
ok: true,
|
|
463
631
|
mode: "fire",
|
|
464
|
-
chainId,
|
|
465
|
-
requestKey: result.reqKey ||
|
|
632
|
+
chainId: outcome.chainId,
|
|
633
|
+
requestKey: result.reqKey || outcome.requestKey,
|
|
466
634
|
rawResult: result.result,
|
|
467
635
|
terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", true)
|
|
468
636
|
};
|
|
469
637
|
}
|
|
638
|
+
async function runSubmit(ctx, definition, signers) {
|
|
639
|
+
const { runtime } = ctx;
|
|
640
|
+
const { chainId } = definition.config;
|
|
641
|
+
const client = runtime.createClient(runtime.getPactUrl(chainId));
|
|
642
|
+
const ceiling = await resolveCeiling(ctx, client, chainId);
|
|
643
|
+
const outcome = await submitTransaction(ctx, definition, signers, client, ceiling);
|
|
644
|
+
if (!outcome.ok) {
|
|
645
|
+
return {
|
|
646
|
+
ok: false,
|
|
647
|
+
mode: "submit",
|
|
648
|
+
chainId: outcome.chainId,
|
|
649
|
+
error: outcome.error,
|
|
650
|
+
rawResult: outcome.rawResult
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
return {
|
|
654
|
+
ok: true,
|
|
655
|
+
mode: "submit",
|
|
656
|
+
requestKey: outcome.requestKey,
|
|
657
|
+
chainId: outcome.chainId,
|
|
658
|
+
networkId: outcome.networkId
|
|
659
|
+
};
|
|
660
|
+
}
|
|
470
661
|
async function executeCodexTransaction(definition, mode, ctx) {
|
|
471
662
|
const { runtime } = ctx;
|
|
472
663
|
if (mode === "simulate") {
|
|
@@ -478,6 +669,25 @@ async function executeCodexTransaction(definition, mode, ctx) {
|
|
|
478
669
|
}
|
|
479
670
|
return runSimulate(ctx, definition, signers);
|
|
480
671
|
}
|
|
672
|
+
if (mode === "submit") {
|
|
673
|
+
try {
|
|
674
|
+
const signers = effectiveSigners(definition, runtime.namespace);
|
|
675
|
+
if (signers.length === 0) {
|
|
676
|
+
throw new Error(
|
|
677
|
+
"At least one signer is required to build a codex transaction."
|
|
678
|
+
);
|
|
679
|
+
}
|
|
680
|
+
return await runSubmit(ctx, definition, signers);
|
|
681
|
+
} catch (e) {
|
|
682
|
+
const error = describeThrown(e, "submit");
|
|
683
|
+
return {
|
|
684
|
+
ok: false,
|
|
685
|
+
mode: "submit",
|
|
686
|
+
chainId: definition.config.chainId,
|
|
687
|
+
error
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
}
|
|
481
691
|
try {
|
|
482
692
|
const signers = effectiveSigners(definition, runtime.namespace);
|
|
483
693
|
if (signers.length === 0) {
|
|
@@ -487,7 +697,7 @@ async function executeCodexTransaction(definition, mode, ctx) {
|
|
|
487
697
|
}
|
|
488
698
|
return await runFire(ctx, definition, signers);
|
|
489
699
|
} catch (e) {
|
|
490
|
-
const error = (e
|
|
700
|
+
const error = describeThrown(e, "fire");
|
|
491
701
|
return {
|
|
492
702
|
ok: false,
|
|
493
703
|
mode: "fire",
|
|
@@ -499,6 +709,9 @@ async function executeCodexTransaction(definition, mode, ctx) {
|
|
|
499
709
|
}
|
|
500
710
|
|
|
501
711
|
// src/server/store/errors.ts
|
|
712
|
+
function isUniqueConstraintError(error) {
|
|
713
|
+
return error instanceof Error && error.code === "SQLITE_CONSTRAINT_UNIQUE";
|
|
714
|
+
}
|
|
502
715
|
var CodexCronotonValidationError = class extends Error {
|
|
503
716
|
constructor(message) {
|
|
504
717
|
super(message);
|
|
@@ -525,6 +738,52 @@ var ManualBatchActiveError = class extends Error {
|
|
|
525
738
|
this.name = "ManualBatchActiveError";
|
|
526
739
|
}
|
|
527
740
|
};
|
|
741
|
+
var RunAlreadyInFlightError = class extends Error {
|
|
742
|
+
constructor(codexCronotonId) {
|
|
743
|
+
super(
|
|
744
|
+
`codex cronoton ${codexCronotonId} already has a non-terminal run in flight \u2014 a new run cannot start until it settles`
|
|
745
|
+
);
|
|
746
|
+
this.name = "RunAlreadyInFlightError";
|
|
747
|
+
}
|
|
748
|
+
};
|
|
749
|
+
var LegAlreadySubmittedError = class extends Error {
|
|
750
|
+
constructor(legId) {
|
|
751
|
+
super(
|
|
752
|
+
`run leg ${legId} is already submitted (or past submission) \u2014 re-submission is refused, only polling for its outcome is allowed`
|
|
753
|
+
);
|
|
754
|
+
this.name = "LegAlreadySubmittedError";
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
var LegNotSubmittedError = class extends Error {
|
|
758
|
+
constructor(legId) {
|
|
759
|
+
super(
|
|
760
|
+
`run leg ${legId} is not in 'submitted' status \u2014 it has either never been submitted or is already in a terminal status (confirmed/failed)`
|
|
761
|
+
);
|
|
762
|
+
this.name = "LegNotSubmittedError";
|
|
763
|
+
}
|
|
764
|
+
};
|
|
765
|
+
var RunLegAlreadyExistsError = class extends Error {
|
|
766
|
+
constructor(runId, stepIndex, legIndex) {
|
|
767
|
+
super(
|
|
768
|
+
`run ${runId} already has a leg at step ${stepIndex}, leg ${legIndex} \u2014 that slot cannot be inserted twice`
|
|
769
|
+
);
|
|
770
|
+
this.name = "RunLegAlreadyExistsError";
|
|
771
|
+
}
|
|
772
|
+
};
|
|
773
|
+
var RunStepMismatchError = class extends Error {
|
|
774
|
+
constructor(runId, expectedStepIndex) {
|
|
775
|
+
super(
|
|
776
|
+
`run ${runId} is not at step ${expectedStepIndex} \u2014 its step_index has already moved on, so this advance is stale`
|
|
777
|
+
);
|
|
778
|
+
this.name = "RunStepMismatchError";
|
|
779
|
+
}
|
|
780
|
+
};
|
|
781
|
+
var RunAlreadyTerminalError = class extends Error {
|
|
782
|
+
constructor(runId) {
|
|
783
|
+
super(`run ${runId} is already in a terminal status (succeeded/failed/abandoned)`);
|
|
784
|
+
this.name = "RunAlreadyTerminalError";
|
|
785
|
+
}
|
|
786
|
+
};
|
|
528
787
|
var MANUAL_BATCH_MIN = 2;
|
|
529
788
|
var MANUAL_BATCH_MAX = 60;
|
|
530
789
|
var MANUAL_BATCH_INTERVAL_SECONDS = 60;
|
|
@@ -547,6 +806,17 @@ function rowToDefinition(row) {
|
|
|
547
806
|
serverResolver: row.server_resolver ?? void 0
|
|
548
807
|
};
|
|
549
808
|
}
|
|
809
|
+
function stepRowToDefinition(step) {
|
|
810
|
+
return {
|
|
811
|
+
pactCode: step.pact_code ?? "",
|
|
812
|
+
config: parseJson(step.config_json, {}),
|
|
813
|
+
payload: parseJson(step.payload_json, {}),
|
|
814
|
+
gasPayer: parseJson(step.gas_payer_json, {
|
|
815
|
+
type: "gas-station"
|
|
816
|
+
}),
|
|
817
|
+
signers: parseJson(step.signers_json, [])
|
|
818
|
+
};
|
|
819
|
+
}
|
|
550
820
|
function rowExternalFireable(row) {
|
|
551
821
|
return row.external_fireable === 1;
|
|
552
822
|
}
|
|
@@ -1042,6 +1312,14 @@ function parseTxKeys(json2) {
|
|
|
1042
1312
|
return [];
|
|
1043
1313
|
}
|
|
1044
1314
|
}
|
|
1315
|
+
function parseChainResponse(json2) {
|
|
1316
|
+
if (!json2) return null;
|
|
1317
|
+
try {
|
|
1318
|
+
return JSON.parse(json2);
|
|
1319
|
+
} catch {
|
|
1320
|
+
return null;
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1045
1323
|
function listFires(id, params = {}, dep) {
|
|
1046
1324
|
const db = dep.db;
|
|
1047
1325
|
const limit = Math.min(Math.max(params.limit ?? 20, 1), 100);
|
|
@@ -1062,7 +1340,7 @@ function listFires(id, params = {}, dep) {
|
|
|
1062
1340
|
requestKey: r.request_key,
|
|
1063
1341
|
chainId: r.chain_id,
|
|
1064
1342
|
errorMessage: r.error_message,
|
|
1065
|
-
chainResponse:
|
|
1343
|
+
chainResponse: parseChainResponse(r.chain_response_json),
|
|
1066
1344
|
definitionFingerprint: r.definition_fingerprint,
|
|
1067
1345
|
mode: r.mode === "live" ? "live" : "test",
|
|
1068
1346
|
recoveredAt: r.recovered_at,
|
|
@@ -1106,14 +1384,29 @@ async function dispatchMultiTxResolver(name, opts) {
|
|
|
1106
1384
|
function postponed(error) {
|
|
1107
1385
|
return { ok: false, mode: "fire", error, terminalIntent: null };
|
|
1108
1386
|
}
|
|
1387
|
+
function toReportedOk(value) {
|
|
1388
|
+
if (typeof value === "boolean") return value;
|
|
1389
|
+
if (typeof value === "number") return value !== 0;
|
|
1390
|
+
if (typeof value === "string") {
|
|
1391
|
+
const lower = value.toLowerCase();
|
|
1392
|
+
if (lower === "true") return true;
|
|
1393
|
+
if (lower === "false") return false;
|
|
1394
|
+
}
|
|
1395
|
+
return void 0;
|
|
1396
|
+
}
|
|
1109
1397
|
function adaptMultiTxSummary(summary) {
|
|
1110
1398
|
const s = summary ?? {};
|
|
1111
|
-
const
|
|
1399
|
+
const batches = Array.isArray(s.batches) ? s.batches : [];
|
|
1400
|
+
const firstBatchKey = batches.length > 0 ? batches[0]?.requestKey : void 0;
|
|
1401
|
+
const reported = batches.map((b) => toReportedOk(b.ok)).filter((v) => v !== void 0);
|
|
1402
|
+
const ok = reported.length === 0 ? true : reported.every((v) => v === true);
|
|
1403
|
+
const failedCount = reported.filter((v) => v === false).length;
|
|
1112
1404
|
return {
|
|
1113
|
-
ok
|
|
1405
|
+
ok,
|
|
1114
1406
|
mode: "fire",
|
|
1115
1407
|
requestKey: firstBatchKey,
|
|
1116
1408
|
rawResult: summary,
|
|
1409
|
+
error: ok ? void 0 : `${failedCount} of ${reported.length} reporting batch(es) failed`,
|
|
1117
1410
|
terminalIntent: null
|
|
1118
1411
|
};
|
|
1119
1412
|
}
|
|
@@ -1557,6 +1850,420 @@ function computeDefinitionFingerprint(row) {
|
|
|
1557
1850
|
const canonical = JSON.stringify(canonicalize(parts));
|
|
1558
1851
|
return crypto2.createHash("sha256").update(canonical).digest("hex");
|
|
1559
1852
|
}
|
|
1853
|
+
function listStepsForCronoton(codexCronotonId, dep) {
|
|
1854
|
+
return dep.db.prepare(
|
|
1855
|
+
`SELECT * FROM codex_cronoton_steps
|
|
1856
|
+
WHERE codex_cronoton_id = ?
|
|
1857
|
+
ORDER BY step_index ASC`
|
|
1858
|
+
).all(codexCronotonId);
|
|
1859
|
+
}
|
|
1860
|
+
function createRun(input, dep) {
|
|
1861
|
+
const id = randomUUID();
|
|
1862
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1863
|
+
try {
|
|
1864
|
+
dep.db.prepare(
|
|
1865
|
+
`INSERT INTO codex_cronoton_runs
|
|
1866
|
+
(id, codex_cronoton_id, step_count, started_at, modified_at, deadline_at, context_json)
|
|
1867
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
|
1868
|
+
).run(
|
|
1869
|
+
id,
|
|
1870
|
+
input.codexCronotonId,
|
|
1871
|
+
input.stepCount,
|
|
1872
|
+
now,
|
|
1873
|
+
now,
|
|
1874
|
+
input.deadlineAt ?? null,
|
|
1875
|
+
input.contextJson !== void 0 ? JSON.stringify(input.contextJson) : null
|
|
1876
|
+
);
|
|
1877
|
+
} catch (error) {
|
|
1878
|
+
if (isUniqueConstraintError(error)) {
|
|
1879
|
+
throw new RunAlreadyInFlightError(input.codexCronotonId);
|
|
1880
|
+
}
|
|
1881
|
+
throw error;
|
|
1882
|
+
}
|
|
1883
|
+
return id;
|
|
1884
|
+
}
|
|
1885
|
+
function getRun(runId, dep) {
|
|
1886
|
+
const row = dep.db.prepare(`SELECT * FROM codex_cronoton_runs WHERE id = ?`).get(runId);
|
|
1887
|
+
return row ?? null;
|
|
1888
|
+
}
|
|
1889
|
+
function listRunLegs(runId, dep) {
|
|
1890
|
+
return dep.db.prepare(
|
|
1891
|
+
`SELECT * FROM codex_cronoton_run_legs
|
|
1892
|
+
WHERE run_id = ?
|
|
1893
|
+
ORDER BY step_index ASC, leg_index ASC`
|
|
1894
|
+
).all(runId);
|
|
1895
|
+
}
|
|
1896
|
+
function insertRunLeg(input, dep) {
|
|
1897
|
+
const id = randomUUID();
|
|
1898
|
+
try {
|
|
1899
|
+
dep.db.prepare(
|
|
1900
|
+
`INSERT INTO codex_cronoton_run_legs (id, run_id, step_index, leg_index, definition_json, attempt)
|
|
1901
|
+
VALUES (?, ?, ?, ?, ?, ?)`
|
|
1902
|
+
).run(
|
|
1903
|
+
id,
|
|
1904
|
+
input.runId,
|
|
1905
|
+
input.stepIndex,
|
|
1906
|
+
input.legIndex,
|
|
1907
|
+
input.definitionJson,
|
|
1908
|
+
input.attempt ?? 0
|
|
1909
|
+
);
|
|
1910
|
+
} catch (error) {
|
|
1911
|
+
if (isUniqueConstraintError(error)) {
|
|
1912
|
+
throw new RunLegAlreadyExistsError(input.runId, input.stepIndex, input.legIndex);
|
|
1913
|
+
}
|
|
1914
|
+
throw error;
|
|
1915
|
+
}
|
|
1916
|
+
return id;
|
|
1917
|
+
}
|
|
1918
|
+
function claimLegForSubmit(legId, claimedAt, dep) {
|
|
1919
|
+
const result = dep.db.prepare(
|
|
1920
|
+
`UPDATE codex_cronoton_run_legs
|
|
1921
|
+
SET claimed_at = ?
|
|
1922
|
+
WHERE id = ? AND status = 'pending' AND claimed_at IS NULL`
|
|
1923
|
+
).run(claimedAt, legId);
|
|
1924
|
+
return result.changes === 1;
|
|
1925
|
+
}
|
|
1926
|
+
function releaseLegClaim(legId, dep) {
|
|
1927
|
+
dep.db.prepare(`UPDATE codex_cronoton_run_legs SET claimed_at = NULL WHERE id = ?`).run(legId);
|
|
1928
|
+
}
|
|
1929
|
+
function markLegSubmitted(legId, input, dep) {
|
|
1930
|
+
const result = dep.db.prepare(
|
|
1931
|
+
`UPDATE codex_cronoton_run_legs
|
|
1932
|
+
SET status = 'submitted', request_key = ?, chain_id = ?, submitted_at = ?
|
|
1933
|
+
WHERE id = ? AND status = 'pending'`
|
|
1934
|
+
).run(input.requestKey, input.chainId, (/* @__PURE__ */ new Date()).toISOString(), legId);
|
|
1935
|
+
if (result.changes !== 1) {
|
|
1936
|
+
throw new LegAlreadySubmittedError(legId);
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
function markLegConfirmed(legId, dep) {
|
|
1940
|
+
const result = dep.db.prepare(
|
|
1941
|
+
`UPDATE codex_cronoton_run_legs
|
|
1942
|
+
SET status = 'confirmed', confirmed_at = ?
|
|
1943
|
+
WHERE id = ? AND status = 'submitted'`
|
|
1944
|
+
).run((/* @__PURE__ */ new Date()).toISOString(), legId);
|
|
1945
|
+
if (result.changes !== 1) {
|
|
1946
|
+
throw new LegNotSubmittedError(legId);
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
function markLegFailed(legId, input, dep) {
|
|
1950
|
+
const result = dep.db.prepare(
|
|
1951
|
+
`UPDATE codex_cronoton_run_legs
|
|
1952
|
+
SET status = 'failed', error_message = ?
|
|
1953
|
+
WHERE id = ? AND status = 'submitted'`
|
|
1954
|
+
).run(input.errorMessage, legId);
|
|
1955
|
+
if (result.changes !== 1) {
|
|
1956
|
+
throw new LegNotSubmittedError(legId);
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
function advanceRunStep(runId, input, dep) {
|
|
1960
|
+
const result = dep.db.prepare(
|
|
1961
|
+
`UPDATE codex_cronoton_runs
|
|
1962
|
+
SET step_index = ?, attempt = 0, deadline_at = ?, modified_at = ?
|
|
1963
|
+
WHERE id = ? AND step_index = ?`
|
|
1964
|
+
).run(
|
|
1965
|
+
input.toStepIndex,
|
|
1966
|
+
input.deadlineAt,
|
|
1967
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
1968
|
+
runId,
|
|
1969
|
+
input.fromStepIndex
|
|
1970
|
+
);
|
|
1971
|
+
if (result.changes !== 1) {
|
|
1972
|
+
throw new RunStepMismatchError(runId, input.fromStepIndex);
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
function bumpRunAttempt(runId, dep) {
|
|
1976
|
+
dep.db.prepare(
|
|
1977
|
+
`UPDATE codex_cronoton_runs SET attempt = attempt + 1, modified_at = ? WHERE id = ?`
|
|
1978
|
+
).run((/* @__PURE__ */ new Date()).toISOString(), runId);
|
|
1979
|
+
}
|
|
1980
|
+
function touchRunDeadline(runId, deadlineAt, dep) {
|
|
1981
|
+
dep.db.prepare(
|
|
1982
|
+
`UPDATE codex_cronoton_runs SET deadline_at = ?, modified_at = ? WHERE id = ?`
|
|
1983
|
+
).run(deadlineAt, (/* @__PURE__ */ new Date()).toISOString(), runId);
|
|
1984
|
+
}
|
|
1985
|
+
function markRunTerminal(runId, status, dep) {
|
|
1986
|
+
const result = dep.db.prepare(
|
|
1987
|
+
`UPDATE codex_cronoton_runs
|
|
1988
|
+
SET status = ?, modified_at = ?
|
|
1989
|
+
WHERE id = ? AND status NOT IN ('succeeded', 'failed', 'abandoned')`
|
|
1990
|
+
).run(status, (/* @__PURE__ */ new Date()).toISOString(), runId);
|
|
1991
|
+
if (result.changes !== 1) {
|
|
1992
|
+
throw new RunAlreadyTerminalError(runId);
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
|
|
1996
|
+
// src/server/planners/registry.ts
|
|
1997
|
+
var STEP_PLANNERS = {};
|
|
1998
|
+
function getStepPlanner(name) {
|
|
1999
|
+
return STEP_PLANNERS[name];
|
|
2000
|
+
}
|
|
2001
|
+
function resolvePlannerFor(step, seams) {
|
|
2002
|
+
const planner = getStepPlanner(step.planner_name ?? "");
|
|
2003
|
+
if (!planner) return void 0;
|
|
2004
|
+
const plannerCtx = { runtime: seams.runtime, resolver: seams.resolver, config: seams.config };
|
|
2005
|
+
return { planner, plannerCtx };
|
|
2006
|
+
}
|
|
2007
|
+
|
|
2008
|
+
// src/server/runs-driver.ts
|
|
2009
|
+
var PlannerNotRegisteredError = class extends Error {
|
|
2010
|
+
constructor(plannerName) {
|
|
2011
|
+
super(`planner '${plannerName}' is not registered in the StepPlanner registry`);
|
|
2012
|
+
this.name = "PlannerNotRegisteredError";
|
|
2013
|
+
}
|
|
2014
|
+
};
|
|
2015
|
+
function computeStepDeadline(now, ctx) {
|
|
2016
|
+
return new Date(now.getTime() + (ctx.config?.runStepDeadlineMs ?? RUN_STEP_DEADLINE_MS)).toISOString();
|
|
2017
|
+
}
|
|
2018
|
+
function parseLegDefinition(definitionJson) {
|
|
2019
|
+
const parsed = JSON.parse(definitionJson);
|
|
2020
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
2021
|
+
throw new Error("leg definition is not an object");
|
|
2022
|
+
}
|
|
2023
|
+
const def = parsed;
|
|
2024
|
+
if (typeof def.pactCode !== "string" || def.pactCode.length === 0) {
|
|
2025
|
+
throw new Error("leg definition is missing a non-empty pactCode");
|
|
2026
|
+
}
|
|
2027
|
+
if (!Array.isArray(def.signers)) {
|
|
2028
|
+
throw new Error("leg definition is missing a signers array");
|
|
2029
|
+
}
|
|
2030
|
+
if (typeof def.gasPayer !== "object" || def.gasPayer === null) {
|
|
2031
|
+
throw new Error("leg definition is missing a gasPayer object");
|
|
2032
|
+
}
|
|
2033
|
+
if (typeof def.config !== "object" || def.config === null) {
|
|
2034
|
+
throw new Error("leg definition is missing a config object");
|
|
2035
|
+
}
|
|
2036
|
+
return parsed;
|
|
2037
|
+
}
|
|
2038
|
+
async function handleSubmitLeg(legIndex, run, stepLegs, now, ctx) {
|
|
2039
|
+
const leg = stepLegs.find((l) => l.leg_index === legIndex);
|
|
2040
|
+
if (!leg) {
|
|
2041
|
+
await ctx.onAudit({
|
|
2042
|
+
action: "codex_cronoton_run_leg.not_found",
|
|
2043
|
+
result: "failure",
|
|
2044
|
+
targetKind: "codex_cronoton_run",
|
|
2045
|
+
targetId: run.id,
|
|
2046
|
+
detail: { codexCronotonId: run.codex_cronoton_id, stepIndex: run.step_index, legIndex }
|
|
2047
|
+
});
|
|
2048
|
+
return false;
|
|
2049
|
+
}
|
|
2050
|
+
let definition;
|
|
2051
|
+
try {
|
|
2052
|
+
definition = parseLegDefinition(leg.definition_json);
|
|
2053
|
+
} catch (err2) {
|
|
2054
|
+
await ctx.onAudit({
|
|
2055
|
+
action: "codex_cronoton_run_leg.invalid_definition",
|
|
2056
|
+
result: "failure",
|
|
2057
|
+
targetKind: "codex_cronoton_run_leg",
|
|
2058
|
+
targetId: leg.id,
|
|
2059
|
+
detail: {
|
|
2060
|
+
runId: run.id,
|
|
2061
|
+
stepIndex: run.step_index,
|
|
2062
|
+
legIndex,
|
|
2063
|
+
error: err2 instanceof Error ? err2.message : String(err2)
|
|
2064
|
+
}
|
|
2065
|
+
});
|
|
2066
|
+
return false;
|
|
2067
|
+
}
|
|
2068
|
+
const claimed = claimLegForSubmit(leg.id, now.toISOString(), { db: ctx.db });
|
|
2069
|
+
if (!claimed) {
|
|
2070
|
+
return false;
|
|
2071
|
+
}
|
|
2072
|
+
const result = await executeCodexTransaction(definition, "submit", {
|
|
2073
|
+
runtime: ctx.runtime,
|
|
2074
|
+
resolver: ctx.resolver,
|
|
2075
|
+
config: ctx.config
|
|
2076
|
+
});
|
|
2077
|
+
if (result.ok && result.requestKey && result.chainId) {
|
|
2078
|
+
markLegSubmitted(leg.id, { requestKey: result.requestKey, chainId: result.chainId }, { db: ctx.db });
|
|
2079
|
+
return true;
|
|
2080
|
+
}
|
|
2081
|
+
releaseLegClaim(leg.id, { db: ctx.db });
|
|
2082
|
+
await ctx.onAudit({
|
|
2083
|
+
action: "codex_cronoton_run_leg.submit_failed",
|
|
2084
|
+
result: "failure",
|
|
2085
|
+
targetKind: "codex_cronoton_run_leg",
|
|
2086
|
+
targetId: leg.id,
|
|
2087
|
+
detail: { runId: run.id, stepIndex: run.step_index, legIndex, error: result.error }
|
|
2088
|
+
});
|
|
2089
|
+
return false;
|
|
2090
|
+
}
|
|
2091
|
+
async function handlePoll(stepLegs, ctx) {
|
|
2092
|
+
const submitted = stepLegs.filter(
|
|
2093
|
+
(l) => l.status === "submitted" && l.request_key != null && l.chain_id != null
|
|
2094
|
+
);
|
|
2095
|
+
if (submitted.length === 0) return false;
|
|
2096
|
+
const byChain = /* @__PURE__ */ new Map();
|
|
2097
|
+
for (const leg of submitted) {
|
|
2098
|
+
const group = byChain.get(leg.chain_id) ?? [];
|
|
2099
|
+
group.push(leg);
|
|
2100
|
+
byChain.set(leg.chain_id, group);
|
|
2101
|
+
}
|
|
2102
|
+
let mutated = false;
|
|
2103
|
+
for (const [chainId, legsForChain] of byChain) {
|
|
2104
|
+
const client = ctx.runtime.createClient(ctx.runtime.getPactUrl(chainId));
|
|
2105
|
+
const polled = await client.pollRequestKeys?.(legsForChain.map((l) => l.request_key), chainId) ?? {};
|
|
2106
|
+
for (const leg of legsForChain) {
|
|
2107
|
+
const landed = polled[leg.request_key];
|
|
2108
|
+
if (!landed) continue;
|
|
2109
|
+
if (landed.result.status === "success") {
|
|
2110
|
+
markLegConfirmed(leg.id, { db: ctx.db });
|
|
2111
|
+
} else {
|
|
2112
|
+
markLegFailed(
|
|
2113
|
+
leg.id,
|
|
2114
|
+
{ errorMessage: landed.result.error?.message ?? "transaction failed on-chain" },
|
|
2115
|
+
{ db: ctx.db }
|
|
2116
|
+
);
|
|
2117
|
+
}
|
|
2118
|
+
mutated = true;
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
return mutated;
|
|
2122
|
+
}
|
|
2123
|
+
function handleAdvanceStep(run, now, ctx) {
|
|
2124
|
+
if (run.step_index + 1 >= run.step_count) {
|
|
2125
|
+
markRunTerminal(run.id, "succeeded", { db: ctx.db });
|
|
2126
|
+
} else {
|
|
2127
|
+
advanceRunStep(
|
|
2128
|
+
run.id,
|
|
2129
|
+
{ fromStepIndex: run.step_index, toStepIndex: run.step_index + 1, deadlineAt: computeStepDeadline(now, ctx) },
|
|
2130
|
+
{ db: ctx.db }
|
|
2131
|
+
);
|
|
2132
|
+
}
|
|
2133
|
+
return true;
|
|
2134
|
+
}
|
|
2135
|
+
async function handleReplanStep(run, step, allRunLegs, now, ctx) {
|
|
2136
|
+
const stepHasAnyLegs = allRunLegs.some((l) => l.step_index === run.step_index);
|
|
2137
|
+
try {
|
|
2138
|
+
return await handleReplanStepInner(run, step, allRunLegs, now, ctx);
|
|
2139
|
+
} catch (err2) {
|
|
2140
|
+
if (stepHasAnyLegs || err2 instanceof RunLegAlreadyExistsError) {
|
|
2141
|
+
throw err2;
|
|
2142
|
+
}
|
|
2143
|
+
const reason = `replan-step threw: ${err2 instanceof Error ? err2.message : String(err2)}`;
|
|
2144
|
+
await handleFailRun(run, reason, ctx);
|
|
2145
|
+
throw err2;
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
async function handleReplanStepInner(run, step, allRunLegs, now, ctx) {
|
|
2149
|
+
if (step.mode === "planner") {
|
|
2150
|
+
const resolved = resolvePlannerFor(step, ctx);
|
|
2151
|
+
if (!resolved) {
|
|
2152
|
+
throw new PlannerNotRegisteredError(step.planner_name ?? "(unnamed)");
|
|
2153
|
+
}
|
|
2154
|
+
const legs = await resolved.planner(step, resolved.plannerCtx);
|
|
2155
|
+
if (legs.length === 0) {
|
|
2156
|
+
return handleAdvanceStep(run, now, ctx);
|
|
2157
|
+
}
|
|
2158
|
+
const allStepLegs = allRunLegs.filter((l) => l.step_index === run.step_index);
|
|
2159
|
+
const isReplan = allStepLegs.length > 0;
|
|
2160
|
+
const newAttempt = isReplan ? run.attempt + 1 : run.attempt;
|
|
2161
|
+
const startLegIndex = isReplan ? Math.max(...allStepLegs.map((l) => l.leg_index)) + 1 : 0;
|
|
2162
|
+
if (isReplan) {
|
|
2163
|
+
bumpRunAttempt(run.id, { db: ctx.db });
|
|
2164
|
+
touchRunDeadline(run.id, computeStepDeadline(now, ctx), { db: ctx.db });
|
|
2165
|
+
}
|
|
2166
|
+
legs.forEach((leg, i) => {
|
|
2167
|
+
insertRunLeg(
|
|
2168
|
+
{
|
|
2169
|
+
runId: run.id,
|
|
2170
|
+
stepIndex: run.step_index,
|
|
2171
|
+
legIndex: startLegIndex + i,
|
|
2172
|
+
definitionJson: JSON.stringify(leg),
|
|
2173
|
+
attempt: newAttempt
|
|
2174
|
+
},
|
|
2175
|
+
{ db: ctx.db }
|
|
2176
|
+
);
|
|
2177
|
+
});
|
|
2178
|
+
if (!isReplan) {
|
|
2179
|
+
advanceRunStep(
|
|
2180
|
+
run.id,
|
|
2181
|
+
{ fromStepIndex: run.step_index, toStepIndex: run.step_index, deadlineAt: computeStepDeadline(now, ctx) },
|
|
2182
|
+
{ db: ctx.db }
|
|
2183
|
+
);
|
|
2184
|
+
}
|
|
2185
|
+
return true;
|
|
2186
|
+
}
|
|
2187
|
+
const definition = stepRowToDefinition(step);
|
|
2188
|
+
insertRunLeg(
|
|
2189
|
+
{ runId: run.id, stepIndex: run.step_index, legIndex: 0, definitionJson: JSON.stringify(definition) },
|
|
2190
|
+
{ db: ctx.db }
|
|
2191
|
+
);
|
|
2192
|
+
advanceRunStep(
|
|
2193
|
+
run.id,
|
|
2194
|
+
{ fromStepIndex: run.step_index, toStepIndex: run.step_index, deadlineAt: computeStepDeadline(now, ctx) },
|
|
2195
|
+
{ db: ctx.db }
|
|
2196
|
+
);
|
|
2197
|
+
return true;
|
|
2198
|
+
}
|
|
2199
|
+
async function handleFailRun(run, reason, ctx) {
|
|
2200
|
+
markRunTerminal(run.id, "failed", { db: ctx.db });
|
|
2201
|
+
await ctx.onAudit({
|
|
2202
|
+
action: "codex_cronoton_run.failed",
|
|
2203
|
+
result: "failure",
|
|
2204
|
+
targetKind: "codex_cronoton_run",
|
|
2205
|
+
targetId: run.id,
|
|
2206
|
+
detail: { codexCronotonId: run.codex_cronoton_id, stepIndex: run.step_index, reason }
|
|
2207
|
+
});
|
|
2208
|
+
return true;
|
|
2209
|
+
}
|
|
2210
|
+
async function executeAction(action, run, step, stepLegs, allRunLegs, now, ctx) {
|
|
2211
|
+
switch (action.kind) {
|
|
2212
|
+
case "submit-leg":
|
|
2213
|
+
return handleSubmitLeg(action.legIndex, run, stepLegs, now, ctx);
|
|
2214
|
+
case "poll":
|
|
2215
|
+
return handlePoll(stepLegs, ctx);
|
|
2216
|
+
case "advance-step":
|
|
2217
|
+
return handleAdvanceStep(run, now, ctx);
|
|
2218
|
+
case "replan-step":
|
|
2219
|
+
return handleReplanStep(run, step, allRunLegs, now, ctx);
|
|
2220
|
+
case "fail-run":
|
|
2221
|
+
return handleFailRun(run, action.reason, ctx);
|
|
2222
|
+
case "wait":
|
|
2223
|
+
return false;
|
|
2224
|
+
}
|
|
2225
|
+
}
|
|
2226
|
+
async function driveRunOnce(runId, now, ctx) {
|
|
2227
|
+
for (; ; ) {
|
|
2228
|
+
const run = getRun(runId, { db: ctx.db });
|
|
2229
|
+
if (!run) return;
|
|
2230
|
+
const steps = listStepsForCronoton(run.codex_cronoton_id, { db: ctx.db });
|
|
2231
|
+
const step = steps.find((s) => s.step_index === run.step_index);
|
|
2232
|
+
if (!step) {
|
|
2233
|
+
markRunTerminal(runId, "failed", { db: ctx.db });
|
|
2234
|
+
await ctx.onAudit({
|
|
2235
|
+
action: "codex_cronoton_run.step_missing",
|
|
2236
|
+
result: "failure",
|
|
2237
|
+
targetKind: "codex_cronoton_run",
|
|
2238
|
+
targetId: runId,
|
|
2239
|
+
detail: { codexCronotonId: run.codex_cronoton_id, stepIndex: run.step_index }
|
|
2240
|
+
});
|
|
2241
|
+
return;
|
|
2242
|
+
}
|
|
2243
|
+
const allRunLegs = listRunLegs(runId, { db: ctx.db });
|
|
2244
|
+
const stepLegs = allRunLegs.filter((l) => l.step_index === run.step_index && l.attempt === run.attempt);
|
|
2245
|
+
const legs = stepLegs.map((l) => ({ legIndex: l.leg_index, status: l.status }));
|
|
2246
|
+
const policy = {
|
|
2247
|
+
stepMode: step.mode === "single" ? "serial" : "parallel",
|
|
2248
|
+
canReplan: step.mode === "planner",
|
|
2249
|
+
maxReplanAttempts: ctx.config?.maxReplanAttempts ?? DEFAULT_MAX_REPLAN_ATTEMPTS
|
|
2250
|
+
};
|
|
2251
|
+
const runState = {
|
|
2252
|
+
status: run.status,
|
|
2253
|
+
stepIndex: run.step_index,
|
|
2254
|
+
stepCount: run.step_count,
|
|
2255
|
+
deadlineAt: run.deadline_at,
|
|
2256
|
+
attempt: run.attempt
|
|
2257
|
+
};
|
|
2258
|
+
const actions = advanceRun(runState, legs, now, policy);
|
|
2259
|
+
let progressed = false;
|
|
2260
|
+
for (const action of actions) {
|
|
2261
|
+
const mutated = await executeAction(action, run, step, stepLegs, allRunLegs, now, ctx);
|
|
2262
|
+
if (mutated) progressed = true;
|
|
2263
|
+
}
|
|
2264
|
+
if (!progressed) return;
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
1560
2267
|
|
|
1561
2268
|
// src/handlers/http.ts
|
|
1562
2269
|
function json(status, body) {
|
|
@@ -1719,4 +2426,4 @@ async function runGated2(fn, options = {}) {
|
|
|
1719
2426
|
}
|
|
1720
2427
|
}
|
|
1721
2428
|
|
|
1722
|
-
export { CodexCronotonValidationError, DEFAULT_EXPLORER_BASE, DEFAULT_PAGE_SIZE, DEFAULT_POLL_CADENCE_MS, InvalidScheduleConfigError, KhronotonStaticContext, KhronotonStatusContext, NeedsConfirmError, applyRuntimeArgs, applyTerminalIntent, assertAdapter, cancelManualBatch, commitCodexCronoton, computeDefinitionFingerprint, computeNextFire, createManualBatch, defaultOpenAuth, defaultSignerSource, deleteCodexCronoton, editCodexCronoton, emptySnapshot, err, executeCodexTransaction, fireByServerResolver, getActiveManualBatchForCronoton, getCodexCronoton, getServerResolver, installSchema, json, listCodexCronotons, listFires, listServerResolvers, manualBatchView, parseRuntimeArgKeys, pauseCodexCronoton, recordFire, recoverFire, resolveConfig, resolveServerVars, resumeCodexCronoton, rowRuntimeArgKeys, rowToDefinition, runGated2 as runGated, summariseSchedule, useKhronoton, useKhronotonAdapter, useKhronotonConfig, validateRuntimeArgs, withConfirm, withRead };
|
|
2429
|
+
export { CodexCronotonValidationError, DEFAULT_EXPLORER_BASE, DEFAULT_PAGE_SIZE, DEFAULT_POLL_CADENCE_MS, InvalidScheduleConfigError, KhronotonStaticContext, KhronotonStatusContext, NeedsConfirmError, RunAlreadyInFlightError, applyRuntimeArgs, applyTerminalIntent, assertAdapter, cancelManualBatch, commitCodexCronoton, computeDefinitionFingerprint, computeNextFire, createManualBatch, createRun, defaultOnAudit, defaultOpenAuth, defaultSignerSource, deleteCodexCronoton, driveRunOnce, editCodexCronoton, emptySnapshot, err, executeCodexTransaction, fireByServerResolver, getActiveManualBatchForCronoton, getCodexCronoton, getRun, getServerResolver, installSchema, json, listCodexCronotons, listFires, listServerResolvers, listStepsForCronoton, manualBatchView, parseRuntimeArgKeys, pauseCodexCronoton, recordFire, recoverFire, resolveConfig, resolveServerVars, resumeCodexCronoton, rowRuntimeArgKeys, rowToDefinition, runGated2 as runGated, summariseSchedule, useKhronoton, useKhronotonAdapter, useKhronotonConfig, validateRuntimeArgs, withConfirm, withRead };
|