theorum 0.1.4 → 0.1.6

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 (191) hide show
  1. package/docs/AGENT_PROFILE_CONTRACT.md +2 -2
  2. package/esm/_dnt.polyfills.d.ts +110 -0
  3. package/esm/_dnt.polyfills.js +144 -0
  4. package/esm/_dnt.shims.d.ts +5 -0
  5. package/esm/_dnt.shims.js +61 -0
  6. package/{mod.ts → esm/mod.d.ts} +17 -57
  7. package/esm/mod.js +50 -0
  8. package/esm/package.json +3 -0
  9. package/esm/src/cli/commands/profile.d.ts +2 -0
  10. package/esm/src/cli/commands/profile.js +53 -0
  11. package/esm/src/cli/commands/run.d.ts +10 -0
  12. package/esm/src/cli/commands/run.js +55 -0
  13. package/esm/src/cli/commands/test.d.ts +15 -0
  14. package/esm/src/cli/commands/test.js +140 -0
  15. package/esm/src/cli/index.d.ts +4 -0
  16. package/esm/src/cli/index.js +148 -0
  17. package/esm/src/cli/matrix/fixtures.d.ts +13 -0
  18. package/esm/src/cli/matrix/fixtures.js +77 -0
  19. package/esm/src/cli/matrix/synthesizer.d.ts +29 -0
  20. package/esm/src/cli/matrix/synthesizer.js +187 -0
  21. package/esm/src/guardrails/error.d.ts +45 -0
  22. package/esm/src/guardrails/error.js +149 -0
  23. package/esm/src/guardrails/injection.d.ts +12 -0
  24. package/esm/src/guardrails/injection.js +220 -0
  25. package/esm/src/guardrails/mod.d.ts +16 -0
  26. package/esm/src/guardrails/mod.js +15 -0
  27. package/esm/src/guardrails/quota.d.ts +10 -0
  28. package/esm/src/guardrails/quota.js +64 -0
  29. package/esm/src/guardrails/sanitize.d.ts +22 -0
  30. package/esm/src/guardrails/sanitize.js +133 -0
  31. package/esm/src/guardrails/sensitive.d.ts +12 -0
  32. package/esm/src/guardrails/sensitive.js +88 -0
  33. package/esm/src/host/mint-trace.d.ts +27 -0
  34. package/esm/src/host/mint-trace.js +33 -0
  35. package/esm/src/host/mod.d.ts +13 -0
  36. package/{src/host/mod.ts → esm/src/host/mod.js} +3 -11
  37. package/esm/src/host/reply.d.ts +14 -0
  38. package/esm/src/host/reply.js +27 -0
  39. package/esm/src/kernel/engine/boundary.d.ts +10 -0
  40. package/esm/src/kernel/engine/boundary.js +55 -0
  41. package/esm/src/kernel/engine/delta.d.ts +8 -0
  42. package/esm/src/kernel/engine/delta.js +389 -0
  43. package/esm/src/kernel/engine/hash.d.ts +1 -0
  44. package/esm/src/kernel/engine/hash.js +9 -0
  45. package/esm/src/kernel/engine/record.d.ts +2 -0
  46. package/esm/src/kernel/engine/record.js +7 -0
  47. package/esm/src/kernel/engine/repair.d.ts +7 -0
  48. package/esm/src/kernel/engine/repair.js +38 -0
  49. package/esm/src/kernel/engine/runner/gates.d.ts +4 -0
  50. package/esm/src/kernel/engine/runner/gates.js +208 -0
  51. package/esm/src/kernel/engine/runner/mod.d.ts +14 -0
  52. package/esm/src/kernel/engine/runner/mod.js +103 -0
  53. package/esm/src/kernel/engine/runner/schema-validation.d.ts +22 -0
  54. package/esm/src/kernel/engine/runner/schema-validation.js +113 -0
  55. package/esm/src/kernel/engine/runner/state.d.ts +16 -0
  56. package/esm/src/kernel/engine/runner/state.js +8 -0
  57. package/esm/src/kernel/engine/runner/steps.d.ts +15 -0
  58. package/esm/src/kernel/engine/runner/steps.js +127 -0
  59. package/esm/src/kernel/engine/runner/stream.d.ts +11 -0
  60. package/esm/src/kernel/engine/runner/stream.js +70 -0
  61. package/esm/src/kernel/engine/runner/tokens.d.ts +3 -0
  62. package/esm/src/kernel/engine/runner/tokens.js +38 -0
  63. package/esm/src/kernel/engine/runner/tools.d.ts +13 -0
  64. package/esm/src/kernel/engine/runner/tools.js +192 -0
  65. package/{src/kernel/engine/runner.ts → esm/src/kernel/engine/runner.d.ts} +1 -2
  66. package/esm/src/kernel/engine/runner.js +6 -0
  67. package/esm/src/kernel/engine/tree.d.ts +2 -0
  68. package/esm/src/kernel/engine/tree.js +17 -0
  69. package/esm/src/kernel/mod.d.ts +18 -0
  70. package/esm/src/kernel/mod.js +16 -0
  71. package/esm/src/kernel/registry/attachments.d.ts +16 -0
  72. package/esm/src/kernel/registry/attachments.js +156 -0
  73. package/esm/src/kernel/registry/catalog.d.ts +31 -0
  74. package/esm/src/kernel/registry/catalog.js +135 -0
  75. package/esm/src/kernel/registry/ingress.d.ts +13 -0
  76. package/esm/src/kernel/registry/ingress.js +163 -0
  77. package/esm/src/kernel/registry/profiles.d.ts +34 -0
  78. package/esm/src/kernel/registry/profiles.js +120 -0
  79. package/esm/src/kernel/registry/provider-request.d.ts +4 -0
  80. package/esm/src/kernel/registry/provider-request.js +25 -0
  81. package/esm/src/kernel/registry/resolve.d.ts +19 -0
  82. package/esm/src/kernel/registry/resolve.js +217 -0
  83. package/esm/src/kernel/registry/schemas.d.ts +14 -0
  84. package/esm/src/kernel/registry/schemas.js +23 -0
  85. package/esm/src/kernel/registry/tools.d.ts +12 -0
  86. package/esm/src/kernel/registry/tools.js +36 -0
  87. package/{src/kernel/registry/vault.ts → esm/src/kernel/registry/vault.d.ts} +2 -17
  88. package/esm/src/kernel/registry/vault.js +18 -0
  89. package/esm/src/kernel/types.d.ts +528 -0
  90. package/esm/src/kernel/types.js +10 -0
  91. package/esm/src/observability/mod.d.ts +12 -0
  92. package/{src/observability/mod.ts → esm/src/observability/mod.js} +2 -11
  93. package/esm/src/observability/spans.d.ts +16 -0
  94. package/esm/src/observability/spans.js +56 -0
  95. package/esm/src/observability/trace-attach.d.ts +16 -0
  96. package/esm/src/observability/trace-attach.js +67 -0
  97. package/esm/src/observability/trace-record.d.ts +113 -0
  98. package/esm/src/observability/trace-record.js +143 -0
  99. package/esm/src/observability/trace-usage.d.ts +3 -0
  100. package/esm/src/observability/trace-usage.js +32 -0
  101. package/esm/src/observability/trace.d.ts +23 -0
  102. package/esm/src/observability/trace.js +121 -0
  103. package/esm/src/presets/google.d.ts +50 -0
  104. package/esm/src/presets/google.js +96 -0
  105. package/esm/src/presets/mod.d.ts +11 -0
  106. package/esm/src/presets/mod.js +10 -0
  107. package/esm/src/providers/create-provider.d.ts +29 -0
  108. package/esm/src/providers/create-provider.js +38 -0
  109. package/esm/src/providers/gemini-tape.d.ts +2 -0
  110. package/esm/src/providers/gemini-tape.js +46 -0
  111. package/esm/src/providers/google-tap.d.ts +3 -0
  112. package/esm/src/providers/google-tap.js +48 -0
  113. package/esm/src/providers/interactions.d.ts +5 -0
  114. package/esm/src/providers/interactions.js +153 -0
  115. package/esm/src/providers/keys.d.ts +19 -0
  116. package/esm/src/providers/keys.js +129 -0
  117. package/esm/src/providers/mod.d.ts +12 -0
  118. package/{src/providers/mod.ts → esm/src/providers/mod.js} +2 -4
  119. package/esm/src/providers/openrouter-mod.d.ts +13 -0
  120. package/{src/providers/openrouter-mod.ts → esm/src/providers/openrouter-mod.js} +3 -7
  121. package/esm/src/providers/openrouter-payload.d.ts +32 -0
  122. package/esm/src/providers/openrouter-payload.js +179 -0
  123. package/esm/src/providers/openrouter.d.ts +15 -0
  124. package/esm/src/providers/openrouter.js +589 -0
  125. package/esm/src/providers/pcm.d.ts +7 -0
  126. package/esm/src/providers/pcm.js +35 -0
  127. package/esm/src/providers/provider.d.ts +15 -0
  128. package/esm/src/providers/provider.js +160 -0
  129. package/esm/src/providers/speech.d.ts +23 -0
  130. package/esm/src/providers/speech.js +125 -0
  131. package/esm/src/providers/sse.d.ts +7 -0
  132. package/esm/src/providers/sse.js +53 -0
  133. package/package.json +45 -36
  134. package/deno.json +0 -57
  135. package/deno.lock +0 -469
  136. package/src/cli/commands/profile.ts +0 -57
  137. package/src/cli/commands/run.ts +0 -66
  138. package/src/cli/commands/test.ts +0 -195
  139. package/src/cli/index.ts +0 -161
  140. package/src/cli/matrix/fixtures.ts +0 -96
  141. package/src/cli/matrix/synthesizer.ts +0 -240
  142. package/src/guardrails/error.ts +0 -142
  143. package/src/guardrails/injection.ts +0 -254
  144. package/src/guardrails/mod.ts +0 -40
  145. package/src/guardrails/quota.ts +0 -87
  146. package/src/guardrails/sanitize.ts +0 -165
  147. package/src/guardrails/sensitive.ts +0 -96
  148. package/src/host/mint-trace.ts +0 -54
  149. package/src/host/reply.ts +0 -32
  150. package/src/kernel/engine/assert.ts +0 -29
  151. package/src/kernel/engine/boundary.ts +0 -75
  152. package/src/kernel/engine/delta.ts +0 -440
  153. package/src/kernel/engine/hash.ts +0 -11
  154. package/src/kernel/engine/record.ts +0 -8
  155. package/src/kernel/engine/repair.ts +0 -56
  156. package/src/kernel/engine/runner/gates.ts +0 -338
  157. package/src/kernel/engine/runner/mod.ts +0 -135
  158. package/src/kernel/engine/runner/state.ts +0 -31
  159. package/src/kernel/engine/runner/steps.ts +0 -183
  160. package/src/kernel/engine/runner/stream.ts +0 -83
  161. package/src/kernel/engine/runner/tokens.ts +0 -47
  162. package/src/kernel/engine/runner/tools.ts +0 -266
  163. package/src/kernel/engine/tree.ts +0 -18
  164. package/src/kernel/mod.ts +0 -39
  165. package/src/kernel/registry/attachments.ts +0 -195
  166. package/src/kernel/registry/catalog.ts +0 -181
  167. package/src/kernel/registry/ingress.ts +0 -223
  168. package/src/kernel/registry/profiles.ts +0 -165
  169. package/src/kernel/registry/provider-request.ts +0 -31
  170. package/src/kernel/registry/resolve.ts +0 -290
  171. package/src/kernel/registry/schemas.ts +0 -29
  172. package/src/kernel/registry/tools.ts +0 -45
  173. package/src/kernel/types.ts +0 -576
  174. package/src/observability/spans.ts +0 -70
  175. package/src/observability/trace-attach.ts +0 -96
  176. package/src/observability/trace-record.ts +0 -254
  177. package/src/observability/trace-usage.ts +0 -36
  178. package/src/observability/trace.ts +0 -143
  179. package/src/presets/google.ts +0 -147
  180. package/src/presets/mod.ts +0 -24
  181. package/src/providers/create-provider.ts +0 -64
  182. package/src/providers/gemini-tape.ts +0 -59
  183. package/src/providers/google-tap.ts +0 -57
  184. package/src/providers/interactions.ts +0 -182
  185. package/src/providers/keys.ts +0 -182
  186. package/src/providers/openrouter-payload.ts +0 -232
  187. package/src/providers/openrouter.ts +0 -758
  188. package/src/providers/pcm.ts +0 -37
  189. package/src/providers/provider.ts +0 -206
  190. package/src/providers/speech.ts +0 -180
  191. package/src/providers/sse.ts +0 -59
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Public-safe error mapping for THEORUM.
3
+ *
4
+ * Kernel internals may contain provider status text, tool names, or exception
5
+ * details. This module maps those failures to stable user-safe strings.
6
+ *
7
+ * @module
8
+ */
9
+ /** Error class used for expected THEORUM contract failures. */
10
+ class TheorumError extends Error {
11
+ constructor(message = '', options) {
12
+ super(message, options);
13
+ this.name = 'TheorumError';
14
+ }
15
+ }
16
+ /** Internal marker for provider or transport failure. */
17
+ const UPSTREAM_FAILED = 'upstream failed';
18
+ /** Generic safe fallback shown when details must not be surfaced. */
19
+ const PUBLIC_GENERIC = 'Something went wrong. Try again.';
20
+ /** Safe copy for transient provider unavailability. */
21
+ const PUBLIC_UNAVAILABLE = 'The model is unavailable. Try again.';
22
+ /** Safe copy for canary or egress disclosure violations. */
23
+ const PUBLIC_CANARY = "That reply wasn't safe to show. Try again.";
24
+ /** Safe copy for tool or permission denials. */
25
+ const PUBLIC_ACTION = "That action isn't available.";
26
+ /** Safe copy for unsupported MIME types. */
27
+ const PUBLIC_FILE_TYPE = "That file type isn't supported.";
28
+ /** Safe copy for oversized files. */
29
+ const PUBLIC_FILE_SIZE = 'That file is too large.';
30
+ /** Safe copy for too many files in one turn. */
31
+ const PUBLIC_FILE_COUNT = 'Too many files for one message.';
32
+ /** Safe copy for unsupported generated image dimensions. */
33
+ const PUBLIC_IMAGE_SIZE = "That image size isn't supported.";
34
+ const EXACT = {
35
+ [UPSTREAM_FAILED]: PUBLIC_UNAVAILABLE,
36
+ 'empty Gemini stream': PUBLIC_UNAVAILABLE,
37
+ 'canary leaked': PUBLIC_CANARY,
38
+ 'Turn withheld: egress disclosure violation': PUBLIC_CANARY,
39
+ 'expected JSON object': 'Something was wrong with that request.',
40
+ 'user input cannot be placed in the system block': PUBLIC_GENERIC,
41
+ 'attachment data must be base64': PUBLIC_FILE_TYPE,
42
+ 'attachment is too large': PUBLIC_FILE_SIZE,
43
+ 'attachments exceed the per-turn budget': PUBLIC_FILE_SIZE,
44
+ 'askUser.kind must be confirm, choice, or text': "That question isn't valid.",
45
+ 'askUser.prompt is required': 'That question needs a prompt.',
46
+ 'This profile does not accept text input': PUBLIC_ACTION,
47
+ };
48
+ const RULES = [
49
+ {
50
+ match: (t) => /^(Gemini|OpenRouter|TTS|OpenRouter TTS|Speech) HTTP/.test(t) ||
51
+ t.includes('TTS HTTP') ||
52
+ t.includes('Speech HTTP'),
53
+ resolve: () => PUBLIC_UNAVAILABLE,
54
+ },
55
+ {
56
+ match: (t) => t.includes('not gated') ||
57
+ t.includes('not allowed') ||
58
+ t.includes('has no kernel executor') ||
59
+ t.includes('Unknown model select') ||
60
+ t.includes('Grounding tools'),
61
+ resolve: () => PUBLIC_ACTION,
62
+ },
63
+ {
64
+ match: (t) => t.includes('MIME') ||
65
+ t.includes('does not accept attachments') ||
66
+ t.includes('does not accept voice'),
67
+ resolve: () => PUBLIC_FILE_TYPE,
68
+ },
69
+ {
70
+ match: (t) => t.startsWith('At most'),
71
+ resolve: () => PUBLIC_FILE_COUNT,
72
+ },
73
+ {
74
+ match: (t) => (t.startsWith('Only ') && t.includes('file')) ||
75
+ t.startsWith('Each file must be') ||
76
+ t.startsWith('Those files together'),
77
+ resolve: (t) => t,
78
+ },
79
+ {
80
+ match: (t) => t.includes('attachment'),
81
+ resolve: () => PUBLIC_FILE_SIZE,
82
+ },
83
+ {
84
+ match: (t) => t.includes('aspect or size'),
85
+ resolve: () => PUBLIC_IMAGE_SIZE,
86
+ },
87
+ {
88
+ match: (t) => t.includes('must pin thinking') || t.includes('has no models'),
89
+ resolve: () => PUBLIC_GENERIC,
90
+ },
91
+ ];
92
+ const ALREADY_PUBLIC = new Set([
93
+ PUBLIC_GENERIC,
94
+ PUBLIC_UNAVAILABLE,
95
+ PUBLIC_CANARY,
96
+ PUBLIC_ACTION,
97
+ PUBLIC_FILE_TYPE,
98
+ PUBLIC_FILE_SIZE,
99
+ PUBLIC_FILE_COUNT,
100
+ PUBLIC_IMAGE_SIZE,
101
+ ]);
102
+ function publicText(text) {
103
+ if (ALREADY_PUBLIC.has(text)) {
104
+ return text;
105
+ }
106
+ const exact = EXACT[text];
107
+ if (exact) {
108
+ return exact;
109
+ }
110
+ for (const rule of RULES) {
111
+ if (rule.match(text)) {
112
+ return rule.resolve(text);
113
+ }
114
+ }
115
+ return PUBLIC_GENERIC;
116
+ }
117
+ /** Convert an unknown thrown value or internal message to user-safe text. */
118
+ function publicError(err) {
119
+ if (typeof err === 'string') {
120
+ return publicText(err);
121
+ }
122
+ if (err instanceof TheorumError) {
123
+ return publicText(err.message);
124
+ }
125
+ return PUBLIC_UNAVAILABLE;
126
+ }
127
+ /** Raw diagnostic text for hosts, traces, and logs (never shown to end users). */
128
+ function describeError(err) {
129
+ if (typeof err === 'string') {
130
+ return err;
131
+ }
132
+ if (err instanceof Error && err.message) {
133
+ return err.message;
134
+ }
135
+ return String(err);
136
+ }
137
+ /**
138
+ * Stream error event with a public-safe `error` and a preserved `errorInternal`.
139
+ * Providers and the runner should emit this instead of public-only error strings
140
+ * so traces and host logs are never a black box.
141
+ */
142
+ function toErrorEvent(err) {
143
+ return {
144
+ type: 'error',
145
+ error: publicError(err),
146
+ errorInternal: describeError(err),
147
+ };
148
+ }
149
+ export { describeError, PUBLIC_ACTION, PUBLIC_CANARY, PUBLIC_FILE_COUNT, PUBLIC_FILE_SIZE, PUBLIC_FILE_TYPE, PUBLIC_GENERIC, PUBLIC_IMAGE_SIZE, PUBLIC_UNAVAILABLE, publicError, TheorumError, toErrorEvent, UPSTREAM_FAILED, };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Prompt-injection span detection.
3
+ *
4
+ * These utilities return spans that can be redacted from untrusted user text
5
+ * before provider submission.
6
+ *
7
+ * @module
8
+ */
9
+ import { type RedactSpan } from '../observability/spans.js';
10
+ /** Detect prompt-injection spans in a string. */
11
+ declare function injectionSpans(text: string): RedactSpan[];
12
+ export { injectionSpans };
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Prompt-injection span detection.
3
+ *
4
+ * These utilities return spans that can be redacted from untrusted user text
5
+ * before provider submission.
6
+ *
7
+ * @module
8
+ */
9
+ import { blobAt, spansFromPatterns } from '../observability/spans.js';
10
+ const IGNORE_PREVIOUS = /ignore\s+(all\s+)?(previous|prior)\s+((?:safety|security|system|operational|internal|core|original|initial|existing|given|stated|provided|defined|specified|established)\s+)?(instructions?|rules?|guidelines?|constraints?|directives?)/gi;
11
+ const DISREGARD_INSTRUCTIONS = /disregard\s+(all\s+)?(previous|prior|above)\s+(instructions?|rules?|guidelines?|constraints?|directives?)/gi;
12
+ const FORGET_INSTRUCTIONS = /forget\s+(all\s+)?(previous|prior|above)\s+(instructions?|rules?|guidelines?|constraints?|directives?)/gi;
13
+ const NEW_INSTRUCTIONS = /new\s+instructions?:/gi;
14
+ const DO_NOT_FOLLOW = /do\s+not\s+follow\s+(the\s+)?(system|developer|previous|original)/gi;
15
+ const SUPERSEDE_INSTRUCTIONS = /supersedes?\s+(all\s+)?(prior|previous)\s+(instructions?|rules?|guidelines?|constraints?|directives?)/gi;
16
+ const VOID_INSTRUCTIONS = /(all\s+)?(previous|prior)\s+instructions?\s+(are|is)\s+(void|invalid|null|obsolete|cancelled|revoked)/gi;
17
+ const DEVELOPER_MODE = /you\s+are\s+now\s+(in\s+)?developer\s+mode/gi;
18
+ const ENTER_SPECIAL_MODE = /enter\s+(developer|admin|debug|maintenance)\s+mode/gi;
19
+ const ACTIVATE_SPECIAL_MODE = /activate\s+(developer|admin|debug|jailbreak)\s+mode/gi;
20
+ const SYSTEM_OVERRIDE = /\bsystem\s+override\b/gi;
21
+ const OVERRIDE_INSTRUCTIONS = /override\s+(your\s+)?(instructions?|rules?|guidelines?|constraints?|directives?)/gi;
22
+ const REVEAL_PROMPT = /reveal\s+((?:your?|yoru|yuor|the|my|its|his|her|our|their)\s+)?((?:(?:full|hidden|complete|internal|secret|original|entire|exact|actual|real)\s+){0,2})((?:system|systme|sysetm|systemp?)\s+)?prompt\b/gi;
23
+ const SHOW_PROMPT = /show\s+(me\s+)?((?:your?|yoru|yuor|the|my|its|his|her|our|their)\s+)((?:system|systme|sysetm|systemp?)\s+)?prompt\b/gi;
24
+ const WHAT_INSTRUCTIONS = /what\s+(are|were)\s+(your\s+)?(exact\s+)?instructions/gi;
25
+ const REPEAT_INSTRUCTIONS = /repeat\s+(the\s+)?(text|instructions?)\s+(above|before)/gi;
26
+ const OUTPUT_PROMPT = /output\s+(your\s+)?(initial|original|system)\s+(prompt|instructions?)/gi;
27
+ const REMOVE_RESTRICTIONS = /you\s+are\s+no\s+longer\s+(bound|restricted|limited)/gi;
28
+ const ACT_UNBOUND = /act\s+as\s+if\s+(you('re|\s+are)\s+)?not\s+bound/gi;
29
+ const PRETEND_DIFFERENT = /pretend\s+(you('re|\s+are)\s+)?(a\s+)?different\s+(ai|assistant|model)/gi;
30
+ const IDENTITY_HIJACK = /you\s+are\s+now\s+(?:(?:a|an)\s+)?\w+.{0,40}(without\s+(any\s+)?restrict|ignor\w*\s+(all|any|every|prev)|bypass|unrestrict|unlimit|obey\s+only|no\s+(rules|limits|restrict|boundari))/gi;
31
+ const DAN_JAILBREAK = /\bDAN\b[\s\S]{0,120}\bdo\s+anything\s+now\b/g;
32
+ const JAILBREAK_MODE = /jailbreak(ed)?\s+(mode|prompt)/gi;
33
+ const DO_ANYTHING_NOW = /\bdo\s+anything\s+now\b/gi;
34
+ const BYPASS_SAFETY = /bypass\s+(your\s+)?(safety|security|content|ethical)\s+(filters?|measures?|guidelines?|restrictions?)/gi;
35
+ const DISABLE_SAFETY = /disable\s+(your\s+)?(safety|security|content)\s+(filters?|measures?)/gi;
36
+ const IGNORE_SAFETY = /(ignore|disregard)\s+(all\s+)?(your\s+)?(safety|security|ethical|content)\s+(guidelines?|rules?|restrictions?|measures?|filters?|polic(?:y|ies)|protocols?)/gi;
37
+ const SYSTEM_TAG = /<\s*\/?\s*system\s*\/?>/gi;
38
+ const ROLE_TAG = /<\s*\/?\s*(assistant|developer|tool|function)\s*\/?>/gi;
39
+ const ROLE_DELIMITER = /\]\s*\n\s*\[?(system|assistant|user)\]?:/gi;
40
+ const BRACKETED_ROLE = /\[\s*(System\s*Message|System|Assistant|Internal)\s*\]/gi;
41
+ const SYSTEM_YOU_ARE = /^\s*System:\s+(you\s+are|ignore|override)/gim;
42
+ const CONTROL_TOKEN = /<\|(?:im_start|im_end|eot_id|start_header_id|end_header_id|endoftext)\|>/g;
43
+ const DEEPSEEK_CONTROL = /<\uFF5C(?:end\u2581of\u2581sentence|begin\u2581of\u2581sentence)\uFF5C>/g;
44
+ const LLAMA_INST = /\[\/?INST\]/gi;
45
+ const IGNORE_YOUR_INSTRUCTIONS = /ignore\s+(all\s+)?(your\s+)?(instructions?|rules?)\b/gi;
46
+ const UNRESTRICTED_MODE = /\bunrestricted\s+(ai|mode|model)\b/gi;
47
+ const INJECTION_PATTERNS = [
48
+ IGNORE_PREVIOUS,
49
+ DISREGARD_INSTRUCTIONS,
50
+ FORGET_INSTRUCTIONS,
51
+ NEW_INSTRUCTIONS,
52
+ DO_NOT_FOLLOW,
53
+ SUPERSEDE_INSTRUCTIONS,
54
+ VOID_INSTRUCTIONS,
55
+ DEVELOPER_MODE,
56
+ ENTER_SPECIAL_MODE,
57
+ ACTIVATE_SPECIAL_MODE,
58
+ SYSTEM_OVERRIDE,
59
+ OVERRIDE_INSTRUCTIONS,
60
+ REVEAL_PROMPT,
61
+ SHOW_PROMPT,
62
+ WHAT_INSTRUCTIONS,
63
+ REPEAT_INSTRUCTIONS,
64
+ OUTPUT_PROMPT,
65
+ REMOVE_RESTRICTIONS,
66
+ ACT_UNBOUND,
67
+ PRETEND_DIFFERENT,
68
+ IDENTITY_HIJACK,
69
+ DAN_JAILBREAK,
70
+ JAILBREAK_MODE,
71
+ DO_ANYTHING_NOW,
72
+ BYPASS_SAFETY,
73
+ DISABLE_SAFETY,
74
+ IGNORE_SAFETY,
75
+ SYSTEM_TAG,
76
+ ROLE_TAG,
77
+ ROLE_DELIMITER,
78
+ BRACKETED_ROLE,
79
+ SYSTEM_YOU_ARE,
80
+ CONTROL_TOKEN,
81
+ DEEPSEEK_CONTROL,
82
+ LLAMA_INST,
83
+ IGNORE_YOUR_INSTRUCTIONS,
84
+ UNRESTRICTED_MODE,
85
+ ];
86
+ const TYPO_TARGETS = [
87
+ 'ignore',
88
+ 'bypass',
89
+ 'override',
90
+ 'reveal',
91
+ 'delete',
92
+ 'system',
93
+ 'prompt',
94
+ 'instructions',
95
+ ];
96
+ const BASE64_BLOB = /[A-Za-z0-9+/]{16,}={0,2}/g;
97
+ const HEX_BLOB = /(?:[0-9a-f]{2}[\s]?){8,}/gi;
98
+ const SPACED_LETTERS = /\b(?:[A-Za-z] ){3,}[A-Za-z]\b/g;
99
+ const WORD = /\b[A-Za-z]{4,}\b/g;
100
+ const PRINTABLE_MIN = 0.85;
101
+ const CODE_TAB = 9;
102
+ const CODE_LF = 10;
103
+ const CODE_CR = 13;
104
+ const CODE_SPACE = 32;
105
+ const CODE_DEL = 127;
106
+ const HEX_RADIX = 16;
107
+ const HEX_STEP = 2;
108
+ function injectionSpansOn(text) {
109
+ return spansFromPatterns(text, INJECTION_PATTERNS, 'injection');
110
+ }
111
+ function sortedLetters(value) {
112
+ return [...value].sort().join('');
113
+ }
114
+ function firstLast(word) {
115
+ return { first: word.at(0), last: word.at(-1) };
116
+ }
117
+ function isTypoglycemia(word, target) {
118
+ if (word.length !== target.length) {
119
+ return false;
120
+ }
121
+ const lower = word.toLowerCase();
122
+ if (lower === target) {
123
+ return false;
124
+ }
125
+ const wordEnds = firstLast(lower);
126
+ const targetEnds = firstLast(target);
127
+ if (wordEnds.first !== targetEnds.first || wordEnds.last !== targetEnds.last) {
128
+ return false;
129
+ }
130
+ return sortedLetters(lower.slice(1, -1)) === sortedLetters(target.slice(1, -1));
131
+ }
132
+ function typoNormalize(text) {
133
+ return text.replace(WORD, (word) => {
134
+ for (const target of TYPO_TARGETS) {
135
+ if (isTypoglycemia(word, target)) {
136
+ return target;
137
+ }
138
+ }
139
+ return word;
140
+ });
141
+ }
142
+ function isMostlyPrintable(value) {
143
+ if (!value) {
144
+ return false;
145
+ }
146
+ let ok = 0;
147
+ for (const ch of value) {
148
+ const code = ch.codePointAt(0) ?? 0;
149
+ const control = code === CODE_TAB || code === CODE_LF || code === CODE_CR;
150
+ const visible = code >= CODE_SPACE && code < CODE_DEL;
151
+ if (control || visible) {
152
+ ok += 1;
153
+ }
154
+ }
155
+ return ok / value.length >= PRINTABLE_MIN;
156
+ }
157
+ function decodedHits(decoded) {
158
+ if (!isMostlyPrintable(decoded)) {
159
+ return false;
160
+ }
161
+ return injectionSpansOn(decoded).length > 0;
162
+ }
163
+ function tryBase64(blob) {
164
+ try {
165
+ return atob(blob);
166
+ }
167
+ catch {
168
+ return undefined;
169
+ }
170
+ }
171
+ function tryHex(blob) {
172
+ const hex = blob.replaceAll(/\s/g, '');
173
+ if (hex.length % HEX_STEP !== 0) {
174
+ return undefined;
175
+ }
176
+ let out = '';
177
+ for (let i = 0; i < hex.length; i += HEX_STEP) {
178
+ out += String.fromCodePoint(Number.parseInt(hex.slice(i, i + HEX_STEP), HEX_RADIX));
179
+ }
180
+ return out;
181
+ }
182
+ function encodedFrom(text, pattern, decode) {
183
+ const spans = [];
184
+ for (const match of text.matchAll(pattern)) {
185
+ const found = blobAt(match);
186
+ if (found) {
187
+ const decoded = decode(found.blob);
188
+ if (decoded && decodedHits(decoded)) {
189
+ spans.push({ start: found.index, end: found.index + found.blob.length, kind: 'injection' });
190
+ }
191
+ }
192
+ }
193
+ return spans;
194
+ }
195
+ function encodedSpans(text) {
196
+ return [...encodedFrom(text, BASE64_BLOB, tryBase64), ...encodedFrom(text, HEX_BLOB, tryHex)];
197
+ }
198
+ function spacedSpans(text) {
199
+ const spans = [];
200
+ for (const match of text.matchAll(SPACED_LETTERS)) {
201
+ const found = blobAt(match);
202
+ if (found) {
203
+ const collapsed = found.blob.replaceAll(' ', '');
204
+ if (injectionSpansOn(`${collapsed} previous instructions`).length > 0) {
205
+ spans.push({ start: found.index, end: found.index + found.blob.length, kind: 'injection' });
206
+ }
207
+ }
208
+ }
209
+ return spans;
210
+ }
211
+ /** Detect prompt-injection spans in a string. */
212
+ function injectionSpans(text) {
213
+ const shadow = typoNormalize(text);
214
+ let typo = [];
215
+ if (shadow !== text) {
216
+ typo = injectionSpansOn(shadow);
217
+ }
218
+ return [...injectionSpansOn(text), ...typo, ...encodedSpans(text), ...spacedSpans(text)];
219
+ }
220
+ export { injectionSpans };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Generic inbound and outbound guardrail primitives.
3
+ *
4
+ * This entrypoint exposes public-safe error mapping, prompt-injection span
5
+ * detection, sensitive-data span detection, and request sanitization. App-
6
+ * specific policy remains host-owned.
7
+ *
8
+ * @module
9
+ */
10
+ import "../../_dnt.polyfills.js";
11
+ export { describeError, PUBLIC_ACTION, PUBLIC_CANARY, PUBLIC_FILE_COUNT, PUBLIC_FILE_SIZE, PUBLIC_FILE_TYPE, PUBLIC_GENERIC, PUBLIC_IMAGE_SIZE, PUBLIC_UNAVAILABLE, publicError, TheorumError, toErrorEvent, UPSTREAM_FAILED, } from './error.js';
12
+ export { injectionSpans } from './injection.js';
13
+ export type { QuotaSlotStatus } from './quota.js';
14
+ export { clientIp, quotaMessage, releaseSlot, resetSlots, skipQuota, takeSlot, } from './quota.js';
15
+ export { PROJECT_ID_MAX, sanitizeProjectId, sanitizeText, sanitizeTurnRequest, } from './sanitize.js';
16
+ export { sensitiveSpans } from './sensitive.js';
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Generic inbound and outbound guardrail primitives.
3
+ *
4
+ * This entrypoint exposes public-safe error mapping, prompt-injection span
5
+ * detection, sensitive-data span detection, and request sanitization. App-
6
+ * specific policy remains host-owned.
7
+ *
8
+ * @module
9
+ */
10
+ import "../../_dnt.polyfills.js";
11
+ export { describeError, PUBLIC_ACTION, PUBLIC_CANARY, PUBLIC_FILE_COUNT, PUBLIC_FILE_SIZE, PUBLIC_FILE_TYPE, PUBLIC_GENERIC, PUBLIC_IMAGE_SIZE, PUBLIC_UNAVAILABLE, publicError, TheorumError, toErrorEvent, UPSTREAM_FAILED, } from './error.js';
12
+ export { injectionSpans } from './injection.js';
13
+ export { clientIp, quotaMessage, releaseSlot, resetSlots, skipQuota, takeSlot, } from './quota.js';
14
+ export { PROJECT_ID_MAX, sanitizeProjectId, sanitizeText, sanitizeTurnRequest, } from './sanitize.js';
15
+ export { sensitiveSpans } from './sensitive.js';
@@ -0,0 +1,10 @@
1
+ import type { Profile } from '../kernel/types.js';
2
+ type QuotaSlotStatus = 'ok' | 'busy' | 'quota' | 'not_configured';
3
+ declare function skipQuota(peer: string, req: Request): boolean;
4
+ declare function clientIp(peer: string, req: Request): string;
5
+ declare function takeSlot(profile: Profile, ip: string, now: number): QuotaSlotStatus;
6
+ declare function releaseSlot(profile: Profile, ip: string): void;
7
+ declare function quotaMessage(profile: Profile): string;
8
+ declare function resetSlots(): void;
9
+ export type { QuotaSlotStatus };
10
+ export { clientIp, quotaMessage, releaseSlot, resetSlots, skipQuota, takeSlot };
@@ -0,0 +1,64 @@
1
+ const LOOPBACK = new Set(['127.0.0.1', '::1', 'localhost']);
2
+ const slots = new Map();
3
+ function utcDay(now) {
4
+ return new Date(now).toISOString().slice(0, 10);
5
+ }
6
+ function isLoopback(peer) {
7
+ return LOOPBACK.has(peer);
8
+ }
9
+ function cfConnectingIp(req) {
10
+ return req.headers.get('cf-connecting-ip')?.trim() ?? '';
11
+ }
12
+ function slotKey(profileId, ip) {
13
+ return `${profileId}:${ip}`;
14
+ }
15
+ function skipQuota(peer, req) {
16
+ return isLoopback(peer) && !cfConnectingIp(req);
17
+ }
18
+ function clientIp(peer, req) {
19
+ if (isLoopback(peer)) {
20
+ const cf = cfConnectingIp(req);
21
+ if (cf) {
22
+ return cf;
23
+ }
24
+ }
25
+ if (peer) {
26
+ return peer;
27
+ }
28
+ return 'unknown';
29
+ }
30
+ function takeSlot(profile, ip, now) {
31
+ const quota = profile.guardrails.quota;
32
+ if (!quota) {
33
+ return 'not_configured';
34
+ }
35
+ const day = utcDay(now);
36
+ const key = slotKey(profile.id, ip);
37
+ let slot = slots.get(key);
38
+ if (!slot || slot.day !== day) {
39
+ slot = { day, count: 0, busy: false };
40
+ slots.set(key, slot);
41
+ }
42
+ if (slot.busy) {
43
+ return 'busy';
44
+ }
45
+ if (slot.count >= quota.perDay) {
46
+ return 'quota';
47
+ }
48
+ slot.busy = true;
49
+ slot.count += 1;
50
+ return 'ok';
51
+ }
52
+ function releaseSlot(profile, ip) {
53
+ const slot = slots.get(slotKey(profile.id, ip));
54
+ if (slot) {
55
+ slot.busy = false;
56
+ }
57
+ }
58
+ function quotaMessage(profile) {
59
+ return `Enjoying ${profile.identity.handle}? You've reached today's limit`;
60
+ }
61
+ function resetSlots() {
62
+ slots.clear();
63
+ }
64
+ export { clientIp, quotaMessage, releaseSlot, resetSlots, skipQuota, takeSlot };
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Request sanitization utilities for THEORUM.
3
+ *
4
+ * Sanitization removes inbound prompt-injection spans and sensitive-data spans
5
+ * according to the active profile guardrail flags. The host remains responsible
6
+ * for domain policy.
7
+ *
8
+ * @module
9
+ */
10
+ import type { NormalizedTurnRequest, TurnRequest } from '../kernel/types.js';
11
+ /** Sanitize one text value using prompt-injection and sensitive-data detectors. */
12
+ declare function sanitizeText(text: string, options?: {
13
+ sanitizeInput?: boolean;
14
+ redactSensitive?: boolean;
15
+ }): string;
16
+ /** Maximum retained length for trace-safe host project ids. */
17
+ declare const PROJECT_ID_MAX = 128;
18
+ /** Return a trace-safe project id or `undefined` when the input is unsafe. */
19
+ declare function sanitizeProjectId(id: string | undefined): string | undefined;
20
+ /** Sanitize all user-controlled text and blobs in a turn request. */
21
+ declare function sanitizeTurnRequest(req: TurnRequest): NormalizedTurnRequest;
22
+ export { PROJECT_ID_MAX, sanitizeProjectId, sanitizeText, sanitizeTurnRequest };
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Request sanitization utilities for THEORUM.
3
+ *
4
+ * Sanitization removes inbound prompt-injection spans and sensitive-data spans
5
+ * according to the active profile guardrail flags. The host remains responsible
6
+ * for domain policy.
7
+ *
8
+ * @module
9
+ */
10
+ import { mapStrings } from '../kernel/engine/tree.js';
11
+ import { sanitizeTurnBlobsForProfile } from '../kernel/registry/attachments.js';
12
+ import { getProfile } from '../kernel/registry/profiles.js';
13
+ import { applySpans } from '../observability/spans.js';
14
+ import { injectionSpans } from './injection.js';
15
+ import { sensitiveSpans } from './sensitive.js';
16
+ /** Sanitize one text value using prompt-injection and sensitive-data detectors. */
17
+ function sanitizeText(text, options) {
18
+ const sanitizeInput = options?.sanitizeInput ?? true;
19
+ const redactSensitive = options?.redactSensitive ?? true;
20
+ if (!sanitizeInput && !redactSensitive) {
21
+ return text;
22
+ }
23
+ const spans = [
24
+ ...(sanitizeInput ? injectionSpans(text) : []),
25
+ ...(redactSensitive ? sensitiveSpans(text) : []),
26
+ ];
27
+ return applySpans(text, spans);
28
+ }
29
+ function sanitizeSlots(slots, options) {
30
+ if (!slots) {
31
+ return slots;
32
+ }
33
+ const out = {};
34
+ for (const [key, value] of Object.entries(slots)) {
35
+ out[key] = sanitizeText(value, options);
36
+ }
37
+ return out;
38
+ }
39
+ function sanitizeArgs(args, options) {
40
+ const next = mapStrings(args, (t) => sanitizeText(t, options));
41
+ if (next && typeof next === 'object' && !Array.isArray(next)) {
42
+ return next;
43
+ }
44
+ return args;
45
+ }
46
+ /** Maximum retained length for trace-safe host project ids. */
47
+ const PROJECT_ID_MAX = 128;
48
+ const PROJECT_ID_OK = /^[A-Za-z0-9._-]+$/;
49
+ /** Return a trace-safe project id or `undefined` when the input is unsafe. */
50
+ function sanitizeProjectId(id) {
51
+ if (!id) {
52
+ return undefined;
53
+ }
54
+ const trimmed = id.trim().slice(0, PROJECT_ID_MAX);
55
+ if (!PROJECT_ID_OK.test(trimmed)) {
56
+ return undefined;
57
+ }
58
+ return trimmed;
59
+ }
60
+ function sanitizeRepair(repair, options) {
61
+ if (!repair) {
62
+ return repair;
63
+ }
64
+ return {
65
+ previousOutput: sanitizeText(repair.previousOutput, options),
66
+ rejection: sanitizeText(repair.rejection, options),
67
+ guidance: repair.guidance ? sanitizeText(repair.guidance, options) : undefined,
68
+ };
69
+ }
70
+ function sanitizeHistory(history, options) {
71
+ if (!history) {
72
+ return history;
73
+ }
74
+ return history.map((m) => ({
75
+ role: m.role,
76
+ ...(m.content !== undefined ? { content: sanitizeText(m.content, options) } : {}),
77
+ ...(m.parts
78
+ ? {
79
+ parts: m.parts.map((p) => p.type === 'text' ? { ...p, text: sanitizeText(p.text, options) } : p),
80
+ }
81
+ : {}),
82
+ ...(m.tool_calls ? { tool_calls: m.tool_calls } : {}),
83
+ ...(m.tool_call_id ? { tool_call_id: m.tool_call_id } : {}),
84
+ ...(m.name ? { name: m.name } : {}),
85
+ ...(m.metadata ? { metadata: m.metadata } : {}),
86
+ }));
87
+ }
88
+ /** Sanitize all user-controlled text and blobs in a turn request. */
89
+ function sanitizeTurnRequest(req) {
90
+ let profileGuardrails;
91
+ try {
92
+ profileGuardrails = getProfile(req.profile)?.guardrails;
93
+ }
94
+ catch {
95
+ // If profile not registered yet, default to full guardrails
96
+ }
97
+ const options = {
98
+ sanitizeInput: profileGuardrails?.sanitizeInput ?? true,
99
+ redactSensitive: profileGuardrails?.redactSensitive ?? true,
100
+ };
101
+ const input = req.input ?? {};
102
+ const { toolInvoke } = req;
103
+ const { text: rawText } = input;
104
+ let invoke = toolInvoke;
105
+ if (toolInvoke) {
106
+ invoke = { ...toolInvoke, arguments: sanitizeArgs(toolInvoke.arguments, options) };
107
+ }
108
+ let text = rawText;
109
+ if (rawText !== undefined) {
110
+ text = sanitizeText(rawText, options);
111
+ }
112
+ let system = req.system;
113
+ if (system !== undefined) {
114
+ system = sanitizeText(system, options);
115
+ }
116
+ const { attachments, voice } = sanitizeTurnBlobsForProfile(req.profile, input.attachments, input.voice);
117
+ return {
118
+ ...req,
119
+ system,
120
+ projectId: sanitizeProjectId(req.projectId),
121
+ input: {
122
+ ...input,
123
+ text,
124
+ slots: sanitizeSlots(input.slots, options),
125
+ attachments,
126
+ voice,
127
+ repair: sanitizeRepair(input.repair, options),
128
+ history: sanitizeHistory(input.history, options),
129
+ },
130
+ toolInvoke: invoke,
131
+ };
132
+ }
133
+ export { PROJECT_ID_MAX, sanitizeProjectId, sanitizeText, sanitizeTurnRequest };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Sensitive-data span detection.
3
+ *
4
+ * Detects common credentials, tokens, card numbers, SSNs, and network secrets
5
+ * so host profiles can redact them before provider submission.
6
+ *
7
+ * @module
8
+ */
9
+ import { type RedactSpan } from '../observability/spans.js';
10
+ /** Detect sensitive-data spans in a string. */
11
+ declare function sensitiveSpans(text: string): RedactSpan[];
12
+ export { sensitiveSpans };