@ancientpantheon/khronoton-core 0.2.0 → 0.4.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.
@@ -0,0 +1,675 @@
1
+ import { assertAdapter, resolveConfig, KhronotonStaticContext, KhronotonStatusContext, NeedsConfirmError, installSchema, defaultOpenAuth, withConfirm, err, recoverFire, json, createManualBatch, manualBatchView, getCodexCronoton, validateRuntimeArgs, rowRuntimeArgKeys, applyRuntimeArgs, rowToDefinition, getServerResolver, resolveServerVars, executeCodexTransaction, CodexCronotonValidationError, deleteCodexCronoton, resumeCodexCronoton, pauseCodexCronoton, editCodexCronoton, commitCodexCronoton, withRead, listFires, listCodexCronotons, getActiveManualBatchForCronoton, cancelManualBatch, defaultSignerSource, fireByServerResolver, computeDefinitionFingerprint, recordFire, applyTerminalIntent } from '../chunk-U3F5HEHO.js';
2
+ export { DEFAULT_EXPLORER_BASE, DEFAULT_PAGE_SIZE, DEFAULT_POLL_CADENCE_MS, NeedsConfirmError, assertAdapter, emptySnapshot, runGated, useKhronoton } from '../chunk-U3F5HEHO.js';
3
+ import { useRef, useState, useEffect } from 'react';
4
+ import { jsx } from 'react/jsx-runtime';
5
+
6
+ function KhronotonProvider(props) {
7
+ const { children } = props;
8
+ const staticRef = useRef(null);
9
+ if (staticRef.current === null) {
10
+ assertAdapter(props.adapter);
11
+ staticRef.current = { adapter: props.adapter, config: resolveConfig(props) };
12
+ }
13
+ const [status, setStatus] = useState({
14
+ ready: false,
15
+ error: null
16
+ });
17
+ useEffect(() => {
18
+ setStatus({ ready: true, error: null });
19
+ }, []);
20
+ return /* @__PURE__ */ jsx(KhronotonStaticContext.Provider, { value: staticRef.current, children: /* @__PURE__ */ jsx(KhronotonStatusContext.Provider, { value: status, children }) });
21
+ }
22
+
23
+ // src/provider/status-map.ts
24
+ function errorCode(body) {
25
+ if (body && typeof body === "object" && "error" in body) {
26
+ const value = body.error;
27
+ if (typeof value === "string") {
28
+ return value;
29
+ }
30
+ }
31
+ return void 0;
32
+ }
33
+ function parseHandlerResult({ status, body }) {
34
+ if (status >= 200 && status < 300) {
35
+ return body;
36
+ }
37
+ const code = errorCode(body);
38
+ if (status === 401 && code === "admin_confirm_required") {
39
+ throw new NeedsConfirmError();
40
+ }
41
+ throw new Error(code ?? `HTTP ${status}`);
42
+ }
43
+ async function parseFetchResponse(res) {
44
+ let body;
45
+ try {
46
+ body = await res.json();
47
+ } catch {
48
+ body = {};
49
+ }
50
+ return parseHandlerResult({ status: res.status, body });
51
+ }
52
+
53
+ // src/provider/fetch-adapter.ts
54
+ var CONFIRMED_HEADER = "x-khronoton-confirmed";
55
+ function resolveFetch(injected) {
56
+ if (injected) {
57
+ return injected;
58
+ }
59
+ const globalFetch = globalThis.fetch;
60
+ if (!globalFetch) {
61
+ throw new Error("createFetchAdapter: no fetch available \u2014 pass opts.fetch");
62
+ }
63
+ return globalFetch;
64
+ }
65
+ function createFetchAdapter(baseUrl, opts = {}) {
66
+ const base = baseUrl.replace(/\/+$/, "");
67
+ function staticHeaders() {
68
+ return typeof opts.headers === "function" ? opts.headers() : { ...opts.headers };
69
+ }
70
+ async function request(method, path, init = {}) {
71
+ const headers = { ...staticHeaders() };
72
+ let body;
73
+ if (init.body !== void 0) {
74
+ headers["content-type"] = "application/json";
75
+ body = JSON.stringify(init.body);
76
+ }
77
+ if (init.confirmed === true) {
78
+ headers[CONFIRMED_HEADER] = "1";
79
+ }
80
+ const doFetch = resolveFetch(opts.fetch);
81
+ const res = await doFetch(`${base}${path}`, { method, headers, body });
82
+ return parseFetchResponse(res);
83
+ }
84
+ function firesPath({ id, limit, offset }) {
85
+ const params = new URLSearchParams();
86
+ if (limit !== void 0) {
87
+ params.set("limit", String(limit));
88
+ }
89
+ if (offset !== void 0) {
90
+ params.set("offset", String(offset));
91
+ }
92
+ const qs = params.toString();
93
+ return `/${id}/fires${qs ? `?${qs}` : ""}`;
94
+ }
95
+ function listPath(query) {
96
+ const params = new URLSearchParams();
97
+ if (query?.limit !== void 0) {
98
+ params.set("limit", String(query.limit));
99
+ }
100
+ if (query?.offset !== void 0) {
101
+ params.set("offset", String(query.offset));
102
+ }
103
+ if (query?.status !== void 0) {
104
+ params.set("status", query.status);
105
+ }
106
+ const qs = params.toString();
107
+ return qs ? `?${qs}` : "";
108
+ }
109
+ return {
110
+ // Read tier (confirm-free)
111
+ list(query) {
112
+ return request("GET", listPath(query));
113
+ },
114
+ get(id) {
115
+ return request("GET", `/${id}`);
116
+ },
117
+ fires(query) {
118
+ return request("GET", firesPath(query));
119
+ },
120
+ signers() {
121
+ return request("GET", "/signers");
122
+ },
123
+ // Lifecycle tier (confirm-gated)
124
+ commit(body, confirm) {
125
+ return request("POST", "", { body, confirmed: confirm?.confirmed });
126
+ },
127
+ edit(id, patch, confirm) {
128
+ return request("PATCH", `/${id}`, { body: patch, confirmed: confirm?.confirmed });
129
+ },
130
+ pause(id, confirm) {
131
+ return request("PATCH", `/${id}/pause`, { confirmed: confirm?.confirmed });
132
+ },
133
+ resume(id, confirm) {
134
+ return request("PATCH", `/${id}/resume`, { confirmed: confirm?.confirmed });
135
+ },
136
+ delete(id, confirm) {
137
+ return request("DELETE", `/${id}`, { confirmed: confirm?.confirmed });
138
+ },
139
+ // Execution tier (confirm-gated; simulate/executeNow/trigger are 200-on-ok:false)
140
+ simulate(envelope, confirm) {
141
+ return request("POST", "/simulate", {
142
+ body: { envelope },
143
+ confirmed: confirm?.confirmed
144
+ });
145
+ },
146
+ executeNow(id, confirm) {
147
+ return request("POST", `/${id}/execute`, { confirmed: confirm?.confirmed });
148
+ },
149
+ trigger(id, args, confirm) {
150
+ return request("POST", `/${id}/trigger`, {
151
+ body: { args },
152
+ confirmed: confirm?.confirmed
153
+ });
154
+ },
155
+ // Manual-batch tier (start confirm-gated; get/cancel confirm-free)
156
+ startBatch(id, count, confirm) {
157
+ return request("POST", `/${id}/execute-batch`, {
158
+ body: { count },
159
+ confirmed: confirm?.confirmed
160
+ });
161
+ },
162
+ getBatch(id) {
163
+ return request("GET", `/${id}/execute-batch`);
164
+ },
165
+ cancelBatch(id) {
166
+ return request("DELETE", `/${id}/execute-batch`);
167
+ },
168
+ // Recover a stale failed fire (confirm-gated; REQ-G09)
169
+ recover(id, fireId, requestKey, confirm) {
170
+ return request("POST", `/${id}/fires/${fireId}/recover`, {
171
+ body: { requestKey },
172
+ confirmed: confirm?.confirmed
173
+ });
174
+ }
175
+ };
176
+ }
177
+
178
+ // src/handlers/read.ts
179
+ function firstScalar(raw) {
180
+ const value = Array.isArray(raw) ? raw[0] : raw;
181
+ return value === void 0 || value === null || value === "" ? void 0 : value;
182
+ }
183
+ function clampInt(raw, { def, min, max }) {
184
+ const scalar = firstScalar(raw);
185
+ const parsed = scalar === void 0 ? Number.NaN : Number.parseInt(scalar, 10);
186
+ const base = Number.isNaN(parsed) ? def : parsed;
187
+ const lowerBounded = Math.max(base, min);
188
+ return max === void 0 ? lowerBounded : Math.min(lowerBounded, max);
189
+ }
190
+ var CRONOTON_STATUSES = /* @__PURE__ */ new Set([
191
+ "active",
192
+ "paused",
193
+ "completed",
194
+ "error"
195
+ ]);
196
+ function parseStatus(raw) {
197
+ const scalar = firstScalar(raw);
198
+ return scalar !== void 0 && CRONOTON_STATUSES.has(scalar) ? scalar : void 0;
199
+ }
200
+ async function listHandler(ctx, request) {
201
+ return withRead(ctx, request, async () => {
202
+ const query = request.query ?? {};
203
+ const codexCronotons = listCodexCronotons(
204
+ {
205
+ limit: clampInt(query.limit, { def: 50, min: 1, max: 200 }),
206
+ offset: clampInt(query.offset, { def: 0, min: 0 }),
207
+ status: parseStatus(query.status)
208
+ },
209
+ { db: ctx.db }
210
+ );
211
+ return json(200, { ok: true, codexCronotons });
212
+ });
213
+ }
214
+ async function getHandler(ctx, request) {
215
+ return withRead(ctx, request, async () => {
216
+ const id = request.params?.id ?? "";
217
+ const codexCronoton = getCodexCronoton(id, { db: ctx.db });
218
+ if (!codexCronoton) {
219
+ return err(404, "not found");
220
+ }
221
+ return json(200, { ok: true, codexCronoton });
222
+ });
223
+ }
224
+ async function signersHandler(ctx, request) {
225
+ return withRead(ctx, request, async () => {
226
+ const source = ctx.signers ?? defaultSignerSource(ctx.resolver);
227
+ const signers = await source.listSignerDescriptors();
228
+ return json(200, { ok: true, signers });
229
+ });
230
+ }
231
+ async function firesHandler(ctx, request) {
232
+ return withRead(ctx, request, async () => {
233
+ const id = request.params?.id ?? "";
234
+ const query = request.query ?? {};
235
+ const limit = clampInt(query.limit, { def: 50, min: 1, max: 100 });
236
+ const offset = clampInt(query.offset, { def: 0, min: 0 });
237
+ const { fires, total } = listFires(id, { limit, offset }, { db: ctx.db });
238
+ return json(200, { ok: true, fires, total, limit, offset });
239
+ });
240
+ }
241
+
242
+ // src/handlers/cronoton.ts
243
+ function requireObject(value, message) {
244
+ if (!value || typeof value !== "object") {
245
+ throw new CodexCronotonValidationError(message);
246
+ }
247
+ return value;
248
+ }
249
+ function createdByOf(identity) {
250
+ return identity?.email ?? identity?.id ?? "system";
251
+ }
252
+ function toCommitInput(body, createdBy) {
253
+ const b = requireObject(body, "request body must be a commit object");
254
+ const envelope = requireObject(b.envelope, "envelope is required");
255
+ const schedule = requireObject(b.schedule, "schedule is required");
256
+ return {
257
+ name: b.name,
258
+ description: b.description ?? null,
259
+ pactCode: envelope.pactCode,
260
+ config: envelope.config,
261
+ payload: envelope.payload ?? {},
262
+ gasPayer: envelope.gasPayer,
263
+ signers: envelope.signers ?? [],
264
+ scheduleMode: schedule.mode,
265
+ scheduleConfig: schedule.config,
266
+ createdBy,
267
+ serverResolver: envelope.serverResolver,
268
+ externalFireable: envelope.externalFireable,
269
+ runtimeArgKeys: envelope.runtimeArgKeys
270
+ };
271
+ }
272
+ function toEditPatch(body) {
273
+ const b = requireObject(body, "request body must be an edit object");
274
+ const patch = {};
275
+ if (b.name !== void 0) patch.name = b.name;
276
+ if (b.description !== void 0) patch.description = b.description;
277
+ const env = b.envelope;
278
+ if (env && typeof env === "object") {
279
+ const e = env;
280
+ if (e.pactCode !== void 0) patch.pactCode = e.pactCode;
281
+ if (e.config !== void 0) patch.config = e.config;
282
+ if (e.payload !== void 0) patch.payload = e.payload;
283
+ if (e.gasPayer !== void 0) patch.gasPayer = e.gasPayer;
284
+ if (e.signers !== void 0) patch.signers = e.signers;
285
+ if (e.serverResolver !== void 0) patch.serverResolver = e.serverResolver;
286
+ }
287
+ const sched = b.schedule;
288
+ if (sched && typeof sched === "object") {
289
+ const s = sched;
290
+ patch.scheduleMode = s.mode;
291
+ patch.scheduleConfig = s.config;
292
+ }
293
+ return patch;
294
+ }
295
+ function paramId(req) {
296
+ return req.params?.id ?? "";
297
+ }
298
+ async function commitCodexCronoton2(ctx, req) {
299
+ return withConfirm(ctx, req, async (identity) => {
300
+ const input = toCommitInput(req.body, createdByOf(identity));
301
+ const { id, nextFireAt } = commitCodexCronoton(input, { db: ctx.db });
302
+ await ctx.onAudit?.({
303
+ action: "codex_cronoton.commit",
304
+ result: "ok",
305
+ targetKind: "codex_cronoton",
306
+ targetId: id,
307
+ detail: { name: input.name }
308
+ });
309
+ return json(201, { ok: true, codexCronotonId: id, nextFireAt });
310
+ });
311
+ }
312
+ async function editCodexCronoton2(ctx, req) {
313
+ return withConfirm(ctx, req, async () => {
314
+ const { nextFireAt } = editCodexCronoton(paramId(req), toEditPatch(req.body), { db: ctx.db });
315
+ return json(200, { ok: true, nextFireAt });
316
+ });
317
+ }
318
+ async function pauseCodexCronoton2(ctx, req) {
319
+ return withConfirm(ctx, req, async () => {
320
+ const { status, nextFireAt } = pauseCodexCronoton(paramId(req), { db: ctx.db });
321
+ return json(200, { ok: true, status, nextFireAt });
322
+ });
323
+ }
324
+ async function resumeCodexCronoton2(ctx, req) {
325
+ return withConfirm(ctx, req, async () => {
326
+ const { status, nextFireAt } = resumeCodexCronoton(paramId(req), { db: ctx.db });
327
+ return json(200, { ok: true, status, nextFireAt });
328
+ });
329
+ }
330
+ async function deleteCodexCronoton2(ctx, req) {
331
+ return withConfirm(ctx, req, async () => {
332
+ const id = paramId(req);
333
+ const row = getCodexCronoton(id, { db: ctx.db });
334
+ if (!row) throw new CodexCronotonValidationError("not found");
335
+ if (row.server_resolver) {
336
+ return json(409, {
337
+ error: "System cronoton \u2014 cannot be deleted. Pause it to disable instead.",
338
+ protected: true
339
+ });
340
+ }
341
+ deleteCodexCronoton(id, { db: ctx.db });
342
+ await ctx.onAudit?.({
343
+ action: "codex_cronoton.delete",
344
+ result: "ok",
345
+ targetKind: "codex_cronoton",
346
+ targetId: id,
347
+ detail: { serverResolver: row.server_resolver ?? null }
348
+ });
349
+ return json(200, { ok: true });
350
+ });
351
+ }
352
+
353
+ // src/handlers/execute.ts
354
+ var REQUEST_KEY_RE = /^[A-Za-z0-9_-]{40,48}$/;
355
+ var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "error"]);
356
+ function envelopeToDefinition(envelope) {
357
+ return {
358
+ pactCode: typeof envelope.pactCode === "string" ? envelope.pactCode : "",
359
+ config: envelope.config,
360
+ payload: envelope.payload ?? {},
361
+ gasPayer: envelope.gasPayer ?? { type: "gas-station" },
362
+ signers: envelope.signers ?? [],
363
+ scheduleKind: envelope.scheduleKind,
364
+ serverResolver: typeof envelope.serverResolver === "string" ? envelope.serverResolver : void 0
365
+ };
366
+ }
367
+ function chainDataFrom(rawResult) {
368
+ if (rawResult && typeof rawResult === "object" && "data" in rawResult) {
369
+ return rawResult.data;
370
+ }
371
+ return void 0;
372
+ }
373
+ async function fireAndRecord(ctx, row, definition) {
374
+ const result = await fireByServerResolver(definition, row, {
375
+ runtime: ctx.runtime,
376
+ resolver: ctx.resolver,
377
+ config: ctx.config,
378
+ db: ctx.db
379
+ });
380
+ const fingerprint = computeDefinitionFingerprint(row);
381
+ const fireId = recordFire(
382
+ {
383
+ codexCronotonId: row.id,
384
+ jobId: null,
385
+ firedAt: (/* @__PURE__ */ new Date()).toISOString(),
386
+ status: result.ok ? "success" : "failure",
387
+ requestKey: result.requestKey,
388
+ chainId: result.chainId,
389
+ errorMessage: result.error,
390
+ chainResponse: result.rawResult,
391
+ definitionFingerprint: fingerprint
392
+ },
393
+ { db: ctx.db, resolveFireMode: ctx.resolveFireMode }
394
+ );
395
+ if ((definition.scheduleKind ?? "recurring") === "one-time") {
396
+ applyTerminalIntent(row.id, result.terminalIntent, { db: ctx.db });
397
+ }
398
+ await ctx.onAudit?.({
399
+ action: result.ok ? "codex_cronoton.fire" : "codex_cronoton.fire_failed",
400
+ result: result.ok ? "success" : "failure",
401
+ targetKind: "codex_cronoton",
402
+ targetId: row.id,
403
+ detail: {
404
+ codexCronotonId: row.id,
405
+ fireId,
406
+ requestKey: result.requestKey,
407
+ chainId: result.chainId,
408
+ actor: "ancient",
409
+ definitionFingerprint: fingerprint,
410
+ errorMessage: result.error
411
+ }
412
+ });
413
+ return { result, fireId };
414
+ }
415
+ var simulateCodexTx = (ctx, req) => withConfirm(ctx, req, async () => {
416
+ const body = req.body ?? {};
417
+ if (!body.envelope || typeof body.envelope !== "object") {
418
+ return err(400, "envelope is required");
419
+ }
420
+ let definition = envelopeToDefinition(body.envelope);
421
+ let plannedCount;
422
+ let postponed;
423
+ if (definition.serverResolver) {
424
+ const resolution = resolveServerVars(definition.serverResolver, { db: ctx.db });
425
+ if (resolution) {
426
+ plannedCount = resolution.plan.length;
427
+ postponed = resolution.plan.length === 0;
428
+ definition = {
429
+ ...definition,
430
+ payload: { ...definition.payload, ...resolution.payload }
431
+ };
432
+ }
433
+ }
434
+ const result = await executeCodexTransaction(definition, "simulate", {
435
+ runtime: ctx.runtime,
436
+ resolver: ctx.resolver,
437
+ config: ctx.config
438
+ });
439
+ return json(200, {
440
+ ok: result.ok,
441
+ calibratedGasLimit: result.calibratedGasLimit,
442
+ gasUsed: result.gasUsed,
443
+ error: result.error,
444
+ rawResult: result.rawResult,
445
+ postponed,
446
+ plannedCount,
447
+ chainData: chainDataFrom(result.rawResult)
448
+ });
449
+ });
450
+ var executeNow = (ctx, req) => withConfirm(ctx, req, async () => {
451
+ const id = req.params?.id;
452
+ if (!id) return err(400, "cronoton id is required");
453
+ const row = getCodexCronoton(id, { db: ctx.db });
454
+ if (!row) return err(404, "not found");
455
+ if (row.status === "paused") return err(400, "cannot execute a paused cronoton");
456
+ if (TERMINAL_STATUSES.has(row.status)) {
457
+ return err(400, "cannot execute a terminal cronoton");
458
+ }
459
+ const resolverName = row.server_resolver ?? void 0;
460
+ if (resolverName && getServerResolver(resolverName)?.kind === "multi-tx") {
461
+ return json(202, { ok: true, queued: true });
462
+ }
463
+ const { result, fireId } = await fireAndRecord(ctx, row, rowToDefinition(row));
464
+ return json(200, {
465
+ ok: result.ok,
466
+ fireId,
467
+ requestKey: result.requestKey,
468
+ error: result.error
469
+ });
470
+ });
471
+ var triggerCronoton = (ctx, req) => withConfirm(ctx, req, async () => {
472
+ const id = req.params?.id;
473
+ if (!id) return err(400, "cronoton id is required");
474
+ const row = getCodexCronoton(id, { db: ctx.db });
475
+ if (!row) return err(404, "not found");
476
+ if (row.status === "paused") return err(400, "cannot trigger a paused cronoton");
477
+ if (TERMINAL_STATUSES.has(row.status)) {
478
+ return err(400, "cannot trigger a terminal cronoton");
479
+ }
480
+ const args = req.body?.args;
481
+ const validated = validateRuntimeArgs(rowRuntimeArgKeys(row), args);
482
+ if (!validated.ok) return err(400, validated.error);
483
+ const definition = applyRuntimeArgs(rowToDefinition(row), validated.args);
484
+ const { result, fireId } = await fireAndRecord(ctx, row, definition);
485
+ return json(200, {
486
+ ok: result.ok,
487
+ fireId,
488
+ requestKey: result.requestKey,
489
+ error: result.error
490
+ });
491
+ });
492
+ var recoverFire2 = (ctx, req) => withConfirm(ctx, req, async () => {
493
+ const fireId = req.params?.fireId;
494
+ if (!fireId) return err(400, "fireId is required");
495
+ const requestKey = req.body?.requestKey;
496
+ if (typeof requestKey !== "string" || !REQUEST_KEY_RE.test(requestKey)) {
497
+ return err(400, "requestKey must be a 40\u201348 char URL-safe key");
498
+ }
499
+ const recovered = recoverFire(fireId, requestKey, { db: ctx.db });
500
+ if (!recovered) return err(404, "No failed fire to recover");
501
+ await ctx.onAudit?.({
502
+ action: "codex_cronoton.fire_recover",
503
+ result: "success",
504
+ targetKind: "codex_cronoton_fire",
505
+ targetId: fireId,
506
+ detail: { fireId, requestKey, actor: "ancient" }
507
+ });
508
+ return json(200, { ok: true, fireId, requestKey });
509
+ });
510
+
511
+ // src/handlers/batch.ts
512
+ async function startExecuteBatch(ctx, req) {
513
+ return withConfirm(ctx, req, async (identity) => {
514
+ const cronotonId = req.params?.id ?? "";
515
+ const count = req.body?.count;
516
+ const row = createManualBatch(
517
+ { cronotonId, total: count, createdBy: identity?.email ?? identity?.id ?? "unknown" },
518
+ { db: ctx.db, config: ctx.config }
519
+ );
520
+ return json(200, { ok: true, batch: manualBatchView(row) });
521
+ });
522
+ }
523
+ async function getExecuteBatch(ctx, req) {
524
+ return withRead(ctx, req, async () => {
525
+ const cronotonId = req.params?.id ?? "";
526
+ const batch = getActiveManualBatchForCronoton(cronotonId, { db: ctx.db });
527
+ return json(200, { ok: true, batch: batch ? manualBatchView(batch) : null });
528
+ });
529
+ }
530
+ async function cancelExecuteBatch(ctx, req) {
531
+ return withRead(ctx, req, async () => {
532
+ const cronotonId = req.params?.id ?? "";
533
+ const active = getActiveManualBatchForCronoton(cronotonId, { db: ctx.db });
534
+ const cancelled = active ? cancelManualBatch(active.id, { db: ctx.db }).ok : false;
535
+ return json(200, { ok: true, cancelled });
536
+ });
537
+ }
538
+
539
+ // src/provider/memory-adapter.ts
540
+ function emptyResolver() {
541
+ return {
542
+ getKeyPairByPublicKey: async (publicKey) => ({
543
+ publicKey,
544
+ privateKey: "",
545
+ seedType: "seed"
546
+ }),
547
+ listCodexPubs: async () => /* @__PURE__ */ new Set()
548
+ };
549
+ }
550
+ function throwingRuntime() {
551
+ const notWired = () => {
552
+ throw new Error(
553
+ "MemoryAdapter: no ChainRuntime injected \u2014 pass opts.runtime to run simulate/executeNow/trigger. Read, lifecycle, and batch ops need none."
554
+ );
555
+ };
556
+ return {
557
+ Pact: { builder: { execution: notWired } },
558
+ createClient: notWired,
559
+ isSignedTransaction: notWired,
560
+ universalSignTransaction: notWired,
561
+ calculateAutoGasLimit: notWired,
562
+ anuToStoa: notWired,
563
+ getPactUrl: notWired,
564
+ networkId: "memory",
565
+ namespace: "memory-ns",
566
+ gasStationAccount: "c:MEMORY"
567
+ };
568
+ }
569
+ function scalarQuery(entries) {
570
+ const query = {};
571
+ for (const [key, value] of Object.entries(entries)) {
572
+ if (value !== void 0) {
573
+ query[key] = String(value);
574
+ }
575
+ }
576
+ return query;
577
+ }
578
+ function createMemoryAdapter(opts) {
579
+ const { db } = opts;
580
+ if (opts.migrate !== false) {
581
+ installSchema(db);
582
+ }
583
+ const ctx = {
584
+ db,
585
+ runtime: opts.runtime ?? throwingRuntime(),
586
+ resolver: opts.resolver ?? emptyResolver(),
587
+ resolveFireMode: opts.resolveFireMode ?? (() => "live"),
588
+ onAudit: opts.onAudit,
589
+ config: opts.config,
590
+ auth: opts.auth ?? defaultOpenAuth,
591
+ signers: opts.signers
592
+ };
593
+ async function call(handler, req) {
594
+ const { status, body } = await handler(ctx, req);
595
+ return parseHandlerResult({ status, body });
596
+ }
597
+ return {
598
+ // Read tier (confirm-free)
599
+ list(query) {
600
+ return call(listHandler, {
601
+ query: scalarQuery({ limit: query?.limit, offset: query?.offset, status: query?.status })
602
+ });
603
+ },
604
+ get(id) {
605
+ return call(getHandler, { params: { id } });
606
+ },
607
+ fires({ id, limit, offset }) {
608
+ return call(firesHandler, { params: { id }, query: scalarQuery({ limit, offset }) });
609
+ },
610
+ signers() {
611
+ return call(signersHandler, {});
612
+ },
613
+ // Lifecycle tier (confirm-gated)
614
+ commit(body, confirm) {
615
+ return call(commitCodexCronoton2, { body, confirmed: confirm?.confirmed });
616
+ },
617
+ edit(id, patch, confirm) {
618
+ return call(editCodexCronoton2, {
619
+ params: { id },
620
+ body: patch,
621
+ confirmed: confirm?.confirmed
622
+ });
623
+ },
624
+ pause(id, confirm) {
625
+ return call(pauseCodexCronoton2, { params: { id }, confirmed: confirm?.confirmed });
626
+ },
627
+ resume(id, confirm) {
628
+ return call(resumeCodexCronoton2, { params: { id }, confirmed: confirm?.confirmed });
629
+ },
630
+ delete(id, confirm) {
631
+ return call(deleteCodexCronoton2, { params: { id }, confirmed: confirm?.confirmed });
632
+ },
633
+ // Execution tier (confirm-gated; simulate/executeNow/trigger are 200-on-ok:false)
634
+ simulate(envelope, confirm) {
635
+ return call(simulateCodexTx, {
636
+ body: { envelope },
637
+ confirmed: confirm?.confirmed
638
+ });
639
+ },
640
+ executeNow(id, confirm) {
641
+ return call(executeNow, { params: { id }, confirmed: confirm?.confirmed });
642
+ },
643
+ trigger(id, args, confirm) {
644
+ return call(triggerCronoton, {
645
+ params: { id },
646
+ body: { args },
647
+ confirmed: confirm?.confirmed
648
+ });
649
+ },
650
+ // Manual-batch tier (start confirm-gated; get/cancel confirm-free)
651
+ startBatch(id, count, confirm) {
652
+ return call(startExecuteBatch, {
653
+ params: { id },
654
+ body: { count },
655
+ confirmed: confirm?.confirmed
656
+ });
657
+ },
658
+ getBatch(id) {
659
+ return call(getExecuteBatch, { params: { id } });
660
+ },
661
+ cancelBatch(id) {
662
+ return call(cancelExecuteBatch, { params: { id } });
663
+ },
664
+ // Recover a stale failed fire (confirm-gated; REQ-G09)
665
+ recover(id, fireId, requestKey, confirm) {
666
+ return call(recoverFire2, {
667
+ params: { id, fireId },
668
+ body: { requestKey },
669
+ confirmed: confirm?.confirmed
670
+ });
671
+ }
672
+ };
673
+ }
674
+
675
+ export { CONFIRMED_HEADER, KhronotonProvider, createFetchAdapter, createMemoryAdapter, parseFetchResponse, parseHandlerResult };