@llmguard/opencode 0.0.0-stage → 0.1.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/MANUAL-TEST-G.md +167 -0
- package/README.md +334 -2
- package/RELEASE.md +122 -0
- package/bin/darwin-amd64/helper +0 -0
- package/bin/darwin-arm64/helper +0 -0
- package/bin/linux-amd64/helper +0 -0
- package/bin/linux-arm64/helper +0 -0
- package/bin/manifest.json +51 -0
- package/bin/windows-amd64/helper.exe +0 -0
- package/bin/windows-arm64/helper.exe +0 -0
- package/bridge/client.d.ts +55 -0
- package/bridge/client.js +425 -0
- package/bridge/framing.d.ts +19 -0
- package/bridge/framing.js +110 -0
- package/bridge/process.d.ts +38 -0
- package/bridge/process.js +378 -0
- package/bridge/protocol.d.ts +184 -0
- package/bridge/protocol.js +683 -0
- package/connection-catalog.d.ts +69 -0
- package/connection-catalog.js +287 -0
- package/connections-tui.d.ts +11 -0
- package/connections-tui.js +394 -0
- package/demasking.d.ts +2 -0
- package/demasking.js +445 -0
- package/gui-experimental.cjs +33 -0
- package/hook-trace.d.ts +2 -0
- package/hook-trace.js +35 -0
- package/index.d.ts +1 -0
- package/index.js +1 -0
- package/licenses/Go-LICENSE +27 -0
- package/messages.d.ts +230 -0
- package/messages.js +231 -0
- package/native/index.d.ts +1 -0
- package/native/index.js +1 -0
- package/native/tui.d.ts +1 -0
- package/native/tui.js +1 -0
- package/package.json +49 -4
- package/plugin-runtime.d.ts +3 -0
- package/plugin-runtime.js +3 -0
- package/plugin-settings.d.ts +77 -0
- package/plugin-settings.js +487 -0
- package/plugin.d.ts +41 -0
- package/plugin.js +10 -0
- package/response-diagnostics.d.ts +13 -0
- package/response-diagnostics.js +142 -0
- package/runtime/attachments.d.ts +4 -0
- package/runtime/attachments.js +19 -0
- package/runtime/errors.d.ts +18 -0
- package/runtime/errors.js +26 -0
- package/runtime/json.d.ts +14 -0
- package/runtime/json.js +243 -0
- package/runtime/limits.d.ts +2 -0
- package/runtime/limits.js +3 -0
- package/runtime/native-edit.d.ts +14 -0
- package/runtime/native-edit.js +73 -0
- package/runtime/runtime.d.ts +43 -0
- package/runtime/runtime.js +345 -0
- package/runtime/session-state.d.ts +13 -0
- package/runtime/session-state.js +73 -0
- package/runtime/text-layout.d.ts +9 -0
- package/runtime/text-layout.js +47 -0
- package/server.d.ts +1 -0
- package/server.js +1 -0
- package/settings-rpc.d.ts +511 -0
- package/settings-rpc.js +197 -0
- package/tui-messages.d.ts +1 -0
- package/tui-messages.js +84 -0
- package/tui.d.ts +17 -0
- package/tui.js +427 -0
- package/v1/hooks.d.ts +81 -0
- package/v1/hooks.js +97 -0
- package/v1/projection.d.ts +32 -0
- package/v1/projection.js +217 -0
- package/v1.d.ts +2 -0
- package/v1.js +2 -0
- package/v2/projection.d.ts +36 -0
- package/v2/projection.js +374 -0
- package/v2/server.d.ts +6 -0
- package/v2/server.js +633 -0
package/v1/projection.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { blocked } from "../runtime/errors.js";
|
|
2
|
+
import { snapshotObject, applyNativeEdits, } from "../runtime/native-edit.js";
|
|
3
|
+
import { layoutField, messageModelName, modelField, } from "../runtime/text-layout.js";
|
|
4
|
+
import { maxProjection } from "../bridge/protocol.js";
|
|
5
|
+
// Roles come from untrusted message info; anything else keeps legacy semantics.
|
|
6
|
+
const messageRole = (message) => typeof message.info.role === "string" ? message.info.role : undefined;
|
|
7
|
+
const dataURL = /^data:([^;,]*)(?:;[^,]*)?;base64,([A-Za-z0-9+/]*={0,2})$/;
|
|
8
|
+
// A v1 file part names its content by URL. Only a data URL carries the bytes:
|
|
9
|
+
// its base64 payload is handed over as it is. A link or a local path is never
|
|
10
|
+
// opened here; it is reported as uninspectable, so the policy decides.
|
|
11
|
+
function filePart(part, layout) {
|
|
12
|
+
const url = typeof part.url === "string" ? part.url : "";
|
|
13
|
+
const match = dataURL.exec(url);
|
|
14
|
+
const mime = typeof part.mime === "string" && part.mime ? part.mime : (match?.[1] ?? "");
|
|
15
|
+
if (match && mime && match[2].length > 0 && match[2].length % 4 === 0) {
|
|
16
|
+
return {
|
|
17
|
+
param: { media_type: mime, data_b64: match[2], layout },
|
|
18
|
+
// The header of the data URL stays as it was; only the payload changes.
|
|
19
|
+
edit: (body) => ({
|
|
20
|
+
target: part,
|
|
21
|
+
key: "url",
|
|
22
|
+
value: url.slice(0, url.indexOf(",") + 1) + body.toString("base64"),
|
|
23
|
+
}),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
if (/^(?:https?|file):/i.test(url)) {
|
|
27
|
+
return { param: { uninspectable: "url", layout } };
|
|
28
|
+
}
|
|
29
|
+
return { param: { uninspectable: "unsupported_source", layout } };
|
|
30
|
+
}
|
|
31
|
+
export function messageProjection(output) {
|
|
32
|
+
const attachments = [];
|
|
33
|
+
const rewriters = [];
|
|
34
|
+
const texts = [];
|
|
35
|
+
const items = [];
|
|
36
|
+
let textBytes = 0;
|
|
37
|
+
const guards = [];
|
|
38
|
+
const slots = [];
|
|
39
|
+
const nativeMessages = output.messages;
|
|
40
|
+
const messageSnapshots = nativeMessages.map((message) => ({
|
|
41
|
+
message,
|
|
42
|
+
info: message.info,
|
|
43
|
+
session: message.info.sessionID,
|
|
44
|
+
role: message.info.role,
|
|
45
|
+
parts: message.parts,
|
|
46
|
+
members: [...message.parts],
|
|
47
|
+
types: message.parts.map((part) => part.type),
|
|
48
|
+
}));
|
|
49
|
+
const ids = new Set(output.messages.map((m) => m.info.sessionID));
|
|
50
|
+
const session = ids.size === 1 ? [...ids][0] : null;
|
|
51
|
+
const add = (node, key, item) => {
|
|
52
|
+
if (typeof node[key] !== "string") {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
textBytes += Buffer.byteLength(node[key]);
|
|
56
|
+
if (textBytes > maxProjection || texts.length >= 4096) {
|
|
57
|
+
blocked();
|
|
58
|
+
}
|
|
59
|
+
texts.push(node[key]);
|
|
60
|
+
items.push(item);
|
|
61
|
+
slots.push({ target: node, key, value: node[key] });
|
|
62
|
+
};
|
|
63
|
+
const strings = (value, depth = 0, item) => {
|
|
64
|
+
if (depth > 32) {
|
|
65
|
+
blocked();
|
|
66
|
+
}
|
|
67
|
+
if (!value || typeof value !== "object") {
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (depth === 0) {
|
|
71
|
+
guards.push(snapshotObject(value));
|
|
72
|
+
}
|
|
73
|
+
for (const [key, child] of Object.entries(value)) {
|
|
74
|
+
if (typeof child === "string") {
|
|
75
|
+
add(value, key, item);
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
strings(child, depth + 1, item);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
// Roles derive from message info, never from text matching. The latest
|
|
83
|
+
// user text keeps legacy semantics when a role is unknown.
|
|
84
|
+
let currentUser = -1;
|
|
85
|
+
for (let i = 0; i < output.messages.length; i++) {
|
|
86
|
+
const role = messageRole(output.messages[i]);
|
|
87
|
+
if (role === "user" &&
|
|
88
|
+
output.messages[i].parts.some((part) => part.type === "text" && typeof part.text === "string")) {
|
|
89
|
+
currentUser = i;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
let remainingPromptTexts = 0;
|
|
93
|
+
if (currentUser >= 0) {
|
|
94
|
+
remainingPromptTexts = output.messages[currentUser].parts.filter((part) => part.type === "text" && typeof part.text === "string").length;
|
|
95
|
+
}
|
|
96
|
+
const messageItem = (index, role) => role === "user" || role === "assistant" || role === "system"
|
|
97
|
+
? { role, kind: role === "system" ? "context" : "history" }
|
|
98
|
+
: undefined;
|
|
99
|
+
for (let i = 0; i < output.messages.length; i++) {
|
|
100
|
+
const message = output.messages[i];
|
|
101
|
+
const role = messageRole(message);
|
|
102
|
+
for (const part of message.parts) {
|
|
103
|
+
if (part.type === "text") {
|
|
104
|
+
if (typeof part.text !== "string") {
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
add(part, "text", messageItem(i, role));
|
|
108
|
+
if (i === currentUser && --remainingPromptTexts === 0) {
|
|
109
|
+
items[items.length - 1] = {
|
|
110
|
+
role: "user",
|
|
111
|
+
kind: "current_prompt",
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
else if (part.type === "reasoning") {
|
|
116
|
+
add(part, "text", { role: "assistant", kind: "history" });
|
|
117
|
+
}
|
|
118
|
+
else if (part.type === "tool") {
|
|
119
|
+
if (!part.state ||
|
|
120
|
+
typeof part.state !== "object" ||
|
|
121
|
+
Array.isArray(part.state)) {
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
const state = part.state;
|
|
125
|
+
const status = state.status;
|
|
126
|
+
const input = state.input;
|
|
127
|
+
guards.push(() => part.state === state &&
|
|
128
|
+
state.status === status &&
|
|
129
|
+
state.input === input);
|
|
130
|
+
strings(state.input, 0, { role: "assistant", kind: "history" });
|
|
131
|
+
if (state.status === "completed") {
|
|
132
|
+
add(state, "output", { role: "tool", kind: "history" });
|
|
133
|
+
}
|
|
134
|
+
else if (state.status === "error") {
|
|
135
|
+
add(state, "error", { role: "tool", kind: "history" });
|
|
136
|
+
}
|
|
137
|
+
else if (state.status === "pending" &&
|
|
138
|
+
typeof state.raw === "string") {
|
|
139
|
+
add(state, "raw", { role: "assistant", kind: "history" });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
else if (part.type === "subtask") {
|
|
143
|
+
// A subtask is a separate session request; no role is claimed.
|
|
144
|
+
add(part, "prompt");
|
|
145
|
+
add(part, "description");
|
|
146
|
+
}
|
|
147
|
+
else if (part.type === "file") {
|
|
148
|
+
const url = part.url;
|
|
149
|
+
const mime = part.mime;
|
|
150
|
+
guards.push(() => part.url === url && part.mime === mime);
|
|
151
|
+
// Unknown roles count as user history, as in the other protocols.
|
|
152
|
+
const found = filePart(part, messageItem(i, role) ?? { role: "user", kind: "history" });
|
|
153
|
+
attachments.push(found.param);
|
|
154
|
+
rewriters.push(found.edit);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
// Subtask or unknown-role slots disable the layout and retain legacy
|
|
159
|
+
// semantics instead of inventing roles.
|
|
160
|
+
const layout = items.every((item) => item !== undefined)
|
|
161
|
+
? items
|
|
162
|
+
: undefined;
|
|
163
|
+
// The latest message that names a model is the one the next request uses.
|
|
164
|
+
let modelId;
|
|
165
|
+
for (let i = nativeMessages.length - 1; i >= 0 && !modelId; i--) {
|
|
166
|
+
const info = nativeMessages[i].info;
|
|
167
|
+
modelId = messageModelName(info);
|
|
168
|
+
}
|
|
169
|
+
const sourcePayload = layout || modelId
|
|
170
|
+
? {
|
|
171
|
+
...(layout ? { [layoutField]: { version: 1, items: layout } } : {}),
|
|
172
|
+
...(modelId ? { [modelField]: modelId } : {}),
|
|
173
|
+
}
|
|
174
|
+
: undefined;
|
|
175
|
+
const attachmentEdits = (replacements) => replacements.map(({ index, data }) => {
|
|
176
|
+
const rewrite = rewriters[index];
|
|
177
|
+
if (!rewrite) {
|
|
178
|
+
return blocked();
|
|
179
|
+
}
|
|
180
|
+
return rewrite(data);
|
|
181
|
+
});
|
|
182
|
+
return {
|
|
183
|
+
texts,
|
|
184
|
+
attachments,
|
|
185
|
+
// Puts the masked body of a plain-text attachment in its place.
|
|
186
|
+
replaceAttachments(replacements) {
|
|
187
|
+
applyNativeEdits(attachmentEdits(replacements));
|
|
188
|
+
},
|
|
189
|
+
session,
|
|
190
|
+
sourcePayload,
|
|
191
|
+
unchanged: () => output.messages === nativeMessages &&
|
|
192
|
+
nativeMessages.length === messageSnapshots.length &&
|
|
193
|
+
messageSnapshots.every((saved, i) => nativeMessages[i] === saved.message &&
|
|
194
|
+
saved.message.info === saved.info &&
|
|
195
|
+
saved.info.sessionID === saved.session &&
|
|
196
|
+
saved.info.role === saved.role &&
|
|
197
|
+
saved.message.parts === saved.parts &&
|
|
198
|
+
saved.parts.length === saved.members.length &&
|
|
199
|
+
saved.members.every((part, j) => saved.parts[j] === part && part.type === saved.types[j])) &&
|
|
200
|
+
slots.every((slot) => slot.target[slot.key] === slot.value) &&
|
|
201
|
+
guards.every((guard) => guard()),
|
|
202
|
+
apply: (candidate, replacements = []) => {
|
|
203
|
+
if (candidate.length !== slots.length ||
|
|
204
|
+
!candidate.every((value) => typeof value === "string")) {
|
|
205
|
+
blocked();
|
|
206
|
+
}
|
|
207
|
+
applyNativeEdits([
|
|
208
|
+
...slots.map((slot, i) => ({
|
|
209
|
+
target: slot.target,
|
|
210
|
+
key: slot.key,
|
|
211
|
+
value: candidate[i],
|
|
212
|
+
})),
|
|
213
|
+
...attachmentEdits(replacements),
|
|
214
|
+
]);
|
|
215
|
+
},
|
|
216
|
+
};
|
|
217
|
+
}
|
package/v1.d.ts
ADDED
package/v1.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type NativeEdit } from "../runtime/native-edit.js";
|
|
2
|
+
import type { SessionRequest } from "@opencode/plugin/promise/session";
|
|
3
|
+
import type { TextLayoutItem } from "../runtime/text-layout.js";
|
|
4
|
+
import type { AttachmentParam } from "../bridge/protocol.js";
|
|
5
|
+
export { layoutField } from "../runtime/text-layout.js";
|
|
6
|
+
export type { TextLayoutItem } from "../runtime/text-layout.js";
|
|
7
|
+
type Node = Record<string, unknown>;
|
|
8
|
+
export type FoundAttachment = {
|
|
9
|
+
param: AttachmentParam;
|
|
10
|
+
edit?: (body: Buffer) => NativeEdit;
|
|
11
|
+
};
|
|
12
|
+
export declare function modelProjection(event: Pick<SessionRequest, "system" | "messages">, reserveSystemText?: boolean): {
|
|
13
|
+
texts: string[];
|
|
14
|
+
allTexts: string[];
|
|
15
|
+
attachments: AttachmentParam[];
|
|
16
|
+
layout: TextLayoutItem[] | undefined;
|
|
17
|
+
replaceAttachments(replacements: {
|
|
18
|
+
index: number;
|
|
19
|
+
data: Buffer;
|
|
20
|
+
}[]): void;
|
|
21
|
+
apply(candidate: string[], replacements?: {
|
|
22
|
+
index: number;
|
|
23
|
+
data: Buffer;
|
|
24
|
+
}[]): void;
|
|
25
|
+
};
|
|
26
|
+
export declare function argumentProjection(holder: {
|
|
27
|
+
input: unknown;
|
|
28
|
+
}): {
|
|
29
|
+
texts: string[];
|
|
30
|
+
items: (TextLayoutItem | undefined)[];
|
|
31
|
+
add: (target: Node, key: string, item?: TextLayoutItem) => void;
|
|
32
|
+
strings: (value: unknown, depth?: number, item?: TextLayoutItem) => void;
|
|
33
|
+
watch(check: () => boolean): void;
|
|
34
|
+
prepare: (candidate: string[]) => NativeEdit[];
|
|
35
|
+
apply: (candidate: string[]) => void;
|
|
36
|
+
};
|
package/v2/projection.js
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import { applyNativeEdits, snapshotObject, } from "../runtime/native-edit.js";
|
|
2
|
+
import { blocked } from "../runtime/errors.js";
|
|
3
|
+
import { maxProjection } from "../bridge/protocol.js";
|
|
4
|
+
export { layoutField } from "../runtime/text-layout.js";
|
|
5
|
+
const node = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
6
|
+
const base64 = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
7
|
+
function attachment(part, layout, watch) {
|
|
8
|
+
if (part.type !== "media") {
|
|
9
|
+
return undefined;
|
|
10
|
+
}
|
|
11
|
+
const media = node(part.media) ? part.media : undefined;
|
|
12
|
+
const source = media && node(media.source) ? media.source : undefined;
|
|
13
|
+
const data = source?.data;
|
|
14
|
+
const sourceType = source?.type;
|
|
15
|
+
const sourceMediaType = source?.mediaType;
|
|
16
|
+
watch(() => Object.is(part.media, media) &&
|
|
17
|
+
Object.is(media?.source, source) &&
|
|
18
|
+
Object.is(source?.data, data) &&
|
|
19
|
+
source?.type === sourceType &&
|
|
20
|
+
source?.mediaType === sourceMediaType);
|
|
21
|
+
const media_type = typeof source?.mediaType === "string" ? source.mediaType : "";
|
|
22
|
+
if (source?.type === "bytes" && data instanceof Uint8Array && media_type) {
|
|
23
|
+
const snapshot = Buffer.from(data);
|
|
24
|
+
watch(() => snapshot.equals(data));
|
|
25
|
+
return data.length
|
|
26
|
+
? {
|
|
27
|
+
param: {
|
|
28
|
+
media_type,
|
|
29
|
+
data_b64: snapshot.toString("base64"),
|
|
30
|
+
layout,
|
|
31
|
+
},
|
|
32
|
+
edit: (body) => ({
|
|
33
|
+
target: source,
|
|
34
|
+
key: "data",
|
|
35
|
+
value: new Uint8Array(body),
|
|
36
|
+
}),
|
|
37
|
+
}
|
|
38
|
+
: { param: { uninspectable: "unsupported_source", layout } };
|
|
39
|
+
}
|
|
40
|
+
if (source?.type === "base64" && typeof data === "string" && media_type) {
|
|
41
|
+
return data.length > 0 && data.length % 4 === 0 && base64.test(data)
|
|
42
|
+
? {
|
|
43
|
+
param: { media_type, data_b64: data, layout },
|
|
44
|
+
edit: (body) => ({
|
|
45
|
+
target: source,
|
|
46
|
+
key: "data",
|
|
47
|
+
value: body.toString("base64"),
|
|
48
|
+
}),
|
|
49
|
+
}
|
|
50
|
+
: { param: { uninspectable: "unsupported_source", layout } };
|
|
51
|
+
}
|
|
52
|
+
if (source?.type === "url") {
|
|
53
|
+
return { param: { uninspectable: "url", layout } };
|
|
54
|
+
}
|
|
55
|
+
if (source?.type === "ref") {
|
|
56
|
+
return { param: { uninspectable: "file_id", layout } };
|
|
57
|
+
}
|
|
58
|
+
return { param: { uninspectable: "unsupported_source", layout } };
|
|
59
|
+
}
|
|
60
|
+
function projection() {
|
|
61
|
+
const texts = [];
|
|
62
|
+
const items = [];
|
|
63
|
+
const slots = [];
|
|
64
|
+
const checks = [];
|
|
65
|
+
let bytes = 0;
|
|
66
|
+
const add = (target, key, item) => {
|
|
67
|
+
if (typeof target[key] !== "string") {
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
bytes += Buffer.byteLength(target[key]);
|
|
71
|
+
if (bytes > maxProjection || texts.length >= 4096) {
|
|
72
|
+
throw new Error("LLMGuard: content limit exceeded");
|
|
73
|
+
}
|
|
74
|
+
texts.push(target[key]);
|
|
75
|
+
items.push(item);
|
|
76
|
+
slots.push({ target, key, original: target[key] });
|
|
77
|
+
};
|
|
78
|
+
const strings = (value, depth = 0, item) => {
|
|
79
|
+
if (depth > 32) {
|
|
80
|
+
throw new Error("LLMGuard: content depth exceeded");
|
|
81
|
+
}
|
|
82
|
+
if (!value || typeof value !== "object") {
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
checks.push(snapshotObject(value));
|
|
86
|
+
for (const [key, child] of Object.entries(value)) {
|
|
87
|
+
if (typeof child === "string") {
|
|
88
|
+
add(value, key, item);
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
strings(child, depth + 1, item);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
const prepare = (candidate) => {
|
|
96
|
+
if (!checks.every((check) => check()) ||
|
|
97
|
+
!slots.every((slot) => slot.target[slot.key] === slot.original)) {
|
|
98
|
+
blocked();
|
|
99
|
+
}
|
|
100
|
+
if (candidate.length !== texts.length ||
|
|
101
|
+
!candidate.every((value) => typeof value === "string")) {
|
|
102
|
+
throw new Error("LLMGuard: invalid candidate");
|
|
103
|
+
}
|
|
104
|
+
return slots.map((slot, i) => ({
|
|
105
|
+
target: slot.target,
|
|
106
|
+
key: slot.key,
|
|
107
|
+
value: candidate[i],
|
|
108
|
+
}));
|
|
109
|
+
};
|
|
110
|
+
return {
|
|
111
|
+
texts,
|
|
112
|
+
items,
|
|
113
|
+
add,
|
|
114
|
+
strings,
|
|
115
|
+
watch(check) {
|
|
116
|
+
checks.push(check);
|
|
117
|
+
},
|
|
118
|
+
prepare,
|
|
119
|
+
apply: (candidate) => applyNativeEdits(prepare(candidate)),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
// Explicit AI content fields only. Unknown/native/media/metadata fields pass
|
|
123
|
+
// through without being traversed, decoded, serialized or used as policy claims.
|
|
124
|
+
export function modelProjection(event, reserveSystemText = false) {
|
|
125
|
+
const selected = projection();
|
|
126
|
+
const attachments = [];
|
|
127
|
+
const rewriters = [];
|
|
128
|
+
const collect = (part, role) => {
|
|
129
|
+
// Unknown roles are treated as user history, like the other protocols do.
|
|
130
|
+
const layout = {
|
|
131
|
+
role: role === "system" ||
|
|
132
|
+
role === "user" ||
|
|
133
|
+
role === "assistant" ||
|
|
134
|
+
role === "tool"
|
|
135
|
+
? role
|
|
136
|
+
: "user",
|
|
137
|
+
kind: role === "system" ? "context" : "history",
|
|
138
|
+
};
|
|
139
|
+
const found = attachment(part, layout, selected.watch);
|
|
140
|
+
if (found) {
|
|
141
|
+
attachments.push(found.param);
|
|
142
|
+
rewriters.push(found.edit);
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
// Bind routing, membership and selected fields while Go checks the clone.
|
|
146
|
+
// Never walk attachment payloads or unknown metadata recursively.
|
|
147
|
+
const watch = (value) => {
|
|
148
|
+
if (!value || typeof value !== "object") {
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const target = value;
|
|
152
|
+
const keys = Object.keys(target);
|
|
153
|
+
const values = keys.map((key) => target[key]);
|
|
154
|
+
selected.watch(() => Object.keys(target).join("\0") === keys.join("\0") &&
|
|
155
|
+
keys.every((key, i) => Object.is(target[key], values[i])));
|
|
156
|
+
};
|
|
157
|
+
watch(event);
|
|
158
|
+
watch(event.system);
|
|
159
|
+
event.system.forEach(watch);
|
|
160
|
+
watch(event.messages);
|
|
161
|
+
for (const message of event.messages) {
|
|
162
|
+
watch(message);
|
|
163
|
+
if (!Array.isArray(message.content)) {
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
watch(message.content);
|
|
167
|
+
for (const value of message.content) {
|
|
168
|
+
watch(value);
|
|
169
|
+
const part = value;
|
|
170
|
+
if (part.type === "tool-result" && node(part.result)) {
|
|
171
|
+
watch(part.result);
|
|
172
|
+
if (part.result.type === "content" &&
|
|
173
|
+
Array.isArray(part.result.value)) {
|
|
174
|
+
watch(part.result.value);
|
|
175
|
+
part.result.value.forEach(watch);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const messages = Array.isArray(event.messages) ? event.messages : [];
|
|
181
|
+
// Guard renders the latest user text as the active message. Instructions and
|
|
182
|
+
// context stay before conversational content; a request that continues a
|
|
183
|
+
// tool loop keeps the turn's user input as its current prompt.
|
|
184
|
+
let currentUser = -1;
|
|
185
|
+
for (let i = 0; i < messages.length; i++) {
|
|
186
|
+
const message = messages[i];
|
|
187
|
+
if (!node(message) ||
|
|
188
|
+
message.role !== "user" ||
|
|
189
|
+
!Array.isArray(message.content)) {
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
if (message.content.some((part) => node(part) && part.type === "text" && typeof part.text === "string")) {
|
|
193
|
+
currentUser = i;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
let remainingPromptTexts = 0;
|
|
197
|
+
if (currentUser >= 0) {
|
|
198
|
+
const content = messages[currentUser].content;
|
|
199
|
+
remainingPromptTexts = content.filter((part) => node(part) && part.type === "text" && typeof part.text === "string").length;
|
|
200
|
+
}
|
|
201
|
+
const item = (messageIndex, role, part) => {
|
|
202
|
+
if (messageIndex === currentUser && part.type === "text") {
|
|
203
|
+
const last = remainingPromptTexts === 1;
|
|
204
|
+
remainingPromptTexts--;
|
|
205
|
+
if (last) {
|
|
206
|
+
return { role, kind: "current_prompt" };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return { role, kind: role === "system" ? "context" : "history" };
|
|
210
|
+
};
|
|
211
|
+
// A virtual slot is committed only after Guard authorizes the candidate.
|
|
212
|
+
const virtualSystem = reserveSystemText && !event.system.some((part) => part.type === "text")
|
|
213
|
+
? { type: "text", text: "" }
|
|
214
|
+
: undefined;
|
|
215
|
+
if (virtualSystem) {
|
|
216
|
+
selected.add(virtualSystem, "text", { role: "system", kind: "context" });
|
|
217
|
+
selected.watch(() => {
|
|
218
|
+
const descriptor = Object.getOwnPropertyDescriptor(event, "system");
|
|
219
|
+
return (!!descriptor && "value" in descriptor && descriptor.writable === true);
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
for (const part of event.system) {
|
|
223
|
+
if (part.type === "text") {
|
|
224
|
+
selected.add(part, "text", { role: "system", kind: "context" });
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
for (let i = 0; i < messages.length; i++) {
|
|
228
|
+
const message = messages[i];
|
|
229
|
+
if (!node(message) || !Array.isArray(message.content)) {
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
const messageRole = message.role;
|
|
233
|
+
if (messageRole !== "user" &&
|
|
234
|
+
messageRole !== "assistant" &&
|
|
235
|
+
messageRole !== "system" &&
|
|
236
|
+
messageRole !== "tool") {
|
|
237
|
+
// Unknown roles keep masking coverage but cannot claim a Guard role.
|
|
238
|
+
for (const part of message.content) {
|
|
239
|
+
const p = part;
|
|
240
|
+
if (p.type === "text" ||
|
|
241
|
+
p.type === "reasoning" ||
|
|
242
|
+
p.type === "compaction") {
|
|
243
|
+
selected.add(p, "text");
|
|
244
|
+
}
|
|
245
|
+
else if (p.type === "tool-call") {
|
|
246
|
+
if (typeof p.input === "string") {
|
|
247
|
+
selected.add(p, "input");
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
selected.strings(p.input);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
else if (p.type === "tool-result" && node(p.result)) {
|
|
254
|
+
const result = p.result;
|
|
255
|
+
if (["text", "error", "json"].includes(String(result.type))) {
|
|
256
|
+
if (typeof result.value === "string") {
|
|
257
|
+
selected.add(result, "value");
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
selected.strings(result.value);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
else if (result.type === "content" && Array.isArray(result.value)) {
|
|
264
|
+
for (const item of result.value) {
|
|
265
|
+
if (node(item) && item.type === "text") {
|
|
266
|
+
selected.add(item, "text");
|
|
267
|
+
}
|
|
268
|
+
else if (node(item)) {
|
|
269
|
+
collect(item, undefined);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
else if (p.type === "media") {
|
|
275
|
+
collect(p, undefined);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
for (const part of message.content) {
|
|
281
|
+
const p = part;
|
|
282
|
+
if (p.type === "text") {
|
|
283
|
+
selected.add(p, "text", item(i, messageRole, p));
|
|
284
|
+
}
|
|
285
|
+
else if (p.type === "reasoning") {
|
|
286
|
+
selected.add(p, "text", { role: "assistant", kind: "history" });
|
|
287
|
+
}
|
|
288
|
+
else if (p.type === "compaction") {
|
|
289
|
+
selected.add(p, "text", { role: "system", kind: "context" });
|
|
290
|
+
}
|
|
291
|
+
else if (p.type === "tool-call") {
|
|
292
|
+
if (typeof p.input === "string") {
|
|
293
|
+
selected.add(p, "input", { role: "assistant", kind: "history" });
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
selected.strings(p.input, 0, { role: "assistant", kind: "history" });
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
else if (p.type === "tool-result" && node(p.result)) {
|
|
300
|
+
const result = p.result;
|
|
301
|
+
if (["text", "error", "json"].includes(String(result.type))) {
|
|
302
|
+
if (typeof result.value === "string") {
|
|
303
|
+
selected.add(result, "value", { role: "tool", kind: "history" });
|
|
304
|
+
}
|
|
305
|
+
else {
|
|
306
|
+
selected.strings(result.value, 0, {
|
|
307
|
+
role: "tool",
|
|
308
|
+
kind: "history",
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
else if (result.type === "content" && Array.isArray(result.value)) {
|
|
313
|
+
for (const entry of result.value) {
|
|
314
|
+
if (node(entry) && entry.type === "text") {
|
|
315
|
+
selected.add(entry, "text", { role: "tool", kind: "history" });
|
|
316
|
+
}
|
|
317
|
+
else if (node(entry)) {
|
|
318
|
+
collect(entry, "tool");
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
else if (p.type === "media") {
|
|
324
|
+
collect(p, messageRole);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
const layout = (reserveSystemText || (currentUser >= 0 && remainingPromptTexts === 0)) &&
|
|
329
|
+
selected.items.length > 0 &&
|
|
330
|
+
selected.items.every((value) => value !== undefined)
|
|
331
|
+
? selected.items
|
|
332
|
+
: undefined;
|
|
333
|
+
const attachmentEdits = (replacements) => replacements.map(({ index, data }) => {
|
|
334
|
+
const rewrite = rewriters[index];
|
|
335
|
+
if (!rewrite) {
|
|
336
|
+
return blocked();
|
|
337
|
+
}
|
|
338
|
+
return rewrite(data);
|
|
339
|
+
});
|
|
340
|
+
return {
|
|
341
|
+
// Preserve the opaque-only bypass: a virtual slot alone is not content.
|
|
342
|
+
texts: virtualSystem && selected.texts.length === 1 ? [] : selected.texts,
|
|
343
|
+
// Every selected slot, including a reserved system slot. A request that
|
|
344
|
+
// carries only attachments is checked with these, so apply keeps its shape.
|
|
345
|
+
allTexts: selected.texts,
|
|
346
|
+
attachments,
|
|
347
|
+
layout,
|
|
348
|
+
// Puts the masked body of a plain-text attachment in its place. An attachment
|
|
349
|
+
// that cannot be rewritten has no business being in the list.
|
|
350
|
+
replaceAttachments(replacements) {
|
|
351
|
+
applyNativeEdits(attachmentEdits(replacements));
|
|
352
|
+
},
|
|
353
|
+
apply(candidate, replacements = []) {
|
|
354
|
+
applyNativeEdits([
|
|
355
|
+
...selected.prepare(candidate),
|
|
356
|
+
...attachmentEdits(replacements),
|
|
357
|
+
...(virtualSystem
|
|
358
|
+
? [
|
|
359
|
+
{
|
|
360
|
+
target: event,
|
|
361
|
+
key: "system",
|
|
362
|
+
value: [virtualSystem, ...event.system],
|
|
363
|
+
},
|
|
364
|
+
]
|
|
365
|
+
: []),
|
|
366
|
+
]);
|
|
367
|
+
},
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
export function argumentProjection(holder) {
|
|
371
|
+
const selected = projection();
|
|
372
|
+
selected.strings(holder);
|
|
373
|
+
return selected;
|
|
374
|
+
}
|