@drakon-systems/shieldcortex-realtime 4.54.15 → 5.0.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/provenance.ts ADDED
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Provenance labelling for the OpenClaw realtime `llm_input` hook.
3
+ *
4
+ * The hook used to hand every text to the scanner with no origin attached:
5
+ * the operator's own prompt and a web page that arrived inside a tool result
6
+ * were judged by the identical detector. That is the wall the L2 policy
7
+ * exists to break — the same sentence is an instruction from the operator and
8
+ * an injection from a fetched document, and only the ORIGIN separates them.
9
+ *
10
+ * Two rules govern everything here:
11
+ *
12
+ * 1. NEVER GUESS UPWARDS. A shape this file does not recognise is labelled
13
+ * `unknown`, which keeps exactly the pre-existing L1 path and is counted
14
+ * so an operator can see that their host's event shape is not being
15
+ * classified. Guessing `user` would silence L2 on real tool output;
16
+ * guessing `tool_result` would apply an aggressive policy to the
17
+ * operator's own words.
18
+ *
19
+ * 2. NEVER INVENT A DISTINCTION THE EVENT DOES NOT CARRY. The OpenClaw
20
+ * `llm_input` event exposes `prompt`, `systemPrompt`, `historyMessages`
21
+ * and counters — nothing in it says "this tool result was a fetched web
22
+ * page" or "this was a file read". So this file emits `tool_result` for
23
+ * all tool-origin content and never `web`/`document`. Those two labels
24
+ * remain reachable from ingresses that genuinely know (the `scan` CLI's
25
+ * --source), and adding them here later needs a host field to read, not
26
+ * a heuristic.
27
+ *
28
+ * Pure and synchronous: no I/O, no config read, no defence module. The plugin
29
+ * calls it once per hook invocation before any scanning happens.
30
+ *
31
+ * The label vocabulary MIRRORS `ProvenanceLabel` in the main package
32
+ * (src/defence/types.ts). It is spelled out rather than imported because this
33
+ * plugin compiles against its own rootDir and must build without the package
34
+ * source on disk. Only the subset this hook can honestly emit appears here —
35
+ * a label this file cannot justify is a label it must not produce.
36
+ */
37
+
38
+ export const PLUGIN_PROVENANCE_LABELS = ['user', 'tool_result', 'unknown'] as const;
39
+
40
+ export type PluginProvenanceLabel = (typeof PLUGIN_PROVENANCE_LABELS)[number];
41
+
42
+ export interface LabelledInput {
43
+ text: string;
44
+ label: PluginProvenanceLabel;
45
+ }
46
+
47
+ /**
48
+ * The result of labelling one event: the texts to scan, and how many
49
+ * tool-origin blocks carried no readable text.
50
+ *
51
+ * The second number exists because "dropped silently" is the one outcome a
52
+ * provenance layer must not have. A host that wraps its tool results in a
53
+ * shape this file cannot read produces no inputs AND no counter, so the
54
+ * operator sees a clean plane that is in fact looking at nothing. The count
55
+ * is of BLOCKS, never their content.
56
+ */
57
+ export interface LabelledInputs {
58
+ inputs: LabelledInput[];
59
+ unreadableToolBlocks: number;
60
+ }
61
+
62
+ /**
63
+ * How many history texts the hook looks at. Unchanged from the pre-provenance
64
+ * behaviour (`extractUserContent(...).slice(-5)`): labelling widens WHICH
65
+ * messages are eligible, not how many are scanned per turn.
66
+ */
67
+ export const HISTORY_SCAN_LIMIT = 5;
68
+
69
+ /** Roles that carry tool output back to the model, across host encodings. */
70
+ const TOOL_ROLES = new Set(['tool', 'tool_result', 'function', 'tool-result']);
71
+ /** Roles that are the human speaking to the agent. */
72
+ const USER_ROLES = new Set(['user', 'human']);
73
+
74
+ function asRecord(value: unknown): Record<string, unknown> | null {
75
+ return value && typeof value === 'object' && !Array.isArray(value)
76
+ ? (value as Record<string, unknown>)
77
+ : null;
78
+ }
79
+
80
+ function blockText(block: unknown): string | null {
81
+ const b = asRecord(block);
82
+ if (!b) return typeof block === 'string' ? block : null;
83
+ if (typeof b.text === 'string') return b.text;
84
+ if (typeof b.content === 'string') return b.content;
85
+ return null;
86
+ }
87
+
88
+ /** A content block that IS a tool result, by any of the encodings in use. */
89
+ function isToolResultBlock(block: unknown): boolean {
90
+ const b = asRecord(block);
91
+ if (!b) return false;
92
+ if (typeof b.type === 'string' && TOOL_ROLES.has(b.type)) return true;
93
+ // Anthropic-shaped blocks correlate a result to its call; the presence of
94
+ // that correlation id is the structural tell, independent of `type`.
95
+ return typeof b.tool_use_id === 'string' || typeof b.toolUseId === 'string';
96
+ }
97
+
98
+ /** Nested tool-result content is flattened at most this deep. */
99
+ const MAX_NESTING = 3;
100
+
101
+ /**
102
+ * Pull every readable text out of one tool-result block, however the host
103
+ * nested it, and count the parts that carried none.
104
+ *
105
+ * Anthropic-shaped results are `{type:'tool_result', tool_use_id, content:[
106
+ * {type:'text', text}]}` — a content ARRAY, which the r1 `blockText` could
107
+ * not read, so the whole result was dropped before its tool-result structure
108
+ * was ever examined and no counter moved either. The established provenance
109
+ * is preserved through every child representation: once a block is
110
+ * tool-origin, everything inside it is too.
111
+ */
112
+ function flattenToolResult(block: unknown, depth: number, out: string[]): number {
113
+ const direct = blockText(block);
114
+ if (direct) {
115
+ out.push(direct);
116
+ return 0;
117
+ }
118
+ const b = asRecord(block);
119
+ if (!b || depth >= MAX_NESTING) return 1;
120
+ const inner = b.content ?? b.result ?? b.output;
121
+ if (Array.isArray(inner)) {
122
+ if (inner.length === 0) return 1;
123
+ let unreadable = 0;
124
+ for (const child of inner) unreadable += flattenToolResult(child, depth + 1, out);
125
+ return unreadable;
126
+ }
127
+ if (inner && typeof inner === 'object') return flattenToolResult(inner, depth + 1, out);
128
+ return 1;
129
+ }
130
+
131
+ /**
132
+ * Label one history message.
133
+ *
134
+ * A user-role message is NOT automatically `user`: on Anthropic-shaped
135
+ * histories a tool result is delivered as a user-role message whose content
136
+ * blocks are tool results. That is precisely the indirect-injection path, so
137
+ * the BLOCK decides, not the role.
138
+ */
139
+ export function labelHistoryMessage(msg: unknown): LabelledInputs {
140
+ const m = asRecord(msg);
141
+ if (!m) return { inputs: [], unreadableToolBlocks: 0 };
142
+ const role = typeof m.role === 'string' ? m.role.toLowerCase() : '';
143
+ const roleLabel: PluginProvenanceLabel | null = TOOL_ROLES.has(role)
144
+ ? 'tool_result'
145
+ : USER_ROLES.has(role)
146
+ ? 'user'
147
+ : null;
148
+
149
+ if (typeof m.content === 'string') {
150
+ // A bare string carries no block structure. A TOOL role still decides —
151
+ // the host declared the origin and inheriting it can only tighten. A USER
152
+ // role does not: rule #1 forbids guessing upwards, and a host that
153
+ // flattens tool results into user-role strings would otherwise turn L2
154
+ // off by accident. `unknown` costs nothing here (both labels are L2-off)
155
+ // and buys the honesty counter, so the operator sees that this host's
156
+ // history shape is not being classified rather than being told it is.
157
+ const label: PluginProvenanceLabel = roleLabel === 'tool_result' ? 'tool_result' : 'unknown';
158
+ return {
159
+ inputs: m.content ? [{ text: m.content, label }] : [],
160
+ unreadableToolBlocks: 0,
161
+ };
162
+ }
163
+
164
+ if (Array.isArray(m.content)) {
165
+ const inputs: LabelledInput[] = [];
166
+ let unreadableToolBlocks = 0;
167
+ for (const block of m.content) {
168
+ if (isToolResultBlock(block)) {
169
+ const texts: string[] = [];
170
+ unreadableToolBlocks += flattenToolResult(block, 0, texts);
171
+ for (const text of texts) inputs.push({ text, label: 'tool_result' });
172
+ continue;
173
+ }
174
+ const text = blockText(block);
175
+ if (!text) {
176
+ // Only tool-origin loss is counted: an image block in a user turn is
177
+ // not a gap in this layer, it is a thing this layer never judged.
178
+ if (roleLabel === 'tool_result') unreadableToolBlocks += 1;
179
+ continue;
180
+ }
181
+ const b = asRecord(block);
182
+ const isText = b && typeof b.type === 'string' && b.type === 'text';
183
+ // Established untrusted provenance is INHERITED: a string (or any
184
+ // shape) inside a tool-role message is tool output whatever its own
185
+ // block type says. Under any other role only a text block may inherit;
186
+ // anything else is a shape this file cannot account for.
187
+ const label: PluginProvenanceLabel = roleLabel === 'tool_result'
188
+ ? 'tool_result'
189
+ : isText && roleLabel
190
+ ? roleLabel
191
+ : 'unknown';
192
+ inputs.push({ text, label });
193
+ }
194
+ return { inputs, unreadableToolBlocks };
195
+ }
196
+
197
+ return { inputs: [], unreadableToolBlocks: 0 };
198
+ }
199
+
200
+ /**
201
+ * Every text this hook will scan for one `llm_input` event, each with the
202
+ * origin it was declared under.
203
+ *
204
+ * The live `prompt` is the turn the host attributes to the sender, so it is
205
+ * `user` — the same judgement the conversation-trust layer already makes
206
+ * about a turn. History is labelled per message and bounded to the last
207
+ * {@link HISTORY_SCAN_LIMIT}, as before.
208
+ */
209
+ export function labelLlmInput(event: {
210
+ prompt?: unknown;
211
+ historyMessages?: unknown;
212
+ }): LabelledInputs {
213
+ const out: LabelledInput[] = [];
214
+ if (typeof event?.prompt === 'string' && event.prompt) {
215
+ out.push({ text: event.prompt, label: 'user' });
216
+ }
217
+ const history = Array.isArray(event?.historyMessages) ? event.historyMessages : [];
218
+ const labelled: LabelledInput[] = [];
219
+ let unreadableToolBlocks = 0;
220
+ for (const msg of history) {
221
+ const one = labelHistoryMessage(msg);
222
+ labelled.push(...one.inputs);
223
+ unreadableToolBlocks += one.unreadableToolBlocks;
224
+ }
225
+ out.push(...labelled.slice(-HISTORY_SCAN_LIMIT));
226
+ return { inputs: out, unreadableToolBlocks };
227
+ }