@tansr/protocol 0.2.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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +74 -0
  3. package/dist/canonical/common.d.ts +37 -0
  4. package/dist/canonical/common.js +149 -0
  5. package/dist/canonical/digest.d.ts +12 -0
  6. package/dist/canonical/digest.js +58 -0
  7. package/dist/canonical/encode.d.ts +15 -0
  8. package/dist/canonical/encode.js +157 -0
  9. package/dist/canonical/errors.d.ts +81 -0
  10. package/dist/canonical/errors.js +89 -0
  11. package/dist/canonical/index.d.ts +21 -0
  12. package/dist/canonical/index.js +21 -0
  13. package/dist/canonical/parse.d.ts +21 -0
  14. package/dist/canonical/parse.js +295 -0
  15. package/dist/client.d.ts +42 -0
  16. package/dist/client.js +1 -0
  17. package/dist/config.d.ts +4990 -0
  18. package/dist/config.js +657 -0
  19. package/dist/daemon.d.ts +70 -0
  20. package/dist/daemon.js +48 -0
  21. package/dist/events.d.ts +2152 -0
  22. package/dist/events.js +625 -0
  23. package/dist/governance.d.ts +445 -0
  24. package/dist/governance.js +183 -0
  25. package/dist/headless.d.ts +97 -0
  26. package/dist/headless.js +39 -0
  27. package/dist/identity.d.ts +96 -0
  28. package/dist/identity.js +45 -0
  29. package/dist/index.d.ts +525 -0
  30. package/dist/index.js +529 -0
  31. package/dist/ir.d.ts +1418 -0
  32. package/dist/ir.js +283 -0
  33. package/dist/journal.d.ts +297 -0
  34. package/dist/journal.js +150 -0
  35. package/dist/media.d.ts +563 -0
  36. package/dist/media.js +190 -0
  37. package/dist/metering.d.ts +225 -0
  38. package/dist/metering.js +90 -0
  39. package/dist/orchestration.d.ts +1551 -0
  40. package/dist/orchestration.js +333 -0
  41. package/dist/redact-patterns.d.ts +49 -0
  42. package/dist/redact-patterns.js +141 -0
  43. package/dist/storage.d.ts +507 -0
  44. package/dist/storage.js +110 -0
  45. package/dist/tool-result-artifact.d.ts +257 -0
  46. package/dist/tool-result-artifact.js +263 -0
  47. package/package.json +30 -0
@@ -0,0 +1,257 @@
1
+ /** MEDIA-03:仅供呈现的工具产物。写侧摘取受限字段,读侧分类,不把坏产物升级为坏消息。 */
2
+ import { z } from 'zod';
3
+ import type { IRBlock, IRMessage } from './ir.js';
4
+ export declare const TOOL_ARTIFACT_MAX_BYTES: number;
5
+ export declare const HISTORY_ARTIFACT_MAX_BYTES: number;
6
+ export declare const TOOL_ARTIFACT_MAX_ITEMS = 16;
7
+ export declare const ToolResultArtifactV1Schema: z.ZodUnion<[z.ZodObject<{
8
+ v: z.ZodLiteral<1>;
9
+ state: z.ZodLiteral<"available">;
10
+ kind: z.ZodLiteral<"image">;
11
+ data: z.ZodObject<{
12
+ images: z.ZodArray<z.ZodObject<{
13
+ url: z.ZodString;
14
+ }, "strip", z.ZodTypeAny, {
15
+ url: string;
16
+ }, {
17
+ url: string;
18
+ }>, "many">;
19
+ imageCount: z.ZodNumber;
20
+ model: z.ZodString;
21
+ taskId: z.ZodOptional<z.ZodString>;
22
+ }, "strip", z.ZodTypeAny, {
23
+ model: string;
24
+ images: {
25
+ url: string;
26
+ }[];
27
+ imageCount: number;
28
+ taskId?: string | undefined;
29
+ }, {
30
+ model: string;
31
+ images: {
32
+ url: string;
33
+ }[];
34
+ imageCount: number;
35
+ taskId?: string | undefined;
36
+ }>;
37
+ }, "strip", z.ZodTypeAny, {
38
+ data: {
39
+ model: string;
40
+ images: {
41
+ url: string;
42
+ }[];
43
+ imageCount: number;
44
+ taskId?: string | undefined;
45
+ };
46
+ kind: "image";
47
+ v: 1;
48
+ state: "available";
49
+ }, {
50
+ data: {
51
+ model: string;
52
+ images: {
53
+ url: string;
54
+ }[];
55
+ imageCount: number;
56
+ taskId?: string | undefined;
57
+ };
58
+ kind: "image";
59
+ v: 1;
60
+ state: "available";
61
+ }>, z.ZodObject<{
62
+ v: z.ZodLiteral<1>;
63
+ state: z.ZodLiteral<"available">;
64
+ kind: z.ZodLiteral<"video">;
65
+ data: z.ZodObject<{
66
+ videos: z.ZodArray<z.ZodObject<{
67
+ url: z.ZodString;
68
+ }, "strip", z.ZodTypeAny, {
69
+ url: string;
70
+ }, {
71
+ url: string;
72
+ }>, "many">;
73
+ videoCount: z.ZodNumber;
74
+ billedSeconds: z.ZodNumber;
75
+ model: z.ZodString;
76
+ taskId: z.ZodOptional<z.ZodString>;
77
+ }, "strip", z.ZodTypeAny, {
78
+ model: string;
79
+ videos: {
80
+ url: string;
81
+ }[];
82
+ videoCount: number;
83
+ billedSeconds: number;
84
+ taskId?: string | undefined;
85
+ }, {
86
+ model: string;
87
+ videos: {
88
+ url: string;
89
+ }[];
90
+ videoCount: number;
91
+ billedSeconds: number;
92
+ taskId?: string | undefined;
93
+ }>;
94
+ }, "strip", z.ZodTypeAny, {
95
+ data: {
96
+ model: string;
97
+ videos: {
98
+ url: string;
99
+ }[];
100
+ videoCount: number;
101
+ billedSeconds: number;
102
+ taskId?: string | undefined;
103
+ };
104
+ kind: "video";
105
+ v: 1;
106
+ state: "available";
107
+ }, {
108
+ data: {
109
+ model: string;
110
+ videos: {
111
+ url: string;
112
+ }[];
113
+ videoCount: number;
114
+ billedSeconds: number;
115
+ taskId?: string | undefined;
116
+ };
117
+ kind: "video";
118
+ v: 1;
119
+ state: "available";
120
+ }>, z.ZodObject<{
121
+ v: z.ZodLiteral<1>;
122
+ state: z.ZodLiteral<"available">;
123
+ kind: z.ZodLiteral<"speech">;
124
+ data: z.ZodObject<{
125
+ billedChars: z.ZodNumber;
126
+ audio: z.ZodObject<{
127
+ url: z.ZodOptional<z.ZodString>;
128
+ b64: z.ZodOptional<z.ZodString>;
129
+ mime: z.ZodString;
130
+ format: z.ZodString;
131
+ durationMs: z.ZodOptional<z.ZodNumber>;
132
+ sampleRate: z.ZodOptional<z.ZodNumber>;
133
+ }, "strip", z.ZodTypeAny, {
134
+ mime: string;
135
+ format: string;
136
+ url?: string | undefined;
137
+ durationMs?: number | undefined;
138
+ b64?: string | undefined;
139
+ sampleRate?: number | undefined;
140
+ }, {
141
+ mime: string;
142
+ format: string;
143
+ url?: string | undefined;
144
+ durationMs?: number | undefined;
145
+ b64?: string | undefined;
146
+ sampleRate?: number | undefined;
147
+ }>;
148
+ model: z.ZodString;
149
+ taskId: z.ZodOptional<z.ZodString>;
150
+ }, "strip", z.ZodTypeAny, {
151
+ model: string;
152
+ audio: {
153
+ mime: string;
154
+ format: string;
155
+ url?: string | undefined;
156
+ durationMs?: number | undefined;
157
+ b64?: string | undefined;
158
+ sampleRate?: number | undefined;
159
+ };
160
+ billedChars: number;
161
+ taskId?: string | undefined;
162
+ }, {
163
+ model: string;
164
+ audio: {
165
+ mime: string;
166
+ format: string;
167
+ url?: string | undefined;
168
+ durationMs?: number | undefined;
169
+ b64?: string | undefined;
170
+ sampleRate?: number | undefined;
171
+ };
172
+ billedChars: number;
173
+ taskId?: string | undefined;
174
+ }>;
175
+ }, "strip", z.ZodTypeAny, {
176
+ data: {
177
+ model: string;
178
+ audio: {
179
+ mime: string;
180
+ format: string;
181
+ url?: string | undefined;
182
+ durationMs?: number | undefined;
183
+ b64?: string | undefined;
184
+ sampleRate?: number | undefined;
185
+ };
186
+ billedChars: number;
187
+ taskId?: string | undefined;
188
+ };
189
+ kind: "speech";
190
+ v: 1;
191
+ state: "available";
192
+ }, {
193
+ data: {
194
+ model: string;
195
+ audio: {
196
+ mime: string;
197
+ format: string;
198
+ url?: string | undefined;
199
+ durationMs?: number | undefined;
200
+ b64?: string | undefined;
201
+ sampleRate?: number | undefined;
202
+ };
203
+ billedChars: number;
204
+ taskId?: string | undefined;
205
+ };
206
+ kind: "speech";
207
+ v: 1;
208
+ state: "available";
209
+ }>, z.ZodObject<{
210
+ v: z.ZodLiteral<1>;
211
+ state: z.ZodLiteral<"unavailable">;
212
+ kind: z.ZodEnum<["image", "video", "speech"]>;
213
+ reason: z.ZodEnum<["invalid_result", "over_limit", "history_limit"]>;
214
+ }, "strip", z.ZodTypeAny, {
215
+ kind: "image" | "video" | "speech";
216
+ v: 1;
217
+ reason: "invalid_result" | "over_limit" | "history_limit";
218
+ state: "unavailable";
219
+ }, {
220
+ kind: "image" | "video" | "speech";
221
+ v: 1;
222
+ reason: "invalid_result" | "over_limit" | "history_limit";
223
+ state: "unavailable";
224
+ }>]>;
225
+ export type ToolResultArtifactV1 = z.infer<typeof ToolResultArtifactV1Schema>;
226
+ export type ToolArtifactClassification = {
227
+ state: 'available';
228
+ artifact: Extract<ToolResultArtifactV1, {
229
+ state: 'available';
230
+ }>;
231
+ } | {
232
+ state: 'unavailable';
233
+ reason: string;
234
+ } | {
235
+ state: 'unsupported' | 'invalid' | 'absent';
236
+ };
237
+ /** 有界遍历,先拒绝超大字符串/深树/环,再序列化;不调用 toJSON,不复制未声明业务字段。 */
238
+ export declare function artifactJsonBytes(value: unknown, limit?: number): number | undefined;
239
+ /** 原值留在 IR 中;只有当前版本且验证成功的受限投影可以交给 UI。 */
240
+ export declare function classifyToolResultArtifact(value: unknown): ToolArtifactClassification;
241
+ /** 只从真实结构化工具结果生成;不按工具名称、content 或用户文本猜测产物。 */
242
+ export declare function createToolResultArtifact(data: unknown, isError?: boolean): ToolResultArtifactV1 | undefined;
243
+ /** 仅移除呈现扩展,其他 IR 字段保持;无扩展时零复制。模型/指纹/观测缝共用。 */
244
+ export declare function modelViewMessage(message: IRMessage): IRMessage;
245
+ export declare function modelViewMessages(messages: IRMessage[]): IRMessage[];
246
+ /** 持久化版本判定只检查字段在场性;未知/无效原值也必须受旧 writer 保护。 */
247
+ export declare function hasToolResultArtifact(message: unknown): boolean;
248
+ /** 按输入序准入新结果;已存在的产物不逐出,取消收尾同用此入口。 */
249
+ export declare function admitToolResultArtifacts(results: Extract<IRBlock, {
250
+ t: 'tool_result';
251
+ }>[], history: readonly IRMessage[]): Extract<IRBlock, {
252
+ t: 'tool_result';
253
+ }>[];
254
+ /** 历史按出现次序配对;串行复用 id 可区分,并行重号/孤儿回执不猜测归属。 */
255
+ export declare function pairHistoryToolResults(messages: readonly IRMessage[]): ReadonlyMap<IRBlock, Extract<IRBlock, {
256
+ t: 'tool_result';
257
+ }>>;
@@ -0,0 +1,263 @@
1
+ /** MEDIA-03:仅供呈现的工具产物。写侧摘取受限字段,读侧分类,不把坏产物升级为坏消息。 */
2
+ import { z } from 'zod';
3
+ import { isRenderableArtifact } from './media.js';
4
+ export const TOOL_ARTIFACT_MAX_BYTES = 8 * 1024 * 1024;
5
+ export const HISTORY_ARTIFACT_MAX_BYTES = 16 * 1024 * 1024;
6
+ export const TOOL_ARTIFACT_MAX_ITEMS = 16;
7
+ const finite = z.number().finite().nonnegative();
8
+ const common = { model: z.string().max(1024), taskId: z.string().max(4096).optional() };
9
+ const urlItem = z.object({ url: z.string().min(1) });
10
+ const imageData = z.object({ ...common, images: z.array(urlItem).min(1).max(TOOL_ARTIFACT_MAX_ITEMS), imageCount: finite });
11
+ const videoData = z.object({ ...common, videos: z.array(urlItem).min(1).max(TOOL_ARTIFACT_MAX_ITEMS), videoCount: finite, billedSeconds: finite });
12
+ const speechData = z.object({ ...common, billedChars: finite, audio: z.object({
13
+ url: z.string().min(1).optional(), b64: z.string().min(1).optional(),
14
+ mime: z.string().max(128), format: z.string().max(64), durationMs: finite.optional(), sampleRate: finite.optional(),
15
+ }) });
16
+ const unavailable = z.object({ v: z.literal(1), state: z.literal('unavailable'),
17
+ kind: z.enum(['image', 'video', 'speech']),
18
+ reason: z.enum(['invalid_result', 'over_limit', 'history_limit']),
19
+ });
20
+ export const ToolResultArtifactV1Schema = z.union([
21
+ z.object({ v: z.literal(1), state: z.literal('available'), kind: z.literal('image'), data: imageData }),
22
+ z.object({ v: z.literal(1), state: z.literal('available'), kind: z.literal('video'), data: videoData }),
23
+ z.object({ v: z.literal(1), state: z.literal('available'), kind: z.literal('speech'), data: speechData }),
24
+ unavailable,
25
+ ]);
26
+ function object(value) {
27
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
28
+ }
29
+ /** 有界遍历,先拒绝超大字符串/深树/环,再序列化;不调用 toJSON,不复制未声明业务字段。 */
30
+ export function artifactJsonBytes(value, limit = TOOL_ARTIFACT_MAX_BYTES) {
31
+ const seen = new Set();
32
+ let lower = 0;
33
+ let nodes = 0;
34
+ function visit(item, depth) {
35
+ if (++nodes > 4096 || depth > 12)
36
+ return false;
37
+ if (typeof item === 'string') {
38
+ lower += item.length;
39
+ return lower <= limit;
40
+ }
41
+ if (item === null || typeof item === 'boolean')
42
+ return true;
43
+ if (typeof item === 'number')
44
+ return Number.isFinite(item);
45
+ if (typeof item !== 'object' || seen.has(item))
46
+ return false;
47
+ if (!Array.isArray(item) && Object.getPrototypeOf(item) !== Object.prototype && Object.getPrototypeOf(item) !== null)
48
+ return false;
49
+ seen.add(item);
50
+ for (const [key, child] of Object.entries(item)) {
51
+ lower += key.length;
52
+ if (lower > limit || !visit(child, depth + 1))
53
+ return false;
54
+ }
55
+ seen.delete(item);
56
+ return true;
57
+ }
58
+ try {
59
+ if (!visit(value, 0))
60
+ return undefined;
61
+ const encoded = JSON.stringify(value);
62
+ if (encoded === undefined)
63
+ return undefined;
64
+ const bytes = new TextEncoder().encode(encoded).byteLength;
65
+ return bytes <= limit ? bytes : undefined;
66
+ }
67
+ catch {
68
+ return undefined;
69
+ }
70
+ }
71
+ function base64(value) {
72
+ if (value.length === 0 || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value))
73
+ return undefined;
74
+ try {
75
+ const bytes = atob(value);
76
+ return btoa(bytes) === value ? bytes : undefined;
77
+ }
78
+ catch {
79
+ return undefined;
80
+ }
81
+ }
82
+ function portableUrl(value, image) {
83
+ if (value.startsWith('data:')) {
84
+ if (!image)
85
+ return false;
86
+ const match = /^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(value);
87
+ if (!match)
88
+ return false;
89
+ const bytes = base64(match[2]);
90
+ if (bytes === undefined)
91
+ return false;
92
+ const mime = bytes.startsWith('\x89PNG\r\n\x1a\n') ? 'image/png'
93
+ : bytes.startsWith('\xff\xd8\xff') ? 'image/jpeg'
94
+ : /^(GIF87a|GIF89a)/.test(bytes) ? 'image/gif'
95
+ : bytes.startsWith('RIFF') && bytes.slice(8, 12) === 'WEBP' ? 'image/webp' : undefined;
96
+ return mime === match[1];
97
+ }
98
+ if (value.length > 16384)
99
+ return false;
100
+ try {
101
+ const url = new URL(value);
102
+ return (url.protocol === 'https:' || url.protocol === 'http:') && !url.username && !url.password;
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ }
108
+ function validMaterial(artifact) {
109
+ if (artifact.kind === 'image')
110
+ return artifact.data.images.every(i => portableUrl(i.url, true));
111
+ if (artifact.kind === 'video')
112
+ return artifact.data.videos.every(i => portableUrl(i.url, false));
113
+ const audio = artifact.data.audio;
114
+ if (audio.url === undefined && audio.b64 === undefined)
115
+ return false;
116
+ if (audio.url !== undefined && !portableUrl(audio.url, false))
117
+ return false;
118
+ return audio.b64 === undefined || (/^audio\/[a-z0-9.+-]+$/i.test(audio.mime) && base64(audio.b64) !== undefined);
119
+ }
120
+ /** 原值留在 IR 中;只有当前版本且验证成功的受限投影可以交给 UI。 */
121
+ export function classifyToolResultArtifact(value) {
122
+ if (value === undefined)
123
+ return { state: 'absent' };
124
+ if (!object(value))
125
+ return { state: 'invalid' };
126
+ if (value.v !== 1 || !['image', 'video', 'speech'].includes(String(value.kind)))
127
+ return { state: 'unsupported' };
128
+ if (artifactJsonBytes(value) === undefined)
129
+ return { state: 'invalid' };
130
+ if (value.state === 'available' && object(value.data) && !isRenderableArtifact(value.data))
131
+ return { state: 'invalid' };
132
+ const parsed = ToolResultArtifactV1Schema.safeParse(value);
133
+ if (!parsed.success)
134
+ return { state: 'invalid' };
135
+ if (parsed.data.state === 'unavailable')
136
+ return { state: 'unavailable', reason: parsed.data.reason };
137
+ return validMaterial(parsed.data) ? { state: 'available', artifact: parsed.data } : { state: 'invalid' };
138
+ }
139
+ /** 只从真实结构化工具结果生成;不按工具名称、content 或用户文本猜测产物。 */
140
+ export function createToolResultArtifact(data, isError = false) {
141
+ if (isError || !object(data) || !isRenderableArtifact({ errorCode: data.errorCode }))
142
+ return undefined;
143
+ const kind = 'images' in data ? 'image' : 'videos' in data ? 'video' : 'audio' in data ? 'speech' : undefined;
144
+ if (kind === undefined)
145
+ return undefined;
146
+ const failure = (reason) => ({ v: 1, state: 'unavailable', kind, reason });
147
+ try {
148
+ // 先投影字段、限制条目,再由 schema 校验。未知字段及本地 path 不进入存储。
149
+ const selected = { model: data.model };
150
+ if (data.taskId !== undefined)
151
+ selected.taskId = data.taskId;
152
+ if (kind === 'speech') {
153
+ if (!object(data.audio))
154
+ return failure('invalid_result');
155
+ const audio = {};
156
+ for (const key of ['url', 'b64', 'mime', 'format', 'durationMs', 'sampleRate']) {
157
+ if (data.audio[key] !== undefined)
158
+ audio[key] = data.audio[key];
159
+ }
160
+ selected.audio = audio;
161
+ selected.billedChars = data.billedChars;
162
+ }
163
+ else {
164
+ const key = kind === 'image' ? 'images' : 'videos';
165
+ const items = data[key];
166
+ if (!Array.isArray(items))
167
+ return failure('invalid_result');
168
+ if (items.length > TOOL_ARTIFACT_MAX_ITEMS)
169
+ return failure('over_limit');
170
+ selected[key] = items.map(item => ({ url: object(item) ? item.url : undefined }));
171
+ selected[kind === 'image' ? 'imageCount' : 'videoCount'] = data[kind === 'image' ? 'imageCount' : 'videoCount'];
172
+ if (kind === 'video')
173
+ selected.billedSeconds = data.billedSeconds;
174
+ }
175
+ const candidate = { v: 1, state: 'available', kind, data: selected };
176
+ // 缺字段/错误类型属于 invalid_result,不能因 JSON 不可编码误报容量超限。
177
+ const parsed = ToolResultArtifactV1Schema.safeParse(candidate);
178
+ if (!parsed.success)
179
+ return failure('invalid_result');
180
+ if (artifactJsonBytes(parsed.data) === undefined)
181
+ return failure('over_limit');
182
+ const classified = classifyToolResultArtifact(parsed.data);
183
+ return classified.state === 'available' ? classified.artifact : failure('invalid_result');
184
+ }
185
+ catch {
186
+ return failure('invalid_result');
187
+ }
188
+ }
189
+ /** 仅移除呈现扩展,其他 IR 字段保持;无扩展时零复制。模型/指纹/观测缝共用。 */
190
+ export function modelViewMessage(message) {
191
+ if (!message.blocks.some(b => b.t === 'tool_result' && Object.hasOwn(b, 'artifact')))
192
+ return message;
193
+ return { ...message, blocks: message.blocks.map(block => {
194
+ if (block.t !== 'tool_result' || !Object.hasOwn(block, 'artifact'))
195
+ return block;
196
+ const { artifact: _artifact, ...modelBlock } = block;
197
+ return modelBlock;
198
+ }) };
199
+ }
200
+ export function modelViewMessages(messages) {
201
+ const projected = messages.map(modelViewMessage);
202
+ return projected.every((m, i) => m === messages[i]) ? messages : projected;
203
+ }
204
+ /** 持久化版本判定只检查字段在场性;未知/无效原值也必须受旧 writer 保护。 */
205
+ export function hasToolResultArtifact(message) {
206
+ return object(message) && Array.isArray(message.blocks) && message.blocks.some(b => object(b) && b.t === 'tool_result' && Object.hasOwn(b, 'artifact'));
207
+ }
208
+ /** 按输入序准入新结果;已存在的产物不逐出,取消收尾同用此入口。 */
209
+ export function admitToolResultArtifacts(results, history) {
210
+ let used = 0;
211
+ for (const message of history)
212
+ for (const block of message.blocks) {
213
+ if (block.t === 'tool_result' && block.artifact !== undefined) {
214
+ used += artifactJsonBytes(block.artifact, HISTORY_ARTIFACT_MAX_BYTES) ?? HISTORY_ARTIFACT_MAX_BYTES;
215
+ }
216
+ }
217
+ return results.map(block => {
218
+ const classified = classifyToolResultArtifact(block.artifact);
219
+ if (classified.state !== 'available')
220
+ return block;
221
+ const bytes = artifactJsonBytes(block.artifact);
222
+ if (used + bytes > HISTORY_ARTIFACT_MAX_BYTES)
223
+ return { ...block, artifact: {
224
+ v: 1, state: 'unavailable', kind: classified.artifact.kind, reason: 'history_limit',
225
+ } };
226
+ used += bytes;
227
+ return block;
228
+ });
229
+ }
230
+ /** 历史按出现次序配对;串行复用 id 可区分,并行重号/孤儿回执不猜测归属。 */
231
+ export function pairHistoryToolResults(messages) {
232
+ const pending = new Map();
233
+ const paired = new Map();
234
+ const allCalls = new Map();
235
+ const allResults = new Map();
236
+ for (const message of messages)
237
+ for (const block of message.blocks) {
238
+ if (block.t === 'tool_call') {
239
+ const occurrences = allCalls.get(block.id) ?? [];
240
+ occurrences.push(block);
241
+ allCalls.set(block.id, occurrences);
242
+ const calls = pending.get(block.id) ?? [];
243
+ calls.push(block);
244
+ pending.set(block.id, calls);
245
+ }
246
+ else if (block.t === 'tool_result') {
247
+ const occurrences = allResults.get(block.callId) ?? [];
248
+ occurrences.push(block);
249
+ allResults.set(block.callId, occurrences);
250
+ const calls = pending.get(block.callId);
251
+ if (calls?.length === 1)
252
+ paired.set(calls[0], block);
253
+ pending.delete(block.callId);
254
+ }
255
+ }
256
+ // 兼容已有“唯一回执先于调用”的历史投影;只有全卷一对一才允许倒序配对。
257
+ for (const [id, calls] of allCalls) {
258
+ const receipts = allResults.get(id);
259
+ if (calls.length === 1 && receipts?.length === 1 && !paired.has(calls[0]))
260
+ paired.set(calls[0], receipts[0]);
261
+ }
262
+ return paired;
263
+ }
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@tansr/protocol",
3
+ "version": "0.2.0",
4
+ "description": "Tansr L0 contract: IR message model, kernel event protocol, journal & config schemas (public, MIT).",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./canonical": {
15
+ "types": "./dist/canonical/index.d.ts",
16
+ "default": "./dist/canonical/index.js"
17
+ }
18
+ },
19
+ "dependencies": {
20
+ "zod": "^3.23.8"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "LICENSE",
25
+ "README.md"
26
+ ],
27
+ "publishConfig": {
28
+ "access": "public"
29
+ }
30
+ }