@ancientpantheon/khronoton-core 0.12.0 → 0.14.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 +35 -0
- package/README.md +8 -0
- package/dist/blockchain/stoachain.d.ts +1 -1
- package/dist/blockchain/stoachain.js +16 -1
- package/dist/{chunk-GIGLXIMC.js → chunk-A5YODPKQ.js} +820 -23
- package/dist/{chunk-KQZYMPZS.js → chunk-WKI52IPY.js} +1 -1
- 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 +152 -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 +12 -2
- package/dist/server/index.js +38 -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 +118 -0
- package/dist/server/planners/registry.js +94 -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 +26 -0
- package/dist/server/planners/stoa-wrap.js +229 -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/pure/yields.d.ts +57 -0
- package/dist/server/pure/yields.js +101 -0
- package/dist/server/resolvers.js +48 -6
- package/dist/server/runs-driver.d.ts +92 -0
- package/dist/server/runs-driver.js +582 -0
- package/dist/server/schema.d.ts +6 -2
- package/dist/server/schema.js +89 -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 +7 -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/runs.d.ts +233 -0
- package/dist/server/store/runs.js +341 -0
- package/dist/server/store/steps.d.ts +54 -0
- package/dist/server/store/steps.js +74 -0
- package/dist/server/store/yields.d.ts +46 -0
- package/dist/server/store/yields.js +73 -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,97 @@ 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
|
+
|
|
148
|
+
// src/server/pure/yields.ts
|
|
149
|
+
var YieldNotFoundError = class extends Error {
|
|
150
|
+
constructor(name) {
|
|
151
|
+
super(`no yield named "${name}" has been produced yet in this run`);
|
|
152
|
+
this.name = "YieldNotFoundError";
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
function isYieldPlaceholder(value) {
|
|
156
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
157
|
+
const keys = Object.keys(value);
|
|
158
|
+
return keys.length === 1 && keys[0] === "$yield" && typeof value.$yield === "string";
|
|
159
|
+
}
|
|
160
|
+
function resolveYieldRefs(value, pool) {
|
|
161
|
+
if (Array.isArray(value)) {
|
|
162
|
+
return value.map((item) => resolveYieldRefs(item, pool));
|
|
163
|
+
}
|
|
164
|
+
if (isYieldPlaceholder(value)) {
|
|
165
|
+
const name = value.$yield;
|
|
166
|
+
if (!Object.prototype.hasOwnProperty.call(pool, name)) {
|
|
167
|
+
throw new YieldNotFoundError(name);
|
|
168
|
+
}
|
|
169
|
+
return pool[name];
|
|
170
|
+
}
|
|
171
|
+
if (value !== null && typeof value === "object") {
|
|
172
|
+
return Object.fromEntries(
|
|
173
|
+
Object.entries(value).map(([k, v]) => [k, resolveYieldRefs(v, pool)])
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
return value;
|
|
177
|
+
}
|
|
178
|
+
function resolveSingleStepPayload(step, pool) {
|
|
179
|
+
return {
|
|
180
|
+
...step,
|
|
181
|
+
payload_json: JSON.stringify(resolveYieldRefs(JSON.parse(step.payload_json ?? "{}"), pool))
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
90
185
|
// src/server/schema.ts
|
|
91
186
|
var SCHEMA_SQL = `
|
|
92
187
|
CREATE TABLE IF NOT EXISTS codex_cronotons (
|
|
@@ -169,6 +264,82 @@ CREATE INDEX IF NOT EXISTS idx_codex_manual_batches_due
|
|
|
169
264
|
|
|
170
265
|
CREATE INDEX IF NOT EXISTS idx_codex_manual_batches_cronoton
|
|
171
266
|
ON codex_cronoton_manual_batches(codex_cronoton_id);
|
|
267
|
+
|
|
268
|
+
CREATE TABLE IF NOT EXISTS codex_cronoton_steps (
|
|
269
|
+
id TEXT PRIMARY KEY,
|
|
270
|
+
codex_cronoton_id TEXT NOT NULL REFERENCES codex_cronotons(id) ON DELETE CASCADE,
|
|
271
|
+
step_index INTEGER NOT NULL,
|
|
272
|
+
mode TEXT NOT NULL CHECK (mode IN ('single', 'planner')),
|
|
273
|
+
pact_code TEXT,
|
|
274
|
+
config_json TEXT,
|
|
275
|
+
payload_json TEXT,
|
|
276
|
+
gas_payer_json TEXT,
|
|
277
|
+
signers_json TEXT,
|
|
278
|
+
planner_name TEXT,
|
|
279
|
+
planner_params_json TEXT,
|
|
280
|
+
idempotent INTEGER NOT NULL DEFAULT 0,
|
|
281
|
+
created_at TEXT NOT NULL,
|
|
282
|
+
modified_at TEXT NOT NULL,
|
|
283
|
+
CHECK (
|
|
284
|
+
(mode = 'single' AND pact_code IS NOT NULL) OR
|
|
285
|
+
(mode = 'planner' AND planner_name IS NOT NULL)
|
|
286
|
+
)
|
|
287
|
+
);
|
|
288
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_steps_order
|
|
289
|
+
ON codex_cronoton_steps(codex_cronoton_id, step_index);
|
|
290
|
+
|
|
291
|
+
CREATE TABLE IF NOT EXISTS codex_cronoton_runs (
|
|
292
|
+
id TEXT PRIMARY KEY,
|
|
293
|
+
codex_cronoton_id TEXT NOT NULL REFERENCES codex_cronotons(id) ON DELETE CASCADE,
|
|
294
|
+
fire_id TEXT REFERENCES codex_cronoton_fires(id),
|
|
295
|
+
status TEXT NOT NULL DEFAULT 'planning' CHECK (status IN (
|
|
296
|
+
'planning', 'awaiting', 'advancing', 'succeeded', 'failed', 'abandoned'
|
|
297
|
+
)),
|
|
298
|
+
step_index INTEGER NOT NULL DEFAULT 0,
|
|
299
|
+
step_count INTEGER NOT NULL,
|
|
300
|
+
started_at TEXT NOT NULL,
|
|
301
|
+
modified_at TEXT NOT NULL,
|
|
302
|
+
deadline_at TEXT,
|
|
303
|
+
attempt INTEGER NOT NULL DEFAULT 0,
|
|
304
|
+
context_json TEXT
|
|
305
|
+
);
|
|
306
|
+
CREATE INDEX IF NOT EXISTS idx_codex_cronoton_runs_due
|
|
307
|
+
ON codex_cronoton_runs(status, modified_at);
|
|
308
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_runs_self_block
|
|
309
|
+
ON codex_cronoton_runs(codex_cronoton_id)
|
|
310
|
+
WHERE status IN ('planning', 'awaiting', 'advancing');
|
|
311
|
+
|
|
312
|
+
CREATE TABLE IF NOT EXISTS codex_cronoton_run_legs (
|
|
313
|
+
id TEXT PRIMARY KEY,
|
|
314
|
+
run_id TEXT NOT NULL REFERENCES codex_cronoton_runs(id) ON DELETE CASCADE,
|
|
315
|
+
step_index INTEGER NOT NULL,
|
|
316
|
+
leg_index INTEGER NOT NULL,
|
|
317
|
+
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN (
|
|
318
|
+
'pending', 'submitted', 'confirmed', 'failed'
|
|
319
|
+
)),
|
|
320
|
+
request_key TEXT,
|
|
321
|
+
chain_id TEXT,
|
|
322
|
+
definition_json TEXT NOT NULL,
|
|
323
|
+
error_message TEXT,
|
|
324
|
+
submitted_at TEXT,
|
|
325
|
+
confirmed_at TEXT,
|
|
326
|
+
attempt INTEGER NOT NULL DEFAULT 0
|
|
327
|
+
);
|
|
328
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_run_legs_slot
|
|
329
|
+
ON codex_cronoton_run_legs(run_id, step_index, leg_index);
|
|
330
|
+
CREATE INDEX IF NOT EXISTS idx_codex_cronoton_run_legs_barrier
|
|
331
|
+
ON codex_cronoton_run_legs(run_id, step_index, status);
|
|
332
|
+
|
|
333
|
+
CREATE TABLE IF NOT EXISTS codex_cronoton_run_yields (
|
|
334
|
+
id TEXT PRIMARY KEY,
|
|
335
|
+
run_id TEXT NOT NULL REFERENCES codex_cronoton_runs(id) ON DELETE CASCADE,
|
|
336
|
+
name TEXT NOT NULL,
|
|
337
|
+
value_json TEXT NOT NULL,
|
|
338
|
+
step_index INTEGER NOT NULL,
|
|
339
|
+
created_at TEXT NOT NULL
|
|
340
|
+
);
|
|
341
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_run_yields_name
|
|
342
|
+
ON codex_cronoton_run_yields(run_id, name);
|
|
172
343
|
`;
|
|
173
344
|
function ensureColumn(db, table, column, columnDefSql) {
|
|
174
345
|
const existing = db.prepare(`PRAGMA table_info(${table})`).all();
|
|
@@ -184,6 +355,8 @@ function installSchema(db) {
|
|
|
184
355
|
db.exec(
|
|
185
356
|
`CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronotons_public_token ON codex_cronotons(public_token)`
|
|
186
357
|
);
|
|
358
|
+
ensureColumn(db, "codex_cronoton_run_legs", "claimed_at", "TEXT");
|
|
359
|
+
ensureColumn(db, "codex_cronoton_steps", "yield_as", "TEXT");
|
|
187
360
|
}
|
|
188
361
|
|
|
189
362
|
// src/server/executor-signers.ts
|
|
@@ -228,10 +401,17 @@ function effectiveSigners(definition, kadenaNamespace) {
|
|
|
228
401
|
function isSaneCeiling(v) {
|
|
229
402
|
return typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
230
403
|
}
|
|
231
|
-
|
|
404
|
+
var CEILING_CACHE_TTL_MS = 3e4;
|
|
405
|
+
var ceilingCache = /* @__PURE__ */ new Map();
|
|
406
|
+
async function resolveCeiling(ctx, client, chainId) {
|
|
232
407
|
if (isSaneCeiling(ctx.config?.autoGasCeiling)) return ctx.config.autoGasCeiling;
|
|
408
|
+
const now = Date.now();
|
|
409
|
+
const cached = ceilingCache.get(chainId);
|
|
410
|
+
if (cached && cached.expiresAt > now) return cached.value;
|
|
233
411
|
const live = await client.getBlockGasLimit?.();
|
|
234
|
-
|
|
412
|
+
const resolved = isSaneCeiling(live) ? live : AUTO_GAS_CEILING;
|
|
413
|
+
ceilingCache.set(chainId, { value: resolved, expiresAt: now + CEILING_CACHE_TTL_MS });
|
|
414
|
+
return resolved;
|
|
235
415
|
}
|
|
236
416
|
function buildTransaction(runtime, definition, signers, gasLimitOverride) {
|
|
237
417
|
if (signers.length === 0) {
|
|
@@ -309,6 +489,9 @@ async function signTransaction(runtime, resolver, signers, tx) {
|
|
|
309
489
|
function dirtyReadError(result) {
|
|
310
490
|
return result.error?.message || "Transaction simulation failed on-chain.";
|
|
311
491
|
}
|
|
492
|
+
function describeThrown(e, fallbackLabel) {
|
|
493
|
+
return (e instanceof Error ? e.message : String(e)) || (e instanceof Error ? `${e.name} (no message)` : `unknown ${fallbackLabel} error`);
|
|
494
|
+
}
|
|
312
495
|
async function listenWithTimeout(listen, descriptor, timeoutMs) {
|
|
313
496
|
let timeoutId = null;
|
|
314
497
|
try {
|
|
@@ -335,7 +518,7 @@ async function runSimulate(ctx, definition, signers) {
|
|
|
335
518
|
const { runtime, resolver } = ctx;
|
|
336
519
|
const { autoGasLimit } = definition.config;
|
|
337
520
|
const client = runtime.createClient(runtime.getPactUrl(definition.config.chainId));
|
|
338
|
-
const ceiling = await resolveCeiling(ctx, client);
|
|
521
|
+
const ceiling = await resolveCeiling(ctx, client, definition.config.chainId);
|
|
339
522
|
const tx = buildTransaction(
|
|
340
523
|
runtime,
|
|
341
524
|
definition,
|
|
@@ -379,12 +562,9 @@ async function runSimulate(ctx, definition, signers) {
|
|
|
379
562
|
terminalIntent: null
|
|
380
563
|
};
|
|
381
564
|
}
|
|
382
|
-
async function
|
|
565
|
+
async function submitTransaction(ctx, definition, signers, client, ceiling) {
|
|
383
566
|
const { runtime, resolver } = ctx;
|
|
384
|
-
const listenMs = ctx.config?.listenTimeoutMs ?? LISTEN_TIMEOUT_MS;
|
|
385
567
|
const { chainId, autoGasLimit } = definition.config;
|
|
386
|
-
const client = runtime.createClient(runtime.getPactUrl(chainId));
|
|
387
|
-
const ceiling = await resolveCeiling(ctx, client);
|
|
388
568
|
let tx = buildTransaction(
|
|
389
569
|
runtime,
|
|
390
570
|
definition,
|
|
@@ -401,22 +581,19 @@ async function runFire(ctx, definition, signers) {
|
|
|
401
581
|
if (preflight.result.status === "failure") {
|
|
402
582
|
return {
|
|
403
583
|
ok: false,
|
|
404
|
-
mode: "fire",
|
|
405
584
|
chainId,
|
|
406
585
|
error: dirtyReadError(preflight.result),
|
|
407
|
-
rawResult: preflight.result
|
|
408
|
-
terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false)
|
|
586
|
+
rawResult: preflight.result
|
|
409
587
|
};
|
|
410
588
|
}
|
|
411
589
|
const gasUsed = preflight.gas || 0;
|
|
412
590
|
if (gasUsed > ceiling) {
|
|
413
591
|
return {
|
|
414
592
|
ok: false,
|
|
415
|
-
mode: "fire",
|
|
416
593
|
chainId,
|
|
417
594
|
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
595
|
rawResult: preflight.result,
|
|
419
|
-
|
|
596
|
+
gasUsed
|
|
420
597
|
};
|
|
421
598
|
}
|
|
422
599
|
if (autoGasLimit && gasUsed > 0) {
|
|
@@ -446,15 +623,43 @@ async function runFire(ctx, definition, signers) {
|
|
|
446
623
|
if (derivedNetworkId) descriptor.networkId = derivedNetworkId;
|
|
447
624
|
submitResult = descriptor;
|
|
448
625
|
}
|
|
626
|
+
return {
|
|
627
|
+
ok: true,
|
|
628
|
+
chainId,
|
|
629
|
+
requestKey: submitResult.requestKey,
|
|
630
|
+
networkId: derivedNetworkId
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
async function runFire(ctx, definition, signers) {
|
|
634
|
+
const { runtime } = ctx;
|
|
635
|
+
const listenMs = ctx.config?.listenTimeoutMs ?? LISTEN_TIMEOUT_MS;
|
|
636
|
+
const { chainId } = definition.config;
|
|
637
|
+
const client = runtime.createClient(runtime.getPactUrl(chainId));
|
|
638
|
+
const ceiling = await resolveCeiling(ctx, client, chainId);
|
|
639
|
+
const outcome = await submitTransaction(ctx, definition, signers, client, ceiling);
|
|
640
|
+
if (!outcome.ok) {
|
|
641
|
+
return {
|
|
642
|
+
ok: false,
|
|
643
|
+
mode: "fire",
|
|
644
|
+
chainId: outcome.chainId,
|
|
645
|
+
error: outcome.error,
|
|
646
|
+
rawResult: outcome.rawResult,
|
|
647
|
+
terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false)
|
|
648
|
+
};
|
|
649
|
+
}
|
|
449
650
|
let result;
|
|
450
651
|
try {
|
|
451
|
-
result = await listenWithTimeout(
|
|
652
|
+
result = await listenWithTimeout(
|
|
653
|
+
client.listen,
|
|
654
|
+
{ requestKey: outcome.requestKey, chainId: outcome.chainId, networkId: outcome.networkId },
|
|
655
|
+
listenMs
|
|
656
|
+
);
|
|
452
657
|
} catch (listenErr) {
|
|
453
658
|
return {
|
|
454
659
|
ok: false,
|
|
455
660
|
mode: "fire",
|
|
456
|
-
chainId,
|
|
457
|
-
requestKey:
|
|
661
|
+
chainId: outcome.chainId,
|
|
662
|
+
requestKey: outcome.requestKey,
|
|
458
663
|
error: listenErr instanceof Error ? listenErr.message : "Transaction confirmation could not be observed.",
|
|
459
664
|
terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false)
|
|
460
665
|
};
|
|
@@ -463,8 +668,8 @@ async function runFire(ctx, definition, signers) {
|
|
|
463
668
|
return {
|
|
464
669
|
ok: false,
|
|
465
670
|
mode: "fire",
|
|
466
|
-
chainId,
|
|
467
|
-
requestKey: result.reqKey ||
|
|
671
|
+
chainId: outcome.chainId,
|
|
672
|
+
requestKey: result.reqKey || outcome.requestKey,
|
|
468
673
|
error: result.result.error?.message || "Transaction failed on-chain.",
|
|
469
674
|
rawResult: result.result,
|
|
470
675
|
terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false)
|
|
@@ -473,12 +678,35 @@ async function runFire(ctx, definition, signers) {
|
|
|
473
678
|
return {
|
|
474
679
|
ok: true,
|
|
475
680
|
mode: "fire",
|
|
476
|
-
chainId,
|
|
477
|
-
requestKey: result.reqKey ||
|
|
681
|
+
chainId: outcome.chainId,
|
|
682
|
+
requestKey: result.reqKey || outcome.requestKey,
|
|
478
683
|
rawResult: result.result,
|
|
479
684
|
terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", true)
|
|
480
685
|
};
|
|
481
686
|
}
|
|
687
|
+
async function runSubmit(ctx, definition, signers) {
|
|
688
|
+
const { runtime } = ctx;
|
|
689
|
+
const { chainId } = definition.config;
|
|
690
|
+
const client = runtime.createClient(runtime.getPactUrl(chainId));
|
|
691
|
+
const ceiling = await resolveCeiling(ctx, client, chainId);
|
|
692
|
+
const outcome = await submitTransaction(ctx, definition, signers, client, ceiling);
|
|
693
|
+
if (!outcome.ok) {
|
|
694
|
+
return {
|
|
695
|
+
ok: false,
|
|
696
|
+
mode: "submit",
|
|
697
|
+
chainId: outcome.chainId,
|
|
698
|
+
error: outcome.error,
|
|
699
|
+
rawResult: outcome.rawResult
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
return {
|
|
703
|
+
ok: true,
|
|
704
|
+
mode: "submit",
|
|
705
|
+
requestKey: outcome.requestKey,
|
|
706
|
+
chainId: outcome.chainId,
|
|
707
|
+
networkId: outcome.networkId
|
|
708
|
+
};
|
|
709
|
+
}
|
|
482
710
|
async function executeCodexTransaction(definition, mode, ctx) {
|
|
483
711
|
const { runtime } = ctx;
|
|
484
712
|
if (mode === "simulate") {
|
|
@@ -490,6 +718,25 @@ async function executeCodexTransaction(definition, mode, ctx) {
|
|
|
490
718
|
}
|
|
491
719
|
return runSimulate(ctx, definition, signers);
|
|
492
720
|
}
|
|
721
|
+
if (mode === "submit") {
|
|
722
|
+
try {
|
|
723
|
+
const signers = effectiveSigners(definition, runtime.namespace);
|
|
724
|
+
if (signers.length === 0) {
|
|
725
|
+
throw new Error(
|
|
726
|
+
"At least one signer is required to build a codex transaction."
|
|
727
|
+
);
|
|
728
|
+
}
|
|
729
|
+
return await runSubmit(ctx, definition, signers);
|
|
730
|
+
} catch (e) {
|
|
731
|
+
const error = describeThrown(e, "submit");
|
|
732
|
+
return {
|
|
733
|
+
ok: false,
|
|
734
|
+
mode: "submit",
|
|
735
|
+
chainId: definition.config.chainId,
|
|
736
|
+
error
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
}
|
|
493
740
|
try {
|
|
494
741
|
const signers = effectiveSigners(definition, runtime.namespace);
|
|
495
742
|
if (signers.length === 0) {
|
|
@@ -499,7 +746,7 @@ async function executeCodexTransaction(definition, mode, ctx) {
|
|
|
499
746
|
}
|
|
500
747
|
return await runFire(ctx, definition, signers);
|
|
501
748
|
} catch (e) {
|
|
502
|
-
const error = (e
|
|
749
|
+
const error = describeThrown(e, "fire");
|
|
503
750
|
return {
|
|
504
751
|
ok: false,
|
|
505
752
|
mode: "fire",
|
|
@@ -511,6 +758,9 @@ async function executeCodexTransaction(definition, mode, ctx) {
|
|
|
511
758
|
}
|
|
512
759
|
|
|
513
760
|
// src/server/store/errors.ts
|
|
761
|
+
function isUniqueConstraintError(error) {
|
|
762
|
+
return error instanceof Error && error.code === "SQLITE_CONSTRAINT_UNIQUE";
|
|
763
|
+
}
|
|
514
764
|
var CodexCronotonValidationError = class extends Error {
|
|
515
765
|
constructor(message) {
|
|
516
766
|
super(message);
|
|
@@ -537,6 +787,52 @@ var ManualBatchActiveError = class extends Error {
|
|
|
537
787
|
this.name = "ManualBatchActiveError";
|
|
538
788
|
}
|
|
539
789
|
};
|
|
790
|
+
var RunAlreadyInFlightError = class extends Error {
|
|
791
|
+
constructor(codexCronotonId) {
|
|
792
|
+
super(
|
|
793
|
+
`codex cronoton ${codexCronotonId} already has a non-terminal run in flight \u2014 a new run cannot start until it settles`
|
|
794
|
+
);
|
|
795
|
+
this.name = "RunAlreadyInFlightError";
|
|
796
|
+
}
|
|
797
|
+
};
|
|
798
|
+
var LegAlreadySubmittedError = class extends Error {
|
|
799
|
+
constructor(legId) {
|
|
800
|
+
super(
|
|
801
|
+
`run leg ${legId} is already submitted (or past submission) \u2014 re-submission is refused, only polling for its outcome is allowed`
|
|
802
|
+
);
|
|
803
|
+
this.name = "LegAlreadySubmittedError";
|
|
804
|
+
}
|
|
805
|
+
};
|
|
806
|
+
var LegNotSubmittedError = class extends Error {
|
|
807
|
+
constructor(legId) {
|
|
808
|
+
super(
|
|
809
|
+
`run leg ${legId} is not in 'submitted' status \u2014 it has either never been submitted or is already in a terminal status (confirmed/failed)`
|
|
810
|
+
);
|
|
811
|
+
this.name = "LegNotSubmittedError";
|
|
812
|
+
}
|
|
813
|
+
};
|
|
814
|
+
var RunLegAlreadyExistsError = class extends Error {
|
|
815
|
+
constructor(runId, stepIndex, legIndex) {
|
|
816
|
+
super(
|
|
817
|
+
`run ${runId} already has a leg at step ${stepIndex}, leg ${legIndex} \u2014 that slot cannot be inserted twice`
|
|
818
|
+
);
|
|
819
|
+
this.name = "RunLegAlreadyExistsError";
|
|
820
|
+
}
|
|
821
|
+
};
|
|
822
|
+
var RunStepMismatchError = class extends Error {
|
|
823
|
+
constructor(runId, expectedStepIndex) {
|
|
824
|
+
super(
|
|
825
|
+
`run ${runId} is not at step ${expectedStepIndex} \u2014 its step_index has already moved on, so this advance is stale`
|
|
826
|
+
);
|
|
827
|
+
this.name = "RunStepMismatchError";
|
|
828
|
+
}
|
|
829
|
+
};
|
|
830
|
+
var RunAlreadyTerminalError = class extends Error {
|
|
831
|
+
constructor(runId) {
|
|
832
|
+
super(`run ${runId} is already in a terminal status (succeeded/failed/abandoned)`);
|
|
833
|
+
this.name = "RunAlreadyTerminalError";
|
|
834
|
+
}
|
|
835
|
+
};
|
|
540
836
|
var MANUAL_BATCH_MIN = 2;
|
|
541
837
|
var MANUAL_BATCH_MAX = 60;
|
|
542
838
|
var MANUAL_BATCH_INTERVAL_SECONDS = 60;
|
|
@@ -559,6 +855,17 @@ function rowToDefinition(row) {
|
|
|
559
855
|
serverResolver: row.server_resolver ?? void 0
|
|
560
856
|
};
|
|
561
857
|
}
|
|
858
|
+
function stepRowToDefinition(step) {
|
|
859
|
+
return {
|
|
860
|
+
pactCode: step.pact_code ?? "",
|
|
861
|
+
config: parseJson(step.config_json, {}),
|
|
862
|
+
payload: parseJson(step.payload_json, {}),
|
|
863
|
+
gasPayer: parseJson(step.gas_payer_json, {
|
|
864
|
+
type: "gas-station"
|
|
865
|
+
}),
|
|
866
|
+
signers: parseJson(step.signers_json, [])
|
|
867
|
+
};
|
|
868
|
+
}
|
|
562
869
|
function rowExternalFireable(row) {
|
|
563
870
|
return row.external_fireable === 1;
|
|
564
871
|
}
|
|
@@ -1126,14 +1433,29 @@ async function dispatchMultiTxResolver(name, opts) {
|
|
|
1126
1433
|
function postponed(error) {
|
|
1127
1434
|
return { ok: false, mode: "fire", error, terminalIntent: null };
|
|
1128
1435
|
}
|
|
1436
|
+
function toReportedOk(value) {
|
|
1437
|
+
if (typeof value === "boolean") return value;
|
|
1438
|
+
if (typeof value === "number") return value !== 0;
|
|
1439
|
+
if (typeof value === "string") {
|
|
1440
|
+
const lower = value.toLowerCase();
|
|
1441
|
+
if (lower === "true") return true;
|
|
1442
|
+
if (lower === "false") return false;
|
|
1443
|
+
}
|
|
1444
|
+
return void 0;
|
|
1445
|
+
}
|
|
1129
1446
|
function adaptMultiTxSummary(summary) {
|
|
1130
1447
|
const s = summary ?? {};
|
|
1131
|
-
const
|
|
1448
|
+
const batches = Array.isArray(s.batches) ? s.batches : [];
|
|
1449
|
+
const firstBatchKey = batches.length > 0 ? batches[0]?.requestKey : void 0;
|
|
1450
|
+
const reported = batches.map((b) => toReportedOk(b.ok)).filter((v) => v !== void 0);
|
|
1451
|
+
const ok = reported.length === 0 ? true : reported.every((v) => v === true);
|
|
1452
|
+
const failedCount = reported.filter((v) => v === false).length;
|
|
1132
1453
|
return {
|
|
1133
|
-
ok
|
|
1454
|
+
ok,
|
|
1134
1455
|
mode: "fire",
|
|
1135
1456
|
requestKey: firstBatchKey,
|
|
1136
1457
|
rawResult: summary,
|
|
1458
|
+
error: ok ? void 0 : `${failedCount} of ${reported.length} reporting batch(es) failed`,
|
|
1137
1459
|
terminalIntent: null
|
|
1138
1460
|
};
|
|
1139
1461
|
}
|
|
@@ -1577,6 +1899,481 @@ function computeDefinitionFingerprint(row) {
|
|
|
1577
1899
|
const canonical = JSON.stringify(canonicalize(parts));
|
|
1578
1900
|
return crypto2.createHash("sha256").update(canonical).digest("hex");
|
|
1579
1901
|
}
|
|
1902
|
+
function listStepsForCronoton(codexCronotonId, dep) {
|
|
1903
|
+
return dep.db.prepare(
|
|
1904
|
+
`SELECT * FROM codex_cronoton_steps
|
|
1905
|
+
WHERE codex_cronoton_id = ?
|
|
1906
|
+
ORDER BY step_index ASC`
|
|
1907
|
+
).all(codexCronotonId);
|
|
1908
|
+
}
|
|
1909
|
+
function createRun(input, dep) {
|
|
1910
|
+
const id = randomUUID();
|
|
1911
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1912
|
+
try {
|
|
1913
|
+
dep.db.prepare(
|
|
1914
|
+
`INSERT INTO codex_cronoton_runs
|
|
1915
|
+
(id, codex_cronoton_id, step_count, started_at, modified_at, deadline_at, context_json)
|
|
1916
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
|
1917
|
+
).run(
|
|
1918
|
+
id,
|
|
1919
|
+
input.codexCronotonId,
|
|
1920
|
+
input.stepCount,
|
|
1921
|
+
now,
|
|
1922
|
+
now,
|
|
1923
|
+
input.deadlineAt ?? null,
|
|
1924
|
+
input.contextJson !== void 0 ? JSON.stringify(input.contextJson) : null
|
|
1925
|
+
);
|
|
1926
|
+
} catch (error) {
|
|
1927
|
+
if (isUniqueConstraintError(error)) {
|
|
1928
|
+
throw new RunAlreadyInFlightError(input.codexCronotonId);
|
|
1929
|
+
}
|
|
1930
|
+
throw error;
|
|
1931
|
+
}
|
|
1932
|
+
return id;
|
|
1933
|
+
}
|
|
1934
|
+
function getRun(runId, dep) {
|
|
1935
|
+
const row = dep.db.prepare(`SELECT * FROM codex_cronoton_runs WHERE id = ?`).get(runId);
|
|
1936
|
+
return row ?? null;
|
|
1937
|
+
}
|
|
1938
|
+
function listRunLegs(runId, dep) {
|
|
1939
|
+
return dep.db.prepare(
|
|
1940
|
+
`SELECT * FROM codex_cronoton_run_legs
|
|
1941
|
+
WHERE run_id = ?
|
|
1942
|
+
ORDER BY step_index ASC, leg_index ASC`
|
|
1943
|
+
).all(runId);
|
|
1944
|
+
}
|
|
1945
|
+
function insertRunLeg(input, dep) {
|
|
1946
|
+
const id = randomUUID();
|
|
1947
|
+
try {
|
|
1948
|
+
dep.db.prepare(
|
|
1949
|
+
`INSERT INTO codex_cronoton_run_legs (id, run_id, step_index, leg_index, definition_json, attempt)
|
|
1950
|
+
VALUES (?, ?, ?, ?, ?, ?)`
|
|
1951
|
+
).run(
|
|
1952
|
+
id,
|
|
1953
|
+
input.runId,
|
|
1954
|
+
input.stepIndex,
|
|
1955
|
+
input.legIndex,
|
|
1956
|
+
input.definitionJson,
|
|
1957
|
+
input.attempt ?? 0
|
|
1958
|
+
);
|
|
1959
|
+
} catch (error) {
|
|
1960
|
+
if (isUniqueConstraintError(error)) {
|
|
1961
|
+
throw new RunLegAlreadyExistsError(input.runId, input.stepIndex, input.legIndex);
|
|
1962
|
+
}
|
|
1963
|
+
throw error;
|
|
1964
|
+
}
|
|
1965
|
+
return id;
|
|
1966
|
+
}
|
|
1967
|
+
function claimLegForSubmit(legId, claimedAt, dep) {
|
|
1968
|
+
const result = dep.db.prepare(
|
|
1969
|
+
`UPDATE codex_cronoton_run_legs
|
|
1970
|
+
SET claimed_at = ?
|
|
1971
|
+
WHERE id = ? AND status = 'pending' AND claimed_at IS NULL`
|
|
1972
|
+
).run(claimedAt, legId);
|
|
1973
|
+
return result.changes === 1;
|
|
1974
|
+
}
|
|
1975
|
+
function releaseLegClaim(legId, dep) {
|
|
1976
|
+
dep.db.prepare(`UPDATE codex_cronoton_run_legs SET claimed_at = NULL WHERE id = ?`).run(legId);
|
|
1977
|
+
}
|
|
1978
|
+
function markLegSubmitted(legId, input, dep) {
|
|
1979
|
+
const result = dep.db.prepare(
|
|
1980
|
+
`UPDATE codex_cronoton_run_legs
|
|
1981
|
+
SET status = 'submitted', request_key = ?, chain_id = ?, submitted_at = ?
|
|
1982
|
+
WHERE id = ? AND status = 'pending'`
|
|
1983
|
+
).run(input.requestKey, input.chainId, (/* @__PURE__ */ new Date()).toISOString(), legId);
|
|
1984
|
+
if (result.changes !== 1) {
|
|
1985
|
+
throw new LegAlreadySubmittedError(legId);
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
function markLegConfirmed(legId, dep) {
|
|
1989
|
+
const result = dep.db.prepare(
|
|
1990
|
+
`UPDATE codex_cronoton_run_legs
|
|
1991
|
+
SET status = 'confirmed', confirmed_at = ?
|
|
1992
|
+
WHERE id = ? AND status = 'submitted'`
|
|
1993
|
+
).run((/* @__PURE__ */ new Date()).toISOString(), legId);
|
|
1994
|
+
if (result.changes !== 1) {
|
|
1995
|
+
throw new LegNotSubmittedError(legId);
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
function markLegFailed(legId, input, dep) {
|
|
1999
|
+
const result = dep.db.prepare(
|
|
2000
|
+
`UPDATE codex_cronoton_run_legs
|
|
2001
|
+
SET status = 'failed', error_message = ?
|
|
2002
|
+
WHERE id = ? AND status = 'submitted'`
|
|
2003
|
+
).run(input.errorMessage, legId);
|
|
2004
|
+
if (result.changes !== 1) {
|
|
2005
|
+
throw new LegNotSubmittedError(legId);
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
function advanceRunStep(runId, input, dep) {
|
|
2009
|
+
const result = dep.db.prepare(
|
|
2010
|
+
`UPDATE codex_cronoton_runs
|
|
2011
|
+
SET step_index = ?, attempt = 0, deadline_at = ?, modified_at = ?
|
|
2012
|
+
WHERE id = ? AND step_index = ?`
|
|
2013
|
+
).run(
|
|
2014
|
+
input.toStepIndex,
|
|
2015
|
+
input.deadlineAt,
|
|
2016
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
2017
|
+
runId,
|
|
2018
|
+
input.fromStepIndex
|
|
2019
|
+
);
|
|
2020
|
+
if (result.changes !== 1) {
|
|
2021
|
+
throw new RunStepMismatchError(runId, input.fromStepIndex);
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
function bumpRunAttempt(runId, dep) {
|
|
2025
|
+
dep.db.prepare(
|
|
2026
|
+
`UPDATE codex_cronoton_runs SET attempt = attempt + 1, modified_at = ? WHERE id = ?`
|
|
2027
|
+
).run((/* @__PURE__ */ new Date()).toISOString(), runId);
|
|
2028
|
+
}
|
|
2029
|
+
function touchRunDeadline(runId, deadlineAt, dep) {
|
|
2030
|
+
dep.db.prepare(
|
|
2031
|
+
`UPDATE codex_cronoton_runs SET deadline_at = ?, modified_at = ? WHERE id = ?`
|
|
2032
|
+
).run(deadlineAt, (/* @__PURE__ */ new Date()).toISOString(), runId);
|
|
2033
|
+
}
|
|
2034
|
+
function markRunTerminal(runId, status, dep) {
|
|
2035
|
+
const result = dep.db.prepare(
|
|
2036
|
+
`UPDATE codex_cronoton_runs
|
|
2037
|
+
SET status = ?, modified_at = ?
|
|
2038
|
+
WHERE id = ? AND status NOT IN ('succeeded', 'failed', 'abandoned')`
|
|
2039
|
+
).run(status, (/* @__PURE__ */ new Date()).toISOString(), runId);
|
|
2040
|
+
if (result.changes !== 1) {
|
|
2041
|
+
throw new RunAlreadyTerminalError(runId);
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
function upsertYield(input, dep) {
|
|
2045
|
+
const id = crypto2.randomUUID();
|
|
2046
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2047
|
+
const value = input.value === void 0 ? null : input.value;
|
|
2048
|
+
dep.db.prepare(
|
|
2049
|
+
`INSERT INTO codex_cronoton_run_yields (id, run_id, name, value_json, step_index, created_at)
|
|
2050
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
2051
|
+
ON CONFLICT(run_id, name) DO UPDATE SET
|
|
2052
|
+
value_json = excluded.value_json,
|
|
2053
|
+
step_index = excluded.step_index,
|
|
2054
|
+
created_at = excluded.created_at`
|
|
2055
|
+
).run(id, input.runId, input.name, JSON.stringify(value), input.stepIndex, now);
|
|
2056
|
+
}
|
|
2057
|
+
function getYieldPool(runId, dep) {
|
|
2058
|
+
const rows = dep.db.prepare(`SELECT name, value_json FROM codex_cronoton_run_yields WHERE run_id = ?`).all(runId);
|
|
2059
|
+
const pool = /* @__PURE__ */ Object.create(null);
|
|
2060
|
+
for (const row of rows) {
|
|
2061
|
+
pool[row.name] = JSON.parse(row.value_json);
|
|
2062
|
+
}
|
|
2063
|
+
return pool;
|
|
2064
|
+
}
|
|
2065
|
+
|
|
2066
|
+
// src/server/planners/registry.ts
|
|
2067
|
+
function normalizePlannerResult(result) {
|
|
2068
|
+
if (Array.isArray(result)) return { legs: result };
|
|
2069
|
+
return result;
|
|
2070
|
+
}
|
|
2071
|
+
var STEP_PLANNERS = /* @__PURE__ */ Object.create(null);
|
|
2072
|
+
function getStepPlanner(name) {
|
|
2073
|
+
return STEP_PLANNERS[name];
|
|
2074
|
+
}
|
|
2075
|
+
function resolvePlannerFor(step, seams, yieldPool = {}) {
|
|
2076
|
+
const planner = getStepPlanner(step.planner_name ?? "");
|
|
2077
|
+
if (!planner) return void 0;
|
|
2078
|
+
const plannerCtx = { runtime: seams.runtime, resolver: seams.resolver, config: seams.config };
|
|
2079
|
+
const resolvedStep = {
|
|
2080
|
+
...step,
|
|
2081
|
+
planner_params_json: JSON.stringify(
|
|
2082
|
+
resolveYieldRefs(JSON.parse(step.planner_params_json ?? "{}"), yieldPool)
|
|
2083
|
+
)
|
|
2084
|
+
};
|
|
2085
|
+
return { planner, plannerCtx, resolvedStep };
|
|
2086
|
+
}
|
|
2087
|
+
|
|
2088
|
+
// src/server/runs-driver.ts
|
|
2089
|
+
var PlannerNotRegisteredError = class extends Error {
|
|
2090
|
+
constructor(plannerName) {
|
|
2091
|
+
super(`planner '${plannerName}' is not registered in the StepPlanner registry`);
|
|
2092
|
+
this.name = "PlannerNotRegisteredError";
|
|
2093
|
+
}
|
|
2094
|
+
};
|
|
2095
|
+
function computeStepDeadline(now, ctx) {
|
|
2096
|
+
return new Date(now.getTime() + (ctx.config?.runStepDeadlineMs ?? RUN_STEP_DEADLINE_MS)).toISOString();
|
|
2097
|
+
}
|
|
2098
|
+
function parseLegDefinition(definitionJson) {
|
|
2099
|
+
const parsed = JSON.parse(definitionJson);
|
|
2100
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
2101
|
+
throw new Error("leg definition is not an object");
|
|
2102
|
+
}
|
|
2103
|
+
const def = parsed;
|
|
2104
|
+
if (typeof def.pactCode !== "string" || def.pactCode.length === 0) {
|
|
2105
|
+
throw new Error("leg definition is missing a non-empty pactCode");
|
|
2106
|
+
}
|
|
2107
|
+
if (!Array.isArray(def.signers)) {
|
|
2108
|
+
throw new Error("leg definition is missing a signers array");
|
|
2109
|
+
}
|
|
2110
|
+
if (typeof def.gasPayer !== "object" || def.gasPayer === null) {
|
|
2111
|
+
throw new Error("leg definition is missing a gasPayer object");
|
|
2112
|
+
}
|
|
2113
|
+
if (typeof def.config !== "object" || def.config === null) {
|
|
2114
|
+
throw new Error("leg definition is missing a config object");
|
|
2115
|
+
}
|
|
2116
|
+
return parsed;
|
|
2117
|
+
}
|
|
2118
|
+
async function handleSubmitLeg(legIndex, run, stepLegs, now, ctx) {
|
|
2119
|
+
const leg = stepLegs.find((l) => l.leg_index === legIndex);
|
|
2120
|
+
if (!leg) {
|
|
2121
|
+
await ctx.onAudit({
|
|
2122
|
+
action: "codex_cronoton_run_leg.not_found",
|
|
2123
|
+
result: "failure",
|
|
2124
|
+
targetKind: "codex_cronoton_run",
|
|
2125
|
+
targetId: run.id,
|
|
2126
|
+
detail: { codexCronotonId: run.codex_cronoton_id, stepIndex: run.step_index, legIndex }
|
|
2127
|
+
});
|
|
2128
|
+
return false;
|
|
2129
|
+
}
|
|
2130
|
+
let definition;
|
|
2131
|
+
try {
|
|
2132
|
+
definition = parseLegDefinition(leg.definition_json);
|
|
2133
|
+
} catch (err2) {
|
|
2134
|
+
await ctx.onAudit({
|
|
2135
|
+
action: "codex_cronoton_run_leg.invalid_definition",
|
|
2136
|
+
result: "failure",
|
|
2137
|
+
targetKind: "codex_cronoton_run_leg",
|
|
2138
|
+
targetId: leg.id,
|
|
2139
|
+
detail: {
|
|
2140
|
+
runId: run.id,
|
|
2141
|
+
stepIndex: run.step_index,
|
|
2142
|
+
legIndex,
|
|
2143
|
+
error: err2 instanceof Error ? err2.message : String(err2)
|
|
2144
|
+
}
|
|
2145
|
+
});
|
|
2146
|
+
return false;
|
|
2147
|
+
}
|
|
2148
|
+
const claimed = claimLegForSubmit(leg.id, now.toISOString(), { db: ctx.db });
|
|
2149
|
+
if (!claimed) {
|
|
2150
|
+
return false;
|
|
2151
|
+
}
|
|
2152
|
+
const result = await executeCodexTransaction(definition, "submit", {
|
|
2153
|
+
runtime: ctx.runtime,
|
|
2154
|
+
resolver: ctx.resolver,
|
|
2155
|
+
config: ctx.config
|
|
2156
|
+
});
|
|
2157
|
+
if (result.ok && result.requestKey && result.chainId) {
|
|
2158
|
+
markLegSubmitted(leg.id, { requestKey: result.requestKey, chainId: result.chainId }, { db: ctx.db });
|
|
2159
|
+
return true;
|
|
2160
|
+
}
|
|
2161
|
+
releaseLegClaim(leg.id, { db: ctx.db });
|
|
2162
|
+
await ctx.onAudit({
|
|
2163
|
+
action: "codex_cronoton_run_leg.submit_failed",
|
|
2164
|
+
result: "failure",
|
|
2165
|
+
targetKind: "codex_cronoton_run_leg",
|
|
2166
|
+
targetId: leg.id,
|
|
2167
|
+
detail: { runId: run.id, stepIndex: run.step_index, legIndex, error: result.error }
|
|
2168
|
+
});
|
|
2169
|
+
return false;
|
|
2170
|
+
}
|
|
2171
|
+
async function handlePoll(stepLegs, step, ctx) {
|
|
2172
|
+
const submitted = stepLegs.filter(
|
|
2173
|
+
(l) => l.status === "submitted" && l.request_key != null && l.chain_id != null
|
|
2174
|
+
);
|
|
2175
|
+
if (submitted.length === 0) return false;
|
|
2176
|
+
const byChain = /* @__PURE__ */ new Map();
|
|
2177
|
+
for (const leg of submitted) {
|
|
2178
|
+
const group = byChain.get(leg.chain_id) ?? [];
|
|
2179
|
+
group.push(leg);
|
|
2180
|
+
byChain.set(leg.chain_id, group);
|
|
2181
|
+
}
|
|
2182
|
+
let mutated = false;
|
|
2183
|
+
for (const [chainId, legsForChain] of byChain) {
|
|
2184
|
+
const client = ctx.runtime.createClient(ctx.runtime.getPactUrl(chainId));
|
|
2185
|
+
const polled = await client.pollRequestKeys?.(legsForChain.map((l) => l.request_key), chainId) ?? {};
|
|
2186
|
+
for (const leg of legsForChain) {
|
|
2187
|
+
const landed = polled[leg.request_key];
|
|
2188
|
+
if (!landed) continue;
|
|
2189
|
+
if (landed.result.status === "success") {
|
|
2190
|
+
markLegConfirmed(leg.id, { db: ctx.db });
|
|
2191
|
+
if (step.mode === "single" && step.yield_as) {
|
|
2192
|
+
upsertYield(
|
|
2193
|
+
{
|
|
2194
|
+
runId: leg.run_id,
|
|
2195
|
+
name: step.yield_as,
|
|
2196
|
+
value: landed.result.data,
|
|
2197
|
+
stepIndex: step.step_index
|
|
2198
|
+
},
|
|
2199
|
+
{ db: ctx.db }
|
|
2200
|
+
);
|
|
2201
|
+
}
|
|
2202
|
+
} else {
|
|
2203
|
+
markLegFailed(
|
|
2204
|
+
leg.id,
|
|
2205
|
+
{ errorMessage: landed.result.error?.message ?? "transaction failed on-chain" },
|
|
2206
|
+
{ db: ctx.db }
|
|
2207
|
+
);
|
|
2208
|
+
}
|
|
2209
|
+
mutated = true;
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
2212
|
+
return mutated;
|
|
2213
|
+
}
|
|
2214
|
+
function handleAdvanceStep(run, now, ctx) {
|
|
2215
|
+
if (run.step_index + 1 >= run.step_count) {
|
|
2216
|
+
markRunTerminal(run.id, "succeeded", { db: ctx.db });
|
|
2217
|
+
} else {
|
|
2218
|
+
advanceRunStep(
|
|
2219
|
+
run.id,
|
|
2220
|
+
{ fromStepIndex: run.step_index, toStepIndex: run.step_index + 1, deadlineAt: computeStepDeadline(now, ctx) },
|
|
2221
|
+
{ db: ctx.db }
|
|
2222
|
+
);
|
|
2223
|
+
}
|
|
2224
|
+
return true;
|
|
2225
|
+
}
|
|
2226
|
+
async function handleReplanStep(run, step, allRunLegs, now, ctx) {
|
|
2227
|
+
const stepHasAnyLegs = allRunLegs.some((l) => l.step_index === run.step_index);
|
|
2228
|
+
try {
|
|
2229
|
+
return await handleReplanStepInner(run, step, allRunLegs, now, ctx);
|
|
2230
|
+
} catch (err2) {
|
|
2231
|
+
if (stepHasAnyLegs || err2 instanceof RunLegAlreadyExistsError) {
|
|
2232
|
+
throw err2;
|
|
2233
|
+
}
|
|
2234
|
+
const reason = `replan-step threw: ${err2 instanceof Error ? err2.message : String(err2)}`;
|
|
2235
|
+
await handleFailRun(run, reason, ctx);
|
|
2236
|
+
throw err2;
|
|
2237
|
+
}
|
|
2238
|
+
}
|
|
2239
|
+
async function handleReplanStepInner(run, step, allRunLegs, now, ctx) {
|
|
2240
|
+
if (step.mode === "planner") {
|
|
2241
|
+
const pool2 = getYieldPool(run.id, { db: ctx.db });
|
|
2242
|
+
const resolved = resolvePlannerFor(step, ctx, pool2);
|
|
2243
|
+
if (!resolved) {
|
|
2244
|
+
throw new PlannerNotRegisteredError(step.planner_name ?? "(unnamed)");
|
|
2245
|
+
}
|
|
2246
|
+
const rawResult = await resolved.planner(resolved.resolvedStep, resolved.plannerCtx);
|
|
2247
|
+
const normalized = normalizePlannerResult(rawResult);
|
|
2248
|
+
const legs = normalized.legs;
|
|
2249
|
+
if (legs.length === 0) {
|
|
2250
|
+
if (normalized.yield !== void 0 && step.yield_as) {
|
|
2251
|
+
upsertYield(
|
|
2252
|
+
{ runId: run.id, name: step.yield_as, value: normalized.yield, stepIndex: run.step_index },
|
|
2253
|
+
{ db: ctx.db }
|
|
2254
|
+
);
|
|
2255
|
+
}
|
|
2256
|
+
return handleAdvanceStep(run, now, ctx);
|
|
2257
|
+
}
|
|
2258
|
+
const allStepLegs = allRunLegs.filter((l) => l.step_index === run.step_index);
|
|
2259
|
+
const isReplan = allStepLegs.length > 0;
|
|
2260
|
+
const newAttempt = isReplan ? run.attempt + 1 : run.attempt;
|
|
2261
|
+
const startLegIndex = isReplan ? Math.max(...allStepLegs.map((l) => l.leg_index)) + 1 : 0;
|
|
2262
|
+
legs.forEach((leg, i) => {
|
|
2263
|
+
insertRunLeg(
|
|
2264
|
+
{
|
|
2265
|
+
runId: run.id,
|
|
2266
|
+
stepIndex: run.step_index,
|
|
2267
|
+
legIndex: startLegIndex + i,
|
|
2268
|
+
definitionJson: JSON.stringify(leg),
|
|
2269
|
+
attempt: newAttempt
|
|
2270
|
+
},
|
|
2271
|
+
{ db: ctx.db }
|
|
2272
|
+
);
|
|
2273
|
+
});
|
|
2274
|
+
if (isReplan) {
|
|
2275
|
+
bumpRunAttempt(run.id, { db: ctx.db });
|
|
2276
|
+
touchRunDeadline(run.id, computeStepDeadline(now, ctx), { db: ctx.db });
|
|
2277
|
+
}
|
|
2278
|
+
if (normalized.yield !== void 0 && step.yield_as) {
|
|
2279
|
+
upsertYield(
|
|
2280
|
+
{ runId: run.id, name: step.yield_as, value: normalized.yield, stepIndex: run.step_index },
|
|
2281
|
+
{ db: ctx.db }
|
|
2282
|
+
);
|
|
2283
|
+
}
|
|
2284
|
+
if (!isReplan) {
|
|
2285
|
+
advanceRunStep(
|
|
2286
|
+
run.id,
|
|
2287
|
+
{ fromStepIndex: run.step_index, toStepIndex: run.step_index, deadlineAt: computeStepDeadline(now, ctx) },
|
|
2288
|
+
{ db: ctx.db }
|
|
2289
|
+
);
|
|
2290
|
+
}
|
|
2291
|
+
return true;
|
|
2292
|
+
}
|
|
2293
|
+
const pool = getYieldPool(run.id, { db: ctx.db });
|
|
2294
|
+
const resolvedStep = resolveSingleStepPayload(step, pool);
|
|
2295
|
+
const definition = stepRowToDefinition(resolvedStep);
|
|
2296
|
+
insertRunLeg(
|
|
2297
|
+
{ runId: run.id, stepIndex: run.step_index, legIndex: 0, definitionJson: JSON.stringify(definition) },
|
|
2298
|
+
{ db: ctx.db }
|
|
2299
|
+
);
|
|
2300
|
+
advanceRunStep(
|
|
2301
|
+
run.id,
|
|
2302
|
+
{ fromStepIndex: run.step_index, toStepIndex: run.step_index, deadlineAt: computeStepDeadline(now, ctx) },
|
|
2303
|
+
{ db: ctx.db }
|
|
2304
|
+
);
|
|
2305
|
+
return true;
|
|
2306
|
+
}
|
|
2307
|
+
async function handleFailRun(run, reason, ctx) {
|
|
2308
|
+
markRunTerminal(run.id, "failed", { db: ctx.db });
|
|
2309
|
+
await ctx.onAudit({
|
|
2310
|
+
action: "codex_cronoton_run.failed",
|
|
2311
|
+
result: "failure",
|
|
2312
|
+
targetKind: "codex_cronoton_run",
|
|
2313
|
+
targetId: run.id,
|
|
2314
|
+
detail: { codexCronotonId: run.codex_cronoton_id, stepIndex: run.step_index, reason }
|
|
2315
|
+
});
|
|
2316
|
+
return true;
|
|
2317
|
+
}
|
|
2318
|
+
async function executeAction(action, run, step, stepLegs, allRunLegs, now, ctx) {
|
|
2319
|
+
switch (action.kind) {
|
|
2320
|
+
case "submit-leg":
|
|
2321
|
+
return handleSubmitLeg(action.legIndex, run, stepLegs, now, ctx);
|
|
2322
|
+
case "poll":
|
|
2323
|
+
return handlePoll(stepLegs, step, ctx);
|
|
2324
|
+
case "advance-step":
|
|
2325
|
+
return handleAdvanceStep(run, now, ctx);
|
|
2326
|
+
case "replan-step":
|
|
2327
|
+
return handleReplanStep(run, step, allRunLegs, now, ctx);
|
|
2328
|
+
case "fail-run":
|
|
2329
|
+
return handleFailRun(run, action.reason, ctx);
|
|
2330
|
+
case "wait":
|
|
2331
|
+
return false;
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
async function driveRunOnce(runId, now, ctx) {
|
|
2335
|
+
const initialRun = getRun(runId, { db: ctx.db });
|
|
2336
|
+
if (!initialRun) return;
|
|
2337
|
+
const steps = listStepsForCronoton(initialRun.codex_cronoton_id, { db: ctx.db });
|
|
2338
|
+
for (; ; ) {
|
|
2339
|
+
const run = getRun(runId, { db: ctx.db });
|
|
2340
|
+
if (!run) return;
|
|
2341
|
+
const step = steps.find((s) => s.step_index === run.step_index);
|
|
2342
|
+
if (!step) {
|
|
2343
|
+
markRunTerminal(runId, "failed", { db: ctx.db });
|
|
2344
|
+
await ctx.onAudit({
|
|
2345
|
+
action: "codex_cronoton_run.step_missing",
|
|
2346
|
+
result: "failure",
|
|
2347
|
+
targetKind: "codex_cronoton_run",
|
|
2348
|
+
targetId: runId,
|
|
2349
|
+
detail: { codexCronotonId: run.codex_cronoton_id, stepIndex: run.step_index }
|
|
2350
|
+
});
|
|
2351
|
+
return;
|
|
2352
|
+
}
|
|
2353
|
+
const allRunLegs = listRunLegs(runId, { db: ctx.db });
|
|
2354
|
+
const stepLegs = allRunLegs.filter((l) => l.step_index === run.step_index && l.attempt === run.attempt);
|
|
2355
|
+
const legs = stepLegs.map((l) => ({ legIndex: l.leg_index, status: l.status }));
|
|
2356
|
+
const policy = {
|
|
2357
|
+
stepMode: step.mode === "single" ? "serial" : "parallel",
|
|
2358
|
+
canReplan: step.mode === "planner",
|
|
2359
|
+
maxReplanAttempts: ctx.config?.maxReplanAttempts ?? DEFAULT_MAX_REPLAN_ATTEMPTS
|
|
2360
|
+
};
|
|
2361
|
+
const runState = {
|
|
2362
|
+
status: run.status,
|
|
2363
|
+
stepIndex: run.step_index,
|
|
2364
|
+
stepCount: run.step_count,
|
|
2365
|
+
deadlineAt: run.deadline_at,
|
|
2366
|
+
attempt: run.attempt
|
|
2367
|
+
};
|
|
2368
|
+
const actions = advanceRun(runState, legs, now, policy);
|
|
2369
|
+
let progressed = false;
|
|
2370
|
+
for (const action of actions) {
|
|
2371
|
+
const mutated = await executeAction(action, run, step, stepLegs, allRunLegs, now, ctx);
|
|
2372
|
+
if (mutated) progressed = true;
|
|
2373
|
+
}
|
|
2374
|
+
if (!progressed) return;
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
1580
2377
|
|
|
1581
2378
|
// src/handlers/http.ts
|
|
1582
2379
|
function json(status, body) {
|
|
@@ -1739,4 +2536,4 @@ async function runGated2(fn, options = {}) {
|
|
|
1739
2536
|
}
|
|
1740
2537
|
}
|
|
1741
2538
|
|
|
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 };
|
|
2539
|
+
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 };
|