agenthooksprotocol 0.0.0-stage → 0.1.1
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/LICENSE +202 -0
- package/README.md +69 -2
- package/dist/src/client/auth.d.ts +147 -0
- package/dist/src/client/auth.d.ts.map +1 -0
- package/dist/src/client/auth.js +629 -0
- package/dist/src/client/auth.js.map +1 -0
- package/dist/src/client/composition.d.ts +44 -0
- package/dist/src/client/composition.d.ts.map +1 -0
- package/dist/src/client/composition.js +531 -0
- package/dist/src/client/composition.js.map +1 -0
- package/dist/src/client/content.d.ts +75 -0
- package/dist/src/client/content.d.ts.map +1 -0
- package/dist/src/client/content.js +415 -0
- package/dist/src/client/content.js.map +1 -0
- package/dist/src/client/hooks.d.ts +66 -0
- package/dist/src/client/hooks.d.ts.map +1 -0
- package/dist/src/client/hooks.js +1084 -0
- package/dist/src/client/hooks.js.map +1 -0
- package/dist/src/client/index.d.ts +12 -0
- package/dist/src/client/index.d.ts.map +1 -0
- package/dist/src/client/index.js +10 -0
- package/dist/src/client/index.js.map +1 -0
- package/dist/src/client/transport.d.ts +12 -0
- package/dist/src/client/transport.d.ts.map +1 -0
- package/dist/src/client/transport.js +347 -0
- package/dist/src/client/transport.js.map +1 -0
- package/dist/src/client/types.d.ts +117 -0
- package/dist/src/client/types.d.ts.map +1 -0
- package/dist/src/client/types.js +10 -0
- package/dist/src/client/types.js.map +1 -0
- package/dist/src/client/validation.d.ts +3 -0
- package/dist/src/client/validation.d.ts.map +1 -0
- package/dist/src/client/validation.js +25 -0
- package/dist/src/client/validation.js.map +1 -0
- package/dist/src/compaction.d.ts +27 -0
- package/dist/src/compaction.d.ts.map +1 -0
- package/dist/src/compaction.js +155 -0
- package/dist/src/compaction.js.map +1 -0
- package/dist/src/content-upload.d.ts +59 -0
- package/dist/src/content-upload.d.ts.map +1 -0
- package/dist/src/content-upload.js +133 -0
- package/dist/src/content-upload.js.map +1 -0
- package/dist/src/draft/generated.d.ts +3111 -0
- package/dist/src/draft/generated.d.ts.map +1 -0
- package/dist/src/draft/generated.js +15623 -0
- package/dist/src/draft/generated.js.map +1 -0
- package/dist/src/draft/index.d.ts +34 -0
- package/dist/src/draft/index.d.ts.map +1 -0
- package/dist/src/draft/index.js +131 -0
- package/dist/src/draft/index.js.map +1 -0
- package/dist/src/draft/schemas.d.ts +8920 -0
- package/dist/src/draft/schemas.d.ts.map +1 -0
- package/dist/src/draft/schemas.js +9257 -0
- package/dist/src/draft/schemas.js.map +1 -0
- package/dist/src/draft-atomic.d.ts +18 -0
- package/dist/src/draft-atomic.d.ts.map +1 -0
- package/dist/src/draft-atomic.js +102 -0
- package/dist/src/draft-atomic.js.map +1 -0
- package/dist/src/draft-runtime.d.ts +89 -0
- package/dist/src/draft-runtime.d.ts.map +1 -0
- package/dist/src/draft-runtime.js +240 -0
- package/dist/src/draft-runtime.js.map +1 -0
- package/dist/src/elicitation.d.ts +18 -0
- package/dist/src/elicitation.d.ts.map +1 -0
- package/dist/src/elicitation.js +191 -0
- package/dist/src/elicitation.js.map +1 -0
- package/dist/src/errors.d.ts +7 -0
- package/dist/src/errors.d.ts.map +1 -0
- package/dist/src/errors.js +15 -0
- package/dist/src/errors.js.map +1 -0
- package/dist/src/framing.d.ts +7 -0
- package/dist/src/framing.d.ts.map +1 -0
- package/dist/src/framing.js +39 -0
- package/dist/src/framing.js.map +1 -0
- package/dist/src/generated.d.ts +304 -0
- package/dist/src/generated.d.ts.map +1 -0
- package/dist/src/generated.js +1885 -0
- package/dist/src/generated.js.map +1 -0
- package/dist/src/hook-runner.d.ts +11 -0
- package/dist/src/hook-runner.d.ts.map +1 -0
- package/dist/src/hook-runner.js +223 -0
- package/dist/src/hook-runner.js.map +1 -0
- package/dist/src/index.d.ts +8 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +8 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/observation.d.ts +26 -0
- package/dist/src/observation.d.ts.map +1 -0
- package/dist/src/observation.js +28 -0
- package/dist/src/observation.js.map +1 -0
- package/dist/src/server/attachments.d.ts +29 -0
- package/dist/src/server/attachments.d.ts.map +1 -0
- package/dist/src/server/attachments.js +112 -0
- package/dist/src/server/attachments.js.map +1 -0
- package/dist/src/server/hooks.d.ts +20 -0
- package/dist/src/server/hooks.d.ts.map +1 -0
- package/dist/src/server/hooks.js +131 -0
- package/dist/src/server/hooks.js.map +1 -0
- package/dist/src/server/index.d.ts +9 -0
- package/dist/src/server/index.d.ts.map +1 -0
- package/dist/src/server/index.js +5 -0
- package/dist/src/server/index.js.map +1 -0
- package/dist/src/server/stdio.d.ts +15 -0
- package/dist/src/server/stdio.d.ts.map +1 -0
- package/dist/src/server/stdio.js +69 -0
- package/dist/src/server/stdio.js.map +1 -0
- package/dist/src/transport.d.ts +7 -0
- package/dist/src/transport.d.ts.map +1 -0
- package/dist/src/transport.js +195 -0
- package/dist/src/transport.js.map +1 -0
- package/dist/src/types.d.ts +116 -0
- package/dist/src/types.d.ts.map +1 -0
- package/dist/src/types.js +14 -0
- package/dist/src/types.js.map +1 -0
- package/dist/src/validation.d.ts +7 -0
- package/dist/src/validation.d.ts.map +1 -0
- package/dist/src/validation.js +209 -0
- package/dist/src/validation.js.map +1 -0
- package/package.json +62 -4
- package/src/client/auth.ts +1076 -0
- package/src/client/composition.ts +717 -0
- package/src/client/content.ts +522 -0
- package/src/client/hooks.ts +1477 -0
- package/src/client/index.ts +30 -0
- package/src/client/transport.ts +408 -0
- package/src/client/types.ts +173 -0
- package/src/client/validation.ts +24 -0
- package/src/compaction.ts +196 -0
- package/src/content-upload.ts +206 -0
- package/src/draft/README.md +16 -0
- package/src/draft/ahp-codegen.lock.json +131 -0
- package/src/draft/generated.ts +19449 -0
- package/src/draft/index.ts +251 -0
- package/src/draft/schemas.ts +9453 -0
- package/src/draft-atomic.ts +119 -0
- package/src/draft-runtime.ts +363 -0
- package/src/elicitation.ts +254 -0
- package/src/errors.ts +30 -0
- package/src/framing.ts +56 -0
- package/src/generated.ts +2408 -0
- package/src/hook-runner.ts +310 -0
- package/src/index.ts +8 -0
- package/src/observation.ts +65 -0
- package/src/server/attachments.ts +128 -0
- package/src/server/hooks.ts +206 -0
- package/src/server/index.ts +23 -0
- package/src/server/node-crypto.d.ts +7 -0
- package/src/server/stdio.ts +81 -0
- package/src/transport.ts +273 -0
- package/src/types.ts +124 -0
- package/src/validation.ts +372 -0
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
import {
|
|
2
|
+
parseContentUploadReceipt,
|
|
3
|
+
type ContentSelection,
|
|
4
|
+
type ContentUpload,
|
|
5
|
+
} from "../draft/generated.js";
|
|
6
|
+
|
|
7
|
+
/** An owned native content stream, distinct from a receiver content reference.
|
|
8
|
+
* Construction does not read, lock, or upload the stream. Passing this source to
|
|
9
|
+
* an awaited SDK operation transfers cleanup responsibility to that operation;
|
|
10
|
+
* callers must not consume or reuse the underlying stream afterward. Native
|
|
11
|
+
* streams can prefetch independently; use highWaterMark: 0 to disable that.
|
|
12
|
+
*/
|
|
13
|
+
export class ContentSource {
|
|
14
|
+
readonly #stream: ReadableStream<Uint8Array>;
|
|
15
|
+
|
|
16
|
+
constructor(stream: ReadableStream<Uint8Array>) {
|
|
17
|
+
if (!(stream instanceof ReadableStream))
|
|
18
|
+
throw new Error("Content source requires a native ReadableStream");
|
|
19
|
+
this.#stream = stream;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Native stream identity is preserved for snapshot sharing and cleanup. */
|
|
23
|
+
get stream(): ReadableStream<Uint8Array> {
|
|
24
|
+
return this.#stream;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function sourceStream(value: unknown): ReadableStream<Uint8Array> | undefined {
|
|
29
|
+
if (value instanceof ContentSource) return value.stream;
|
|
30
|
+
return value instanceof ReadableStream ? value : undefined;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Producer content is metadata with an owned source or raw stream in `body`. */
|
|
34
|
+
export interface StreamContentItem {
|
|
35
|
+
id: string;
|
|
36
|
+
kind: string;
|
|
37
|
+
mediaType: string;
|
|
38
|
+
body: ContentSource | ReadableStream<Uint8Array>;
|
|
39
|
+
category?: string;
|
|
40
|
+
size?: number;
|
|
41
|
+
sha256?: string;
|
|
42
|
+
[key: string]: unknown;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Authenticate this upload independently, including discovery when auth is absent.
|
|
46
|
+
* Implementations must honor init.signal and init.redirect; never reuse event credentials.
|
|
47
|
+
*/
|
|
48
|
+
export type ContentUploadRequest = (
|
|
49
|
+
endpoint: string,
|
|
50
|
+
init: RequestInit,
|
|
51
|
+
upload: ContentUpload,
|
|
52
|
+
) => Promise<Response>;
|
|
53
|
+
|
|
54
|
+
export interface ContentManagerOptions {
|
|
55
|
+
/** Aggregate retained byte limit, not a truncation threshold. Default: 64 MiB.
|
|
56
|
+
* Snapshots are kept until close. Chunk assembly, hashing, and each concurrent
|
|
57
|
+
* request also use bounded copies. Streams exceeding it fail explicitly.
|
|
58
|
+
*/
|
|
59
|
+
maxSnapshotBytes?: number;
|
|
60
|
+
allowLoopback?: boolean;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
type Snapshot = { bytes: Uint8Array; size: number; sha256: string };
|
|
64
|
+
|
|
65
|
+
/** One manager per producer/session. Selection is NOT authorization: callers must
|
|
66
|
+
* authorize/project opaque native/input/output data before prepare. References
|
|
67
|
+
* are deliberately never cached: each prepare uploads in its receiver's scope.
|
|
68
|
+
*/
|
|
69
|
+
export class ContentManager {
|
|
70
|
+
private snapshots = new WeakMap<
|
|
71
|
+
ReadableStream<Uint8Array>,
|
|
72
|
+
Promise<Snapshot>
|
|
73
|
+
>();
|
|
74
|
+
private readers = new Set<ReadableStreamDefaultReader<Uint8Array>>();
|
|
75
|
+
private seenStreams = new Set<ReadableStream<Uint8Array>>();
|
|
76
|
+
private lifetime = new AbortController();
|
|
77
|
+
private retainedBytes = 0;
|
|
78
|
+
private closePromise: Promise<void> | undefined;
|
|
79
|
+
private readonly limit: number;
|
|
80
|
+
private readonly allowLoopback: boolean;
|
|
81
|
+
|
|
82
|
+
constructor(options: ContentManagerOptions = {}) {
|
|
83
|
+
this.limit = options.maxSnapshotBytes ?? 64 * 1024 * 1024;
|
|
84
|
+
if (!Number.isSafeInteger(this.limit) || this.limit < 0)
|
|
85
|
+
throw new Error("Invalid snapshot byte limit");
|
|
86
|
+
this.allowLoopback = options.allowLoopback ?? false;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Take cleanup ownership without selecting or reading any body. Call before
|
|
90
|
+
* routing/projection so unmatched and unauthorized sources are also closed.
|
|
91
|
+
* Close the manager in the operation's finally block, including on failure.
|
|
92
|
+
*/
|
|
93
|
+
own(event: unknown): void {
|
|
94
|
+
this.lifetime.signal.throwIfAborted();
|
|
95
|
+
const visited = new WeakSet<object>();
|
|
96
|
+
const visit = (value: unknown): void => {
|
|
97
|
+
if (value === null || typeof value !== "object" || visited.has(value))
|
|
98
|
+
return;
|
|
99
|
+
visited.add(value);
|
|
100
|
+
const stream = sourceStream(value);
|
|
101
|
+
if (stream) {
|
|
102
|
+
this.seenStreams.add(stream);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
for (const child of Object.values(value)) visit(child);
|
|
106
|
+
};
|
|
107
|
+
visit(event);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Reads local producer bytes for composition, never remote references.
|
|
111
|
+
* Reuses the same bounded snapshot as prepare; returns an independent copy.
|
|
112
|
+
* Aborting the initial read cancels the stream and leaves that snapshot failed.
|
|
113
|
+
*/
|
|
114
|
+
async readBody(
|
|
115
|
+
body: ContentSource | ReadableStream<Uint8Array>,
|
|
116
|
+
signal?: AbortSignal,
|
|
117
|
+
): Promise<Uint8Array> {
|
|
118
|
+
this.lifetime.signal.throwIfAborted();
|
|
119
|
+
this.own(body);
|
|
120
|
+
signal?.throwIfAborted();
|
|
121
|
+
const stream = sourceStream(body);
|
|
122
|
+
if (!stream)
|
|
123
|
+
throw new Error(
|
|
124
|
+
"Content body must be a ContentSource or raw ReadableStream",
|
|
125
|
+
);
|
|
126
|
+
const controller = new AbortController();
|
|
127
|
+
const abort = () =>
|
|
128
|
+
controller.abort(signal?.reason ?? this.lifetime.signal.reason);
|
|
129
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
130
|
+
this.lifetime.signal.addEventListener("abort", abort, { once: true });
|
|
131
|
+
if (signal?.aborted || this.lifetime.signal.aborted) abort();
|
|
132
|
+
try {
|
|
133
|
+
const snapshot = await abortable(
|
|
134
|
+
this.snapshot(stream, controller.signal),
|
|
135
|
+
controller.signal,
|
|
136
|
+
);
|
|
137
|
+
controller.signal.throwIfAborted();
|
|
138
|
+
return snapshot.bytes.slice();
|
|
139
|
+
} finally {
|
|
140
|
+
signal?.removeEventListener("abort", abort);
|
|
141
|
+
this.lifetime.signal.removeEventListener("abort", abort);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Returns a fresh wire tree; never mutates the producer event or reads an
|
|
146
|
+
* omitted/metadata stream. All selected uploads finish before this resolves.
|
|
147
|
+
*/
|
|
148
|
+
async prepare(
|
|
149
|
+
event: any,
|
|
150
|
+
selection: ContentSelection,
|
|
151
|
+
upload: ContentUpload | undefined,
|
|
152
|
+
send: ContentUploadRequest,
|
|
153
|
+
signal?: AbortSignal,
|
|
154
|
+
): Promise<any> {
|
|
155
|
+
this.lifetime.signal.throwIfAborted();
|
|
156
|
+
this.own(event);
|
|
157
|
+
signal?.throwIfAborted();
|
|
158
|
+
const omitted = Symbol("omitted file content");
|
|
159
|
+
const visit = async (
|
|
160
|
+
value: any,
|
|
161
|
+
path: Array<string | number> = [],
|
|
162
|
+
): Promise<any> => {
|
|
163
|
+
if (event?.type === "file.changed" && isFileReferencePath(path)) {
|
|
164
|
+
// Reuse normalized preparation internally; only the confirmed body is
|
|
165
|
+
// emitted in this bare-reference slot. Private identity never goes out.
|
|
166
|
+
const prepared = await visit(
|
|
167
|
+
{
|
|
168
|
+
id: "local-file-content",
|
|
169
|
+
kind: "file",
|
|
170
|
+
category: "files",
|
|
171
|
+
mediaType: "application/octet-stream",
|
|
172
|
+
body: value,
|
|
173
|
+
},
|
|
174
|
+
["instructions"],
|
|
175
|
+
);
|
|
176
|
+
return prepared.body ?? omitted;
|
|
177
|
+
}
|
|
178
|
+
if (value === null || typeof value !== "object") return value;
|
|
179
|
+
if (Array.isArray(value))
|
|
180
|
+
return Promise.all(
|
|
181
|
+
value.map((child, index) => visit(child, [...path, index])),
|
|
182
|
+
);
|
|
183
|
+
if (sourceStream(value)) return value;
|
|
184
|
+
if (
|
|
185
|
+
isContentPath(path) &&
|
|
186
|
+
typeof value.id === "string" &&
|
|
187
|
+
typeof value.kind === "string" &&
|
|
188
|
+
typeof value.mediaType === "string"
|
|
189
|
+
) {
|
|
190
|
+
const stream = sourceStream(value.body);
|
|
191
|
+
const category =
|
|
192
|
+
value.kind === "reasoning"
|
|
193
|
+
? "reasoning"
|
|
194
|
+
: (value.category ?? mediaCategory(value.mediaType));
|
|
195
|
+
const mode = Object.hasOwn(selection, category)
|
|
196
|
+
? selection[category]
|
|
197
|
+
: selection.default;
|
|
198
|
+
if (mode !== "body" && mode !== "metadata" && mode !== "omit")
|
|
199
|
+
throw new Error("Unsupported content selection");
|
|
200
|
+
const result: Record<string, unknown> = {};
|
|
201
|
+
for (const [key, child] of Object.entries(value)) {
|
|
202
|
+
if (key !== "body" && key !== "gap" && key !== "selection")
|
|
203
|
+
result[key] = await visit(child, [...path, key]);
|
|
204
|
+
}
|
|
205
|
+
result.selection = mode;
|
|
206
|
+
if (mode !== "body") return result;
|
|
207
|
+
if (value.gap !== undefined && value.body === undefined) {
|
|
208
|
+
result.gap = await visit(value.gap, [...path, "gap"]);
|
|
209
|
+
return result;
|
|
210
|
+
}
|
|
211
|
+
if (!stream)
|
|
212
|
+
throw new Error(
|
|
213
|
+
"Body selection requires a ContentSource or raw ReadableStream, not a receiver reference",
|
|
214
|
+
);
|
|
215
|
+
if (!upload)
|
|
216
|
+
throw new Error("Body selection requires upload configuration");
|
|
217
|
+
this.validateUpload(upload);
|
|
218
|
+
const controller = new AbortController();
|
|
219
|
+
const abort = () =>
|
|
220
|
+
controller.abort(signal?.reason ?? this.lifetime.signal.reason);
|
|
221
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
222
|
+
this.lifetime.signal.addEventListener("abort", abort, { once: true });
|
|
223
|
+
if (signal?.aborted || this.lifetime.signal.aborted) abort();
|
|
224
|
+
const timeout = setTimeout(
|
|
225
|
+
() =>
|
|
226
|
+
controller.abort(
|
|
227
|
+
new DOMException("Content upload timed out", "TimeoutError"),
|
|
228
|
+
),
|
|
229
|
+
upload.timeoutMs,
|
|
230
|
+
);
|
|
231
|
+
try {
|
|
232
|
+
const snapshot = await abortable(
|
|
233
|
+
this.snapshot(stream, controller.signal),
|
|
234
|
+
controller.signal,
|
|
235
|
+
);
|
|
236
|
+
if (value.size !== undefined && value.size !== snapshot.size)
|
|
237
|
+
throw new Error("Content size mismatch");
|
|
238
|
+
if (value.sha256 !== undefined && value.sha256 !== snapshot.sha256)
|
|
239
|
+
throw new Error("Content SHA-256 mismatch");
|
|
240
|
+
if (snapshot.size > upload.maxBytes)
|
|
241
|
+
throw new Error("Content exceeds upload maxBytes");
|
|
242
|
+
const response = await abortable(
|
|
243
|
+
send(
|
|
244
|
+
upload.endpoint,
|
|
245
|
+
{
|
|
246
|
+
method: "POST",
|
|
247
|
+
redirect: "error",
|
|
248
|
+
signal: controller.signal,
|
|
249
|
+
headers: {
|
|
250
|
+
"content-type": "application/octet-stream",
|
|
251
|
+
"content-length": String(snapshot.size),
|
|
252
|
+
"ahp-content-sha256": snapshot.sha256,
|
|
253
|
+
},
|
|
254
|
+
// Never expose the reusable private snapshot to an injected callback.
|
|
255
|
+
body: snapshot.bytes.slice(),
|
|
256
|
+
},
|
|
257
|
+
upload,
|
|
258
|
+
).then((response) => {
|
|
259
|
+
if (controller.signal.aborted) {
|
|
260
|
+
void response.body?.cancel().catch(() => undefined);
|
|
261
|
+
controller.signal.throwIfAborted();
|
|
262
|
+
}
|
|
263
|
+
return response;
|
|
264
|
+
}),
|
|
265
|
+
controller.signal,
|
|
266
|
+
);
|
|
267
|
+
const parsed = parseContentUploadReceipt(
|
|
268
|
+
await readConfirmation(response, controller.signal),
|
|
269
|
+
);
|
|
270
|
+
if (
|
|
271
|
+
!parsed.ok ||
|
|
272
|
+
parsed.value.size !== snapshot.size ||
|
|
273
|
+
parsed.value.sha256 !== snapshot.sha256
|
|
274
|
+
) {
|
|
275
|
+
throw new Error("Invalid or mismatched upload reference");
|
|
276
|
+
}
|
|
277
|
+
delete result.size;
|
|
278
|
+
delete result.sha256;
|
|
279
|
+
result.body = { ref: parsed.value.ref };
|
|
280
|
+
return result;
|
|
281
|
+
} finally {
|
|
282
|
+
clearTimeout(timeout);
|
|
283
|
+
signal?.removeEventListener("abort", abort);
|
|
284
|
+
this.lifetime.signal.removeEventListener("abort", abort);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
const result: Record<string, unknown> = {};
|
|
288
|
+
for (const [key, child] of Object.entries(value)) {
|
|
289
|
+
const prepared = await visit(child, [...path, key]);
|
|
290
|
+
if (prepared !== omitted) result[key] = prepared;
|
|
291
|
+
}
|
|
292
|
+
return result;
|
|
293
|
+
};
|
|
294
|
+
return visit(event);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Copy an already selected snapshot without reading unselected sources. */
|
|
298
|
+
async copySnapshot(
|
|
299
|
+
body: ReadableStream<Uint8Array>,
|
|
300
|
+
): Promise<Uint8Array | undefined> {
|
|
301
|
+
const snapshot = this.snapshots.get(body);
|
|
302
|
+
if (!snapshot) return undefined;
|
|
303
|
+
try {
|
|
304
|
+
return (await snapshot).bytes.slice();
|
|
305
|
+
} catch {
|
|
306
|
+
// Failed reads have no reusable result payload; delivery reports the error.
|
|
307
|
+
return undefined;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Initiates cancellation and releases snapshots; repeated calls return the
|
|
312
|
+
* same promise. Never waits for producer-controlled cancellation promises.
|
|
313
|
+
*/
|
|
314
|
+
close(): Promise<void> {
|
|
315
|
+
if (this.closePromise) return this.closePromise;
|
|
316
|
+
this.closePromise = Promise.resolve();
|
|
317
|
+
this.lifetime.abort(new Error("Content manager closed"));
|
|
318
|
+
const readers = [...this.readers];
|
|
319
|
+
this.snapshots = new WeakMap();
|
|
320
|
+
const unread = [...this.seenStreams].filter((stream) => !stream.locked);
|
|
321
|
+
this.seenStreams.clear();
|
|
322
|
+
this.readers.clear();
|
|
323
|
+
for (const reader of readers) void reader.cancel().catch(() => undefined);
|
|
324
|
+
for (const stream of unread) void stream.cancel().catch(() => undefined);
|
|
325
|
+
this.retainedBytes = 0;
|
|
326
|
+
return this.closePromise;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
private validateUpload(upload: ContentUpload): void {
|
|
330
|
+
const url = new URL(upload.endpoint);
|
|
331
|
+
const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
332
|
+
if (
|
|
333
|
+
/[\r\n]/.test(upload.endpoint) ||
|
|
334
|
+
url.username ||
|
|
335
|
+
url.password ||
|
|
336
|
+
url.hash ||
|
|
337
|
+
(url.protocol !== "https:" &&
|
|
338
|
+
!(this.allowLoopback && loopback && url.protocol === "http:"))
|
|
339
|
+
)
|
|
340
|
+
throw new Error("Unsafe upload endpoint");
|
|
341
|
+
if (
|
|
342
|
+
!Number.isSafeInteger(upload.maxBytes) ||
|
|
343
|
+
upload.maxBytes < 0 ||
|
|
344
|
+
!Number.isSafeInteger(upload.timeoutMs) ||
|
|
345
|
+
upload.timeoutMs < 1
|
|
346
|
+
)
|
|
347
|
+
throw new Error("Invalid upload budget");
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
private snapshot(
|
|
351
|
+
stream: ReadableStream<Uint8Array>,
|
|
352
|
+
signal: AbortSignal,
|
|
353
|
+
): Promise<Snapshot> {
|
|
354
|
+
const existing = this.snapshots.get(stream);
|
|
355
|
+
if (existing) return existing;
|
|
356
|
+
const pending = this.readSnapshot(stream, signal);
|
|
357
|
+
this.snapshots.set(stream, pending);
|
|
358
|
+
return pending;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
private async readSnapshot(
|
|
362
|
+
stream: ReadableStream<Uint8Array>,
|
|
363
|
+
signal: AbortSignal,
|
|
364
|
+
): Promise<Snapshot> {
|
|
365
|
+
signal.throwIfAborted();
|
|
366
|
+
const reader = stream.getReader();
|
|
367
|
+
this.readers.add(reader);
|
|
368
|
+
const chunks: Uint8Array[] = [];
|
|
369
|
+
let size = 0;
|
|
370
|
+
const cancel = () => {
|
|
371
|
+
void reader.cancel(signal.reason).catch(() => undefined);
|
|
372
|
+
};
|
|
373
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
374
|
+
try {
|
|
375
|
+
for (;;) {
|
|
376
|
+
const next = await abortable(reader.read(), signal);
|
|
377
|
+
signal.throwIfAborted();
|
|
378
|
+
if (next.done) break;
|
|
379
|
+
if (!(next.value instanceof Uint8Array))
|
|
380
|
+
throw new Error("Content stream must yield Uint8Array chunks");
|
|
381
|
+
if (this.retainedBytes + next.value.byteLength > this.limit)
|
|
382
|
+
throw new Error("Content snapshot memory limit exceeded");
|
|
383
|
+
if (next.value.byteLength === 0) continue;
|
|
384
|
+
chunks.push(next.value.slice());
|
|
385
|
+
size += next.value.byteLength;
|
|
386
|
+
this.retainedBytes += next.value.byteLength;
|
|
387
|
+
}
|
|
388
|
+
const bytes = new Uint8Array(size);
|
|
389
|
+
let offset = 0;
|
|
390
|
+
for (const chunk of chunks) {
|
|
391
|
+
bytes.set(chunk, offset);
|
|
392
|
+
offset += chunk.byteLength;
|
|
393
|
+
}
|
|
394
|
+
chunks.length = 0;
|
|
395
|
+
const digest = new Uint8Array(
|
|
396
|
+
await crypto.subtle.digest("SHA-256", bytes),
|
|
397
|
+
);
|
|
398
|
+
signal.throwIfAborted();
|
|
399
|
+
return {
|
|
400
|
+
bytes,
|
|
401
|
+
size,
|
|
402
|
+
sha256: Array.from(digest, (byte) =>
|
|
403
|
+
byte.toString(16).padStart(2, "0"),
|
|
404
|
+
).join(""),
|
|
405
|
+
};
|
|
406
|
+
} catch (error) {
|
|
407
|
+
if (!this.lifetime.signal.aborted) this.retainedBytes -= size;
|
|
408
|
+
void reader.cancel(error).catch(() => undefined);
|
|
409
|
+
throw error;
|
|
410
|
+
} finally {
|
|
411
|
+
signal.removeEventListener("abort", cancel);
|
|
412
|
+
this.readers.delete(reader);
|
|
413
|
+
reader.releaseLock();
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function isFileReferencePath(path: Array<string | number>): boolean {
|
|
419
|
+
return (
|
|
420
|
+
path.length === 3 &&
|
|
421
|
+
path[0] === "changes" &&
|
|
422
|
+
typeof path[1] === "number" &&
|
|
423
|
+
(path[2] === "before" || path[2] === "after")
|
|
424
|
+
);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// Match positions, not descriptor-looking objects in opaque operation data.
|
|
428
|
+
function isContentPath(path: Array<string | number>): boolean {
|
|
429
|
+
if (path.length === 1)
|
|
430
|
+
return ["instructions", "summary", "partialOutput", "delta"].includes(
|
|
431
|
+
String(path[0]),
|
|
432
|
+
);
|
|
433
|
+
if (path.length === 2) {
|
|
434
|
+
return (
|
|
435
|
+
(path[0] === "items" && typeof path[1] === "number") ||
|
|
436
|
+
(path[0] === "elicitation" &&
|
|
437
|
+
["request", "result"].includes(String(path[1])))
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
if (path.length !== 3) return false;
|
|
441
|
+
return (
|
|
442
|
+
(path[0] === "attention" &&
|
|
443
|
+
["title", "message"].includes(String(path[1])) &&
|
|
444
|
+
typeof path[2] === "number") ||
|
|
445
|
+
(path[0] === "message" &&
|
|
446
|
+
["text", "payload"].includes(String(path[1])) &&
|
|
447
|
+
typeof path[2] === "number") ||
|
|
448
|
+
(path[0] === "fileChanges" &&
|
|
449
|
+
typeof path[1] === "number" &&
|
|
450
|
+
["before", "after"].includes(String(path[2])))
|
|
451
|
+
);
|
|
452
|
+
// Bare file.changed references are projected separately above.
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
async function readConfirmation(
|
|
456
|
+
response: Response,
|
|
457
|
+
signal: AbortSignal,
|
|
458
|
+
): Promise<unknown> {
|
|
459
|
+
const reader = response.body?.getReader();
|
|
460
|
+
try {
|
|
461
|
+
signal.throwIfAborted();
|
|
462
|
+
if (
|
|
463
|
+
response.status !== 201 ||
|
|
464
|
+
response.headers
|
|
465
|
+
.get("content-type")
|
|
466
|
+
?.split(";")[0]
|
|
467
|
+
?.trim()
|
|
468
|
+
.toLowerCase() !== "application/json"
|
|
469
|
+
) {
|
|
470
|
+
throw new Error("Upload requires HTTP 201 application/json confirmation");
|
|
471
|
+
}
|
|
472
|
+
if (!reader) throw new Error("Missing upload confirmation body");
|
|
473
|
+
const chunks: Uint8Array[] = [];
|
|
474
|
+
let size = 0;
|
|
475
|
+
for (;;) {
|
|
476
|
+
const next = await abortable(reader.read(), signal);
|
|
477
|
+
signal.throwIfAborted();
|
|
478
|
+
if (next.done) break;
|
|
479
|
+
size += next.value.byteLength;
|
|
480
|
+
if (size > 1024 * 1024)
|
|
481
|
+
throw new Error("Upload confirmation exceeds 1 MiB limit");
|
|
482
|
+
if (next.value.byteLength !== 0) chunks.push(next.value.slice());
|
|
483
|
+
}
|
|
484
|
+
const bytes = new Uint8Array(size);
|
|
485
|
+
let offset = 0;
|
|
486
|
+
for (const chunk of chunks) {
|
|
487
|
+
bytes.set(chunk, offset);
|
|
488
|
+
offset += chunk.byteLength;
|
|
489
|
+
}
|
|
490
|
+
return JSON.parse(
|
|
491
|
+
new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes),
|
|
492
|
+
);
|
|
493
|
+
} finally {
|
|
494
|
+
if (reader) {
|
|
495
|
+
// Cancellation settles outstanding reads without waiting for the source's
|
|
496
|
+
// cancellation promise. Release the lock on every status/parse/abort path.
|
|
497
|
+
void reader.cancel().catch(() => undefined);
|
|
498
|
+
reader.releaseLock();
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function mediaCategory(mediaType: string): string {
|
|
504
|
+
const type = mediaType.toLowerCase().split(";")[0]!.trim();
|
|
505
|
+
if (type.startsWith("text/") || type === "application/json") return "text";
|
|
506
|
+
if (type.startsWith("image/")) return "images";
|
|
507
|
+
if (type.startsWith("audio/")) return "audio";
|
|
508
|
+
if (type.startsWith("video/")) return "video";
|
|
509
|
+
return "files";
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function abortable<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
513
|
+
return new Promise<T>((resolve, reject) => {
|
|
514
|
+
const abort = () =>
|
|
515
|
+
reject(signal.reason ?? new Error("Content operation aborted"));
|
|
516
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
517
|
+
pending
|
|
518
|
+
.then(resolve, reject)
|
|
519
|
+
.finally(() => signal.removeEventListener("abort", abort));
|
|
520
|
+
if (signal.aborted) abort();
|
|
521
|
+
});
|
|
522
|
+
}
|