@ancientpantheon/khronoton-core 0.12.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 +20 -0
- package/README.md +4 -0
- package/dist/blockchain/stoachain.d.ts +1 -1
- package/dist/blockchain/stoachain.js +16 -1
- package/dist/{chunk-KQZYMPZS.js → chunk-7H5TM3CS.js} +1 -1
- package/dist/{chunk-GIGLXIMC.js → chunk-IAK4UEAA.js} +710 -23
- package/dist/{context-CApk-LP4.d.ts → context-P-rCtBbJ.d.ts} +1 -1
- package/dist/handlers/execute.d.ts +12 -4
- package/dist/handlers/execute.js +42 -5
- package/dist/handlers/index.d.ts +2 -1
- package/dist/handlers/index.js +4 -1
- 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 +3 -3
- package/dist/hooks/index.js +2 -2
- package/dist/provider/index.d.ts +3 -3
- 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 +5 -2
- package/dist/server/schema.js +73 -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/index.d.ts +6 -2
- package/dist/server/store/index.js +6 -2
- package/dist/server/store/mappers.d.ts +11 -0
- package/dist/server/store/mappers.js +20 -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 +42 -3
- 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,6 +227,71 @@ 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
|
`;
|
|
173
296
|
function ensureColumn(db, table, column, columnDefSql) {
|
|
174
297
|
const existing = db.prepare(`PRAGMA table_info(${table})`).all();
|
|
@@ -184,6 +307,7 @@ function installSchema(db) {
|
|
|
184
307
|
db.exec(
|
|
185
308
|
`CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronotons_public_token ON codex_cronotons(public_token)`
|
|
186
309
|
);
|
|
310
|
+
ensureColumn(db, "codex_cronoton_run_legs", "claimed_at", "TEXT");
|
|
187
311
|
}
|
|
188
312
|
|
|
189
313
|
// src/server/executor-signers.ts
|
|
@@ -228,10 +352,17 @@ function effectiveSigners(definition, kadenaNamespace) {
|
|
|
228
352
|
function isSaneCeiling(v) {
|
|
229
353
|
return typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
230
354
|
}
|
|
231
|
-
|
|
355
|
+
var CEILING_CACHE_TTL_MS = 3e4;
|
|
356
|
+
var ceilingCache = /* @__PURE__ */ new Map();
|
|
357
|
+
async function resolveCeiling(ctx, client, chainId) {
|
|
232
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;
|
|
233
362
|
const live = await client.getBlockGasLimit?.();
|
|
234
|
-
|
|
363
|
+
const resolved = isSaneCeiling(live) ? live : AUTO_GAS_CEILING;
|
|
364
|
+
ceilingCache.set(chainId, { value: resolved, expiresAt: now + CEILING_CACHE_TTL_MS });
|
|
365
|
+
return resolved;
|
|
235
366
|
}
|
|
236
367
|
function buildTransaction(runtime, definition, signers, gasLimitOverride) {
|
|
237
368
|
if (signers.length === 0) {
|
|
@@ -309,6 +440,9 @@ async function signTransaction(runtime, resolver, signers, tx) {
|
|
|
309
440
|
function dirtyReadError(result) {
|
|
310
441
|
return result.error?.message || "Transaction simulation failed on-chain.";
|
|
311
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
|
+
}
|
|
312
446
|
async function listenWithTimeout(listen, descriptor, timeoutMs) {
|
|
313
447
|
let timeoutId = null;
|
|
314
448
|
try {
|
|
@@ -335,7 +469,7 @@ async function runSimulate(ctx, definition, signers) {
|
|
|
335
469
|
const { runtime, resolver } = ctx;
|
|
336
470
|
const { autoGasLimit } = definition.config;
|
|
337
471
|
const client = runtime.createClient(runtime.getPactUrl(definition.config.chainId));
|
|
338
|
-
const ceiling = await resolveCeiling(ctx, client);
|
|
472
|
+
const ceiling = await resolveCeiling(ctx, client, definition.config.chainId);
|
|
339
473
|
const tx = buildTransaction(
|
|
340
474
|
runtime,
|
|
341
475
|
definition,
|
|
@@ -379,12 +513,9 @@ async function runSimulate(ctx, definition, signers) {
|
|
|
379
513
|
terminalIntent: null
|
|
380
514
|
};
|
|
381
515
|
}
|
|
382
|
-
async function
|
|
516
|
+
async function submitTransaction(ctx, definition, signers, client, ceiling) {
|
|
383
517
|
const { runtime, resolver } = ctx;
|
|
384
|
-
const listenMs = ctx.config?.listenTimeoutMs ?? LISTEN_TIMEOUT_MS;
|
|
385
518
|
const { chainId, autoGasLimit } = definition.config;
|
|
386
|
-
const client = runtime.createClient(runtime.getPactUrl(chainId));
|
|
387
|
-
const ceiling = await resolveCeiling(ctx, client);
|
|
388
519
|
let tx = buildTransaction(
|
|
389
520
|
runtime,
|
|
390
521
|
definition,
|
|
@@ -401,22 +532,19 @@ async function runFire(ctx, definition, signers) {
|
|
|
401
532
|
if (preflight.result.status === "failure") {
|
|
402
533
|
return {
|
|
403
534
|
ok: false,
|
|
404
|
-
mode: "fire",
|
|
405
535
|
chainId,
|
|
406
536
|
error: dirtyReadError(preflight.result),
|
|
407
|
-
rawResult: preflight.result
|
|
408
|
-
terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false)
|
|
537
|
+
rawResult: preflight.result
|
|
409
538
|
};
|
|
410
539
|
}
|
|
411
540
|
const gasUsed = preflight.gas || 0;
|
|
412
541
|
if (gasUsed > ceiling) {
|
|
413
542
|
return {
|
|
414
543
|
ok: false,
|
|
415
|
-
mode: "fire",
|
|
416
544
|
chainId,
|
|
417
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.`,
|
|
418
546
|
rawResult: preflight.result,
|
|
419
|
-
|
|
547
|
+
gasUsed
|
|
420
548
|
};
|
|
421
549
|
}
|
|
422
550
|
if (autoGasLimit && gasUsed > 0) {
|
|
@@ -446,15 +574,43 @@ async function runFire(ctx, definition, signers) {
|
|
|
446
574
|
if (derivedNetworkId) descriptor.networkId = derivedNetworkId;
|
|
447
575
|
submitResult = descriptor;
|
|
448
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
|
+
}
|
|
449
601
|
let result;
|
|
450
602
|
try {
|
|
451
|
-
result = await listenWithTimeout(
|
|
603
|
+
result = await listenWithTimeout(
|
|
604
|
+
client.listen,
|
|
605
|
+
{ requestKey: outcome.requestKey, chainId: outcome.chainId, networkId: outcome.networkId },
|
|
606
|
+
listenMs
|
|
607
|
+
);
|
|
452
608
|
} catch (listenErr) {
|
|
453
609
|
return {
|
|
454
610
|
ok: false,
|
|
455
611
|
mode: "fire",
|
|
456
|
-
chainId,
|
|
457
|
-
requestKey:
|
|
612
|
+
chainId: outcome.chainId,
|
|
613
|
+
requestKey: outcome.requestKey,
|
|
458
614
|
error: listenErr instanceof Error ? listenErr.message : "Transaction confirmation could not be observed.",
|
|
459
615
|
terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false)
|
|
460
616
|
};
|
|
@@ -463,8 +619,8 @@ async function runFire(ctx, definition, signers) {
|
|
|
463
619
|
return {
|
|
464
620
|
ok: false,
|
|
465
621
|
mode: "fire",
|
|
466
|
-
chainId,
|
|
467
|
-
requestKey: result.reqKey ||
|
|
622
|
+
chainId: outcome.chainId,
|
|
623
|
+
requestKey: result.reqKey || outcome.requestKey,
|
|
468
624
|
error: result.result.error?.message || "Transaction failed on-chain.",
|
|
469
625
|
rawResult: result.result,
|
|
470
626
|
terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false)
|
|
@@ -473,12 +629,35 @@ async function runFire(ctx, definition, signers) {
|
|
|
473
629
|
return {
|
|
474
630
|
ok: true,
|
|
475
631
|
mode: "fire",
|
|
476
|
-
chainId,
|
|
477
|
-
requestKey: result.reqKey ||
|
|
632
|
+
chainId: outcome.chainId,
|
|
633
|
+
requestKey: result.reqKey || outcome.requestKey,
|
|
478
634
|
rawResult: result.result,
|
|
479
635
|
terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", true)
|
|
480
636
|
};
|
|
481
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
|
+
}
|
|
482
661
|
async function executeCodexTransaction(definition, mode, ctx) {
|
|
483
662
|
const { runtime } = ctx;
|
|
484
663
|
if (mode === "simulate") {
|
|
@@ -490,6 +669,25 @@ async function executeCodexTransaction(definition, mode, ctx) {
|
|
|
490
669
|
}
|
|
491
670
|
return runSimulate(ctx, definition, signers);
|
|
492
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
|
+
}
|
|
493
691
|
try {
|
|
494
692
|
const signers = effectiveSigners(definition, runtime.namespace);
|
|
495
693
|
if (signers.length === 0) {
|
|
@@ -499,7 +697,7 @@ async function executeCodexTransaction(definition, mode, ctx) {
|
|
|
499
697
|
}
|
|
500
698
|
return await runFire(ctx, definition, signers);
|
|
501
699
|
} catch (e) {
|
|
502
|
-
const error = (e
|
|
700
|
+
const error = describeThrown(e, "fire");
|
|
503
701
|
return {
|
|
504
702
|
ok: false,
|
|
505
703
|
mode: "fire",
|
|
@@ -511,6 +709,9 @@ async function executeCodexTransaction(definition, mode, ctx) {
|
|
|
511
709
|
}
|
|
512
710
|
|
|
513
711
|
// src/server/store/errors.ts
|
|
712
|
+
function isUniqueConstraintError(error) {
|
|
713
|
+
return error instanceof Error && error.code === "SQLITE_CONSTRAINT_UNIQUE";
|
|
714
|
+
}
|
|
514
715
|
var CodexCronotonValidationError = class extends Error {
|
|
515
716
|
constructor(message) {
|
|
516
717
|
super(message);
|
|
@@ -537,6 +738,52 @@ var ManualBatchActiveError = class extends Error {
|
|
|
537
738
|
this.name = "ManualBatchActiveError";
|
|
538
739
|
}
|
|
539
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
|
+
};
|
|
540
787
|
var MANUAL_BATCH_MIN = 2;
|
|
541
788
|
var MANUAL_BATCH_MAX = 60;
|
|
542
789
|
var MANUAL_BATCH_INTERVAL_SECONDS = 60;
|
|
@@ -559,6 +806,17 @@ function rowToDefinition(row) {
|
|
|
559
806
|
serverResolver: row.server_resolver ?? void 0
|
|
560
807
|
};
|
|
561
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
|
+
}
|
|
562
820
|
function rowExternalFireable(row) {
|
|
563
821
|
return row.external_fireable === 1;
|
|
564
822
|
}
|
|
@@ -1126,14 +1384,29 @@ async function dispatchMultiTxResolver(name, opts) {
|
|
|
1126
1384
|
function postponed(error) {
|
|
1127
1385
|
return { ok: false, mode: "fire", error, terminalIntent: null };
|
|
1128
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
|
+
}
|
|
1129
1397
|
function adaptMultiTxSummary(summary) {
|
|
1130
1398
|
const s = summary ?? {};
|
|
1131
|
-
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;
|
|
1132
1404
|
return {
|
|
1133
|
-
ok
|
|
1405
|
+
ok,
|
|
1134
1406
|
mode: "fire",
|
|
1135
1407
|
requestKey: firstBatchKey,
|
|
1136
1408
|
rawResult: summary,
|
|
1409
|
+
error: ok ? void 0 : `${failedCount} of ${reported.length} reporting batch(es) failed`,
|
|
1137
1410
|
terminalIntent: null
|
|
1138
1411
|
};
|
|
1139
1412
|
}
|
|
@@ -1577,6 +1850,420 @@ function computeDefinitionFingerprint(row) {
|
|
|
1577
1850
|
const canonical = JSON.stringify(canonicalize(parts));
|
|
1578
1851
|
return crypto2.createHash("sha256").update(canonical).digest("hex");
|
|
1579
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
|
+
}
|
|
1580
2267
|
|
|
1581
2268
|
// src/handlers/http.ts
|
|
1582
2269
|
function json(status, body) {
|
|
@@ -1739,4 +2426,4 @@ async function runGated2(fn, options = {}) {
|
|
|
1739
2426
|
}
|
|
1740
2427
|
}
|
|
1741
2428
|
|
|
1742
|
-
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 };
|