@ancientpantheon/khronoton-core 0.2.0 → 0.3.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 +10 -0
- package/README.md +9 -1
- package/dist/PactCodeMirror-HQTGE2K3.js +64 -0
- package/dist/chunk-DK4CDPXH.js +379 -0
- package/dist/chunk-U3F5HEHO.js +1639 -0
- package/dist/context-BKtdrA2B.d.ts +363 -0
- package/dist/handlers/batch.d.ts +21 -0
- package/dist/handlers/batch.js +57 -0
- package/dist/handlers/context.d.ts +94 -0
- package/dist/handlers/context.js +75 -0
- package/dist/handlers/cronoton.d.ts +70 -0
- package/dist/handlers/cronoton.js +165 -0
- package/dist/handlers/execute.d.ts +30 -0
- package/dist/handlers/execute.js +227 -0
- package/dist/handlers/http.d.ts +85 -0
- package/dist/handlers/http.js +84 -0
- package/dist/handlers/index.d.ts +27 -0
- package/dist/handlers/index.js +34 -0
- package/dist/handlers/read.d.ts +29 -0
- package/dist/handlers/read.js +94 -0
- package/dist/hooks/index.d.ts +143 -0
- package/dist/hooks/index.js +2 -0
- package/dist/provider/index.d.ts +421 -0
- package/dist/provider/index.js +675 -0
- package/dist/types-u_nUX1Bg.d.ts +222 -0
- package/dist/ui/index.d.ts +235 -0
- package/dist/ui/index.js +3646 -0
- package/dist/ui.css +35 -0
- package/package.json +52 -5
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cronoton-lifecycle handlers: the confirm-gated commit/edit/pause/resume/delete
|
|
3
|
+
* half of the codex-cronoton route surface.
|
|
4
|
+
*
|
|
5
|
+
* Each handler is a thin, framework-agnostic adapter over the `/server` store: it
|
|
6
|
+
* runs behind the CONFIRM gate ({@link withConfirm} — every operation here mutates,
|
|
7
|
+
* so a fresh admin-confirm is demanded), shapes the normalized request body into
|
|
8
|
+
* the store's input, and lets the store's typed errors flow back through
|
|
9
|
+
* {@link mapStoreError} (a `not found` → 404, any other validation → 400, a
|
|
10
|
+
* terminal row → 409). The store functions are imported under `store*` aliases so
|
|
11
|
+
* these handlers can carry the canonical contract names.
|
|
12
|
+
*
|
|
13
|
+
* Two invariants live in this layer rather than the store:
|
|
14
|
+
* - **Shape validation (REQ-H01):** a malformed commit/edit body is a CLIENT error
|
|
15
|
+
* (400), so the body adapters throw {@link CodexCronotonValidationError} for a
|
|
16
|
+
* missing envelope/schedule instead of letting a `TypeError` become a 500.
|
|
17
|
+
* - **Server-resolver delete-lock (REQ-H05):** a row bound to a server resolver is
|
|
18
|
+
* a system cronoton that must be paused, never deleted — the delete handler
|
|
19
|
+
* loads the row FIRST and refuses with 409 before the store's unconditional
|
|
20
|
+
* delete would run.
|
|
21
|
+
*
|
|
22
|
+
* Commit and delete emit an audit event through `ctx.onAudit` (the store does not
|
|
23
|
+
* audit these transitions, so there is no double-audit); edit/pause/resume carry
|
|
24
|
+
* no audit here.
|
|
25
|
+
*/
|
|
26
|
+
import { type CodexGasPayer, type CodexSigner, type CodexTxConfig, type ScheduleConfig, type ScheduleMode } from "../server/index.js";
|
|
27
|
+
import { type HandlerContext } from "./context.js";
|
|
28
|
+
import { type HandlerRequest, type HandlerResponse } from "./http.js";
|
|
29
|
+
/**
|
|
30
|
+
* The transaction envelope half of a {@link CommitBody}: everything that
|
|
31
|
+
* describes WHAT fires, independent of WHEN. Maps 1:1 onto the store input's
|
|
32
|
+
* definition fields.
|
|
33
|
+
*/
|
|
34
|
+
export interface CommitEnvelope {
|
|
35
|
+
pactCode: string;
|
|
36
|
+
config: CodexTxConfig;
|
|
37
|
+
payload?: Record<string, unknown>;
|
|
38
|
+
gasPayer: CodexGasPayer;
|
|
39
|
+
signers: CodexSigner[];
|
|
40
|
+
serverResolver?: string;
|
|
41
|
+
externalFireable?: boolean;
|
|
42
|
+
runtimeArgKeys?: string[];
|
|
43
|
+
}
|
|
44
|
+
/** The schedule half of a {@link CommitBody}: mode + its config. */
|
|
45
|
+
export interface CommitSchedule {
|
|
46
|
+
mode: ScheduleMode;
|
|
47
|
+
config: ScheduleConfig;
|
|
48
|
+
}
|
|
49
|
+
/** The client-facing commit payload the route accepts (POST body). */
|
|
50
|
+
export interface CommitBody {
|
|
51
|
+
name: string;
|
|
52
|
+
description?: string | null;
|
|
53
|
+
envelope: CommitEnvelope;
|
|
54
|
+
schedule: CommitSchedule;
|
|
55
|
+
}
|
|
56
|
+
/** POST / — commit a new codex cronoton. Confirm-gated; 201 on success. */
|
|
57
|
+
export declare function commitCodexCronoton(ctx: HandlerContext, req: HandlerRequest): Promise<HandlerResponse>;
|
|
58
|
+
/** PATCH /[id] — apply an at-next-fire edit. Confirm-gated; 404 when missing. */
|
|
59
|
+
export declare function editCodexCronoton(ctx: HandlerContext, req: HandlerRequest): Promise<HandlerResponse>;
|
|
60
|
+
/** PATCH /[id]/pause — pause a running row. Confirm-gated; 409 when terminal. */
|
|
61
|
+
export declare function pauseCodexCronoton(ctx: HandlerContext, req: HandlerRequest): Promise<HandlerResponse>;
|
|
62
|
+
/** PATCH /[id]/resume — resume a paused row. Confirm-gated; 409 when terminal. */
|
|
63
|
+
export declare function resumeCodexCronoton(ctx: HandlerContext, req: HandlerRequest): Promise<HandlerResponse>;
|
|
64
|
+
/**
|
|
65
|
+
* DELETE /[id] — remove a codex cronoton. Confirm-gated. A row bound to a server
|
|
66
|
+
* resolver is a SYSTEM cronoton: it is delete-locked (pause to disable instead),
|
|
67
|
+
* so the handler loads the row first and refuses with 409 before the store's
|
|
68
|
+
* unconditional delete would run (REQ-H05).
|
|
69
|
+
*/
|
|
70
|
+
export declare function deleteCodexCronoton(ctx: HandlerContext, req: HandlerRequest): Promise<HandlerResponse>;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cronoton-lifecycle handlers: the confirm-gated commit/edit/pause/resume/delete
|
|
3
|
+
* half of the codex-cronoton route surface.
|
|
4
|
+
*
|
|
5
|
+
* Each handler is a thin, framework-agnostic adapter over the `/server` store: it
|
|
6
|
+
* runs behind the CONFIRM gate ({@link withConfirm} — every operation here mutates,
|
|
7
|
+
* so a fresh admin-confirm is demanded), shapes the normalized request body into
|
|
8
|
+
* the store's input, and lets the store's typed errors flow back through
|
|
9
|
+
* {@link mapStoreError} (a `not found` → 404, any other validation → 400, a
|
|
10
|
+
* terminal row → 409). The store functions are imported under `store*` aliases so
|
|
11
|
+
* these handlers can carry the canonical contract names.
|
|
12
|
+
*
|
|
13
|
+
* Two invariants live in this layer rather than the store:
|
|
14
|
+
* - **Shape validation (REQ-H01):** a malformed commit/edit body is a CLIENT error
|
|
15
|
+
* (400), so the body adapters throw {@link CodexCronotonValidationError} for a
|
|
16
|
+
* missing envelope/schedule instead of letting a `TypeError` become a 500.
|
|
17
|
+
* - **Server-resolver delete-lock (REQ-H05):** a row bound to a server resolver is
|
|
18
|
+
* a system cronoton that must be paused, never deleted — the delete handler
|
|
19
|
+
* loads the row FIRST and refuses with 409 before the store's unconditional
|
|
20
|
+
* delete would run.
|
|
21
|
+
*
|
|
22
|
+
* Commit and delete emit an audit event through `ctx.onAudit` (the store does not
|
|
23
|
+
* audit these transitions, so there is no double-audit); edit/pause/resume carry
|
|
24
|
+
* no audit here.
|
|
25
|
+
*/
|
|
26
|
+
import { CodexCronotonValidationError, commitCodexCronoton as storeCommit, deleteCodexCronoton as storeDelete, editCodexCronoton as storeEdit, getCodexCronoton as storeGet, pauseCodexCronoton as storePause, resumeCodexCronoton as storeResume, } from "../server/index.js";
|
|
27
|
+
import { withConfirm } from "./context.js";
|
|
28
|
+
import { json } from "./http.js";
|
|
29
|
+
function requireObject(value, message) {
|
|
30
|
+
if (!value || typeof value !== "object") {
|
|
31
|
+
throw new CodexCronotonValidationError(message);
|
|
32
|
+
}
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
/** Attribute a write to the gate identity, falling back to a system marker. */
|
|
36
|
+
function createdByOf(identity) {
|
|
37
|
+
return identity?.email ?? identity?.id ?? "system";
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Adapt a normalized `CommitBody` into the store's `CommitCodexCronotonInput`.
|
|
41
|
+
* A missing/mistyped body, envelope, or schedule is surfaced as a 400 client
|
|
42
|
+
* error (the store then validates the field-level shape — empty name, bad
|
|
43
|
+
* config — and throws its own 400/404).
|
|
44
|
+
*/
|
|
45
|
+
function toCommitInput(body, createdBy) {
|
|
46
|
+
const b = requireObject(body, "request body must be a commit object");
|
|
47
|
+
const envelope = requireObject(b.envelope, "envelope is required");
|
|
48
|
+
const schedule = requireObject(b.schedule, "schedule is required");
|
|
49
|
+
return {
|
|
50
|
+
name: b.name,
|
|
51
|
+
description: b.description ?? null,
|
|
52
|
+
pactCode: envelope.pactCode,
|
|
53
|
+
config: envelope.config,
|
|
54
|
+
payload: envelope.payload ?? {},
|
|
55
|
+
gasPayer: envelope.gasPayer,
|
|
56
|
+
signers: envelope.signers ?? [],
|
|
57
|
+
scheduleMode: schedule.mode,
|
|
58
|
+
scheduleConfig: schedule.config,
|
|
59
|
+
createdBy,
|
|
60
|
+
serverResolver: envelope.serverResolver,
|
|
61
|
+
externalFireable: envelope.externalFireable,
|
|
62
|
+
runtimeArgKeys: envelope.runtimeArgKeys,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** Adapt a `Partial<CommitBody>` into a store edit patch (apply-at-next-fire). */
|
|
66
|
+
function toEditPatch(body) {
|
|
67
|
+
const b = requireObject(body, "request body must be an edit object");
|
|
68
|
+
const patch = {};
|
|
69
|
+
if (b.name !== undefined)
|
|
70
|
+
patch.name = b.name;
|
|
71
|
+
if (b.description !== undefined)
|
|
72
|
+
patch.description = b.description;
|
|
73
|
+
const env = b.envelope;
|
|
74
|
+
if (env && typeof env === "object") {
|
|
75
|
+
const e = env;
|
|
76
|
+
if (e.pactCode !== undefined)
|
|
77
|
+
patch.pactCode = e.pactCode;
|
|
78
|
+
if (e.config !== undefined)
|
|
79
|
+
patch.config = e.config;
|
|
80
|
+
if (e.payload !== undefined)
|
|
81
|
+
patch.payload = e.payload;
|
|
82
|
+
if (e.gasPayer !== undefined)
|
|
83
|
+
patch.gasPayer = e.gasPayer;
|
|
84
|
+
if (e.signers !== undefined)
|
|
85
|
+
patch.signers = e.signers;
|
|
86
|
+
if (e.serverResolver !== undefined)
|
|
87
|
+
patch.serverResolver = e.serverResolver;
|
|
88
|
+
}
|
|
89
|
+
const sched = b.schedule;
|
|
90
|
+
if (sched && typeof sched === "object") {
|
|
91
|
+
const s = sched;
|
|
92
|
+
patch.scheduleMode = s.mode;
|
|
93
|
+
patch.scheduleConfig = s.config;
|
|
94
|
+
}
|
|
95
|
+
return patch;
|
|
96
|
+
}
|
|
97
|
+
function paramId(req) {
|
|
98
|
+
return req.params?.id ?? "";
|
|
99
|
+
}
|
|
100
|
+
// ── Handlers ─────────────────────────────────────────────────────────────────
|
|
101
|
+
/** POST / — commit a new codex cronoton. Confirm-gated; 201 on success. */
|
|
102
|
+
export async function commitCodexCronoton(ctx, req) {
|
|
103
|
+
return withConfirm(ctx, req, async (identity) => {
|
|
104
|
+
const input = toCommitInput(req.body, createdByOf(identity));
|
|
105
|
+
const { id, nextFireAt } = storeCommit(input, { db: ctx.db });
|
|
106
|
+
await ctx.onAudit?.({
|
|
107
|
+
action: "codex_cronoton.commit",
|
|
108
|
+
result: "ok",
|
|
109
|
+
targetKind: "codex_cronoton",
|
|
110
|
+
targetId: id,
|
|
111
|
+
detail: { name: input.name },
|
|
112
|
+
});
|
|
113
|
+
return json(201, { ok: true, codexCronotonId: id, nextFireAt });
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
/** PATCH /[id] — apply an at-next-fire edit. Confirm-gated; 404 when missing. */
|
|
117
|
+
export async function editCodexCronoton(ctx, req) {
|
|
118
|
+
return withConfirm(ctx, req, async () => {
|
|
119
|
+
const { nextFireAt } = storeEdit(paramId(req), toEditPatch(req.body), { db: ctx.db });
|
|
120
|
+
return json(200, { ok: true, nextFireAt });
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
/** PATCH /[id]/pause — pause a running row. Confirm-gated; 409 when terminal. */
|
|
124
|
+
export async function pauseCodexCronoton(ctx, req) {
|
|
125
|
+
return withConfirm(ctx, req, async () => {
|
|
126
|
+
const { status, nextFireAt } = storePause(paramId(req), { db: ctx.db });
|
|
127
|
+
return json(200, { ok: true, status, nextFireAt });
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
/** PATCH /[id]/resume — resume a paused row. Confirm-gated; 409 when terminal. */
|
|
131
|
+
export async function resumeCodexCronoton(ctx, req) {
|
|
132
|
+
return withConfirm(ctx, req, async () => {
|
|
133
|
+
const { status, nextFireAt } = storeResume(paramId(req), { db: ctx.db });
|
|
134
|
+
return json(200, { ok: true, status, nextFireAt });
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* DELETE /[id] — remove a codex cronoton. Confirm-gated. A row bound to a server
|
|
139
|
+
* resolver is a SYSTEM cronoton: it is delete-locked (pause to disable instead),
|
|
140
|
+
* so the handler loads the row first and refuses with 409 before the store's
|
|
141
|
+
* unconditional delete would run (REQ-H05).
|
|
142
|
+
*/
|
|
143
|
+
export async function deleteCodexCronoton(ctx, req) {
|
|
144
|
+
return withConfirm(ctx, req, async () => {
|
|
145
|
+
const id = paramId(req);
|
|
146
|
+
const row = storeGet(id, { db: ctx.db });
|
|
147
|
+
if (!row)
|
|
148
|
+
throw new CodexCronotonValidationError("not found");
|
|
149
|
+
if (row.server_resolver) {
|
|
150
|
+
return json(409, {
|
|
151
|
+
error: "System cronoton — cannot be deleted. Pause it to disable instead.",
|
|
152
|
+
protected: true,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
storeDelete(id, { db: ctx.db });
|
|
156
|
+
await ctx.onAudit?.({
|
|
157
|
+
action: "codex_cronoton.delete",
|
|
158
|
+
result: "ok",
|
|
159
|
+
targetKind: "codex_cronoton",
|
|
160
|
+
targetId: id,
|
|
161
|
+
detail: { serverResolver: row.server_resolver ?? null },
|
|
162
|
+
});
|
|
163
|
+
return json(200, { ok: true });
|
|
164
|
+
});
|
|
165
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Handler } from "./context.js";
|
|
2
|
+
/**
|
|
3
|
+
* Preview a transaction WITHOUT submitting. Returns the full simulate union
|
|
4
|
+
* (REQ-H11) at HTTP 200 even when `ok` is false. When the envelope names a
|
|
5
|
+
* single-tx server resolver, `plannedCount`/`postponed` are derived GENERICALLY
|
|
6
|
+
* from `resolveServerVars` (plan length / empty plan) and the resolved payload
|
|
7
|
+
* is merged so the preview reflects the real fire — never coupled to a name.
|
|
8
|
+
*/
|
|
9
|
+
export declare const simulateCodexTx: Handler;
|
|
10
|
+
/**
|
|
11
|
+
* Fire a committed cronoton on demand, outside its schedule. A multi-tx
|
|
12
|
+
* server-resolved row is queued (202) rather than fired inline (REQ-H06); every
|
|
13
|
+
* other row fires + records exactly one fire row and returns HTTP 200 with the
|
|
14
|
+
* fire outcome in the body (`ok:false` still 200 — REQ-H04).
|
|
15
|
+
*/
|
|
16
|
+
export declare const executeNow: Handler;
|
|
17
|
+
/**
|
|
18
|
+
* Fire a runtime-arg cronoton with trigger-supplied args. The supplied args must
|
|
19
|
+
* match the row's declared keys exactly (else 400); valid args are merged into
|
|
20
|
+
* the payload before firing, then the shared fire + record path runs (200 on
|
|
21
|
+
* `ok:false`).
|
|
22
|
+
*/
|
|
23
|
+
export declare const triggerCronoton: Handler;
|
|
24
|
+
/**
|
|
25
|
+
* Reconcile a stale `failure` fire to its true on-chain `success` by attaching
|
|
26
|
+
* the confirmed request key (e.g. an nginx 504 that hid a landed submit). The
|
|
27
|
+
* key must match the request-key shape (else 400); a fire that is not found or
|
|
28
|
+
* not in `failure` yields 404 `No failed fire to recover`.
|
|
29
|
+
*/
|
|
30
|
+
export declare const recoverFire: Handler;
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Execution handlers: `simulateCodexTx`, `executeNow`, `triggerCronoton`,
|
|
3
|
+
* `recoverFire`.
|
|
4
|
+
*
|
|
5
|
+
* These are the mutate-tier route surface that DRIVES the chain: a preview
|
|
6
|
+
* (`simulate`), an on-demand fire (`executeNow`), a runtime-arg fire
|
|
7
|
+
* (`triggerCronoton`), and the recover-a-stale-failure reconciliation
|
|
8
|
+
* (`recoverFire`). All four run behind the CONFIRM gate.
|
|
9
|
+
*
|
|
10
|
+
* ── 200-on-`ok:false` (REQ-H04) ───────────────────────────────────────────────
|
|
11
|
+
* `simulate`/`executeNow`/`triggerCronoton` return HTTP **200** even when the
|
|
12
|
+
* operation's own `ok` is false — a chain/build failure rides in the body
|
|
13
|
+
* (`{ ok:false, error }`) and the caller checks `result.ok`. Only a gate
|
|
14
|
+
* rejection (401) or a request-shape/validation error (400/404) is a non-200.
|
|
15
|
+
*
|
|
16
|
+
* ── 202-queued multi-tx (REQ-H06) ─────────────────────────────────────────────
|
|
17
|
+
* A row bound to a registered **multi-tx** server resolver is NOT fired inline:
|
|
18
|
+
* this package ships no concrete multi-tx orchestrator, so `executeNow` returns
|
|
19
|
+
* **202 `{ ok:true, queued:true }`** and the consumer's resolver runs the async
|
|
20
|
+
* multi-transaction job. Ordinary + single-tx rows fire inline through the shared
|
|
21
|
+
* `fireByServerResolver` + `recordFire` path (mirroring the tick), so a failed
|
|
22
|
+
* fire still records a `failure` row.
|
|
23
|
+
*/
|
|
24
|
+
import { json, err } from "./http.js";
|
|
25
|
+
import { withConfirm } from "./context.js";
|
|
26
|
+
import { executeCodexTransaction, fireByServerResolver, getServerResolver, resolveServerVars, getCodexCronoton, recordFire, recoverFire as recoverFireInStore, applyTerminalIntent, rowToDefinition, rowRuntimeArgKeys, computeDefinitionFingerprint, validateRuntimeArgs, applyRuntimeArgs, } from "../server/index.js";
|
|
27
|
+
/** A landed on-chain request key: 40–48 URL-safe base64 chars. */
|
|
28
|
+
const REQUEST_KEY_RE = /^[A-Za-z0-9_-]{40,48}$/;
|
|
29
|
+
/** Terminal statuses cannot be fired on demand (their single/spent attempt is done). */
|
|
30
|
+
const TERMINAL_STATUSES = new Set(["completed", "error"]);
|
|
31
|
+
/**
|
|
32
|
+
* Build the executor definition from a simulate envelope. The envelope carries
|
|
33
|
+
* the same tx parts as a committed row's definition; missing optionals fall back
|
|
34
|
+
* to their neutral defaults so a caller can preview a minimal transaction.
|
|
35
|
+
*/
|
|
36
|
+
function envelopeToDefinition(envelope) {
|
|
37
|
+
return {
|
|
38
|
+
pactCode: typeof envelope.pactCode === "string" ? envelope.pactCode : "",
|
|
39
|
+
config: envelope.config,
|
|
40
|
+
payload: envelope.payload ?? {},
|
|
41
|
+
gasPayer: envelope.gasPayer ?? { type: "gas-station" },
|
|
42
|
+
signers: envelope.signers ?? [],
|
|
43
|
+
scheduleKind: envelope.scheduleKind,
|
|
44
|
+
serverResolver: typeof envelope.serverResolver === "string" ? envelope.serverResolver : undefined,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** The pretty chain payload the detail view renders: `rawResult.data` when present. */
|
|
48
|
+
function chainDataFrom(rawResult) {
|
|
49
|
+
if (rawResult && typeof rawResult === "object" && "data" in rawResult) {
|
|
50
|
+
return rawResult.data;
|
|
51
|
+
}
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Fire a loaded row inline through the shared dispatcher, record exactly one
|
|
56
|
+
* fire row (success or failure), and apply the one-time terminal transition —
|
|
57
|
+
* the same fire → record → finalize path the tick runs, minus the pre-fire
|
|
58
|
+
* claim (an on-demand fire has no scheduler race to guard against).
|
|
59
|
+
*/
|
|
60
|
+
async function fireAndRecord(ctx, row, definition) {
|
|
61
|
+
const result = await fireByServerResolver(definition, row, {
|
|
62
|
+
runtime: ctx.runtime,
|
|
63
|
+
resolver: ctx.resolver,
|
|
64
|
+
config: ctx.config,
|
|
65
|
+
db: ctx.db,
|
|
66
|
+
});
|
|
67
|
+
const fingerprint = computeDefinitionFingerprint(row);
|
|
68
|
+
const fireId = recordFire({
|
|
69
|
+
codexCronotonId: row.id,
|
|
70
|
+
jobId: null,
|
|
71
|
+
firedAt: new Date().toISOString(),
|
|
72
|
+
status: result.ok ? "success" : "failure",
|
|
73
|
+
requestKey: result.requestKey,
|
|
74
|
+
chainId: result.chainId,
|
|
75
|
+
errorMessage: result.error,
|
|
76
|
+
chainResponse: result.rawResult,
|
|
77
|
+
definitionFingerprint: fingerprint,
|
|
78
|
+
}, { db: ctx.db, resolveFireMode: ctx.resolveFireMode });
|
|
79
|
+
if ((definition.scheduleKind ?? "recurring") === "one-time") {
|
|
80
|
+
applyTerminalIntent(row.id, result.terminalIntent, { db: ctx.db });
|
|
81
|
+
}
|
|
82
|
+
await ctx.onAudit?.({
|
|
83
|
+
action: result.ok ? "codex_cronoton.fire" : "codex_cronoton.fire_failed",
|
|
84
|
+
result: result.ok ? "success" : "failure",
|
|
85
|
+
targetKind: "codex_cronoton",
|
|
86
|
+
targetId: row.id,
|
|
87
|
+
detail: {
|
|
88
|
+
codexCronotonId: row.id,
|
|
89
|
+
fireId,
|
|
90
|
+
requestKey: result.requestKey,
|
|
91
|
+
chainId: result.chainId,
|
|
92
|
+
actor: "ancient",
|
|
93
|
+
definitionFingerprint: fingerprint,
|
|
94
|
+
errorMessage: result.error,
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
return { result, fireId };
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Preview a transaction WITHOUT submitting. Returns the full simulate union
|
|
101
|
+
* (REQ-H11) at HTTP 200 even when `ok` is false. When the envelope names a
|
|
102
|
+
* single-tx server resolver, `plannedCount`/`postponed` are derived GENERICALLY
|
|
103
|
+
* from `resolveServerVars` (plan length / empty plan) and the resolved payload
|
|
104
|
+
* is merged so the preview reflects the real fire — never coupled to a name.
|
|
105
|
+
*/
|
|
106
|
+
export const simulateCodexTx = (ctx, req) => withConfirm(ctx, req, async () => {
|
|
107
|
+
const body = (req.body ?? {});
|
|
108
|
+
if (!body.envelope || typeof body.envelope !== "object") {
|
|
109
|
+
return err(400, "envelope is required");
|
|
110
|
+
}
|
|
111
|
+
let definition = envelopeToDefinition(body.envelope);
|
|
112
|
+
let plannedCount;
|
|
113
|
+
let postponed;
|
|
114
|
+
if (definition.serverResolver) {
|
|
115
|
+
const resolution = resolveServerVars(definition.serverResolver, { db: ctx.db });
|
|
116
|
+
if (resolution) {
|
|
117
|
+
plannedCount = resolution.plan.length;
|
|
118
|
+
postponed = resolution.plan.length === 0;
|
|
119
|
+
definition = {
|
|
120
|
+
...definition,
|
|
121
|
+
payload: { ...definition.payload, ...resolution.payload },
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const result = await executeCodexTransaction(definition, "simulate", {
|
|
126
|
+
runtime: ctx.runtime,
|
|
127
|
+
resolver: ctx.resolver,
|
|
128
|
+
config: ctx.config,
|
|
129
|
+
});
|
|
130
|
+
return json(200, {
|
|
131
|
+
ok: result.ok,
|
|
132
|
+
calibratedGasLimit: result.calibratedGasLimit,
|
|
133
|
+
gasUsed: result.gasUsed,
|
|
134
|
+
error: result.error,
|
|
135
|
+
rawResult: result.rawResult,
|
|
136
|
+
postponed,
|
|
137
|
+
plannedCount,
|
|
138
|
+
chainData: chainDataFrom(result.rawResult),
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
/**
|
|
142
|
+
* Fire a committed cronoton on demand, outside its schedule. A multi-tx
|
|
143
|
+
* server-resolved row is queued (202) rather than fired inline (REQ-H06); every
|
|
144
|
+
* other row fires + records exactly one fire row and returns HTTP 200 with the
|
|
145
|
+
* fire outcome in the body (`ok:false` still 200 — REQ-H04).
|
|
146
|
+
*/
|
|
147
|
+
export const executeNow = (ctx, req) => withConfirm(ctx, req, async () => {
|
|
148
|
+
const id = req.params?.id;
|
|
149
|
+
if (!id)
|
|
150
|
+
return err(400, "cronoton id is required");
|
|
151
|
+
const row = getCodexCronoton(id, { db: ctx.db });
|
|
152
|
+
if (!row)
|
|
153
|
+
return err(404, "not found");
|
|
154
|
+
if (row.status === "paused")
|
|
155
|
+
return err(400, "cannot execute a paused cronoton");
|
|
156
|
+
if (TERMINAL_STATUSES.has(row.status)) {
|
|
157
|
+
return err(400, "cannot execute a terminal cronoton");
|
|
158
|
+
}
|
|
159
|
+
const resolverName = row.server_resolver ?? undefined;
|
|
160
|
+
if (resolverName && getServerResolver(resolverName)?.kind === "multi-tx") {
|
|
161
|
+
return json(202, { ok: true, queued: true });
|
|
162
|
+
}
|
|
163
|
+
const { result, fireId } = await fireAndRecord(ctx, row, rowToDefinition(row));
|
|
164
|
+
return json(200, {
|
|
165
|
+
ok: result.ok,
|
|
166
|
+
fireId,
|
|
167
|
+
requestKey: result.requestKey,
|
|
168
|
+
error: result.error,
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
/**
|
|
172
|
+
* Fire a runtime-arg cronoton with trigger-supplied args. The supplied args must
|
|
173
|
+
* match the row's declared keys exactly (else 400); valid args are merged into
|
|
174
|
+
* the payload before firing, then the shared fire + record path runs (200 on
|
|
175
|
+
* `ok:false`).
|
|
176
|
+
*/
|
|
177
|
+
export const triggerCronoton = (ctx, req) => withConfirm(ctx, req, async () => {
|
|
178
|
+
const id = req.params?.id;
|
|
179
|
+
if (!id)
|
|
180
|
+
return err(400, "cronoton id is required");
|
|
181
|
+
const row = getCodexCronoton(id, { db: ctx.db });
|
|
182
|
+
if (!row)
|
|
183
|
+
return err(404, "not found");
|
|
184
|
+
if (row.status === "paused")
|
|
185
|
+
return err(400, "cannot trigger a paused cronoton");
|
|
186
|
+
if (TERMINAL_STATUSES.has(row.status)) {
|
|
187
|
+
return err(400, "cannot trigger a terminal cronoton");
|
|
188
|
+
}
|
|
189
|
+
const args = req.body?.args;
|
|
190
|
+
const validated = validateRuntimeArgs(rowRuntimeArgKeys(row), args);
|
|
191
|
+
if (!validated.ok)
|
|
192
|
+
return err(400, validated.error);
|
|
193
|
+
const definition = applyRuntimeArgs(rowToDefinition(row), validated.args);
|
|
194
|
+
const { result, fireId } = await fireAndRecord(ctx, row, definition);
|
|
195
|
+
return json(200, {
|
|
196
|
+
ok: result.ok,
|
|
197
|
+
fireId,
|
|
198
|
+
requestKey: result.requestKey,
|
|
199
|
+
error: result.error,
|
|
200
|
+
});
|
|
201
|
+
});
|
|
202
|
+
/**
|
|
203
|
+
* Reconcile a stale `failure` fire to its true on-chain `success` by attaching
|
|
204
|
+
* the confirmed request key (e.g. an nginx 504 that hid a landed submit). The
|
|
205
|
+
* key must match the request-key shape (else 400); a fire that is not found or
|
|
206
|
+
* not in `failure` yields 404 `No failed fire to recover`.
|
|
207
|
+
*/
|
|
208
|
+
export const recoverFire = (ctx, req) => withConfirm(ctx, req, async () => {
|
|
209
|
+
const fireId = req.params?.fireId;
|
|
210
|
+
if (!fireId)
|
|
211
|
+
return err(400, "fireId is required");
|
|
212
|
+
const requestKey = req.body?.requestKey;
|
|
213
|
+
if (typeof requestKey !== "string" || !REQUEST_KEY_RE.test(requestKey)) {
|
|
214
|
+
return err(400, "requestKey must be a 40–48 char URL-safe key");
|
|
215
|
+
}
|
|
216
|
+
const recovered = recoverFireInStore(fireId, requestKey, { db: ctx.db });
|
|
217
|
+
if (!recovered)
|
|
218
|
+
return err(404, "No failed fire to recover");
|
|
219
|
+
await ctx.onAudit?.({
|
|
220
|
+
action: "codex_cronoton.fire_recover",
|
|
221
|
+
result: "success",
|
|
222
|
+
targetKind: "codex_cronoton_fire",
|
|
223
|
+
targetId: fireId,
|
|
224
|
+
detail: { fireId, requestKey, actor: "ancient" },
|
|
225
|
+
});
|
|
226
|
+
return json(200, { ok: true, fireId, requestKey });
|
|
227
|
+
});
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The framework-agnostic HTTP contract for `@ancientpantheon/khronoton-core/handlers`.
|
|
3
|
+
*
|
|
4
|
+
* A handler never imports an HTTP framework object. The CONSUMER adapts its
|
|
5
|
+
* framework's request/response (Next route handler, Express, Fastify, a test
|
|
6
|
+
* driver, …) into {@link HandlerRequest} / {@link HandlerResponse} at the call
|
|
7
|
+
* boundary: read `params`/`query`/`body` off the incoming request, set the
|
|
8
|
+
* consumer's confirm signal on `confirmed`, then write the returned
|
|
9
|
+
* `{ status, body }` back onto its native response.
|
|
10
|
+
*
|
|
11
|
+
* This module owns the error contract too: {@link mapStoreError} translates the
|
|
12
|
+
* typed store errors from `/server` into the HTTP status the route surface
|
|
13
|
+
* promises, and {@link json} / {@link errorBody} shape a response body. The
|
|
14
|
+
* signer descriptor seam ({@link SignerSource} + {@link CodexSignerDescriptor})
|
|
15
|
+
* lives here as a shared, secret-free contract the read handlers consume.
|
|
16
|
+
*/
|
|
17
|
+
import { type KeyResolver } from "../server/index.js";
|
|
18
|
+
/**
|
|
19
|
+
* A framework-neutral request. The consumer populates it from its own request
|
|
20
|
+
* object: `params` from the route match, `query` from the URL search params,
|
|
21
|
+
* `body` from the parsed JSON payload, and `confirmed` from whatever fresh-admin
|
|
22
|
+
* -confirm signal the consumer's auth flow produced (the auth seam interprets it).
|
|
23
|
+
*/
|
|
24
|
+
export interface HandlerRequest {
|
|
25
|
+
params?: Record<string, string>;
|
|
26
|
+
query?: Record<string, string | string[] | undefined>;
|
|
27
|
+
body?: unknown;
|
|
28
|
+
/** The consumer's signal that a fresh admin-confirm accompanied this request. */
|
|
29
|
+
confirmed?: boolean;
|
|
30
|
+
}
|
|
31
|
+
/** A framework-neutral response the consumer writes back onto its native response. */
|
|
32
|
+
export interface HandlerResponse {
|
|
33
|
+
status: number;
|
|
34
|
+
body: unknown;
|
|
35
|
+
}
|
|
36
|
+
/** Pack a status + body into a {@link HandlerResponse}. */
|
|
37
|
+
export declare function json(status: number, body: unknown): HandlerResponse;
|
|
38
|
+
/**
|
|
39
|
+
* The canonical error body: `{ error }`, defaulting the message to `HTTP {status}`
|
|
40
|
+
* when the caller has none (REQ-H03).
|
|
41
|
+
*/
|
|
42
|
+
export declare function errorBody(status: number, message?: string): {
|
|
43
|
+
error: string;
|
|
44
|
+
};
|
|
45
|
+
/** A non-ok response carrying the `{ error }` body — `json` + `errorBody` in one call. */
|
|
46
|
+
export declare function err(status: number, message?: string): HandlerResponse;
|
|
47
|
+
/**
|
|
48
|
+
* Translate a thrown store/executor error into the HTTP status the route surface
|
|
49
|
+
* promises, always producing `{ status, body: { error } }`:
|
|
50
|
+
*
|
|
51
|
+
* - `CodexCronotonValidationError` whose message is `not found` → **404**
|
|
52
|
+
* - any other `CodexCronotonValidationError` (incl. `AutoGasGateError`) → **400**
|
|
53
|
+
* - `TerminalCronotonError` → **409**
|
|
54
|
+
* - `ManualBatchActiveError` → **409**
|
|
55
|
+
* - anything else → **500**
|
|
56
|
+
*
|
|
57
|
+
* `ManualBatchActiveError`/`TerminalCronotonError` are checked before
|
|
58
|
+
* `CodexCronotonValidationError` for clarity — they are not subclasses of it, so
|
|
59
|
+
* ordering does not change the result, but `AutoGasGateError` (which IS a
|
|
60
|
+
* subclass) is deliberately caught by the validation arm and kept a 400.
|
|
61
|
+
*/
|
|
62
|
+
export declare function mapStoreError(error: unknown): HandlerResponse;
|
|
63
|
+
/**
|
|
64
|
+
* A secret-free signer projection: only the public key and a coarse provenance
|
|
65
|
+
* label. NEVER carries key material — this is the invariant every
|
|
66
|
+
* {@link SignerSource} implementation must uphold regardless of how much
|
|
67
|
+
* provenance it knows.
|
|
68
|
+
*/
|
|
69
|
+
export interface CodexSignerDescriptor {
|
|
70
|
+
publicKey: string;
|
|
71
|
+
display: "derived" | "foreign";
|
|
72
|
+
}
|
|
73
|
+
/** Enumerates the signer descriptors the consumer's key store can sign for. */
|
|
74
|
+
export interface SignerSource {
|
|
75
|
+
listSignerDescriptors(): Promise<CodexSignerDescriptor[]>;
|
|
76
|
+
}
|
|
77
|
+
/** Map a signer's source tag to its display provenance: 'seed' → 'derived', else 'foreign'. */
|
|
78
|
+
export declare function descriptorSourceToDisplay(source: string): "derived" | "foreign";
|
|
79
|
+
/**
|
|
80
|
+
* The default signer source: projects the resolver's owned public keys to
|
|
81
|
+
* secret-free descriptors. The `/server` {@link KeyResolver} carries no
|
|
82
|
+
* seed/foreign provenance (only `listCodexPubs()`), so every descriptor is
|
|
83
|
+
* `foreign`; a consumer that knows provenance injects a richer source.
|
|
84
|
+
*/
|
|
85
|
+
export declare function defaultSignerSource(resolver: KeyResolver): SignerSource;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The framework-agnostic HTTP contract for `@ancientpantheon/khronoton-core/handlers`.
|
|
3
|
+
*
|
|
4
|
+
* A handler never imports an HTTP framework object. The CONSUMER adapts its
|
|
5
|
+
* framework's request/response (Next route handler, Express, Fastify, a test
|
|
6
|
+
* driver, …) into {@link HandlerRequest} / {@link HandlerResponse} at the call
|
|
7
|
+
* boundary: read `params`/`query`/`body` off the incoming request, set the
|
|
8
|
+
* consumer's confirm signal on `confirmed`, then write the returned
|
|
9
|
+
* `{ status, body }` back onto its native response.
|
|
10
|
+
*
|
|
11
|
+
* This module owns the error contract too: {@link mapStoreError} translates the
|
|
12
|
+
* typed store errors from `/server` into the HTTP status the route surface
|
|
13
|
+
* promises, and {@link json} / {@link errorBody} shape a response body. The
|
|
14
|
+
* signer descriptor seam ({@link SignerSource} + {@link CodexSignerDescriptor})
|
|
15
|
+
* lives here as a shared, secret-free contract the read handlers consume.
|
|
16
|
+
*/
|
|
17
|
+
import { CodexCronotonValidationError, ManualBatchActiveError, TerminalCronotonError, } from "../server/index.js";
|
|
18
|
+
/** Pack a status + body into a {@link HandlerResponse}. */
|
|
19
|
+
export function json(status, body) {
|
|
20
|
+
return { status, body };
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The canonical error body: `{ error }`, defaulting the message to `HTTP {status}`
|
|
24
|
+
* when the caller has none (REQ-H03).
|
|
25
|
+
*/
|
|
26
|
+
export function errorBody(status, message) {
|
|
27
|
+
return { error: message ?? `HTTP ${status}` };
|
|
28
|
+
}
|
|
29
|
+
/** A non-ok response carrying the `{ error }` body — `json` + `errorBody` in one call. */
|
|
30
|
+
export function err(status, message) {
|
|
31
|
+
return json(status, errorBody(status, message));
|
|
32
|
+
}
|
|
33
|
+
// ── Error contract (REQ-H03) ─────────────────────────────────────────────────
|
|
34
|
+
/**
|
|
35
|
+
* Translate a thrown store/executor error into the HTTP status the route surface
|
|
36
|
+
* promises, always producing `{ status, body: { error } }`:
|
|
37
|
+
*
|
|
38
|
+
* - `CodexCronotonValidationError` whose message is `not found` → **404**
|
|
39
|
+
* - any other `CodexCronotonValidationError` (incl. `AutoGasGateError`) → **400**
|
|
40
|
+
* - `TerminalCronotonError` → **409**
|
|
41
|
+
* - `ManualBatchActiveError` → **409**
|
|
42
|
+
* - anything else → **500**
|
|
43
|
+
*
|
|
44
|
+
* `ManualBatchActiveError`/`TerminalCronotonError` are checked before
|
|
45
|
+
* `CodexCronotonValidationError` for clarity — they are not subclasses of it, so
|
|
46
|
+
* ordering does not change the result, but `AutoGasGateError` (which IS a
|
|
47
|
+
* subclass) is deliberately caught by the validation arm and kept a 400.
|
|
48
|
+
*/
|
|
49
|
+
export function mapStoreError(error) {
|
|
50
|
+
if (error instanceof ManualBatchActiveError) {
|
|
51
|
+
return json(409, errorBody(409, error.message));
|
|
52
|
+
}
|
|
53
|
+
if (error instanceof TerminalCronotonError) {
|
|
54
|
+
// 409 Conflict (a deliberate improvement over the Hub, which returned 400
|
|
55
|
+
// for pause/resume on a terminal row). A terminal state is a conflict, not a
|
|
56
|
+
// malformed request; the difference is invisible to end users (the UI renders
|
|
57
|
+
// `body.error`). Do NOT "restore" this to 400 in a parity audit.
|
|
58
|
+
return json(409, errorBody(409, error.message));
|
|
59
|
+
}
|
|
60
|
+
if (error instanceof CodexCronotonValidationError) {
|
|
61
|
+
const status = /not found/i.test(error.message) ? 404 : 400;
|
|
62
|
+
return json(status, errorBody(status, error.message));
|
|
63
|
+
}
|
|
64
|
+
const message = error instanceof Error ? error.message : undefined;
|
|
65
|
+
return json(500, errorBody(500, message));
|
|
66
|
+
}
|
|
67
|
+
/** Map a signer's source tag to its display provenance: 'seed' → 'derived', else 'foreign'. */
|
|
68
|
+
export function descriptorSourceToDisplay(source) {
|
|
69
|
+
return source === "seed" ? "derived" : "foreign";
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The default signer source: projects the resolver's owned public keys to
|
|
73
|
+
* secret-free descriptors. The `/server` {@link KeyResolver} carries no
|
|
74
|
+
* seed/foreign provenance (only `listCodexPubs()`), so every descriptor is
|
|
75
|
+
* `foreign`; a consumer that knows provenance injects a richer source.
|
|
76
|
+
*/
|
|
77
|
+
export function defaultSignerSource(resolver) {
|
|
78
|
+
return {
|
|
79
|
+
async listSignerDescriptors() {
|
|
80
|
+
const pubs = await resolver.listCodexPubs();
|
|
81
|
+
return [...pubs].map((publicKey) => ({ publicKey, display: "foreign" }));
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|