@proofoftech/flowsafe 0.3.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 +336 -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/contract.d.ts +29 -0
- package/dist/approval-api/contract.d.ts.map +1 -1
- package/dist/approval-api/d1-store.d.ts.map +1 -1
- package/dist/approval-api/d1-store.js +112 -18
- package/dist/approval-api/d1-store.js.map +1 -1
- package/dist/approval-api/grants.d.ts +1 -1
- package/dist/approval-api/grants.d.ts.map +1 -1
- package/dist/approval-api/grants.js +8 -32
- package/dist/approval-api/grants.js.map +1 -1
- package/dist/approval-api/index.d.ts +2 -2
- 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 +24 -3
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +116 -1
- package/dist/approval-api/service.js.map +1 -1
- package/dist/approval-api/store.d.ts +29 -6
- package/dist/approval-api/store.d.ts.map +1 -1
- package/dist/approval-api/store.js +62 -2
- 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 +17 -1
- package/dist/approval-api/tenant-context.js.map +1 -1
- package/dist/approval-api/tenant-store.d.ts.map +1 -1
- package/dist/approval-api/tenant-store.js +8 -2
- package/dist/approval-api/tenant-store.js.map +1 -1
- package/dist/approval-api/types.d.ts +19 -0
- package/dist/approval-api/types.d.ts.map +1 -1
- package/dist/approval-api/types.js +16 -0
- package/dist/approval-api/types.js.map +1 -1
- package/dist/approval-ui/App.d.ts +9 -1
- package/dist/approval-ui/App.d.ts.map +1 -1
- package/dist/approval-ui/App.js +10 -5
- package/dist/approval-ui/App.js.map +1 -1
- package/dist/approval-ui/DetailView.d.ts +4 -1
- package/dist/approval-ui/DetailView.d.ts.map +1 -1
- package/dist/approval-ui/DetailView.js +2 -2
- package/dist/approval-ui/DetailView.js.map +1 -1
- package/dist/approval-ui/QueueView.d.ts +7 -1
- package/dist/approval-ui/QueueView.d.ts.map +1 -1
- package/dist/approval-ui/QueueView.js +8 -3
- package/dist/approval-ui/QueueView.js.map +1 -1
- package/dist/approval-ui/client.d.ts +19 -0
- package/dist/approval-ui/client.d.ts.map +1 -1
- package/dist/approval-ui/client.js +29 -1
- package/dist/approval-ui/client.js.map +1 -1
- package/dist/approval-ui/components.d.ts +20 -0
- package/dist/approval-ui/components.d.ts.map +1 -1
- package/dist/approval-ui/components.js +2 -0
- package/dist/approval-ui/components.js.map +1 -1
- package/dist/approval-ui/index.d.ts +4 -2
- package/dist/approval-ui/index.d.ts.map +1 -1
- package/dist/approval-ui/index.js +3 -0
- package/dist/approval-ui/index.js.map +1 -1
- package/dist/approval-ui/stream.d.ts +142 -0
- package/dist/approval-ui/stream.d.ts.map +1 -0
- package/dist/approval-ui/stream.js +136 -0
- package/dist/approval-ui/stream.js.map +1 -0
- package/dist/approval-ui/use-approval-dashboard.d.ts +74 -1
- package/dist/approval-ui/use-approval-dashboard.d.ts.map +1 -1
- package/dist/approval-ui/use-approval-dashboard.js +307 -7
- package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
- package/dist/approval-ui/use-web-socket-transport.d.ts +10 -0
- package/dist/approval-ui/use-web-socket-transport.d.ts.map +1 -0
- package/dist/approval-ui/use-web-socket-transport.js +46 -0
- package/dist/approval-ui/use-web-socket-transport.js.map +1 -0
- 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/cf-types.d.ts +70 -2
- package/dist/do-runner/cf-types.d.ts.map +1 -1
- package/dist/do-runner/cf-types.js +30 -1
- package/dist/do-runner/cf-types.js.map +1 -1
- 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 +566 -13
- 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 +5 -2
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +87 -20
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/hub-do.d.ts +55 -0
- package/dist/do-runner/hub-do.d.ts.map +1 -0
- package/dist/do-runner/hub-do.js +197 -0
- package/dist/do-runner/hub-do.js.map +1 -0
- package/dist/do-runner/index.d.ts +12 -4
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +9 -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/path-safe-id.js +1 -1
- package/dist/do-runner/path-safe-id.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 +134 -5
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +283 -47
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/host-approval-service.d.ts +20 -1
- package/dist/host-kit/host-approval-service.d.ts.map +1 -1
- package/dist/host-kit/host-approval-service.js +15 -0
- package/dist/host-kit/host-approval-service.js.map +1 -1
- package/dist/host-kit/hub-topology.d.ts +35 -0
- package/dist/host-kit/hub-topology.d.ts.map +1 -0
- package/dist/host-kit/hub-topology.js +32 -0
- package/dist/host-kit/hub-topology.js.map +1 -0
- package/dist/host-kit/index.d.ts +8 -1
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js +10 -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/stream-router.d.ts +22 -0
- package/dist/host-kit/stream-router.d.ts.map +1 -0
- package/dist/host-kit/stream-router.js +191 -0
- package/dist/host-kit/stream-router.js.map +1 -0
- package/dist/host-kit/stream-ticket.d.ts +55 -0
- package/dist/host-kit/stream-ticket.d.ts.map +1 -0
- package/dist/host-kit/stream-ticket.js +156 -0
- package/dist/host-kit/stream-ticket.js.map +1 -0
- package/dist/host-kit/tenant-registry.js +1 -1
- package/dist/host-kit/tenant-registry.js.map +1 -1
- 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,660 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Track C (M-004) — the signal routes hosted ON the thread DO (CI-M-004-001,
|
|
3
|
+
// DL-002). A thread's agent loop and every signal for that thread both address
|
|
4
|
+
// `idFromName(threadId)`, so the platform serializes them onto ONE isolate — the
|
|
5
|
+
// DO IS the serialization lease Mastra otherwise wants Redis for (DL-002). These
|
|
6
|
+
// routes run AFTER ThreadDurableObject.fetch has already asserted the request's
|
|
7
|
+
// authenticated tenant against the DO name's tenant prefix, so `scope.threadId`
|
|
8
|
+
// and `scope.tenantId` are trusted here; the P6 ingestion gate (allowlist / size
|
|
9
|
+
// cap / rate cap / audit) is the Worker-side createSignalRouter's job, the same
|
|
10
|
+
// split createRunRouter (Worker gate) → DurableObjectRunner (execution) uses.
|
|
11
|
+
//
|
|
12
|
+
// AFFINITY IS THE PUBSUB. Core keys its in-process signal registry by the pubsub
|
|
13
|
+
// instance passed to each agent method (`#statesByPubSub`, falling back to a
|
|
14
|
+
// module-level `defaultAgentThreadPubSub`), so a send only drains into an active
|
|
15
|
+
// loop when BOTH run in one isolate (the DO gives this) AND both use the SAME
|
|
16
|
+
// pubsub. The agent resolves its pubsub from `agent.getPubSub()`, so these routes
|
|
17
|
+
// stamp the DO's ONE identity (`scope.init.pubsub`, Track 0 / DL-001) onto the
|
|
18
|
+
// agent before every call — the exact reason Track A threads that same identity
|
|
19
|
+
// into createRun. Absent (host opted out) ⇒ core's module default, still one per
|
|
20
|
+
// isolate, so affinity holds either way; a wired pubsub additionally makes
|
|
21
|
+
// observe()/replay align (pubsub.ts).
|
|
22
|
+
//
|
|
23
|
+
// core's `agentThreadStreamRuntime` is NOT on the package exports map, so these
|
|
24
|
+
// routes drive the PUBLIC Agent methods only (never a deep dist import — R-001).
|
|
25
|
+
import { createNotificationSignal, createNotificationSummarySignal, summarizeNotifications, } from '@mastra/core/notifications';
|
|
26
|
+
import { isRuntimeDrivenAgent } from '../agent-runner/index.js';
|
|
27
|
+
import { mintSaltedId } from '../do-runner/index.js';
|
|
28
|
+
import { internalErrorResponse } from '../internal-error-response.js';
|
|
29
|
+
import { MAX_NOTIFICATION_DISPATCH_IDS, planNotificationDispatch, } from './notification-dispatch.js';
|
|
30
|
+
/**
|
|
31
|
+
* The idle-thread delivery behavior a send may ask for. `wake` starts a run
|
|
32
|
+
* (run cap consulted first, DL-007); `persist` writes the signal to the durable
|
|
33
|
+
* inbox for the next turn; `discard` drops it. Mirrors core
|
|
34
|
+
* `AgentSignalIdleBehavior`, re-declared so the route body validates the wire
|
|
35
|
+
* value rather than trusting an `as`.
|
|
36
|
+
*/
|
|
37
|
+
export const IDLE_BEHAVIORS = ['wake', 'persist', 'discard'];
|
|
38
|
+
/** The active-thread delivery behavior. Mirrors core `AgentSignalActiveBehavior`. */
|
|
39
|
+
export const ACTIVE_BEHAVIORS = ['deliver', 'persist', 'discard'];
|
|
40
|
+
function json(payload, status = 200) {
|
|
41
|
+
return new Response(JSON.stringify(payload), {
|
|
42
|
+
status,
|
|
43
|
+
headers: { 'content-type': 'application/json' },
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
async function readJson(request) {
|
|
47
|
+
try {
|
|
48
|
+
const parsed = await request.json();
|
|
49
|
+
return typeof parsed === 'object' && parsed !== null
|
|
50
|
+
? parsed
|
|
51
|
+
: null;
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The wire surface accepts STRING contents only — the common case, and the one
|
|
59
|
+
* the P6 ingestion gate can size-cap and (defense-in-depth) escape uniformly.
|
|
60
|
+
* Core's multimodal `AgentSignalContents` array form (TextPart/FilePart) is a
|
|
61
|
+
* documented residual, not exposed over this untrusted channel in v1.
|
|
62
|
+
*/
|
|
63
|
+
function isContents(value) {
|
|
64
|
+
return typeof value === 'string';
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The XML-name rule core's `assertXmlName` applies to a signal's `tagName`
|
|
68
|
+
* (and attribute names) inside `signalToXmlMarkup` — MIRRORED here, not
|
|
69
|
+
* deep-imported: `XML_NAME_PATTERN` / `assertXmlName` are not on core's exports
|
|
70
|
+
* map. Validating the caller-supplied `tagName` at INGEST turns an invalid one
|
|
71
|
+
* into a 400 at the route (the "route-level defense" C-S5 names) rather than a
|
|
72
|
+
* throw at render time inside the agent turn. Kept byte-identical to core
|
|
73
|
+
* (chunk `signalToXmlMarkup`: `/^[A-Za-z_][A-Za-z0-9_.-]*$/`); the C-S5 render
|
|
74
|
+
* test pins core's own neutralization of contents/attribute values so this
|
|
75
|
+
* mirror and that layer are checked together.
|
|
76
|
+
*/
|
|
77
|
+
const XML_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]*$/;
|
|
78
|
+
/** Attributes must be a flat record of primitives (core `AgentSignalAttributes`). */
|
|
79
|
+
function isAttributes(value) {
|
|
80
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
return Object.values(value).every((v) => v === null ||
|
|
84
|
+
v === undefined ||
|
|
85
|
+
typeof v === 'string' ||
|
|
86
|
+
typeof v === 'number' ||
|
|
87
|
+
typeof v === 'boolean');
|
|
88
|
+
}
|
|
89
|
+
export function createThreadSignalRoutes(options) {
|
|
90
|
+
const { resolveAgent, resolveResourceId, consultRunCap, startIdleRun, resolveNotificationsStorage, } = options;
|
|
91
|
+
let wakeTail = Promise.resolve();
|
|
92
|
+
const serializeWake = (operation) => {
|
|
93
|
+
const next = wakeTail.then(operation, operation);
|
|
94
|
+
wakeTail = next.then(() => undefined, () => undefined);
|
|
95
|
+
return next;
|
|
96
|
+
};
|
|
97
|
+
let notificationTail = Promise.resolve();
|
|
98
|
+
const serializeNotification = (operation) => {
|
|
99
|
+
const next = notificationTail.then(operation, operation);
|
|
100
|
+
notificationTail = next.then(() => undefined, () => undefined);
|
|
101
|
+
return next;
|
|
102
|
+
};
|
|
103
|
+
return async (request, scope) => {
|
|
104
|
+
if (request.method !== 'POST')
|
|
105
|
+
return null;
|
|
106
|
+
const url = new URL(request.url);
|
|
107
|
+
const path = url.pathname;
|
|
108
|
+
if (path !== '/signal' && !path.startsWith('/signal/'))
|
|
109
|
+
return null;
|
|
110
|
+
const body = await readJson(request);
|
|
111
|
+
if (!body)
|
|
112
|
+
return json({ error: 'a JSON body is required' }, 400);
|
|
113
|
+
try {
|
|
114
|
+
const requestedAgentId = path === '/signal/notifications/dispatch'
|
|
115
|
+
? typeof body.agentId === 'string' && body.agentId.trim().length > 0
|
|
116
|
+
? body.agentId
|
|
117
|
+
: undefined
|
|
118
|
+
: undefined;
|
|
119
|
+
if (path === '/signal/notifications/dispatch' &&
|
|
120
|
+
requestedAgentId === undefined) {
|
|
121
|
+
return json({ error: 'agentId is required for notification dispatch' }, 400);
|
|
122
|
+
}
|
|
123
|
+
// Affinity: stamp the DO's ONE pubsub identity onto the agent so its signal
|
|
124
|
+
// methods share the registry state the loop registered under. Keep host
|
|
125
|
+
// resolution inside this catch-all: construction/storage failures are
|
|
126
|
+
// internal and must not escape through the outer DO error response.
|
|
127
|
+
const agent = resolveAgent(scope, requestedAgentId);
|
|
128
|
+
if (requestedAgentId !== undefined && agent.id !== requestedAgentId) {
|
|
129
|
+
return json({ error: 'notification agent binding does not match' }, 404);
|
|
130
|
+
}
|
|
131
|
+
const runtimeDriven = isRuntimeDrivenAgent(agent);
|
|
132
|
+
const pubsub = scope.init.pubsub;
|
|
133
|
+
if (pubsub)
|
|
134
|
+
agent.__setPubSub(pubsub);
|
|
135
|
+
const resourceId = resolveResourceId?.(scope);
|
|
136
|
+
const threadId = scope.threadId;
|
|
137
|
+
// POST /signal/message — immediate user message (joins the active loop or,
|
|
138
|
+
// idle, wakes/persists per ifIdle).
|
|
139
|
+
if (path === '/signal/message') {
|
|
140
|
+
return await handleMessage(agent, body, threadId, resourceId, consultRunCap, scope.tenantId, runtimeDriven, scope.requestedBy, startIdleRun, serializeWake);
|
|
141
|
+
}
|
|
142
|
+
// POST /signal/queue — deliver on the NEXT turn (never wakes).
|
|
143
|
+
if (path === '/signal/queue') {
|
|
144
|
+
return await handleQueue(agent, body, threadId, resourceId);
|
|
145
|
+
}
|
|
146
|
+
// POST /signal — a system signal (ifActive/ifIdle deliver/persist/discard/wake).
|
|
147
|
+
if (path === '/signal') {
|
|
148
|
+
return await handleSignal(agent, body, threadId, resourceId, consultRunCap, scope.tenantId, runtimeDriven, scope.requestedBy, startIdleRun, serializeWake);
|
|
149
|
+
}
|
|
150
|
+
// POST /signal/state — a durable thread-state lane (snapshot/delta).
|
|
151
|
+
if (path === '/signal/state') {
|
|
152
|
+
return await handleState(agent, body, threadId, resourceId);
|
|
153
|
+
}
|
|
154
|
+
if (requestedAgentId !== undefined) {
|
|
155
|
+
if (!resolveNotificationsStorage) {
|
|
156
|
+
return json({ error: 'notification dispatch is not configured' }, 404);
|
|
157
|
+
}
|
|
158
|
+
return await serializeNotification(async () => handleNotificationDispatch({
|
|
159
|
+
agent,
|
|
160
|
+
body,
|
|
161
|
+
threadId,
|
|
162
|
+
resourceId,
|
|
163
|
+
tenantId: scope.tenantId,
|
|
164
|
+
requestedBy: scope.requestedBy,
|
|
165
|
+
runtimeDriven,
|
|
166
|
+
consultRunCap,
|
|
167
|
+
startIdleRun,
|
|
168
|
+
serializeWake,
|
|
169
|
+
storage: await resolveNotificationsStorage(scope),
|
|
170
|
+
agentId: requestedAgentId,
|
|
171
|
+
}));
|
|
172
|
+
}
|
|
173
|
+
// POST /signal/notification — the durable AGENT inbox (mastra_notifications).
|
|
174
|
+
if (path === '/signal/notification') {
|
|
175
|
+
return await serializeNotification(() => handleNotification(agent, body, threadId, resourceId));
|
|
176
|
+
}
|
|
177
|
+
return json({ error: 'not found' }, 404);
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
// A send that cannot be routed at all (e.g. an idle wake whose stream setup
|
|
181
|
+
// throws — no model) rejects `accepted`; surface it as a 502 rather than a
|
|
182
|
+
// 500 so a model/config fault reads distinctly from a route bug.
|
|
183
|
+
return internalErrorResponse('signals.thread', error, 502);
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
async function handleNotificationDispatch(options) {
|
|
188
|
+
const ids = options.body.notificationIds;
|
|
189
|
+
if (!Array.isArray(ids) ||
|
|
190
|
+
ids.length === 0 ||
|
|
191
|
+
ids.length > MAX_NOTIFICATION_DISPATCH_IDS ||
|
|
192
|
+
!ids.every((id) => typeof id === 'string' && id.length > 0)) {
|
|
193
|
+
return json({ error: 'notificationIds must contain 1-100 strings' }, 400);
|
|
194
|
+
}
|
|
195
|
+
const uniqueIds = [...new Set(ids)];
|
|
196
|
+
if (options.resourceId === undefined ||
|
|
197
|
+
options.body.resourceId !== options.resourceId) {
|
|
198
|
+
return json({ error: 'notification resource binding does not match' }, 404);
|
|
199
|
+
}
|
|
200
|
+
const resourceId = options.resourceId;
|
|
201
|
+
const now = typeof options.body.now === 'string'
|
|
202
|
+
? new Date(options.body.now)
|
|
203
|
+
: new Date();
|
|
204
|
+
if (Number.isNaN(now.getTime())) {
|
|
205
|
+
return json({ error: 'now must be an ISO timestamp' }, 400);
|
|
206
|
+
}
|
|
207
|
+
const carriesBatchThreadState = Object.hasOwn(options.body, 'batchThreadState');
|
|
208
|
+
const requestedBatchThreadState = options.body.batchThreadState;
|
|
209
|
+
if (carriesBatchThreadState &&
|
|
210
|
+
requestedBatchThreadState !== null &&
|
|
211
|
+
requestedBatchThreadState !== 'active' &&
|
|
212
|
+
requestedBatchThreadState !== 'idle') {
|
|
213
|
+
return json({ error: 'batchThreadState must be null, active, or idle' }, 400);
|
|
214
|
+
}
|
|
215
|
+
const records = [];
|
|
216
|
+
let skipped = 0;
|
|
217
|
+
for (const id of uniqueIds) {
|
|
218
|
+
const current = await options.storage.getNotification({
|
|
219
|
+
threadId: options.threadId,
|
|
220
|
+
id,
|
|
221
|
+
});
|
|
222
|
+
if (current?.status !== 'pending' || current.deliveredSignalId) {
|
|
223
|
+
skipped += 1;
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
if (current.resourceId !== options.resourceId ||
|
|
227
|
+
current.agentId !== options.agentId) {
|
|
228
|
+
return json({ error: 'notification binding does not match' }, 404);
|
|
229
|
+
}
|
|
230
|
+
const due = (current.deliverAt !== undefined &&
|
|
231
|
+
current.deliverAt.getTime() <= now.getTime()) ||
|
|
232
|
+
(current.summaryAt !== undefined &&
|
|
233
|
+
current.summaryAt.getTime() <= now.getTime());
|
|
234
|
+
if (!due) {
|
|
235
|
+
skipped += 1;
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
records.push(current);
|
|
239
|
+
}
|
|
240
|
+
const batchThreadState = requestedBatchThreadState === 'active' ||
|
|
241
|
+
requestedBatchThreadState === 'idle'
|
|
242
|
+
? requestedBatchThreadState
|
|
243
|
+
: typeof options.agent.getActiveThreadRunId === 'function' &&
|
|
244
|
+
options.agent.getActiveThreadRunId({
|
|
245
|
+
threadId: options.threadId,
|
|
246
|
+
resourceId,
|
|
247
|
+
})
|
|
248
|
+
? 'active'
|
|
249
|
+
: 'idle';
|
|
250
|
+
let delivered = 0;
|
|
251
|
+
let failed = 0;
|
|
252
|
+
const updateFailure = async (record, error) => {
|
|
253
|
+
failed += 1;
|
|
254
|
+
await options.storage.updateNotification({
|
|
255
|
+
id: record.id,
|
|
256
|
+
threadId: record.threadId,
|
|
257
|
+
deliveryAttempts: (record.deliveryAttempts ?? 0) + 1,
|
|
258
|
+
lastDeliveryAttemptAt: now,
|
|
259
|
+
lastDeliveryError: error instanceof Error ? error.message : String(error),
|
|
260
|
+
});
|
|
261
|
+
};
|
|
262
|
+
const send = async (signal) => {
|
|
263
|
+
const response = await handleWake({
|
|
264
|
+
agent: options.agent,
|
|
265
|
+
tenantId: options.tenantId,
|
|
266
|
+
threadId: options.threadId,
|
|
267
|
+
resourceId,
|
|
268
|
+
requestedBy: options.requestedBy,
|
|
269
|
+
runtimeDriven: options.runtimeDriven,
|
|
270
|
+
consultRunCap: options.consultRunCap,
|
|
271
|
+
startIdleRun: options.startIdleRun,
|
|
272
|
+
serializeWake: options.serializeWake,
|
|
273
|
+
signal,
|
|
274
|
+
deliverActive: (runId) => options.agent.sendSignal(signal, {
|
|
275
|
+
runId,
|
|
276
|
+
threadId: options.threadId,
|
|
277
|
+
resourceId,
|
|
278
|
+
ifActive: { behavior: 'deliver' },
|
|
279
|
+
}),
|
|
280
|
+
persist: () => options.agent.sendSignal(signal, {
|
|
281
|
+
threadId: options.threadId,
|
|
282
|
+
resourceId,
|
|
283
|
+
ifIdle: { behavior: 'persist' },
|
|
284
|
+
}),
|
|
285
|
+
});
|
|
286
|
+
if (!response.ok)
|
|
287
|
+
throw new Error(`notification signal returned ${response.status}`);
|
|
288
|
+
const result = (await response.json());
|
|
289
|
+
if (!result.signalId)
|
|
290
|
+
throw new Error('notification signal has no id');
|
|
291
|
+
return result.signalId;
|
|
292
|
+
};
|
|
293
|
+
const persistWithoutWake = async (signal) => {
|
|
294
|
+
const result = options.agent.sendSignal(signal, {
|
|
295
|
+
threadId: options.threadId,
|
|
296
|
+
resourceId,
|
|
297
|
+
ifActive: { behavior: 'deliver' },
|
|
298
|
+
ifIdle: { behavior: 'persist' },
|
|
299
|
+
});
|
|
300
|
+
await result.accepted;
|
|
301
|
+
if (result.persisted)
|
|
302
|
+
await result.persisted;
|
|
303
|
+
return result.signal.id;
|
|
304
|
+
};
|
|
305
|
+
for (const item of planNotificationDispatch(records, now)) {
|
|
306
|
+
if (item.type === 'summary') {
|
|
307
|
+
try {
|
|
308
|
+
const signal = createNotificationSummarySignal(summarizeNotifications(item.records));
|
|
309
|
+
const signalId = item.records.every((record) => record.priority === 'low')
|
|
310
|
+
? await persistWithoutWake(signal)
|
|
311
|
+
: await send(signal);
|
|
312
|
+
for (const record of item.records) {
|
|
313
|
+
await options.storage.updateNotification({
|
|
314
|
+
id: record.id,
|
|
315
|
+
threadId: record.threadId,
|
|
316
|
+
summaryAt: null,
|
|
317
|
+
summarySignalId: signalId,
|
|
318
|
+
lastDeliveryAttemptAt: now,
|
|
319
|
+
});
|
|
320
|
+
delivered += 1;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
catch (error) {
|
|
324
|
+
for (const record of item.records)
|
|
325
|
+
await updateFailure(record, error);
|
|
326
|
+
}
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
const selected = item.record;
|
|
330
|
+
try {
|
|
331
|
+
const record = await options.storage.getNotification({
|
|
332
|
+
threadId: selected.threadId,
|
|
333
|
+
id: selected.id,
|
|
334
|
+
});
|
|
335
|
+
const summaryDue = Boolean(record?.summaryAt && record.summaryAt.getTime() <= now.getTime());
|
|
336
|
+
const deliveryDue = Boolean(record?.deliverAt && record.deliverAt.getTime() <= now.getTime());
|
|
337
|
+
if (record?.status !== 'pending' ||
|
|
338
|
+
record.deliveredSignalId ||
|
|
339
|
+
record.resourceId !== resourceId ||
|
|
340
|
+
record.agentId !== options.agentId ||
|
|
341
|
+
summaryDue ||
|
|
342
|
+
!deliveryDue) {
|
|
343
|
+
skipped += 1;
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
if (record.priority === 'high' &&
|
|
347
|
+
record.summarySignalId &&
|
|
348
|
+
batchThreadState === 'active') {
|
|
349
|
+
skipped += 1;
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
const signalId = await send(createNotificationSignal({
|
|
353
|
+
...record,
|
|
354
|
+
status: 'delivered',
|
|
355
|
+
deliveredAt: now,
|
|
356
|
+
}));
|
|
357
|
+
await options.storage.updateNotification({
|
|
358
|
+
id: record.id,
|
|
359
|
+
threadId: record.threadId,
|
|
360
|
+
status: 'delivered',
|
|
361
|
+
deliveredSignalId: signalId,
|
|
362
|
+
lastDeliveryAttemptAt: now,
|
|
363
|
+
});
|
|
364
|
+
delivered += 1;
|
|
365
|
+
}
|
|
366
|
+
catch (error) {
|
|
367
|
+
await updateFailure(selected, error);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return json({
|
|
371
|
+
delivered,
|
|
372
|
+
failed,
|
|
373
|
+
...(skipped > 0 ? { skipped } : {}),
|
|
374
|
+
...(carriesBatchThreadState ? { batchThreadState } : {}),
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Resolve the idle behavior a body asked for. A `wake` STARTS a run, so it is
|
|
379
|
+
* gated twice, both fail-closed to a durable persist (the signal survives the
|
|
380
|
+
* next turn rather than dropping or billing):
|
|
381
|
+
* - the agent must be RUNTIME-DRIVEN (its stream re-enters RunnerRuntime, not
|
|
382
|
+
* the default engine) — else `wakeRefused:'not-runtime-driven'`;
|
|
383
|
+
* - the per-tenant run cap must allow it (DL-007) — else `capped:true`.
|
|
384
|
+
*/
|
|
385
|
+
function requestedIdle(body) {
|
|
386
|
+
const requested = body.ifIdle;
|
|
387
|
+
return typeof requested === 'string' &&
|
|
388
|
+
IDLE_BEHAVIORS.includes(requested)
|
|
389
|
+
? requested
|
|
390
|
+
: 'persist';
|
|
391
|
+
}
|
|
392
|
+
async function handleWake(options) {
|
|
393
|
+
return options.serializeWake(async () => {
|
|
394
|
+
const activeRunId = typeof options.agent.getActiveThreadRunId === 'function'
|
|
395
|
+
? options.agent.getActiveThreadRunId({
|
|
396
|
+
threadId: options.threadId,
|
|
397
|
+
resourceId: options.resourceId,
|
|
398
|
+
})
|
|
399
|
+
: undefined;
|
|
400
|
+
if (activeRunId) {
|
|
401
|
+
const delivered = options.deliverActive(activeRunId);
|
|
402
|
+
return json({
|
|
403
|
+
decision: await delivered.accepted,
|
|
404
|
+
capped: false,
|
|
405
|
+
signalId: delivered.signal.id,
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
const startIdleRun = options.startIdleRun;
|
|
409
|
+
const refusal = !options.runtimeDriven
|
|
410
|
+
? 'not-runtime-driven'
|
|
411
|
+
: !startIdleRun
|
|
412
|
+
? 'no-start-idle-run'
|
|
413
|
+
: undefined;
|
|
414
|
+
const capped = options.runtimeDriven && options.consultRunCap
|
|
415
|
+
? !(await options.consultRunCap(options.tenantId))
|
|
416
|
+
: false;
|
|
417
|
+
if (refusal || capped) {
|
|
418
|
+
const persisted = options.persist();
|
|
419
|
+
const decision = await persisted.accepted;
|
|
420
|
+
if (persisted.persisted)
|
|
421
|
+
await persisted.persisted;
|
|
422
|
+
return json({
|
|
423
|
+
decision,
|
|
424
|
+
capped,
|
|
425
|
+
...(refusal ? { wakeRefused: refusal } : {}),
|
|
426
|
+
signalId: persisted.signal.id,
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
const runId = mintSaltedId(options.tenantId, () => crypto.randomUUID(), 'thread signal wake');
|
|
430
|
+
if (!startIdleRun) {
|
|
431
|
+
throw new Error('idle-start gate allowed a missing startIdleRun seam');
|
|
432
|
+
}
|
|
433
|
+
const started = await startIdleRun({
|
|
434
|
+
agent: options.agent,
|
|
435
|
+
runId,
|
|
436
|
+
threadId: options.threadId,
|
|
437
|
+
resourceId: options.resourceId,
|
|
438
|
+
requestedBy: options.requestedBy,
|
|
439
|
+
...(options.message !== undefined ? { message: options.message } : {}),
|
|
440
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
441
|
+
});
|
|
442
|
+
const signalId = started.signalId ?? options.signal?.id;
|
|
443
|
+
return json({
|
|
444
|
+
decision: { action: 'wake', runId: started.runId },
|
|
445
|
+
capped: false,
|
|
446
|
+
...(signalId !== undefined ? { signalId } : {}),
|
|
447
|
+
});
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
async function handleMessage(agent, body, threadId, resourceId, consultRunCap, tenantId, runtimeDriven, requestedBy, startIdleRun, serializeWake) {
|
|
451
|
+
if (!isContents(body.contents)) {
|
|
452
|
+
return json({ error: 'contents (string) is required' }, 400);
|
|
453
|
+
}
|
|
454
|
+
const message = {
|
|
455
|
+
contents: body.contents,
|
|
456
|
+
...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
|
|
457
|
+
};
|
|
458
|
+
// sendMessage requires a resourceId+threadId target for its idle branch; when a
|
|
459
|
+
// host has not wired a resourceId, only the active/queue path is reachable.
|
|
460
|
+
if (resourceId === undefined) {
|
|
461
|
+
return json({
|
|
462
|
+
error: 'this thread has no resourceId wired; message delivery needs one',
|
|
463
|
+
}, 409);
|
|
464
|
+
}
|
|
465
|
+
const behavior = requestedIdle(body);
|
|
466
|
+
if (behavior === 'wake') {
|
|
467
|
+
return handleWake({
|
|
468
|
+
agent,
|
|
469
|
+
tenantId,
|
|
470
|
+
threadId,
|
|
471
|
+
resourceId,
|
|
472
|
+
requestedBy,
|
|
473
|
+
runtimeDriven,
|
|
474
|
+
consultRunCap,
|
|
475
|
+
startIdleRun,
|
|
476
|
+
serializeWake,
|
|
477
|
+
message,
|
|
478
|
+
deliverActive: (runId) => agent.sendMessage(message, {
|
|
479
|
+
runId,
|
|
480
|
+
threadId,
|
|
481
|
+
resourceId,
|
|
482
|
+
ifActive: { behavior: 'deliver' },
|
|
483
|
+
}),
|
|
484
|
+
persist: () => agent.sendMessage(message, {
|
|
485
|
+
threadId,
|
|
486
|
+
resourceId,
|
|
487
|
+
ifIdle: { behavior: 'persist' },
|
|
488
|
+
}),
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
const result = agent.sendMessage(message, {
|
|
492
|
+
threadId,
|
|
493
|
+
resourceId,
|
|
494
|
+
ifIdle: { behavior },
|
|
495
|
+
});
|
|
496
|
+
const decision = await result.accepted;
|
|
497
|
+
return json({
|
|
498
|
+
decision,
|
|
499
|
+
capped: false,
|
|
500
|
+
signalId: result.signal.id,
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
async function handleQueue(agent, body, threadId, resourceId) {
|
|
504
|
+
if (!isContents(body.contents)) {
|
|
505
|
+
return json({ error: 'contents (string) is required' }, 400);
|
|
506
|
+
}
|
|
507
|
+
if (resourceId === undefined) {
|
|
508
|
+
return json({ error: 'this thread has no resourceId wired; queue needs one' }, 409);
|
|
509
|
+
}
|
|
510
|
+
const message = {
|
|
511
|
+
contents: body.contents,
|
|
512
|
+
...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
|
|
513
|
+
};
|
|
514
|
+
const result = agent.queueMessage(message, { threadId, resourceId });
|
|
515
|
+
const decision = await result.accepted;
|
|
516
|
+
return json({ decision, signalId: result.signal.id });
|
|
517
|
+
}
|
|
518
|
+
async function handleSignal(agent, body, threadId, resourceId, consultRunCap, tenantId, runtimeDriven, requestedBy, startIdleRun, serializeWake) {
|
|
519
|
+
if (!isContents(body.contents)) {
|
|
520
|
+
return json({ error: 'contents (string) is required' }, 400);
|
|
521
|
+
}
|
|
522
|
+
// Route-level tagName defense (C-S5): reject a non-XML-name tagName HERE with a
|
|
523
|
+
// 400, rather than letting core's signalToXmlMarkup throw at render time inside
|
|
524
|
+
// the agent turn. Core still escapes contents/attribute values and re-validates
|
|
525
|
+
// names; this is the ingest-time half the plan calls "route-level defense".
|
|
526
|
+
if (typeof body.tagName === 'string' &&
|
|
527
|
+
!XML_NAME_PATTERN.test(body.tagName)) {
|
|
528
|
+
return json({ error: 'tagName is not a valid XML name' }, 400);
|
|
529
|
+
}
|
|
530
|
+
const signal = {
|
|
531
|
+
type: 'reactive',
|
|
532
|
+
contents: body.contents,
|
|
533
|
+
...(typeof body.tagName === 'string' ? { tagName: body.tagName } : {}),
|
|
534
|
+
...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
|
|
535
|
+
};
|
|
536
|
+
const activeBehavior = typeof body.ifActive === 'string' &&
|
|
537
|
+
ACTIVE_BEHAVIORS.includes(body.ifActive)
|
|
538
|
+
? body.ifActive
|
|
539
|
+
: 'deliver';
|
|
540
|
+
if (resourceId === undefined) {
|
|
541
|
+
// Active-only target: no idle branch available without a resourceId.
|
|
542
|
+
const result = agent.sendSignal(signal, {
|
|
543
|
+
threadId,
|
|
544
|
+
runId: `${tenantId}_signal`,
|
|
545
|
+
ifActive: { behavior: activeBehavior },
|
|
546
|
+
});
|
|
547
|
+
const decision = await result.accepted;
|
|
548
|
+
return json({ decision, signalId: result.signal.id });
|
|
549
|
+
}
|
|
550
|
+
const behavior = requestedIdle(body);
|
|
551
|
+
if (behavior === 'wake') {
|
|
552
|
+
return handleWake({
|
|
553
|
+
agent,
|
|
554
|
+
tenantId,
|
|
555
|
+
threadId,
|
|
556
|
+
resourceId,
|
|
557
|
+
requestedBy,
|
|
558
|
+
runtimeDriven,
|
|
559
|
+
consultRunCap,
|
|
560
|
+
startIdleRun,
|
|
561
|
+
serializeWake,
|
|
562
|
+
signal,
|
|
563
|
+
deliverActive: (runId) => agent.sendSignal(signal, {
|
|
564
|
+
runId,
|
|
565
|
+
threadId,
|
|
566
|
+
resourceId,
|
|
567
|
+
ifActive: { behavior: activeBehavior },
|
|
568
|
+
}),
|
|
569
|
+
persist: () => agent.sendSignal(signal, {
|
|
570
|
+
threadId,
|
|
571
|
+
resourceId,
|
|
572
|
+
ifActive: { behavior: activeBehavior },
|
|
573
|
+
ifIdle: { behavior: 'persist' },
|
|
574
|
+
}),
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
const result = agent.sendSignal(signal, {
|
|
578
|
+
threadId,
|
|
579
|
+
resourceId,
|
|
580
|
+
ifActive: { behavior: activeBehavior },
|
|
581
|
+
ifIdle: { behavior },
|
|
582
|
+
});
|
|
583
|
+
const decision = await result.accepted;
|
|
584
|
+
return json({
|
|
585
|
+
decision,
|
|
586
|
+
capped: false,
|
|
587
|
+
signalId: result.signal.id,
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
async function handleState(agent, body, threadId, resourceId) {
|
|
591
|
+
if (typeof body.id !== 'string' || typeof body.cacheKey !== 'string') {
|
|
592
|
+
return json({ error: 'id and cacheKey are required for a state signal' }, 400);
|
|
593
|
+
}
|
|
594
|
+
if (!isContents(body.contents)) {
|
|
595
|
+
return json({ error: 'contents (string) is required' }, 400);
|
|
596
|
+
}
|
|
597
|
+
if (resourceId === undefined) {
|
|
598
|
+
return json({ error: 'this thread has no resourceId wired; state needs one' }, 409);
|
|
599
|
+
}
|
|
600
|
+
const mode = body.mode === 'delta' ? 'delta' : 'snapshot';
|
|
601
|
+
const state = {
|
|
602
|
+
id: body.id,
|
|
603
|
+
cacheKey: body.cacheKey,
|
|
604
|
+
contents: body.contents,
|
|
605
|
+
mode,
|
|
606
|
+
...(mode === 'snapshot' ? { value: body.value } : { delta: body.delta }),
|
|
607
|
+
...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
|
|
608
|
+
};
|
|
609
|
+
const result = await agent.sendStateSignal(state, { threadId, resourceId });
|
|
610
|
+
// A snapshot whose cacheKey value is unchanged is de-duped (skipped) — no run
|
|
611
|
+
// touched, no signal minted. Surface that distinctly rather than pretend a
|
|
612
|
+
// delivery happened.
|
|
613
|
+
if (result.skipped) {
|
|
614
|
+
return json({ skipped: true, reason: result.reason });
|
|
615
|
+
}
|
|
616
|
+
const decision = await result.accepted;
|
|
617
|
+
return json({ decision, signalId: result.signal.id });
|
|
618
|
+
}
|
|
619
|
+
async function handleNotification(agent, body, threadId, resourceId) {
|
|
620
|
+
if (typeof body.source !== 'string' ||
|
|
621
|
+
typeof body.kind !== 'string' ||
|
|
622
|
+
typeof body.summary !== 'string') {
|
|
623
|
+
return json({ error: 'source, kind and summary are required for a notification' }, 400);
|
|
624
|
+
}
|
|
625
|
+
const notification = {
|
|
626
|
+
source: body.source,
|
|
627
|
+
kind: body.kind,
|
|
628
|
+
summary: body.summary,
|
|
629
|
+
...(typeof body.priority === 'string' &&
|
|
630
|
+
['low', 'medium', 'high', 'urgent'].includes(body.priority)
|
|
631
|
+
? { priority: body.priority }
|
|
632
|
+
: {}),
|
|
633
|
+
...(body.payload !== undefined ? { payload: body.payload } : {}),
|
|
634
|
+
...(typeof body.dedupeKey === 'string'
|
|
635
|
+
? { dedupeKey: body.dedupeKey }
|
|
636
|
+
: {}),
|
|
637
|
+
...(typeof body.coalesceKey === 'string'
|
|
638
|
+
? { coalesceKey: body.coalesceKey }
|
|
639
|
+
: {}),
|
|
640
|
+
...(isAttributes(body.attributes) ? { attributes: body.attributes } : {}),
|
|
641
|
+
};
|
|
642
|
+
// agent.sendNotificationSignal persists via the Mastra storage's notifications
|
|
643
|
+
// domain (mastra_notifications) — D1-backed once createD1Storage composes
|
|
644
|
+
// D1NotificationsStorage — and returns the created record. The durable inbox
|
|
645
|
+
// surfaces on the next turn (the dispatcher reads it at run start); nothing
|
|
646
|
+
// wakes here (P6/P8: an inbound notification is untrusted context, never a
|
|
647
|
+
// capability). Core's notification target REQUIRES a resourceId (it keys the
|
|
648
|
+
// inbox on the owner), so a thread with none wired cannot take one.
|
|
649
|
+
if (resourceId === undefined) {
|
|
650
|
+
return json({ error: 'this thread has no resourceId wired; notifications need one' }, 409);
|
|
651
|
+
}
|
|
652
|
+
const result = await agent.sendNotificationSignal(notification, {
|
|
653
|
+
threadId,
|
|
654
|
+
resourceId,
|
|
655
|
+
});
|
|
656
|
+
if (result.persisted)
|
|
657
|
+
await result.persisted;
|
|
658
|
+
return json({ record: result });
|
|
659
|
+
}
|
|
660
|
+
//# sourceMappingURL=thread-do-routes.js.map
|