@fabric-harness/sdk 6.3.0 → 6.5.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/connector-spec/voice-telephony.md +120 -104
- package/dist/agent-route.d.ts +22 -2
- package/dist/agent-route.d.ts.map +1 -1
- package/dist/agent-route.js +32 -1
- package/dist/agent-route.js.map +1 -1
- package/dist/agent-router.d.ts +46 -0
- package/dist/agent-router.d.ts.map +1 -1
- package/dist/agent-router.js +63 -2
- package/dist/agent-router.js.map +1 -1
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +3 -0
- package/dist/agent.js.map +1 -1
- package/dist/attachment-store.d.ts +69 -0
- package/dist/attachment-store.d.ts.map +1 -1
- package/dist/attachment-store.js +183 -14
- package/dist/attachment-store.js.map +1 -1
- package/dist/attachments.d.ts +136 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/attachments.js +332 -0
- package/dist/attachments.js.map +1 -0
- package/dist/channel.d.ts.map +1 -1
- package/dist/channel.js +26 -3
- package/dist/channel.js.map +1 -1
- package/dist/conversation-history.d.ts +186 -0
- package/dist/conversation-history.d.ts.map +1 -0
- package/dist/conversation-history.js +481 -0
- package/dist/conversation-history.js.map +1 -0
- package/dist/conversation-ui.d.ts +43 -2
- package/dist/conversation-ui.d.ts.map +1 -1
- package/dist/conversation-ui.js +44 -14
- package/dist/conversation-ui.js.map +1 -1
- package/dist/cost-budget.d.ts +50 -0
- package/dist/cost-budget.d.ts.map +1 -1
- package/dist/cost-budget.js +74 -4
- package/dist/cost-budget.js.map +1 -1
- package/dist/cost-enforcement.d.ts +32 -0
- package/dist/cost-enforcement.d.ts.map +1 -0
- package/dist/cost-enforcement.js +116 -0
- package/dist/cost-enforcement.js.map +1 -0
- package/dist/delivered-message.d.ts +20 -6
- package/dist/delivered-message.d.ts.map +1 -1
- package/dist/delivered-message.js +37 -8
- package/dist/delivered-message.js.map +1 -1
- package/dist/events.d.ts +16 -2
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/experimental.d.ts +2 -2
- package/dist/experimental.d.ts.map +1 -1
- package/dist/experimental.js +1 -1
- package/dist/experimental.js.map +1 -1
- package/dist/governed-voice.d.ts +6 -0
- package/dist/governed-voice.d.ts.map +1 -1
- package/dist/governed-voice.js +142 -35
- package/dist/governed-voice.js.map +1 -1
- package/dist/history.d.ts +3 -2
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +57 -23
- package/dist/history.js.map +1 -1
- package/dist/index.d.ts +21 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -7
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +25 -2
- package/dist/loop.d.ts.map +1 -1
- package/dist/loop.js +409 -60
- package/dist/loop.js.map +1 -1
- package/dist/model-pricing.d.ts +77 -4
- package/dist/model-pricing.d.ts.map +1 -1
- package/dist/model-pricing.js +259 -18
- package/dist/model-pricing.js.map +1 -1
- package/dist/model.d.ts +115 -3
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +376 -57
- package/dist/model.js.map +1 -1
- package/dist/otel-observer.d.ts +3 -1
- package/dist/otel-observer.d.ts.map +1 -1
- package/dist/otel-observer.js +40 -8
- package/dist/otel-observer.js.map +1 -1
- package/dist/persistent-agent.d.ts +5 -0
- package/dist/persistent-agent.d.ts.map +1 -1
- package/dist/persistent-agent.js +9 -1
- package/dist/persistent-agent.js.map +1 -1
- package/dist/pi-document-attachments.d.ts +43 -0
- package/dist/pi-document-attachments.d.ts.map +1 -0
- package/dist/pi-document-attachments.js +155 -0
- package/dist/pi-document-attachments.js.map +1 -0
- package/dist/pi-loop-runtime.d.ts +103 -1
- package/dist/pi-loop-runtime.d.ts.map +1 -1
- package/dist/pi-loop-runtime.js +850 -109
- package/dist/pi-loop-runtime.js.map +1 -1
- package/dist/prompt-attachments.d.ts +98 -0
- package/dist/prompt-attachments.d.ts.map +1 -0
- package/dist/prompt-attachments.js +279 -0
- package/dist/prompt-attachments.js.map +1 -0
- package/dist/session.d.ts +52 -0
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +410 -33
- package/dist/session.js.map +1 -1
- package/dist/stream-chunks.d.ts +15 -1
- package/dist/stream-chunks.d.ts.map +1 -1
- package/dist/stream-chunks.js +39 -18
- package/dist/stream-chunks.js.map +1 -1
- package/dist/strict.d.ts +23 -16
- package/dist/strict.d.ts.map +1 -1
- package/dist/strict.js +12 -8
- package/dist/strict.js.map +1 -1
- package/dist/submission-context.d.ts +7 -0
- package/dist/submission-context.d.ts.map +1 -1
- package/dist/submission-context.js.map +1 -1
- package/dist/submission-runner.d.ts +5 -0
- package/dist/submission-runner.d.ts.map +1 -1
- package/dist/submission-runner.js +97 -13
- package/dist/submission-runner.js.map +1 -1
- package/dist/submission-store-contract.d.ts.map +1 -1
- package/dist/submission-store-contract.js +15 -1
- package/dist/submission-store-contract.js.map +1 -1
- package/dist/submission-store.d.ts +12 -0
- package/dist/submission-store.d.ts.map +1 -1
- package/dist/submission-store.js +13 -4
- package/dist/submission-store.js.map +1 -1
- package/dist/trace-content.d.ts +21 -0
- package/dist/trace-content.d.ts.map +1 -0
- package/dist/trace-content.js +69 -0
- package/dist/trace-content.js.map +1 -0
- package/dist/types.d.ts +26 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/usage-completeness.d.ts +39 -0
- package/dist/usage-completeness.d.ts.map +1 -0
- package/dist/usage-completeness.js +135 -0
- package/dist/usage-completeness.js.map +1 -0
- package/dist/voice-openai-realtime.d.ts +24 -2
- package/dist/voice-openai-realtime.d.ts.map +1 -1
- package/dist/voice-openai-realtime.js +266 -49
- package/dist/voice-openai-realtime.js.map +1 -1
- package/dist/voice-pipeline.d.ts +81 -3
- package/dist/voice-pipeline.d.ts.map +1 -1
- package/dist/voice-pipeline.js +429 -60
- package/dist/voice-pipeline.js.map +1 -1
- package/dist/voice-stt-cartesia.d.ts +8 -0
- package/dist/voice-stt-cartesia.d.ts.map +1 -1
- package/dist/voice-stt-cartesia.js +77 -17
- package/dist/voice-stt-cartesia.js.map +1 -1
- package/dist/voice-stt-deepgram.d.ts +10 -2
- package/dist/voice-stt-deepgram.d.ts.map +1 -1
- package/dist/voice-stt-deepgram.js +78 -18
- package/dist/voice-stt-deepgram.js.map +1 -1
- package/dist/voice-stt.d.ts +13 -3
- package/dist/voice-stt.d.ts.map +1 -1
- package/dist/voice-tts-cartesia.d.ts +8 -0
- package/dist/voice-tts-cartesia.d.ts.map +1 -1
- package/dist/voice-tts-cartesia.js +48 -105
- package/dist/voice-tts-cartesia.js.map +1 -1
- package/dist/voice-tts-elevenlabs.d.ts +10 -1
- package/dist/voice-tts-elevenlabs.d.ts.map +1 -1
- package/dist/voice-tts-elevenlabs.js +50 -113
- package/dist/voice-tts-elevenlabs.js.map +1 -1
- package/dist/voice-ws-client.js +16 -3
- package/dist/voice-ws-client.js.map +1 -1
- package/dist/voice-ws-shared.d.ts +205 -6
- package/dist/voice-ws-shared.d.ts.map +1 -1
- package/dist/voice-ws-shared.js +510 -15
- package/dist/voice-ws-shared.js.map +1 -1
- package/dist/voice.d.ts +98 -4
- package/dist/voice.d.ts.map +1 -1
- package/dist/voice.js +71 -1
- package/dist/voice.js.map +1 -1
- package/package.json +3 -3
|
@@ -8,137 +8,153 @@
|
|
|
8
8
|
|
|
9
9
|
# fabric-harness Voice-Telephony Connector Spec
|
|
10
10
|
|
|
11
|
-
This document is the contract for bridging a telephony provider (Twilio Media
|
|
11
|
+
This document is the contract for bridging a telephony provider's media stream (Twilio Media
|
|
12
|
+
Streams, Vonage, Plivo, Telnyx, an in-house SIP or FreeSWITCH gateway) to a **governed** Harness
|
|
13
|
+
voice session so a phone call can talk to an agent.
|
|
12
14
|
|
|
13
|
-
If you are an AI coding agent reading this to build a connector for a user, follow this document
|
|
15
|
+
If you are an AI coding agent reading this to build a connector for a user, follow this document
|
|
16
|
+
literally.
|
|
14
17
|
|
|
15
18
|
---
|
|
16
19
|
|
|
17
|
-
##
|
|
20
|
+
## 0. Twilio: do not write a bridge
|
|
18
21
|
|
|
19
|
-
|
|
22
|
+
Twilio Media Streams is supported by `@fabric-harness/channels/twilio-voice`. Use it:
|
|
20
23
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
+
- `verifyTwilioVoiceWebhook()` for the TwiML webhook,
|
|
25
|
+
- `createTwilioStreamToken()` + `twilioConnectStreamTwiml()` to answer with `<Connect><Stream>`,
|
|
26
|
+
- `verifyTwilioMediaStreamUpgrade()` for the WebSocket upgrade,
|
|
27
|
+
- `attachTwilioMediaStream(socket, { tokenSecret, expectedCallSid, claimStream, resolveCall })` for
|
|
28
|
+
the stream; `claimStream` is required and must atomically record the token nonce (single use),
|
|
29
|
+
- `@fabric-harness/cloudflare/voice` (`routeTwilioMediaStream`, `handleTwilioMediaStream`,
|
|
30
|
+
`createWorkersVoiceSocketFactory`) to host it in one Cloudflare Durable Object per call, or a Node
|
|
31
|
+
`ws` server.
|
|
24
32
|
|
|
25
|
-
|
|
33
|
+
See the public guide `docs/building/voice-telephony` and the runnable
|
|
34
|
+
`examples/voice-twilio-cloudflare` workspace. Generate only the application wiring
|
|
35
|
+
(`claimStream`, `resolveCall`, binding lookup, redaction, authorization) for Twilio. `resolveCall`
|
|
36
|
+
spreads the `voiceOptions` it receives into `session.voice()`.
|
|
26
37
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
## Imports You Will Use
|
|
30
|
-
|
|
31
|
-
All from `@fabric-harness/sdk`:
|
|
32
|
-
|
|
33
|
-
- `OpenAIRealtimeVoiceProvider` — the LLM-side connection
|
|
34
|
-
- `VoiceSession` — what the bridge drives
|
|
35
|
-
- `VoiceEvent` — what the bridge consumes
|
|
38
|
+
For any other provider, build a bridge that meets every requirement below. The Twilio bridge in
|
|
39
|
+
`packages/channels/src/twilio-voice.ts` is the reference implementation.
|
|
36
40
|
|
|
37
41
|
---
|
|
38
42
|
|
|
39
|
-
##
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
if (msg.event === 'media' && msg.media?.payload) {
|
|
66
|
-
// Twilio sends base64 μ-law 8kHz; OpenAI accepts g711_ulaw directly.
|
|
67
|
-
const audio = base64ToBytes(msg.media.payload);
|
|
68
|
-
void voice.sendAudio(audio);
|
|
69
|
-
} else if (msg.event === 'stop') {
|
|
70
|
-
void voice.close();
|
|
71
|
-
ws.close();
|
|
72
|
-
}
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
// fabric-harness → Twilio
|
|
76
|
-
void (async () => {
|
|
77
|
-
for await (const event of voice.events()) {
|
|
78
|
-
if (event.type === 'audio_delta') {
|
|
79
|
-
ws.send(JSON.stringify({
|
|
80
|
-
event: 'media',
|
|
81
|
-
media: { payload: bytesToBase64(event.audio) },
|
|
82
|
-
}));
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
})();
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
```
|
|
89
|
-
|
|
90
|
-
The user wires that handler behind their HTTP framework (Hono, Express, etc.) and points Twilio's `<Stream url="wss://...">` TwiML at it.
|
|
43
|
+
## 1. Non-negotiable security model
|
|
44
|
+
|
|
45
|
+
1. **Governed sessions only.** The bridge drives a session returned by `session.voice(...)`
|
|
46
|
+
(`GovernedVoiceSession`, `governed === true`). Never call `provider.connect()` from a bridge and
|
|
47
|
+
never accept a raw `VoiceSession`: raw sessions have no authorization, tool governance, budget or
|
|
48
|
+
audit.
|
|
49
|
+
2. **Identity is server-owned.** Authenticate the provider's call webhook with its documented
|
|
50
|
+
signature scheme. Resolve tenant, resource/case and session from **your** records for the
|
|
51
|
+
verified call ID, then carry that binding to the media stream in an HMAC-signed, short-lived token
|
|
52
|
+
bound to the provider's call ID. Verify it (constant-time, expiry, call ID match) and claim its
|
|
53
|
+
nonce with one atomic write, so a replayed token is refused, before opening voice. The single-use
|
|
54
|
+
claim is mandatory: a bridge without one must refuse to start. Never take identity, instructions, voice, model or tool grants from stream parameters,
|
|
55
|
+
query strings or caller input.
|
|
56
|
+
3. **Instructions and tools are server-owned.** They are fixed in the application's `resolveCall`,
|
|
57
|
+
not supplied by the telephony provider or the caller.
|
|
58
|
+
4. **Verify the media upgrade** when the provider signs it, and route by a path segment you
|
|
59
|
+
validated (for example the call ID), never by an unauthenticated query string.
|
|
60
|
+
5. **Fail closed.** A missing or invalid signature, token, call ID mismatch, account mismatch,
|
|
61
|
+
unsupported codec or protocol violation closes the stream **before** any audio reaches the
|
|
62
|
+
model. A `resolveCall` rejection closes the stream with no audio forwarded.
|
|
63
|
+
6. **Sanitized errors.** Close reasons, logs and callbacks carry fixed codes. Never echo tokens,
|
|
64
|
+
provider credentials, exception messages, transcripts or audio.
|
|
65
|
+
7. **Keypad input (DTMF) goes to the application**, never to the model by default. Applications
|
|
66
|
+
use it for OTP entry or menu choices.
|
|
67
|
+
8. **Outbound calls are out of scope** for a bridge. Gate outbound dialing, transfers and recordings
|
|
68
|
+
separately.
|
|
91
69
|
|
|
92
70
|
---
|
|
93
71
|
|
|
94
|
-
##
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
72
|
+
## 2. Media contract
|
|
73
|
+
|
|
74
|
+
- **Codec end to end.** Pick one codec for the whole session and configure `session.voice()` with
|
|
75
|
+
it; do not resample at the edge when the provider speaks a codec the model supports.
|
|
76
|
+
Telephony μ-law 8 kHz → `audioFormat: 'g711_ulaw'`, `sampleRate: 8000`. Reject any other stream
|
|
77
|
+
format rather than guessing.
|
|
78
|
+
- **Inbound:** decode the provider frame, bound its size, and call `voice.sendAudio(frame)` through a
|
|
79
|
+
bounded queue. Queue overflow closes the call (`backpressure`); do not grow memory without bound.
|
|
80
|
+
Built-in providers' `sendAudio()` waits for provider-socket capacity and rejects with
|
|
81
|
+
`VoiceBackpressureError` (`code: 'VOICE_BACKPRESSURE'`); map that to `backpressure` too.
|
|
82
|
+
Buffer at most ~1 s of pre-roll while the call resolves, dropping the oldest frames.
|
|
83
|
+
- **Outbound:** for each `audio_delta`, send provider media messages carrying the provider stream ID
|
|
84
|
+
(Twilio: `streamSid`) in bounded frames (Twilio: 160 bytes = 20 ms). Close when the socket
|
|
85
|
+
reports excessive buffered bytes. Workers sockets report no `bufferedAmount`, so also bound audio
|
|
86
|
+
sent but not yet acknowledged by a playback marker, and close when a stalled consumer lets it grow
|
|
87
|
+
past the limit.
|
|
88
|
+
- **Playback tracking:** send a provider playback marker after each chunk (Twilio `mark`) and track
|
|
89
|
+
the acknowledged milliseconds per response. Bound outstanding markers; when the bound is reached,
|
|
90
|
+
keep counting the audio as unplayed and send one marker covering the whole tail as soon as a slot
|
|
91
|
+
frees up. Decide whether playback is outstanding from unacknowledged bytes, never from the number
|
|
92
|
+
of outstanding markers.
|
|
105
93
|
|
|
106
94
|
---
|
|
107
95
|
|
|
108
|
-
##
|
|
109
|
-
|
|
110
|
-
Most providers send DTMF as a separate event (not as audio). Surface it to the LLM by either:
|
|
96
|
+
## 3. Barge-in
|
|
111
97
|
|
|
112
|
-
|
|
113
|
-
- Using a `dtmf_received` tool the LLM can call when it asks for a numeric choice.
|
|
98
|
+
On `speech_started`, if any assistant audio sent to the provider is not yet acknowledged as played:
|
|
114
99
|
|
|
115
|
-
|
|
100
|
+
1. Immediately tell the provider to **drop buffered playback** (Twilio `clear`). This is what stops
|
|
101
|
+
the caller hearing the agent; it must not wait on the model.
|
|
102
|
+
2. Then call `voice.cancelResponse({ playedMs })` with the milliseconds the caller actually heard.
|
|
103
|
+
OpenAI Realtime truncates the assistant item to that point.
|
|
104
|
+
3. Drop further `audio_delta` for the interrupted response until its `response_done`.
|
|
105
|
+
4. Ignore playback-marker echoes for the interrupted response.
|
|
106
|
+
5. Do not treat the clear itself as proof that the discarded audio left the provider. Send a
|
|
107
|
+
playback marker right after the clear and release the cleared audio from the unplayed bound only
|
|
108
|
+
when that marker is echoed (Twilio echoes a mark at once when its buffer is empty); close with
|
|
109
|
+
backpressure if the echo does not arrive within a bound.
|
|
110
|
+
6. `cancelResponse` targets the reply playing when it was requested. Governed voice captures that
|
|
111
|
+
identity before its asynchronous authorization, so a delayed cancel never cancels or truncates a
|
|
112
|
+
newer reply.
|
|
116
113
|
|
|
117
114
|
---
|
|
118
115
|
|
|
119
|
-
##
|
|
116
|
+
## 4. Lifecycle and bounds
|
|
120
117
|
|
|
121
|
-
|
|
118
|
+
- Start timeout (connection → valid start), resolve timeout, idle timeout (no inbound media) and a
|
|
119
|
+
bridge-level maximum call duration in addition to governed `limits.durationMs`.
|
|
120
|
+
- Provider `stop`/hangup, socket close/error, abort signal, voice `error` or end of the governed
|
|
121
|
+
event stream all close the bridge. `close()` is idempotent and always closes the governed session
|
|
122
|
+
within a bounded time.
|
|
123
|
+
- Emit latency metrics through an optional callback: first audio, end-of-speech to first reply
|
|
124
|
+
audio (`speech_stopped` → first `audio_delta`), barge-in stop and cancel latency. `speech_stopped`
|
|
125
|
+
is opt-in: open the session with `emitSpeechStopped: true`. Metrics carry the call ID and a number
|
|
126
|
+
only.
|
|
122
127
|
|
|
123
128
|
---
|
|
124
129
|
|
|
125
|
-
##
|
|
130
|
+
## 5. Hosting
|
|
126
131
|
|
|
127
|
-
|
|
128
|
-
`
|
|
129
|
-
|
|
132
|
+
The bridge must be runtime-neutral: depend only on a minimal socket interface
|
|
133
|
+
(`send(text)`, `close(code, reason)`, `addEventListener('message' | 'close' | 'error')`) so Node `ws`
|
|
134
|
+
sockets and Cloudflare Workers sockets both work. Built-in providers open their own sockets through
|
|
135
|
+
`VoiceSocketFactory`; on Workers pass `createWorkersVoiceSocketFactory()`. Governed voice needs an
|
|
136
|
+
atomic `SessionStore` (`appendEntries`): Durable Object SQL, Postgres, or another durable store.
|
|
130
137
|
|
|
131
138
|
---
|
|
132
139
|
|
|
133
|
-
## Checklist
|
|
134
|
-
|
|
135
|
-
- [ ]
|
|
136
|
-
- [ ]
|
|
137
|
-
- [ ]
|
|
138
|
-
-
|
|
139
|
-
- [ ]
|
|
140
|
-
- [ ]
|
|
141
|
-
- [ ]
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
140
|
+
## 6. Checklist before submitting
|
|
141
|
+
|
|
142
|
+
- [ ] Uses `@fabric-harness/channels/twilio-voice` for Twilio instead of a new bridge.
|
|
143
|
+
- [ ] Opens voice only through `session.voice()`; rejects sessions without `governed === true`.
|
|
144
|
+
- [ ] Webhook and media-upgrade signatures verified; call binding carried in a signed, expiring,
|
|
145
|
+
call-bound token; no identity or instructions from stream parameters.
|
|
146
|
+
- [ ] Codec validated and configured end to end; no silent resampling.
|
|
147
|
+
- [ ] Mandatory atomic single-use claim of the stream token before `resolveCall`.
|
|
148
|
+
- [ ] Bounded inbound queue, outbound buffering check plus a playback-acknowledged bound, frame and
|
|
149
|
+
message size limits.
|
|
150
|
+
- [ ] Barge-in sends the provider's clear/stop-playback first, then `cancelResponse({ playedMs })`.
|
|
151
|
+
- [ ] Start, resolve, idle and duration timeouts; abort signal; idempotent close.
|
|
152
|
+
- [ ] DTMF delivered to an application callback only, through a bounded, ordered queue with one
|
|
153
|
+
callback at a time, a per-callback deadline and an abort signal that fires on close.
|
|
154
|
+
- [ ] Errors, close reasons and logs are fixed codes with no secrets, tokens or transcript text.
|
|
155
|
+
- [ ] Tests cover spoofed webhooks, cross-call and replayed tokens, wrong codec, `resolveCall`
|
|
156
|
+
rejection, backpressure, idle timeout and barge-in ordering, with no live credentials.
|
|
157
|
+
- [ ] Imports use public package exports only (no `/dist/...` or `src/` deep imports).
|
|
158
|
+
|
|
159
|
+
If the provider's documentation is unclear on a frame format or signature scheme, fail closed and
|
|
160
|
+
leave a `// TODO` with a specific question rather than guessing.
|
package/dist/agent-route.d.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* objects, never a store, a submission runner, or a platform binding.
|
|
12
12
|
*/
|
|
13
13
|
/** Subroutes under `/agents/:name/:instanceId`. */
|
|
14
|
-
export type AgentRouteSection = "submissions" | "conversation" | "abort" | "schedules" | "stream";
|
|
14
|
+
export type AgentRouteSection = "submissions" | "conversation" | "history" | "abort" | "schedules" | "stream" | "attachments";
|
|
15
15
|
export interface AgentRouteMatch {
|
|
16
16
|
/** Registered agent name, percent-decoded. */
|
|
17
17
|
agent: string;
|
|
@@ -19,7 +19,10 @@ export interface AgentRouteMatch {
|
|
|
19
19
|
instanceId: string;
|
|
20
20
|
/** Absent for the instance root (`POST`/`GET`/`DELETE`). */
|
|
21
21
|
section?: AgentRouteSection;
|
|
22
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* Trailing identifier, e.g. the submission id under `submissions` or the
|
|
24
|
+
* sha-256 digest under `attachments`.
|
|
25
|
+
*/
|
|
23
26
|
resourceId?: string;
|
|
24
27
|
}
|
|
25
28
|
/**
|
|
@@ -34,6 +37,7 @@ export declare function matchAgentRoute(pathname: string): AgentRouteMatch | und
|
|
|
34
37
|
/** Session name carried by `?session=`, defaulting to `default`. */
|
|
35
38
|
export declare function agentRouteSession(searchParams: URLSearchParams): string;
|
|
36
39
|
export interface AgentSubmissionReceiptInput {
|
|
40
|
+
deduplicated?: boolean;
|
|
37
41
|
submissionId: string;
|
|
38
42
|
agent: string;
|
|
39
43
|
instanceId: string;
|
|
@@ -56,6 +60,7 @@ export interface AgentSubmissionReceiptInput {
|
|
|
56
60
|
updates?: boolean;
|
|
57
61
|
}
|
|
58
62
|
export interface AgentSubmissionReceipt {
|
|
63
|
+
deduplicated?: boolean;
|
|
59
64
|
submissionId: string;
|
|
60
65
|
uid?: string;
|
|
61
66
|
acceptedAt?: string;
|
|
@@ -73,4 +78,19 @@ export declare function agentInstancePath(agent: string, instanceId: string): st
|
|
|
73
78
|
* for compatibility with clients written against the earlier shape.
|
|
74
79
|
*/
|
|
75
80
|
export declare function agentSubmissionReceipt(input: AgentSubmissionReceiptInput): AgentSubmissionReceipt;
|
|
81
|
+
/** Stored attachment metadata needed to answer a download. */
|
|
82
|
+
export interface AttachmentDownloadRef {
|
|
83
|
+
mimeType: string;
|
|
84
|
+
filename?: string;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Response headers for `GET /agents/:name/:instanceId/attachments/:digest`.
|
|
88
|
+
*
|
|
89
|
+
* Attachment bytes are user-uploaded content, so every target serves them the
|
|
90
|
+
* same defensive way: always as a download (`content-disposition: attachment`
|
|
91
|
+
* with a sanitized filename), never sniffed (`nosniff`), never cached by shared
|
|
92
|
+
* caches (`private, no-store`), and sandboxed with an empty CSP should a
|
|
93
|
+
* browser render them anyway.
|
|
94
|
+
*/
|
|
95
|
+
export declare function attachmentDownloadHeaders(ref: AttachmentDownloadRef, byteLength: number): Record<string, string>;
|
|
76
96
|
//# sourceMappingURL=agent-route.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-route.d.ts","sourceRoot":"","sources":["../src/agent-route.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;
|
|
1
|
+
{"version":3,"file":"agent-route.d.ts","sourceRoot":"","sources":["../src/agent-route.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAIH,mDAAmD;AACnD,MAAM,MAAM,iBAAiB,GACzB,aAAa,GACb,cAAc,GACd,SAAS,GACT,OAAO,GACP,WAAW,GACX,QAAQ,GACR,aAAa,CAAC;AAKlB,MAAM,WAAW,eAAe;IAC9B,8CAA8C;IAC9C,KAAK,EAAE,MAAM,CAAC;IACd,0DAA0D;IAC1D,UAAU,EAAE,MAAM,CAAC;IACnB,4DAA4D;IAC5D,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CAAC;CACnB;AAED;;;;;;;;GAQG;AACH,wBAAgB,yBAAyB,CACvC,GAAG,EAAE,qBAAqB,EAC1B,UAAU,EAAE,MAAM,GACjB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CASxB"}
|
package/dist/agent-route.js
CHANGED
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
* Runtime-neutral by construction: this module touches only URLs and plain
|
|
11
11
|
* objects, never a store, a submission runner, or a platform binding.
|
|
12
12
|
*/
|
|
13
|
-
|
|
13
|
+
import { sanitizeAttachmentFilename } from "./attachments.js";
|
|
14
|
+
const AGENT_ROUTE_PATTERN = /^\/agents\/([^/]+)\/([^/]+)(?:\/(submissions|conversation|history|abort|schedules|stream|attachments)(?:\/([^/]+))?)?$/;
|
|
14
15
|
/**
|
|
15
16
|
* Parse a pathname against the agent route surface.
|
|
16
17
|
*
|
|
@@ -67,6 +68,7 @@ export function agentSubmissionReceipt(input) {
|
|
|
67
68
|
const conversationUrl = `${base}/conversation?${query}`;
|
|
68
69
|
return {
|
|
69
70
|
submissionId: input.submissionId,
|
|
71
|
+
...(input.deduplicated !== undefined ? { deduplicated: input.deduplicated } : {}),
|
|
70
72
|
...(input.uid ? { uid: input.uid } : {}),
|
|
71
73
|
...(input.acceptedAt ? { acceptedAt: input.acceptedAt } : {}),
|
|
72
74
|
streamUrl: conversationUrl,
|
|
@@ -75,4 +77,33 @@ export function agentSubmissionReceipt(input) {
|
|
|
75
77
|
offset: input.offset,
|
|
76
78
|
};
|
|
77
79
|
}
|
|
80
|
+
/**
|
|
81
|
+
* Response headers for `GET /agents/:name/:instanceId/attachments/:digest`.
|
|
82
|
+
*
|
|
83
|
+
* Attachment bytes are user-uploaded content, so every target serves them the
|
|
84
|
+
* same defensive way: always as a download (`content-disposition: attachment`
|
|
85
|
+
* with a sanitized filename), never sniffed (`nosniff`), never cached by shared
|
|
86
|
+
* caches (`private, no-store`), and sandboxed with an empty CSP should a
|
|
87
|
+
* browser render them anyway.
|
|
88
|
+
*/
|
|
89
|
+
export function attachmentDownloadHeaders(ref, byteLength) {
|
|
90
|
+
return {
|
|
91
|
+
"content-type": ref.mimeType,
|
|
92
|
+
"content-length": String(byteLength),
|
|
93
|
+
"content-disposition": attachmentContentDisposition(ref.filename),
|
|
94
|
+
"x-content-type-options": "nosniff",
|
|
95
|
+
"cache-control": "private, no-store",
|
|
96
|
+
"content-security-policy": "default-src 'none'; sandbox",
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function attachmentContentDisposition(filename) {
|
|
100
|
+
// Well-formed before encoding: a lone surrogate (from a record admitted by
|
|
101
|
+
// an older release or another path) makes encodeURIComponent throw.
|
|
102
|
+
const safe = filename ? sanitizeAttachmentFilename(filename) : undefined;
|
|
103
|
+
if (!safe)
|
|
104
|
+
return "attachment";
|
|
105
|
+
const ascii = safe.replace(/[^\x20-\x7e]/g, "_").replace(/[\\";]/g, "_");
|
|
106
|
+
const encoded = encodeURIComponent(safe).replace(/['()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
107
|
+
return `attachment; filename="${ascii}"; filename*=UTF-8''${encoded}`;
|
|
108
|
+
}
|
|
78
109
|
//# sourceMappingURL=agent-route.js.map
|
package/dist/agent-route.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-route.js","sourceRoot":"","sources":["../src/agent-route.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;
|
|
1
|
+
{"version":3,"file":"agent-route.js","sourceRoot":"","sources":["../src/agent-route.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AAY9D,MAAM,mBAAmB,GACvB,wHAAwH,CAAC;AAgB3H;;;;;;;GAOG;AACH,MAAM,UAAU,eAAe,CAAC,QAAgB;IAC9C,MAAM,KAAK,GAAG,mBAAmB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACjD,I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E,MAAM,CAAC,UAAU,CAAC;QACpC,qBAAqB,EAAE,4BAA4B,CAAC,GAAG,CAAC,QAAQ,CAAC;QACjE,wBAAwB,EAAE,SAAS;QACnC,eAAe,EAAE,mBAAmB;QACpC,yBAAyB,EAAE,6BAA6B;KACzD,CAAC;AACJ,CAAC;AAED,SAAS,4BAA4B,CAAC,QAA4B;IAChE,2EAA2E;IAC3E,oEAAoE;IACpE,MAAM,IAAI,GAAG,QAAQ,CAAC,CAAC,CAAC,0BAA0B,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACzE,IAAI,CAAC,IAAI;QAAE,OAAO,YAAY,CAAC;IAC/B,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,eAAe,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;IACzE,MAAM,OAAO,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC,OAAO,CAC9C,SAAS,EACT,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,EAAE,CAC9D,CAAC;IACF,OAAO,yBAAyB,KAAK,uBAAuB,OAAO,EAAE,CAAC;AACxE,CAAC"}
|
package/dist/agent-router.d.ts
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
* on Node, Cloudflare, Deno, Bun, or any fetch-capable host.
|
|
17
17
|
*/
|
|
18
18
|
import type { DeliveredMessage } from "./delivered-message.js";
|
|
19
|
+
import { type ConversationHistoryRequest, type ConversationHistoryWindow } from './conversation-history.js';
|
|
19
20
|
/** Identity of one addressed conversation. */
|
|
20
21
|
export interface FabricAgentAddress {
|
|
21
22
|
agent: string;
|
|
@@ -23,6 +24,7 @@ export interface FabricAgentAddress {
|
|
|
23
24
|
session: string;
|
|
24
25
|
}
|
|
25
26
|
export interface FabricAgentAdmission extends FabricAgentAddress {
|
|
27
|
+
idempotencyKey?: string;
|
|
26
28
|
message: DeliveredMessage;
|
|
27
29
|
initialData?: unknown;
|
|
28
30
|
uid?: string | null;
|
|
@@ -30,6 +32,7 @@ export interface FabricAgentAdmission extends FabricAgentAddress {
|
|
|
30
32
|
tenantId?: string;
|
|
31
33
|
}
|
|
32
34
|
export interface FabricAgentAdmissionResult {
|
|
35
|
+
deduplicated?: boolean;
|
|
33
36
|
submissionId: string;
|
|
34
37
|
/**
|
|
35
38
|
* Stream position captured before admission. Reading from it returns this
|
|
@@ -58,6 +61,12 @@ export interface FabricAgentSubmissionStatus {
|
|
|
58
61
|
error?: string;
|
|
59
62
|
answeredBySubmissionId?: string;
|
|
60
63
|
}
|
|
64
|
+
/** Stored attachment bytes returned by {@link FabricAgentRouterBackend.readAttachment}. */
|
|
65
|
+
export interface FabricAgentAttachment {
|
|
66
|
+
mimeType: string;
|
|
67
|
+
filename?: string;
|
|
68
|
+
bytes: Uint8Array;
|
|
69
|
+
}
|
|
61
70
|
export interface FabricAgentDeletion {
|
|
62
71
|
deleted: boolean;
|
|
63
72
|
aborted?: boolean;
|
|
@@ -69,6 +78,8 @@ export interface FabricAgentDeletion {
|
|
|
69
78
|
* generic body rather than leaking host internals to the caller.
|
|
70
79
|
*/
|
|
71
80
|
export interface FabricAgentRouterBackend {
|
|
81
|
+
/** Explicitly advertise atomic keyed admission; otherwise keyed requests fail with 501. */
|
|
82
|
+
supportsIdempotentAdmission?: boolean;
|
|
72
83
|
/**
|
|
73
84
|
* Whether the named agent exists and may be served over HTTP. Returning
|
|
74
85
|
* `exposed: false` produces the same `404` as an unknown agent, so probing
|
|
@@ -79,10 +90,29 @@ export interface FabricAgentRouterBackend {
|
|
|
79
90
|
exposed?: boolean;
|
|
80
91
|
}>;
|
|
81
92
|
admit(input: FabricAgentAdmission): Promise<FabricAgentAdmissionResult>;
|
|
93
|
+
/**
|
|
94
|
+
* One page of the conversation stream. `signal` is the HTTP request's
|
|
95
|
+
* signal when the read serves a history request; a backend may pass it to
|
|
96
|
+
* its storage call so an abandoned request stops reading.
|
|
97
|
+
*/
|
|
82
98
|
readConversation(address: FabricAgentAddress & {
|
|
83
99
|
offset: string;
|
|
84
100
|
limit: number;
|
|
101
|
+
signal?: AbortSignal;
|
|
85
102
|
}): Promise<FabricAgentConversationPage>;
|
|
103
|
+
/**
|
|
104
|
+
* Optional fast path for `GET .../history`. Without it the router pages
|
|
105
|
+
* {@link readConversation} from offset 0 to the head (bounded by
|
|
106
|
+
* `maxHistoryScanRecords`) and selects the window itself. A backend with a
|
|
107
|
+
* fold checkpoint or an index can serve the window directly, for example
|
|
108
|
+
* with `readConversationHistory(store, path, request, { signal })`. It must
|
|
109
|
+
* throw `ConversationHistoryError` for gone cursors and stop when `signal`
|
|
110
|
+
* aborts.
|
|
111
|
+
*/
|
|
112
|
+
readConversationHistory?(address: FabricAgentAddress & {
|
|
113
|
+
request: ConversationHistoryRequest;
|
|
114
|
+
signal: AbortSignal;
|
|
115
|
+
}): Promise<ConversationHistoryWindow>;
|
|
86
116
|
getSubmission(address: FabricAgentAddress & {
|
|
87
117
|
submissionId: string;
|
|
88
118
|
}): Promise<FabricAgentSubmissionStatus | undefined>;
|
|
@@ -94,6 +124,15 @@ export interface FabricAgentRouterBackend {
|
|
|
94
124
|
streamUpdates?(address: FabricAgentAddress & {
|
|
95
125
|
offset: string;
|
|
96
126
|
}, request: Request): Promise<Response>;
|
|
127
|
+
/**
|
|
128
|
+
* Stored attachment bytes for one addressed conversation, keyed by sha-256
|
|
129
|
+
* digest. The backend must scope the read to the address (and to the
|
|
130
|
+
* caller's tenant) and return `undefined` for anything outside it. Hosts
|
|
131
|
+
* without an attachment store omit it and the route 404s.
|
|
132
|
+
*/
|
|
133
|
+
readAttachment?(address: FabricAgentAddress & {
|
|
134
|
+
digest: string;
|
|
135
|
+
}, request: Request): Promise<FabricAgentAttachment | undefined>;
|
|
97
136
|
/** Per-instance schedules, where the host supports them. */
|
|
98
137
|
handleSchedules?(address: FabricAgentAddress, request: Request): Promise<Response | undefined>;
|
|
99
138
|
}
|
|
@@ -106,6 +145,13 @@ export interface FabricAgentRouterOptions {
|
|
|
106
145
|
basePath?: string;
|
|
107
146
|
/** Largest `limit` a conversation read may request. Defaults to 1000. */
|
|
108
147
|
maxReadLimit?: number;
|
|
148
|
+
/**
|
|
149
|
+
* Most stream records a paged history read may scan before answering
|
|
150
|
+
* `503 history_read_incomplete`. Defaults to
|
|
151
|
+
* `CONVERSATION_HISTORY_MAX_SCAN_RECORDS` (250,000). Not applied to a
|
|
152
|
+
* backend's own `readConversationHistory`.
|
|
153
|
+
*/
|
|
154
|
+
maxHistoryScanRecords?: number;
|
|
109
155
|
}
|
|
110
156
|
export interface FabricAgentRouter {
|
|
111
157
|
/** Always returns a `Response`, 404-ing paths outside the agent surface. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-router.d.ts","sourceRoot":"","sources":["../src/agent-router.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;
|
|
1
|
+
{"version":3,"file":"agent-router.d.ts","sourceRoot":"","sources":["../src/agent-router.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAUH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE/D,OAAO,EAIL,KAAK,0BAA0B,EAC/B,KAAK,yBAAyB,EAC/B,MAAM,2BAA2B,CAAC;AAEnC,8CAA8C;AAC9C,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,oBAAqB,SAAQ,kBAAkB;IAC9D,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,OAAO,EAAE,gBAAgB,CAAC;IAC1B,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACp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,CAAC;IAC9C,4DAA4D;IAC5D,eAAe,CAAC,CAAC,OAAO,EAAE,kBAAkB,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC,CAAC;CAChG;AAED,MAAM,WAAW,wBAAwB;IACvC;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,yEAAyE;IACzE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;;OAKG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC;AAED,MAAM,WAAW,iBAAiB;IAChC,4EAA4E;IAC5E,KAAK,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC3C;;;OAGG;IACH,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC,CAAC;CACzD;AA4BD;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,wBAAwB,EACjC,OAAO,GAAE,wBAA6B,GACrC,iBAAiB,CA0NnB"}
|
package/dist/agent-router.js
CHANGED
|
@@ -15,8 +15,10 @@
|
|
|
15
15
|
* Runtime-neutral: only `Request`, `Response`, `URL`, and plain objects. It runs
|
|
16
16
|
* on Node, Cloudflare, Deno, Bun, or any fetch-capable host.
|
|
17
17
|
*/
|
|
18
|
-
import { agentRouteSession, agentSubmissionReceipt, matchAgentRoute, } from "./agent-route.js";
|
|
18
|
+
import { agentRouteSession, agentSubmissionReceipt, attachmentDownloadHeaders, matchAgentRoute, } from "./agent-route.js";
|
|
19
19
|
import { normalizeDeliveredMessage } from "./delivered-message.js";
|
|
20
|
+
import { isFabricError } from './error.js';
|
|
21
|
+
import { ConversationHistoryError, parseConversationHistoryRequest, readConversationHistoryFromPages, } from './conversation-history.js';
|
|
20
22
|
const DEFAULT_MAX_READ_LIMIT = 1000;
|
|
21
23
|
function json(value, status = 200) {
|
|
22
24
|
return new Response(JSON.stringify(value, null, 2), {
|
|
@@ -95,6 +97,32 @@ export function createFabricAgentRouter(backend, options = {}) {
|
|
|
95
97
|
limit: readLimit(url.searchParams, maxReadLimit),
|
|
96
98
|
}));
|
|
97
99
|
}
|
|
100
|
+
case "history": {
|
|
101
|
+
if (request.method !== "GET")
|
|
102
|
+
return methodNotAllowed();
|
|
103
|
+
// Bounded, message-windowed view of the same conversation. A backend
|
|
104
|
+
// may serve it directly; otherwise it is assembled from the backend's
|
|
105
|
+
// paged conversation reads, so every backend serves it. Either way the
|
|
106
|
+
// request's signal stops the read when the caller goes away.
|
|
107
|
+
try {
|
|
108
|
+
const historyRequest = parseConversationHistoryRequest(url.searchParams);
|
|
109
|
+
const signal = request.signal;
|
|
110
|
+
return json(backend.readConversationHistory
|
|
111
|
+
? await backend.readConversationHistory({ ...address, request: historyRequest, signal })
|
|
112
|
+
: await readConversationHistoryFromPages((offset) => backend.readConversation({ ...address, offset, limit: maxReadLimit, signal }), historyRequest, {
|
|
113
|
+
signal,
|
|
114
|
+
...(options.maxHistoryScanRecords !== undefined
|
|
115
|
+
? { maxRecords: options.maxHistoryScanRecords }
|
|
116
|
+
: {}),
|
|
117
|
+
}));
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
if (error instanceof ConversationHistoryError) {
|
|
121
|
+
return json(error.toResponseBody(), error.status);
|
|
122
|
+
}
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
98
126
|
case "abort": {
|
|
99
127
|
if (request.method !== "POST")
|
|
100
128
|
return methodNotAllowed();
|
|
@@ -107,6 +135,22 @@ export function createFabricAgentRouter(backend, options = {}) {
|
|
|
107
135
|
return notFound();
|
|
108
136
|
return backend.streamUpdates({ ...address, offset: url.searchParams.get("offset") ?? "0" }, request);
|
|
109
137
|
}
|
|
138
|
+
case "attachments": {
|
|
139
|
+
if (request.method !== "GET")
|
|
140
|
+
return methodNotAllowed();
|
|
141
|
+
if (!route.resourceId || !backend.readAttachment) {
|
|
142
|
+
return json({ error: "attachment_not_found" }, 404);
|
|
143
|
+
}
|
|
144
|
+
const stored = await backend.readAttachment({ ...address, digest: route.resourceId }, request);
|
|
145
|
+
if (!stored)
|
|
146
|
+
return json({ error: "attachment_not_found" }, 404);
|
|
147
|
+
// Copy into a fresh ArrayBuffer-backed view: `Uint8Array<ArrayBufferLike>`
|
|
148
|
+
// is not `BodyInit` under every DOM lib the SDK is compiled against.
|
|
149
|
+
return new Response(new Uint8Array(stored.bytes), {
|
|
150
|
+
status: 200,
|
|
151
|
+
headers: attachmentDownloadHeaders(stored, stored.bytes.byteLength),
|
|
152
|
+
});
|
|
153
|
+
}
|
|
110
154
|
case "schedules": {
|
|
111
155
|
if (!backend.handleSchedules)
|
|
112
156
|
return notFound();
|
|
@@ -158,8 +202,16 @@ export function createFabricAgentRouter(backend, options = {}) {
|
|
|
158
202
|
}, 400);
|
|
159
203
|
}
|
|
160
204
|
const tenantId = request.headers.get("x-fabric-tenant") ?? undefined;
|
|
205
|
+
const idempotencyKey = request.headers.get('idempotency-key') ?? undefined;
|
|
206
|
+
if (idempotencyKey !== undefined && !/^[\x21-\x7e]{1,256}$/.test(idempotencyKey)) {
|
|
207
|
+
return json({ error: { type: 'invalid_request', message: 'Invalid Idempotency-Key.' } }, 400);
|
|
208
|
+
}
|
|
209
|
+
if (idempotencyKey !== undefined && !backend.supportsIdempotentAdmission) {
|
|
210
|
+
return json({ error: { type: 'unsupported_operation', message: 'Backend does not support idempotent admission.' } }, 501);
|
|
211
|
+
}
|
|
161
212
|
const admitted = await backend.admit({
|
|
162
213
|
...address,
|
|
214
|
+
...(idempotencyKey !== undefined ? { idempotencyKey } : {}),
|
|
163
215
|
message: normalizeDeliveredMessage(message),
|
|
164
216
|
...(body.initialData !== undefined ? { initialData: body.initialData } : {}),
|
|
165
217
|
...(body.uid !== undefined ? { uid: body.uid } : {}),
|
|
@@ -171,6 +223,7 @@ export function createFabricAgentRouter(backend, options = {}) {
|
|
|
171
223
|
instanceId: address.instanceId,
|
|
172
224
|
session: address.session,
|
|
173
225
|
offset: admitted.offset,
|
|
226
|
+
...(admitted.deduplicated !== undefined ? { deduplicated: admitted.deduplicated } : {}),
|
|
174
227
|
...(admitted.uid ? { uid: admitted.uid } : {}),
|
|
175
228
|
...(admitted.acceptedAt ? { acceptedAt: admitted.acceptedAt } : {}),
|
|
176
229
|
updates: backend.streamUpdates !== undefined,
|
|
@@ -180,7 +233,15 @@ export function createFabricAgentRouter(backend, options = {}) {
|
|
|
180
233
|
try {
|
|
181
234
|
return await handle(request);
|
|
182
235
|
}
|
|
183
|
-
catch {
|
|
236
|
+
catch (error) {
|
|
237
|
+
// The caller went away mid-read: nothing will receive a body, and the
|
|
238
|
+
// abort is not a host failure.
|
|
239
|
+
if (request.signal.aborted) {
|
|
240
|
+
return json({ error: { type: 'aborted', message: 'Request was aborted.' } }, 499);
|
|
241
|
+
}
|
|
242
|
+
if (isFabricError(error) && error.code === 'PERSISTENCE_CONFLICT') {
|
|
243
|
+
return json({ error: { ...error.toPublicJSON(), type: 'conflict' } }, 409);
|
|
244
|
+
}
|
|
184
245
|
// Host failures must not leak storage or execution internals to callers.
|
|
185
246
|
return json({ error: { type: "internal_error", message: "Request failed." } }, 500);
|
|
186
247
|
}
|