@proofoftech/flowsafe 0.4.0 → 0.6.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 +307 -0
- package/dist/agent-runner/approval-shapes.d.ts +36 -0
- package/dist/agent-runner/approval-shapes.d.ts.map +1 -0
- package/dist/agent-runner/approval-shapes.js +101 -0
- package/dist/agent-runner/approval-shapes.js.map +1 -0
- package/dist/agent-runner/durable-agent-runner.d.ts +154 -0
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -0
- package/dist/agent-runner/durable-agent-runner.js +291 -0
- package/dist/agent-runner/durable-agent-runner.js.map +1 -0
- package/dist/agent-runner/index.d.ts +3 -0
- package/dist/agent-runner/index.d.ts.map +1 -0
- package/dist/agent-runner/index.js +10 -0
- package/dist/agent-runner/index.js.map +1 -0
- package/dist/approval-api/d1-store.d.ts.map +1 -1
- package/dist/approval-api/d1-store.js +85 -17
- package/dist/approval-api/d1-store.js.map +1 -1
- package/dist/approval-api/index.d.ts +1 -1
- package/dist/approval-api/index.d.ts.map +1 -1
- package/dist/approval-api/index.js.map +1 -1
- package/dist/approval-api/router.d.ts +1 -1
- package/dist/approval-api/router.d.ts.map +1 -1
- package/dist/approval-api/router.js +1 -0
- package/dist/approval-api/router.js.map +1 -1
- package/dist/approval-api/service.d.ts +2 -2
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +15 -1
- package/dist/approval-api/service.js.map +1 -1
- package/dist/approval-api/store.d.ts +10 -6
- package/dist/approval-api/store.d.ts.map +1 -1
- package/dist/approval-api/store.js +15 -0
- package/dist/approval-api/store.js.map +1 -1
- package/dist/approval-api/tenant-context.d.ts.map +1 -1
- package/dist/approval-api/tenant-context.js +15 -0
- package/dist/approval-api/tenant-context.js.map +1 -1
- package/dist/approval-api/types.d.ts +8 -0
- package/dist/approval-api/types.d.ts.map +1 -1
- package/dist/approval-api/types.js.map +1 -1
- package/dist/background-tasks/d1-storage.d.ts +66 -0
- package/dist/background-tasks/d1-storage.d.ts.map +1 -0
- package/dist/background-tasks/d1-storage.js +196 -0
- package/dist/background-tasks/d1-storage.js.map +1 -0
- package/dist/background-tasks/host.d.ts +82 -0
- package/dist/background-tasks/host.d.ts.map +1 -0
- package/dist/background-tasks/host.js +275 -0
- package/dist/background-tasks/host.js.map +1 -0
- package/dist/background-tasks/index.d.ts +7 -0
- package/dist/background-tasks/index.d.ts.map +1 -0
- package/dist/background-tasks/index.js +10 -0
- package/dist/background-tasks/index.js.map +1 -0
- package/dist/background-tasks/routes.d.ts +15 -0
- package/dist/background-tasks/routes.d.ts.map +1 -0
- package/dist/background-tasks/routes.js +144 -0
- package/dist/background-tasks/routes.js.map +1 -0
- package/dist/do-runner/d1-storage.d.ts +343 -2
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +565 -12
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/do-error-response.d.ts +29 -0
- package/dist/do-runner/do-error-response.d.ts.map +1 -0
- package/dist/do-runner/do-error-response.js +73 -0
- package/dist/do-runner/do-error-response.js.map +1 -0
- package/dist/do-runner/durable-object.d.ts +1 -1
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +2 -16
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/index.d.ts +9 -3
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +8 -2
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/init.d.ts +20 -0
- package/dist/do-runner/init.d.ts.map +1 -1
- package/dist/do-runner/init.js +12 -1
- package/dist/do-runner/init.js.map +1 -1
- package/dist/do-runner/pubsub.d.ts +18 -0
- package/dist/do-runner/pubsub.d.ts.map +1 -0
- package/dist/do-runner/pubsub.js +42 -0
- package/dist/do-runner/pubsub.js.map +1 -0
- package/dist/do-runner/runtime.d.ts +24 -0
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +29 -2
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/thread-do.d.ts +74 -0
- package/dist/do-runner/thread-do.d.ts.map +1 -0
- package/dist/do-runner/thread-do.js +156 -0
- package/dist/do-runner/thread-do.js.map +1 -0
- package/dist/do-runner/thread-header.d.ts +16 -0
- package/dist/do-runner/thread-header.d.ts.map +1 -0
- package/dist/do-runner/thread-header.js +24 -0
- package/dist/do-runner/thread-header.js.map +1 -0
- package/dist/goals/index.d.ts +2 -0
- package/dist/goals/index.d.ts.map +1 -0
- package/dist/goals/index.js +7 -0
- package/dist/goals/index.js.map +1 -0
- package/dist/goals/objective-routes.d.ts +87 -0
- package/dist/goals/objective-routes.d.ts.map +1 -0
- package/dist/goals/objective-routes.js +375 -0
- package/dist/goals/objective-routes.js.map +1 -0
- package/dist/host-kit/approval-bridge.d.ts +24 -4
- package/dist/host-kit/approval-bridge.d.ts.map +1 -1
- package/dist/host-kit/approval-bridge.js +32 -10
- package/dist/host-kit/approval-bridge.js.map +1 -1
- package/dist/host-kit/env-vars.d.ts +20 -0
- package/dist/host-kit/env-vars.d.ts.map +1 -1
- package/dist/host-kit/env-vars.js +30 -0
- package/dist/host-kit/env-vars.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +111 -4
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +253 -63
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/index.d.ts +3 -1
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js +7 -0
- package/dist/host-kit/index.js.map +1 -1
- package/dist/host-kit/memory-boundary.d.ts +64 -0
- package/dist/host-kit/memory-boundary.d.ts.map +1 -0
- package/dist/host-kit/memory-boundary.js +109 -0
- package/dist/host-kit/memory-boundary.js.map +1 -0
- package/dist/host-kit/route-path.d.ts +17 -0
- package/dist/host-kit/route-path.d.ts.map +1 -0
- package/dist/host-kit/route-path.js +35 -0
- package/dist/host-kit/route-path.js.map +1 -0
- package/dist/host-kit/thread-topology.d.ts +44 -0
- package/dist/host-kit/thread-topology.d.ts.map +1 -0
- package/dist/host-kit/thread-topology.js +76 -0
- package/dist/host-kit/thread-topology.js.map +1 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/internal-error-response.d.ts +3 -0
- package/dist/internal-error-response.d.ts.map +1 -0
- package/dist/internal-error-response.js +20 -0
- package/dist/internal-error-response.js.map +1 -0
- package/dist/numeric-config.d.ts +4 -0
- package/dist/numeric-config.d.ts.map +1 -0
- package/dist/numeric-config.js +23 -0
- package/dist/numeric-config.js.map +1 -0
- package/dist/schedules/index.d.ts +5 -0
- package/dist/schedules/index.d.ts.map +1 -0
- package/dist/schedules/index.js +13 -0
- package/dist/schedules/index.js.map +1 -0
- package/dist/schedules/router.d.ts +66 -0
- package/dist/schedules/router.d.ts.map +1 -0
- package/dist/schedules/router.js +827 -0
- package/dist/schedules/router.js.map +1 -0
- package/dist/schedules/schedules-d1.d.ts +30 -0
- package/dist/schedules/schedules-d1.d.ts.map +1 -0
- package/dist/schedules/schedules-d1.js +374 -0
- package/dist/schedules/schedules-d1.js.map +1 -0
- package/dist/schedules/storage.d.ts +11 -0
- package/dist/schedules/storage.d.ts.map +1 -0
- package/dist/schedules/storage.js +34 -0
- package/dist/schedules/storage.js.map +1 -0
- package/dist/schedules/tick.d.ts +131 -0
- package/dist/schedules/tick.d.ts.map +1 -0
- package/dist/schedules/tick.js +598 -0
- package/dist/schedules/tick.js.map +1 -0
- package/dist/signal-providers/delivery.d.ts +24 -0
- package/dist/signal-providers/delivery.d.ts.map +1 -0
- package/dist/signal-providers/delivery.js +62 -0
- package/dist/signal-providers/delivery.js.map +1 -0
- package/dist/signal-providers/github-provider.d.ts +33 -0
- package/dist/signal-providers/github-provider.d.ts.map +1 -0
- package/dist/signal-providers/github-provider.js +116 -0
- package/dist/signal-providers/github-provider.js.map +1 -0
- package/dist/signal-providers/host-do.d.ts +79 -0
- package/dist/signal-providers/host-do.d.ts.map +1 -0
- package/dist/signal-providers/host-do.js +216 -0
- package/dist/signal-providers/host-do.js.map +1 -0
- package/dist/signal-providers/index.d.ts +7 -0
- package/dist/signal-providers/index.d.ts.map +1 -0
- package/dist/signal-providers/index.js +19 -0
- package/dist/signal-providers/index.js.map +1 -0
- package/dist/signal-providers/provider.d.ts +92 -0
- package/dist/signal-providers/provider.d.ts.map +1 -0
- package/dist/signal-providers/provider.js +87 -0
- package/dist/signal-providers/provider.js.map +1 -0
- package/dist/signal-providers/subscription-d1.d.ts +88 -0
- package/dist/signal-providers/subscription-d1.d.ts.map +1 -0
- package/dist/signal-providers/subscription-d1.js +259 -0
- package/dist/signal-providers/subscription-d1.js.map +1 -0
- package/dist/signal-providers/webhook-route.d.ts +88 -0
- package/dist/signal-providers/webhook-route.d.ts.map +1 -0
- package/dist/signal-providers/webhook-route.js +391 -0
- package/dist/signal-providers/webhook-route.js.map +1 -0
- package/dist/signals/client.d.ts +72 -0
- package/dist/signals/client.d.ts.map +1 -0
- package/dist/signals/client.js +87 -0
- package/dist/signals/client.js.map +1 -0
- package/dist/signals/d1-shared.d.ts +43 -0
- package/dist/signals/d1-shared.d.ts.map +1 -0
- package/dist/signals/d1-shared.js +46 -0
- package/dist/signals/d1-shared.js.map +1 -0
- package/dist/signals/index.d.ts +9 -0
- package/dist/signals/index.d.ts.map +1 -0
- package/dist/signals/index.js +15 -0
- package/dist/signals/index.js.map +1 -0
- package/dist/signals/notification-dispatch.d.ts +52 -0
- package/dist/signals/notification-dispatch.d.ts.map +1 -0
- package/dist/signals/notification-dispatch.js +198 -0
- package/dist/signals/notification-dispatch.js.map +1 -0
- package/dist/signals/notifications-d1.d.ts +28 -0
- package/dist/signals/notifications-d1.d.ts.map +1 -0
- package/dist/signals/notifications-d1.js +704 -0
- package/dist/signals/notifications-d1.js.map +1 -0
- package/dist/signals/router.d.ts +73 -0
- package/dist/signals/router.d.ts.map +1 -0
- package/dist/signals/router.js +240 -0
- package/dist/signals/router.js.map +1 -0
- package/dist/signals/storage.d.ts +11 -0
- package/dist/signals/storage.d.ts.map +1 -0
- package/dist/signals/storage.js +27 -0
- package/dist/signals/storage.js.map +1 -0
- package/dist/signals/thread-do-routes.d.ts +82 -0
- package/dist/signals/thread-do-routes.d.ts.map +1 -0
- package/dist/signals/thread-do-routes.js +660 -0
- package/dist/signals/thread-do-routes.js.map +1 -0
- package/dist/signals/thread-state-d1.d.ts +22 -0
- package/dist/signals/thread-state-d1.d.ts.map +1 -0
- package/dist/signals/thread-state-d1.js +83 -0
- package/dist/signals/thread-state-d1.js.map +1 -0
- package/package.json +11 -2
|
@@ -0,0 +1,827 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Track D (M-006), CI-M-006-003 — createScheduleRouter, the tenant facade over
|
|
3
|
+
// the schedules domain. Schedule rows have NO tenant column (DL-013): the tenant
|
|
4
|
+
// is stamped into metadata.tenantId at create (server-controlled, never a client
|
|
5
|
+
// value) and every read/list/mutation is tenant-scoped on it. Ids are
|
|
6
|
+
// SERVER-MINTED `${prefix}${uuid}` (agent_/schedule_) — a client cannot name the
|
|
7
|
+
// id, so it cannot collide with (or probe for) another tenant's schedule, the
|
|
8
|
+
// INV-1 posture applied to schedule ids; core's slugified client-id path is
|
|
9
|
+
// avoided (a slugify-drift + existence-oracle vector).
|
|
10
|
+
//
|
|
11
|
+
// The write path is an ingestion trust boundary (P6-lite, DL-006) — the same gate
|
|
12
|
+
// order createSignalRouter / createObjectiveRouter enforce:
|
|
13
|
+
//
|
|
14
|
+
// 1. resolve (authenticate -> INV-3 -> bind) -> 401 / 403
|
|
15
|
+
// 2. coarse role (RUN_START_ROLES) on MUTATIONS -> 403 (reads stay coarse)
|
|
16
|
+
// 3. per-resource ownership (metadata.tenantId match) -> 404 (no oracle)
|
|
17
|
+
// 4. size cap on the raw body, THEN JSON parse -> 413 / 400
|
|
18
|
+
// 5. field validation + per-tenant COUNT cap (create) + fire-RATE cap (DL-007)
|
|
19
|
+
// 6. P4 reserved requestContext-key rejection (DL-004) -> 400
|
|
20
|
+
// 7. audit (schedule.route) + persist
|
|
21
|
+
//
|
|
22
|
+
// P4 STORED-CONTEXT BARRIER (a) (DL-004): a stored WorkflowSchedule.requestContext
|
|
23
|
+
// / agent ScheduleStreamOptions.requestContext replays into a future run, so it is
|
|
24
|
+
// a stored-capability channel — the same class as the approval create-route leak.
|
|
25
|
+
// Create/update REJECT any requestContext naming a reserved key (the whole
|
|
26
|
+
// `breakwater.` namespace + core's 'mastra:goal'), matching the tick's strip
|
|
27
|
+
// (barrier b). Both kinds are guarded (workflow requestContext + agent
|
|
28
|
+
// ifIdle.streamOptions.requestContext).
|
|
29
|
+
//
|
|
30
|
+
// Every MUTATION is audited on ACCEPT and on EVERY post-auth denial (role 403,
|
|
31
|
+
// foreign 404, cap/field/reserved-key 400). A GET/list is audited only on a
|
|
32
|
+
// post-auth denial (a cross-tenant probe); a benign successful read is not. A
|
|
33
|
+
// pre-auth failure (401 / resolver throw -> 403) is NOT audited: an
|
|
34
|
+
// unauthenticated flood must never be able to write the log.
|
|
35
|
+
//
|
|
36
|
+
// AGENT schedules are creatable/manageable here. Their firing belongs solely to
|
|
37
|
+
// the tick's optional runtime-driven `startAgent` seam; without it, the tick
|
|
38
|
+
// retains the audited fail-closed skip. This surface mints no capability and
|
|
39
|
+
// starts no runs.
|
|
40
|
+
import { AGENT_SCHEDULE_PREFIX, ScheduleInputSchema, toScheduleView, WORKFLOW_SCHEDULE_PREFIX, } from '@mastra/core/schedules';
|
|
41
|
+
import { computeNextFireAt, validateCron } from '@mastra/core/workflows';
|
|
42
|
+
import { RUN_START_ROLES, TenantResolutionError, } from '../approval-api/index.js';
|
|
43
|
+
import { RunRouteError, requireOwnedMemoryId } from '../host-kit/index.js';
|
|
44
|
+
import { safeDecodeSegment } from '../host-kit/route-path.js';
|
|
45
|
+
import { internalErrorResponse } from '../internal-error-response.js';
|
|
46
|
+
import { nonnegativeSafeInteger, positiveSafeInteger, } from '../numeric-config.js';
|
|
47
|
+
import { isReservedScheduleContextKey } from './tick.js';
|
|
48
|
+
function json(payload, status = 200) {
|
|
49
|
+
return new Response(JSON.stringify(payload), {
|
|
50
|
+
status,
|
|
51
|
+
headers: {
|
|
52
|
+
'content-type': 'application/json',
|
|
53
|
+
'cache-control': 'no-store',
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function reject(reason, message, status = 400) {
|
|
58
|
+
return { reason, message, status };
|
|
59
|
+
}
|
|
60
|
+
/** A schedule is owned by the tenant iff its metadata.tenantId matches. */
|
|
61
|
+
function ownsSchedule(schedule, tenantId) {
|
|
62
|
+
const owner = schedule.metadata
|
|
63
|
+
?.tenantId;
|
|
64
|
+
return owner === tenantId;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The P4 barrier (a) over BOTH requestContext-carrying surfaces of a create/update
|
|
68
|
+
* body: the top-level `requestContext` (workflow + non-standard agent) and the
|
|
69
|
+
* agent `ifIdle.streamOptions.requestContext` (core's only other stored-context
|
|
70
|
+
* location — `ScheduleIfActive` has none). Returns a Rejection naming the offending
|
|
71
|
+
* key, or undefined when both surfaces are clean. One helper so the create and
|
|
72
|
+
* update paths cannot drift on which surfaces are guarded.
|
|
73
|
+
*/
|
|
74
|
+
function reservedContextRejection(body, target) {
|
|
75
|
+
const idle = body.ifIdle;
|
|
76
|
+
const surfaces = target === 'workflow'
|
|
77
|
+
? [['requestContext', body.requestContext]]
|
|
78
|
+
: [
|
|
79
|
+
[
|
|
80
|
+
'ifIdle.streamOptions.requestContext',
|
|
81
|
+
idle?.streamOptions?.requestContext,
|
|
82
|
+
],
|
|
83
|
+
];
|
|
84
|
+
for (const [label, ctx] of surfaces) {
|
|
85
|
+
if (ctx === undefined)
|
|
86
|
+
continue;
|
|
87
|
+
if (typeof ctx !== 'object' || ctx === null || Array.isArray(ctx)) {
|
|
88
|
+
return reject('reserved-context-key', `${label} must be an object`);
|
|
89
|
+
}
|
|
90
|
+
const offending = Object.keys(ctx).find(isReservedScheduleContextKey);
|
|
91
|
+
if (offending !== undefined) {
|
|
92
|
+
return reject('reserved-context-key', `${label} may not carry the reserved key '${offending}'`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* computeNextFireAt, but a calendrically-impossible cron — one `validateCron`
|
|
99
|
+
* accepts (syntactically legal) yet that has NO future occurrence, e.g.
|
|
100
|
+
* `0 0 30 2 *` — yields a `cron-invalid` Rejection instead of a raw throw. Without
|
|
101
|
+
* this the throw would escape to the router's outer catch and surface as an
|
|
102
|
+
* UNAUDITED 500 with the raw error, where every other cron failure is a clean,
|
|
103
|
+
* audited 400.
|
|
104
|
+
*/
|
|
105
|
+
function nextFireOrReject(cron, timezone, after) {
|
|
106
|
+
try {
|
|
107
|
+
return {
|
|
108
|
+
ok: true,
|
|
109
|
+
value: computeNextFireAt(cron, {
|
|
110
|
+
...(timezone !== undefined ? { timezone } : {}),
|
|
111
|
+
after,
|
|
112
|
+
}),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
return {
|
|
117
|
+
ok: false,
|
|
118
|
+
error: reject('cron-invalid', error instanceof Error
|
|
119
|
+
? error.message
|
|
120
|
+
: 'cron has no future occurrence'),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** Reject a cron whose two-consecutive-fire interval is under the floor (DL-007). */
|
|
125
|
+
function checkFireRate(cron, timezone, minFireIntervalMs, now) {
|
|
126
|
+
const first = nextFireOrReject(cron, timezone, now);
|
|
127
|
+
if (!first.ok)
|
|
128
|
+
return first.error;
|
|
129
|
+
const second = nextFireOrReject(cron, timezone, first.value);
|
|
130
|
+
if (!second.ok)
|
|
131
|
+
return second.error;
|
|
132
|
+
// NOTE (DL-007 limitation): this samples only the NEXT two fires at request
|
|
133
|
+
// time. A non-uniform cron (e.g. a dense minute cluster + a long gap) can pass
|
|
134
|
+
// when sampled during the gap yet still fire the dense cluster later; the
|
|
135
|
+
// per-tenant COUNT cap and the tick's run-cap seam are the real aggregate
|
|
136
|
+
// backstops. A precise cycle-wide bound is deliberately not attempted here.
|
|
137
|
+
if (second.value - first.value < minFireIntervalMs) {
|
|
138
|
+
return reject('fire-rate-too-high', `cron fires more often than the ${minFireIntervalMs}ms floor`);
|
|
139
|
+
}
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
const WORKFLOW_CREATE_FIELDS = new Set([
|
|
143
|
+
'workflowId',
|
|
144
|
+
'cron',
|
|
145
|
+
'timezone',
|
|
146
|
+
'inputData',
|
|
147
|
+
'initialState',
|
|
148
|
+
'requestContext',
|
|
149
|
+
'metadata',
|
|
150
|
+
'status',
|
|
151
|
+
]);
|
|
152
|
+
const AGENT_CREATE_FIELDS = new Set([
|
|
153
|
+
'agentId',
|
|
154
|
+
'cron',
|
|
155
|
+
'prompt',
|
|
156
|
+
'name',
|
|
157
|
+
'timezone',
|
|
158
|
+
'threadId',
|
|
159
|
+
'resourceId',
|
|
160
|
+
'signalType',
|
|
161
|
+
'tagName',
|
|
162
|
+
'attributes',
|
|
163
|
+
'providerOptions',
|
|
164
|
+
'ifActive',
|
|
165
|
+
'ifIdle',
|
|
166
|
+
'metadata',
|
|
167
|
+
'status',
|
|
168
|
+
]);
|
|
169
|
+
const WORKFLOW_UPDATE_FIELDS = new Set([
|
|
170
|
+
'cron',
|
|
171
|
+
'timezone',
|
|
172
|
+
'status',
|
|
173
|
+
'inputData',
|
|
174
|
+
'initialState',
|
|
175
|
+
'requestContext',
|
|
176
|
+
'metadata',
|
|
177
|
+
]);
|
|
178
|
+
const AGENT_UPDATE_FIELDS = new Set([
|
|
179
|
+
'cron',
|
|
180
|
+
'timezone',
|
|
181
|
+
'status',
|
|
182
|
+
'prompt',
|
|
183
|
+
'name',
|
|
184
|
+
'signalType',
|
|
185
|
+
'tagName',
|
|
186
|
+
'attributes',
|
|
187
|
+
'providerOptions',
|
|
188
|
+
'ifActive',
|
|
189
|
+
'ifIdle',
|
|
190
|
+
'metadata',
|
|
191
|
+
]);
|
|
192
|
+
function firstUnknownField(body, allowed) {
|
|
193
|
+
return Object.keys(body).find((key) => !allowed.has(key));
|
|
194
|
+
}
|
|
195
|
+
function nonEmptyString(value) {
|
|
196
|
+
return typeof value === 'string' && value.length > 0;
|
|
197
|
+
}
|
|
198
|
+
function metadataOrReject(value) {
|
|
199
|
+
if (value === undefined ||
|
|
200
|
+
typeof value !== 'object' ||
|
|
201
|
+
value === null ||
|
|
202
|
+
Array.isArray(value)) {
|
|
203
|
+
return {
|
|
204
|
+
ok: false,
|
|
205
|
+
error: reject('metadata-invalid', 'metadata must be an object'),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
return { ok: true, value: value };
|
|
209
|
+
}
|
|
210
|
+
function validateMemoryIds(body, tenant) {
|
|
211
|
+
const hasThread = body.threadId !== undefined;
|
|
212
|
+
const hasResource = body.resourceId !== undefined;
|
|
213
|
+
if (hasThread && !nonEmptyString(body.threadId)) {
|
|
214
|
+
return reject('threadId-invalid', 'threadId must be a non-empty string');
|
|
215
|
+
}
|
|
216
|
+
if (hasResource && !nonEmptyString(body.resourceId)) {
|
|
217
|
+
return reject('resourceId-invalid', 'resourceId must be a non-empty string');
|
|
218
|
+
}
|
|
219
|
+
if (!hasThread) {
|
|
220
|
+
const offender = ['resourceId', 'signalType', 'ifActive', 'ifIdle'].find((field) => body[field] !== undefined);
|
|
221
|
+
if (offender !== undefined) {
|
|
222
|
+
return reject(`threadless-field:${offender}`, `${offender} requires threadId`);
|
|
223
|
+
}
|
|
224
|
+
return undefined;
|
|
225
|
+
}
|
|
226
|
+
if (!hasResource) {
|
|
227
|
+
return reject('resourceId-required', 'resourceId is required when threadId is set');
|
|
228
|
+
}
|
|
229
|
+
requireOwnedMemoryId(tenant, body.threadId, 'threadId');
|
|
230
|
+
requireOwnedMemoryId(tenant, body.resourceId, 'resourceId');
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
function normalizeAgentTarget(scheduleId, values) {
|
|
234
|
+
const parsed = ScheduleInputSchema.safeParse({
|
|
235
|
+
scheduleId,
|
|
236
|
+
agentId: values.agentId,
|
|
237
|
+
prompt: values.prompt,
|
|
238
|
+
threadId: values.threadId,
|
|
239
|
+
resourceId: values.resourceId,
|
|
240
|
+
signalType: values.signalType,
|
|
241
|
+
tagName: values.tagName,
|
|
242
|
+
attributes: values.attributes,
|
|
243
|
+
providerOptions: values.providerOptions,
|
|
244
|
+
ifActive: values.ifActive,
|
|
245
|
+
ifIdle: values.ifIdle,
|
|
246
|
+
});
|
|
247
|
+
if (!parsed.success) {
|
|
248
|
+
return {
|
|
249
|
+
ok: false,
|
|
250
|
+
error: reject('agent-options-invalid', parsed.error.issues[0]?.message ?? 'invalid agent schedule options'),
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
const { scheduleId: _scheduleId, agentId, prompt, ...runtimeFields } = parsed.data;
|
|
254
|
+
return {
|
|
255
|
+
ok: true,
|
|
256
|
+
value: {
|
|
257
|
+
type: 'agent',
|
|
258
|
+
agentId,
|
|
259
|
+
prompt,
|
|
260
|
+
...(values.name !== undefined ? { name: values.name } : {}),
|
|
261
|
+
...runtimeFields,
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
/** Build a fresh Schedule row from a create body, tenant-stamped + server-id'd. */
|
|
266
|
+
function buildCreateRow(body, tenant, now, minFireIntervalMs) {
|
|
267
|
+
const tenantId = tenant.tenantId;
|
|
268
|
+
const hasWorkflow = 'workflowId' in body && body.workflowId !== undefined;
|
|
269
|
+
const hasAgent = 'agentId' in body && body.agentId !== undefined;
|
|
270
|
+
if (hasWorkflow === hasAgent) {
|
|
271
|
+
return {
|
|
272
|
+
ok: false,
|
|
273
|
+
error: reject('target-ambiguous', 'exactly one of workflowId or agentId is required'),
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
if (!nonEmptyString(body.cron)) {
|
|
277
|
+
return {
|
|
278
|
+
ok: false,
|
|
279
|
+
error: reject('cron-invalid', 'cron must be a string'),
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
const cron = body.cron;
|
|
283
|
+
const timezone = body.timezone === undefined ? undefined : body.timezone;
|
|
284
|
+
if (timezone !== undefined && typeof timezone !== 'string') {
|
|
285
|
+
return {
|
|
286
|
+
ok: false,
|
|
287
|
+
error: reject('timezone-invalid', 'timezone must be a string'),
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
try {
|
|
291
|
+
validateCron(cron, timezone);
|
|
292
|
+
}
|
|
293
|
+
catch (error) {
|
|
294
|
+
return {
|
|
295
|
+
ok: false,
|
|
296
|
+
error: reject('cron-invalid', error instanceof Error ? error.message : 'invalid cron'),
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
const fireRate = checkFireRate(cron, timezone, minFireIntervalMs, now);
|
|
300
|
+
if (fireRate)
|
|
301
|
+
return { ok: false, error: fireRate };
|
|
302
|
+
const status = body.status === undefined ? 'active' : body.status;
|
|
303
|
+
if (status !== 'active' && status !== 'paused') {
|
|
304
|
+
return {
|
|
305
|
+
ok: false,
|
|
306
|
+
error: reject('status-invalid', "status must be 'active' or 'paused'"),
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
let clientMetadata = {};
|
|
310
|
+
if (body.metadata !== undefined) {
|
|
311
|
+
const parsedMetadata = metadataOrReject(body.metadata);
|
|
312
|
+
if (!parsedMetadata.ok)
|
|
313
|
+
return parsedMetadata;
|
|
314
|
+
clientMetadata = parsedMetadata.value;
|
|
315
|
+
}
|
|
316
|
+
// tenantId is stamped LAST so a client value can never override it (DL-013).
|
|
317
|
+
const metadata = {
|
|
318
|
+
...clientMetadata,
|
|
319
|
+
tenantId,
|
|
320
|
+
};
|
|
321
|
+
// checkFireRate above already proved the cron has a future occurrence, so this
|
|
322
|
+
// cannot throw; nextFireOrReject keeps it defensive without a bare computeNextFireAt.
|
|
323
|
+
const nextFire = nextFireOrReject(cron, timezone, now);
|
|
324
|
+
if (!nextFire.ok)
|
|
325
|
+
return { ok: false, error: nextFire.error };
|
|
326
|
+
const nextFireAt = nextFire.value;
|
|
327
|
+
const common = {
|
|
328
|
+
cron,
|
|
329
|
+
...(timezone !== undefined ? { timezone } : {}),
|
|
330
|
+
status,
|
|
331
|
+
nextFireAt,
|
|
332
|
+
createdAt: now,
|
|
333
|
+
updatedAt: now,
|
|
334
|
+
metadata,
|
|
335
|
+
};
|
|
336
|
+
if (hasWorkflow) {
|
|
337
|
+
const unknown = firstUnknownField(body, WORKFLOW_CREATE_FIELDS);
|
|
338
|
+
if (unknown !== undefined) {
|
|
339
|
+
return {
|
|
340
|
+
ok: false,
|
|
341
|
+
error: reject(`field-not-allowed:${unknown}`, `field '${unknown}' is not settable on a workflow schedule`),
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
if (!nonEmptyString(body.workflowId)) {
|
|
345
|
+
return {
|
|
346
|
+
ok: false,
|
|
347
|
+
error: reject('workflowId-invalid', 'workflowId must be a non-empty string'),
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
const reserved = reservedContextRejection(body, 'workflow');
|
|
351
|
+
if (reserved)
|
|
352
|
+
return { ok: false, error: reserved };
|
|
353
|
+
const target = {
|
|
354
|
+
type: 'workflow',
|
|
355
|
+
workflowId: body.workflowId,
|
|
356
|
+
...(body.inputData !== undefined ? { inputData: body.inputData } : {}),
|
|
357
|
+
...(body.initialState !== undefined
|
|
358
|
+
? { initialState: body.initialState }
|
|
359
|
+
: {}),
|
|
360
|
+
...(body.requestContext !== undefined
|
|
361
|
+
? { requestContext: body.requestContext }
|
|
362
|
+
: {}),
|
|
363
|
+
};
|
|
364
|
+
return {
|
|
365
|
+
ok: true,
|
|
366
|
+
value: {
|
|
367
|
+
id: `${WORKFLOW_SCHEDULE_PREFIX}${crypto.randomUUID()}`,
|
|
368
|
+
target,
|
|
369
|
+
...common,
|
|
370
|
+
},
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
// Agent schedule.
|
|
374
|
+
const unknown = firstUnknownField(body, AGENT_CREATE_FIELDS);
|
|
375
|
+
if (unknown !== undefined) {
|
|
376
|
+
return {
|
|
377
|
+
ok: false,
|
|
378
|
+
error: reject(`field-not-allowed:${unknown}`, `field '${unknown}' is not settable on an agent schedule`),
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
if (!nonEmptyString(body.agentId)) {
|
|
382
|
+
return {
|
|
383
|
+
ok: false,
|
|
384
|
+
error: reject('agentId-invalid', 'agentId must be a non-empty string'),
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
if (!nonEmptyString(body.prompt)) {
|
|
388
|
+
return {
|
|
389
|
+
ok: false,
|
|
390
|
+
error: reject('prompt-invalid', 'prompt must be a non-empty string'),
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
if (body.name !== undefined && typeof body.name !== 'string') {
|
|
394
|
+
return {
|
|
395
|
+
ok: false,
|
|
396
|
+
error: reject('name-invalid', 'name must be a string'),
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
const memory = validateMemoryIds(body, tenant);
|
|
400
|
+
if (memory)
|
|
401
|
+
return { ok: false, error: memory };
|
|
402
|
+
const reserved = reservedContextRejection(body, 'agent');
|
|
403
|
+
if (reserved)
|
|
404
|
+
return { ok: false, error: reserved };
|
|
405
|
+
const agentTarget = normalizeAgentTarget('pending', body);
|
|
406
|
+
if (!agentTarget.ok)
|
|
407
|
+
return agentTarget;
|
|
408
|
+
return {
|
|
409
|
+
ok: true,
|
|
410
|
+
value: {
|
|
411
|
+
id: `${AGENT_SCHEDULE_PREFIX}${crypto.randomUUID()}`,
|
|
412
|
+
target: agentTarget.value,
|
|
413
|
+
...common,
|
|
414
|
+
ownerType: 'agent',
|
|
415
|
+
ownerId: body.agentId,
|
|
416
|
+
},
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
export function createScheduleRouter(options) {
|
|
420
|
+
const { resolve, store } = options;
|
|
421
|
+
const roles = options.roles ?? RUN_START_ROLES;
|
|
422
|
+
const maxSchedules = nonnegativeSafeInteger(options.maxSchedulesPerTenant ?? 100, 'maxSchedulesPerTenant');
|
|
423
|
+
const minFireIntervalMs = positiveSafeInteger(options.minFireIntervalMs ?? 60_000, 'minFireIntervalMs');
|
|
424
|
+
const maxContentBytes = nonnegativeSafeInteger(options.maxContentBytes ?? 16_384, 'schedule maxContentBytes');
|
|
425
|
+
const base = options.basePath ?? '/api/schedules';
|
|
426
|
+
const baseSegments = base.split('/').filter(Boolean);
|
|
427
|
+
return async (request) => {
|
|
428
|
+
const url = new URL(request.url);
|
|
429
|
+
const segments = url.pathname.split('/').filter(Boolean);
|
|
430
|
+
if (segments.length < baseSegments.length ||
|
|
431
|
+
segments.length > baseSegments.length + 2 ||
|
|
432
|
+
baseSegments.some((seg, i) => segments[i] !== seg)) {
|
|
433
|
+
return null;
|
|
434
|
+
}
|
|
435
|
+
// Malformed percent-encoding in the id is not a real route target —
|
|
436
|
+
// route-absent, never a pre-auth decodeURIComponent throw out of the handler.
|
|
437
|
+
let id;
|
|
438
|
+
if (segments.length > baseSegments.length) {
|
|
439
|
+
id = safeDecodeSegment(segments[baseSegments.length]);
|
|
440
|
+
if (id === undefined)
|
|
441
|
+
return null;
|
|
442
|
+
}
|
|
443
|
+
const sub = segments.length === baseSegments.length + 2
|
|
444
|
+
? segments[baseSegments.length + 1]
|
|
445
|
+
: undefined;
|
|
446
|
+
// Resolve the (method, path shape) into an operation, or fall through / 405.
|
|
447
|
+
const operation = resolveOperation(request.method, id, sub);
|
|
448
|
+
if (operation === null)
|
|
449
|
+
return null;
|
|
450
|
+
if (operation === undefined) {
|
|
451
|
+
return json({ error: 'method not allowed' }, 405);
|
|
452
|
+
}
|
|
453
|
+
const isMutation = operation !== 'get' && operation !== 'list' && operation !== 'triggers';
|
|
454
|
+
// `tenant` is a hoisted `let` so the `audit` closure (defined before the try)
|
|
455
|
+
// can read it. It stays undefined until resolve succeeds, and the closure
|
|
456
|
+
// no-ops while it is — so a pre-auth failure never writes the log (an
|
|
457
|
+
// unauthenticated flood cannot spam the audit sink).
|
|
458
|
+
let tenant;
|
|
459
|
+
const audit = async (outcome, reason) => {
|
|
460
|
+
if (!options.audit || !tenant)
|
|
461
|
+
return;
|
|
462
|
+
// A benign read is not audited; only its denial is.
|
|
463
|
+
if (!isMutation && outcome === 'accepted')
|
|
464
|
+
return;
|
|
465
|
+
await options.audit({
|
|
466
|
+
type: 'schedule.route',
|
|
467
|
+
tenantId: tenant.tenantId,
|
|
468
|
+
actorId: tenant.actor.id,
|
|
469
|
+
operation,
|
|
470
|
+
...(id !== undefined ? { scheduleId: id } : {}),
|
|
471
|
+
outcome,
|
|
472
|
+
...(reason !== undefined ? { reason } : {}),
|
|
473
|
+
timestamp: new Date().toISOString(),
|
|
474
|
+
});
|
|
475
|
+
};
|
|
476
|
+
try {
|
|
477
|
+
// 1. Resolve.
|
|
478
|
+
tenant = await resolve(request);
|
|
479
|
+
if (!tenant)
|
|
480
|
+
return json({ error: 'authentication required' }, 401);
|
|
481
|
+
// Captured after the guard so the closures below don't need a non-null
|
|
482
|
+
// assertion on the hoisted `tenant` let.
|
|
483
|
+
const ownerTenant = tenant.tenantId;
|
|
484
|
+
// 2. Coarse role on mutations.
|
|
485
|
+
if (isMutation && !roles.includes(tenant.actor.role)) {
|
|
486
|
+
await audit('rejected', 'forbidden-role');
|
|
487
|
+
return json({ error: 'forbidden' }, 403);
|
|
488
|
+
}
|
|
489
|
+
// LIST — tenant-filtered (DL-013 post-filter over the domain list).
|
|
490
|
+
if (operation === 'list') {
|
|
491
|
+
const all = await store.listSchedules();
|
|
492
|
+
const mine = all.filter((s) => ownsSchedule(s, ownerTenant));
|
|
493
|
+
return json({ schedules: mine.map(toView) });
|
|
494
|
+
}
|
|
495
|
+
// CREATE — count cap, field/cron/fire-rate/reserved-key checks, persist.
|
|
496
|
+
if (operation === 'create') {
|
|
497
|
+
const parsed = await readBody(request, maxContentBytes);
|
|
498
|
+
if (parsed instanceof Response) {
|
|
499
|
+
await audit('rejected', parsed.status === 413 ? 'payload-too-large' : 'malformed-body');
|
|
500
|
+
return parsed;
|
|
501
|
+
}
|
|
502
|
+
// COUNT cap (DL-007): a tenant may not exceed its schedule budget. This
|
|
503
|
+
// is check-then-act (no atomic increment through the domain seam), so N
|
|
504
|
+
// concurrent creates at count = cap-1 can each read the same count and
|
|
505
|
+
// all insert, overshooting by up to N — self-limited to the requester's
|
|
506
|
+
// own tenant. The tick's run-cap seam is the real cost backstop; a hard
|
|
507
|
+
// atomic cap would need a transaction D1 does not expose here.
|
|
508
|
+
const owned = (await store.listSchedules()).filter((s) => ownsSchedule(s, ownerTenant));
|
|
509
|
+
if (owned.length >= maxSchedules) {
|
|
510
|
+
await audit('rejected', 'schedule-count-cap');
|
|
511
|
+
return json({ error: `tenant schedule cap of ${maxSchedules} reached` }, 400);
|
|
512
|
+
}
|
|
513
|
+
const built = buildCreateRow(parsed, tenant, Date.now(), minFireIntervalMs);
|
|
514
|
+
if (!built.ok) {
|
|
515
|
+
await audit('rejected', built.error.reason);
|
|
516
|
+
return json({ error: built.error.message }, built.error.status);
|
|
517
|
+
}
|
|
518
|
+
const created = await store.createSchedule(built.value);
|
|
519
|
+
await audit('accepted');
|
|
520
|
+
return json({ schedule: toView(created) }, 201);
|
|
521
|
+
}
|
|
522
|
+
// Everything below addresses ONE schedule by id — 404 (no oracle) on a
|
|
523
|
+
// missing OR foreign one, BEFORE any work, both audited the same.
|
|
524
|
+
const scheduleId = id;
|
|
525
|
+
const existing = await store.getSchedule(scheduleId);
|
|
526
|
+
if (!existing || !ownsSchedule(existing, tenant.tenantId)) {
|
|
527
|
+
await audit('rejected', 'not-found');
|
|
528
|
+
return json({ error: 'not found' }, 404);
|
|
529
|
+
}
|
|
530
|
+
if (operation === 'get') {
|
|
531
|
+
return json({ schedule: toView(existing) });
|
|
532
|
+
}
|
|
533
|
+
if (operation === 'triggers') {
|
|
534
|
+
// Default the limit so an omitted/garbage `?limit` never returns an
|
|
535
|
+
// UNBOUNDED history (trigger rows grow per fire; SCHEDULE_TRIGGER_
|
|
536
|
+
// RETENTION_DAYS is opt-in/unset by default).
|
|
537
|
+
const limit = clampLimit(url.searchParams.get('limit')) ?? 100;
|
|
538
|
+
const triggers = await store.listTriggers(scheduleId, { limit });
|
|
539
|
+
return json({ triggers });
|
|
540
|
+
}
|
|
541
|
+
if (operation === 'delete') {
|
|
542
|
+
await store.deleteSchedule(scheduleId);
|
|
543
|
+
await audit('accepted');
|
|
544
|
+
return json({ ok: true });
|
|
545
|
+
}
|
|
546
|
+
if (operation === 'pause') {
|
|
547
|
+
if (existing.status === 'paused') {
|
|
548
|
+
await audit('accepted');
|
|
549
|
+
return json({ schedule: toView(existing) });
|
|
550
|
+
}
|
|
551
|
+
const updated = await store.updateSchedule(scheduleId, {
|
|
552
|
+
status: 'paused',
|
|
553
|
+
});
|
|
554
|
+
await audit('accepted');
|
|
555
|
+
return json({ schedule: toView(updated) });
|
|
556
|
+
}
|
|
557
|
+
if (operation === 'resume') {
|
|
558
|
+
if (existing.status === 'active') {
|
|
559
|
+
await audit('accepted');
|
|
560
|
+
return json({ schedule: toView(existing) });
|
|
561
|
+
}
|
|
562
|
+
// Re-activating recomputes nextFireAt from now (core's resume semantics).
|
|
563
|
+
// Guarded: a legacy row with a calendrically-impossible cron would else
|
|
564
|
+
// throw an unaudited 500 here (create now rejects such crons, so this is
|
|
565
|
+
// defense-in-depth for pre-existing rows).
|
|
566
|
+
const nextFire = nextFireOrReject(existing.cron, existing.timezone, Date.now());
|
|
567
|
+
if (!nextFire.ok) {
|
|
568
|
+
await audit('rejected', nextFire.error.reason);
|
|
569
|
+
return json({ error: nextFire.error.message }, nextFire.error.status);
|
|
570
|
+
}
|
|
571
|
+
const nextFireAt = nextFire.value;
|
|
572
|
+
const updated = await store.updateSchedule(scheduleId, {
|
|
573
|
+
status: 'active',
|
|
574
|
+
nextFireAt,
|
|
575
|
+
});
|
|
576
|
+
await audit('accepted');
|
|
577
|
+
return json({ schedule: toView(updated) });
|
|
578
|
+
}
|
|
579
|
+
// UPDATE (PATCH).
|
|
580
|
+
const parsed = await readBody(request, maxContentBytes);
|
|
581
|
+
if (parsed instanceof Response) {
|
|
582
|
+
await audit('rejected', parsed.status === 413 ? 'payload-too-large' : 'malformed-body');
|
|
583
|
+
return parsed;
|
|
584
|
+
}
|
|
585
|
+
const patch = buildUpdatePatch(existing, parsed, minFireIntervalMs, Date.now());
|
|
586
|
+
if (!patch.ok) {
|
|
587
|
+
await audit('rejected', patch.error.reason);
|
|
588
|
+
return json({ error: patch.error.message }, patch.error.status);
|
|
589
|
+
}
|
|
590
|
+
const updated = await store.updateSchedule(scheduleId, patch.value);
|
|
591
|
+
await audit('accepted');
|
|
592
|
+
return json({ schedule: toView(updated) });
|
|
593
|
+
}
|
|
594
|
+
catch (error) {
|
|
595
|
+
if (error instanceof RunRouteError) {
|
|
596
|
+
await audit('rejected', error.status === 404
|
|
597
|
+
? 'foreign-memory-id'
|
|
598
|
+
: `route-error-${error.status}`);
|
|
599
|
+
return json({ error: error.message }, error.status);
|
|
600
|
+
}
|
|
601
|
+
if (error instanceof TenantResolutionError) {
|
|
602
|
+
// Pre-auth: unauthenticated, so not audited.
|
|
603
|
+
return json({ error: 'forbidden' }, 403);
|
|
604
|
+
}
|
|
605
|
+
return internalErrorResponse('schedules', error);
|
|
606
|
+
}
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* Map (method, path shape) to an operation. `null` = not our route (fall
|
|
611
|
+
* through); `undefined` = our path but a wrong method (405).
|
|
612
|
+
*/
|
|
613
|
+
function resolveOperation(method, id, sub) {
|
|
614
|
+
if (id === undefined) {
|
|
615
|
+
if (method === 'POST')
|
|
616
|
+
return 'create';
|
|
617
|
+
if (method === 'GET')
|
|
618
|
+
return 'list';
|
|
619
|
+
return undefined;
|
|
620
|
+
}
|
|
621
|
+
if (sub === undefined) {
|
|
622
|
+
if (method === 'GET')
|
|
623
|
+
return 'get';
|
|
624
|
+
if (method === 'PATCH')
|
|
625
|
+
return 'update';
|
|
626
|
+
if (method === 'DELETE')
|
|
627
|
+
return 'delete';
|
|
628
|
+
return undefined;
|
|
629
|
+
}
|
|
630
|
+
if (sub === 'pause')
|
|
631
|
+
return method === 'POST' ? 'pause' : undefined;
|
|
632
|
+
if (sub === 'resume')
|
|
633
|
+
return method === 'POST' ? 'resume' : undefined;
|
|
634
|
+
if (sub === 'triggers')
|
|
635
|
+
return method === 'GET' ? 'triggers' : undefined;
|
|
636
|
+
return null;
|
|
637
|
+
}
|
|
638
|
+
function buildUpdatePatch(existing, body, minFireIntervalMs, now) {
|
|
639
|
+
const allowed = existing.target.type === 'workflow'
|
|
640
|
+
? WORKFLOW_UPDATE_FIELDS
|
|
641
|
+
: AGENT_UPDATE_FIELDS;
|
|
642
|
+
const unknown = firstUnknownField(body, allowed);
|
|
643
|
+
if (unknown !== undefined) {
|
|
644
|
+
return {
|
|
645
|
+
ok: false,
|
|
646
|
+
error: reject(`field-not-allowed:${unknown}`, `field '${unknown}' is not updatable`),
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
const patch = {};
|
|
650
|
+
const nextCron = body.cron !== undefined ? body.cron : existing.cron;
|
|
651
|
+
const nextTimezone = body.timezone !== undefined ? body.timezone : existing.timezone;
|
|
652
|
+
if (body.cron !== undefined || body.timezone !== undefined) {
|
|
653
|
+
if (body.cron !== undefined && !nonEmptyString(body.cron)) {
|
|
654
|
+
return {
|
|
655
|
+
ok: false,
|
|
656
|
+
error: reject('cron-invalid', 'cron must be a string'),
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
// The same non-string timezone guard create enforces — a number/boolean
|
|
660
|
+
// timezone else slips past validateCron (which does not throw on it) and
|
|
661
|
+
// persists into the timezone TEXT column.
|
|
662
|
+
if (body.timezone !== undefined && typeof body.timezone !== 'string') {
|
|
663
|
+
return {
|
|
664
|
+
ok: false,
|
|
665
|
+
error: reject('timezone-invalid', 'timezone must be a string'),
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
try {
|
|
669
|
+
validateCron(nextCron, nextTimezone);
|
|
670
|
+
}
|
|
671
|
+
catch (error) {
|
|
672
|
+
return {
|
|
673
|
+
ok: false,
|
|
674
|
+
error: reject('cron-invalid', error instanceof Error ? error.message : 'invalid cron'),
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
const fireRate = checkFireRate(nextCron, nextTimezone, minFireIntervalMs, now);
|
|
678
|
+
if (fireRate)
|
|
679
|
+
return { ok: false, error: fireRate };
|
|
680
|
+
patch.cron = nextCron;
|
|
681
|
+
if (body.timezone !== undefined)
|
|
682
|
+
patch.timezone = nextTimezone;
|
|
683
|
+
// Recompute the next fire on a cron/timezone change (checkFireRate above
|
|
684
|
+
// already proved computability, so this cannot throw).
|
|
685
|
+
const nextFire = nextFireOrReject(nextCron, nextTimezone, now);
|
|
686
|
+
if (!nextFire.ok)
|
|
687
|
+
return { ok: false, error: nextFire.error };
|
|
688
|
+
patch.nextFireAt = nextFire.value;
|
|
689
|
+
}
|
|
690
|
+
if (body.status !== undefined) {
|
|
691
|
+
if (body.status !== 'active' && body.status !== 'paused') {
|
|
692
|
+
return {
|
|
693
|
+
ok: false,
|
|
694
|
+
error: reject('status-invalid', "status must be 'active' or 'paused'"),
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
patch.status = body.status;
|
|
698
|
+
}
|
|
699
|
+
const reserved = reservedContextRejection(body, existing.target.type);
|
|
700
|
+
if (reserved)
|
|
701
|
+
return { ok: false, error: reserved };
|
|
702
|
+
// Patch the target in place (kind is fixed at create — a workflow schedule
|
|
703
|
+
// stays a workflow schedule). Only the settable target fields are merged.
|
|
704
|
+
const nextTarget = patchTarget(existing, body);
|
|
705
|
+
if (!nextTarget.ok)
|
|
706
|
+
return nextTarget;
|
|
707
|
+
if (nextTarget.value !== undefined)
|
|
708
|
+
patch.target = nextTarget.value;
|
|
709
|
+
if (body.metadata !== undefined) {
|
|
710
|
+
// A client may not change tenantId — re-stamp the existing owner.
|
|
711
|
+
const owner = existing.metadata
|
|
712
|
+
?.tenantId;
|
|
713
|
+
const clientMeta = metadataOrReject(body.metadata);
|
|
714
|
+
if (!clientMeta.ok)
|
|
715
|
+
return clientMeta;
|
|
716
|
+
patch.metadata = { ...clientMeta.value, tenantId: owner };
|
|
717
|
+
}
|
|
718
|
+
return { ok: true, value: patch };
|
|
719
|
+
}
|
|
720
|
+
/** Merge the settable target fields; returns undefined when nothing target-side changed. */
|
|
721
|
+
function patchTarget(existing, body) {
|
|
722
|
+
const target = existing.target;
|
|
723
|
+
if (target.type === 'workflow') {
|
|
724
|
+
const changed = body.inputData !== undefined ||
|
|
725
|
+
body.initialState !== undefined ||
|
|
726
|
+
body.requestContext !== undefined;
|
|
727
|
+
if (!changed)
|
|
728
|
+
return { ok: true, value: undefined };
|
|
729
|
+
return {
|
|
730
|
+
ok: true,
|
|
731
|
+
value: {
|
|
732
|
+
...target,
|
|
733
|
+
...(body.inputData !== undefined ? { inputData: body.inputData } : {}),
|
|
734
|
+
...(body.initialState !== undefined
|
|
735
|
+
? { initialState: body.initialState }
|
|
736
|
+
: {}),
|
|
737
|
+
...(body.requestContext !== undefined
|
|
738
|
+
? { requestContext: body.requestContext }
|
|
739
|
+
: {}),
|
|
740
|
+
},
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
const agentKeys = [
|
|
744
|
+
'prompt',
|
|
745
|
+
'name',
|
|
746
|
+
'signalType',
|
|
747
|
+
'tagName',
|
|
748
|
+
'attributes',
|
|
749
|
+
'providerOptions',
|
|
750
|
+
'ifActive',
|
|
751
|
+
'ifIdle',
|
|
752
|
+
];
|
|
753
|
+
if (!agentKeys.some((key) => body[key] !== undefined)) {
|
|
754
|
+
return { ok: true, value: undefined };
|
|
755
|
+
}
|
|
756
|
+
const merged = { ...target };
|
|
757
|
+
for (const key of agentKeys) {
|
|
758
|
+
if (body[key] !== undefined)
|
|
759
|
+
merged[key] = body[key];
|
|
760
|
+
}
|
|
761
|
+
if (!nonEmptyString(merged.prompt)) {
|
|
762
|
+
return {
|
|
763
|
+
ok: false,
|
|
764
|
+
error: reject('prompt-invalid', 'prompt must be a non-empty string'),
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
if (merged.name !== undefined && typeof merged.name !== 'string') {
|
|
768
|
+
return {
|
|
769
|
+
ok: false,
|
|
770
|
+
error: reject('name-invalid', 'name must be a string'),
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
if (merged.threadId === undefined &&
|
|
774
|
+
['resourceId', 'signalType', 'ifActive', 'ifIdle'].some((field) => merged[field] !== undefined)) {
|
|
775
|
+
return {
|
|
776
|
+
ok: false,
|
|
777
|
+
error: reject('threadless-options', 'resourceId, signalType, ifActive, and ifIdle require threadId'),
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
if (merged.threadId !== undefined && merged.resourceId === undefined) {
|
|
781
|
+
return {
|
|
782
|
+
ok: false,
|
|
783
|
+
error: reject('resourceId-required', 'resourceId is required when threadId is set'),
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
const normalized = normalizeAgentTarget(existing.id, merged);
|
|
787
|
+
return normalized.ok ? { ok: true, value: normalized.value } : normalized;
|
|
788
|
+
}
|
|
789
|
+
function toView(schedule) {
|
|
790
|
+
// Core's projection — the response shape can never drift from mastra.schedules.
|
|
791
|
+
const view = toScheduleView(schedule);
|
|
792
|
+
if (!view) {
|
|
793
|
+
// Unreachable for a well-formed row; return a minimal fallback rather than
|
|
794
|
+
// throw (a corrupt row must not 500 a whole list).
|
|
795
|
+
return { id: schedule.id };
|
|
796
|
+
}
|
|
797
|
+
return view;
|
|
798
|
+
}
|
|
799
|
+
function clampLimit(raw) {
|
|
800
|
+
if (raw === null)
|
|
801
|
+
return undefined;
|
|
802
|
+
const parsed = Number(raw);
|
|
803
|
+
if (!Number.isInteger(parsed) || parsed < 1)
|
|
804
|
+
return undefined;
|
|
805
|
+
return Math.min(parsed, 200);
|
|
806
|
+
}
|
|
807
|
+
/** Size-cap the raw body at the wire, THEN parse it to a JSON object. */
|
|
808
|
+
async function readBody(request, maxContentBytes) {
|
|
809
|
+
const raw = await request.text();
|
|
810
|
+
const bytes = new TextEncoder().encode(raw).length;
|
|
811
|
+
if (bytes > maxContentBytes) {
|
|
812
|
+
return json({ error: `payload exceeds ${maxContentBytes} bytes` }, 413);
|
|
813
|
+
}
|
|
814
|
+
try {
|
|
815
|
+
const parsed = raw === '' ? {} : JSON.parse(raw);
|
|
816
|
+
if (typeof parsed !== 'object' ||
|
|
817
|
+
parsed === null ||
|
|
818
|
+
Array.isArray(parsed)) {
|
|
819
|
+
return json({ error: 'a JSON object body is required' }, 400);
|
|
820
|
+
}
|
|
821
|
+
return parsed;
|
|
822
|
+
}
|
|
823
|
+
catch {
|
|
824
|
+
return json({ error: 'a JSON object body is required' }, 400);
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
//# sourceMappingURL=router.js.map
|