@sponsio/sdk 0.1.0-alpha.3

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 (113) hide show
  1. package/contracts/capability/credentials.yaml +188 -0
  2. package/contracts/capability/database.yaml +141 -0
  3. package/contracts/capability/filesystem-strict.yaml +101 -0
  4. package/contracts/capability/filesystem.yaml +239 -0
  5. package/contracts/capability/self-modify.yaml +152 -0
  6. package/contracts/capability/shell.yaml +246 -0
  7. package/contracts/capability/subagent.yaml +184 -0
  8. package/contracts/core/llm_safety.yaml +130 -0
  9. package/contracts/core/runaway.yaml +43 -0
  10. package/contracts/core/universal.yaml +34 -0
  11. package/contracts/incident/claude-code-secret-bypass.yaml +197 -0
  12. package/contracts/incident/cursor-railway-wipe.yaml +164 -0
  13. package/contracts/incident/mcp-composition.yaml +418 -0
  14. package/contracts/incident/openclaw.yaml +500 -0
  15. package/contracts/incident/subagent-escape.yaml +177 -0
  16. package/contracts/premium/.gitkeep +7 -0
  17. package/dist/contract.d.ts +59 -0
  18. package/dist/contract.d.ts.map +1 -0
  19. package/dist/contract.js +97 -0
  20. package/dist/contract.js.map +1 -0
  21. package/dist/core/config-loader.d.ts +90 -0
  22. package/dist/core/config-loader.d.ts.map +1 -0
  23. package/dist/core/config-loader.js +530 -0
  24. package/dist/core/config-loader.js.map +1 -0
  25. package/dist/core/evaluator.d.ts +15 -0
  26. package/dist/core/evaluator.d.ts.map +1 -0
  27. package/dist/core/evaluator.js +87 -0
  28. package/dist/core/evaluator.js.map +1 -0
  29. package/dist/core/formula.d.ts +103 -0
  30. package/dist/core/formula.d.ts.map +1 -0
  31. package/dist/core/formula.js +167 -0
  32. package/dist/core/formula.js.map +1 -0
  33. package/dist/core/grounding.d.ts +43 -0
  34. package/dist/core/grounding.d.ts.map +1 -0
  35. package/dist/core/grounding.js +269 -0
  36. package/dist/core/grounding.js.map +1 -0
  37. package/dist/core/nl-parser.d.ts +12 -0
  38. package/dist/core/nl-parser.d.ts.map +1 -0
  39. package/dist/core/nl-parser.js +152 -0
  40. package/dist/core/nl-parser.js.map +1 -0
  41. package/dist/core/pack-loader.d.ts +15 -0
  42. package/dist/core/pack-loader.d.ts.map +1 -0
  43. package/dist/core/pack-loader.js +220 -0
  44. package/dist/core/pack-loader.js.map +1 -0
  45. package/dist/core/parser.d.ts +19 -0
  46. package/dist/core/parser.d.ts.map +1 -0
  47. package/dist/core/parser.js +235 -0
  48. package/dist/core/parser.js.map +1 -0
  49. package/dist/core/pattern-factory.d.ts +38 -0
  50. package/dist/core/pattern-factory.d.ts.map +1 -0
  51. package/dist/core/pattern-factory.js +222 -0
  52. package/dist/core/pattern-factory.js.map +1 -0
  53. package/dist/core/patterns.d.ts +67 -0
  54. package/dist/core/patterns.d.ts.map +1 -0
  55. package/dist/core/patterns.js +585 -0
  56. package/dist/core/patterns.js.map +1 -0
  57. package/dist/core/session-log.d.ts +91 -0
  58. package/dist/core/session-log.d.ts.map +1 -0
  59. package/dist/core/session-log.js +196 -0
  60. package/dist/core/session-log.js.map +1 -0
  61. package/dist/core/spans.d.ts +92 -0
  62. package/dist/core/spans.d.ts.map +1 -0
  63. package/dist/core/spans.js +148 -0
  64. package/dist/core/spans.js.map +1 -0
  65. package/dist/core/sto.d.ts +120 -0
  66. package/dist/core/sto.d.ts.map +1 -0
  67. package/dist/core/sto.js +147 -0
  68. package/dist/core/sto.js.map +1 -0
  69. package/dist/index.d.ts +267 -0
  70. package/dist/index.d.ts.map +1 -0
  71. package/dist/index.js +540 -0
  72. package/dist/index.js.map +1 -0
  73. package/dist/integrations/claude-agent.d.ts +29 -0
  74. package/dist/integrations/claude-agent.d.ts.map +1 -0
  75. package/dist/integrations/claude-agent.js +40 -0
  76. package/dist/integrations/claude-agent.js.map +1 -0
  77. package/dist/integrations/google-adk.d.ts +27 -0
  78. package/dist/integrations/google-adk.d.ts.map +1 -0
  79. package/dist/integrations/google-adk.js +81 -0
  80. package/dist/integrations/google-adk.js.map +1 -0
  81. package/dist/integrations/langchain.d.ts +26 -0
  82. package/dist/integrations/langchain.d.ts.map +1 -0
  83. package/dist/integrations/langchain.js +74 -0
  84. package/dist/integrations/langchain.js.map +1 -0
  85. package/dist/integrations/openai-agents.d.ts +45 -0
  86. package/dist/integrations/openai-agents.d.ts.map +1 -0
  87. package/dist/integrations/openai-agents.js +81 -0
  88. package/dist/integrations/openai-agents.js.map +1 -0
  89. package/dist/integrations/openai.d.ts +24 -0
  90. package/dist/integrations/openai.d.ts.map +1 -0
  91. package/dist/integrations/openai.js +77 -0
  92. package/dist/integrations/openai.js.map +1 -0
  93. package/dist/integrations/vercel-ai.d.ts +38 -0
  94. package/dist/integrations/vercel-ai.d.ts.map +1 -0
  95. package/dist/integrations/vercel-ai.js +107 -0
  96. package/dist/integrations/vercel-ai.js.map +1 -0
  97. package/dist/render/components.d.ts +23 -0
  98. package/dist/render/components.d.ts.map +1 -0
  99. package/dist/render/components.js +133 -0
  100. package/dist/render/components.js.map +1 -0
  101. package/dist/render/derive.d.ts +23 -0
  102. package/dist/render/derive.d.ts.map +1 -0
  103. package/dist/render/derive.js +92 -0
  104. package/dist/render/derive.js.map +1 -0
  105. package/dist/render/session-view.d.ts +19 -0
  106. package/dist/render/session-view.d.ts.map +1 -0
  107. package/dist/render/session-view.js +236 -0
  108. package/dist/render/session-view.js.map +1 -0
  109. package/dist/render/tokens.d.ts +44 -0
  110. package/dist/render/tokens.d.ts.map +1 -0
  111. package/dist/render/tokens.js +72 -0
  112. package/dist/render/tokens.js.map +1 -0
  113. package/package.json +83 -0
package/dist/index.js ADDED
@@ -0,0 +1,540 @@
1
+ /**
2
+ * @sponsio/sdk — Runtime contract enforcement for LLM agents.
3
+ *
4
+ * Native TypeScript implementation. < 50KB bundle, zero cold start,
5
+ * Edge/Serverless compatible.
6
+ *
7
+ * Usage:
8
+ * import { Sponsio } from "@sponsio/sdk"
9
+ *
10
+ * // Inline contracts:
11
+ * const guard = new Sponsio({
12
+ * agentId: "refund_bot",
13
+ * contracts: ["tool `check_policy` must precede `issue_refund`"]
14
+ * })
15
+ *
16
+ * // Or loaded from a shared sponsio.yaml:
17
+ * const guard = new Sponsio({ config: "sponsio.yaml", agentId: "refund_bot" })
18
+ *
19
+ * const result = guard.guardBefore("issue_refund", { orderId: "#123" })
20
+ * if (result.blocked) { ... }
21
+ */
22
+ import { evaluate } from "./core/evaluator.js";
23
+ import { groundEvent, newGroundingState, collectContentAtoms, } from "./core/grounding.js";
24
+ import { parseNl } from "./core/nl-parser.js";
25
+ import { loadSponsoConfig, } from "./core/config-loader.js";
26
+ import { SessionLogger } from "./core/session-log.js";
27
+ import { ContractCheckSpan, EnforcementSpan, GuaranteeSpan, SpanCollector, } from "./core/spans.js";
28
+ import { renderSession } from "./render/session-view.js";
29
+ // Re-exports
30
+ export { evaluate } from "./core/evaluator.js";
31
+ export * from "./core/formula.js";
32
+ export * from "./core/patterns.js";
33
+ export { parseNl } from "./core/nl-parser.js";
34
+ export { parseRepr, ParseError } from "./core/parser.js";
35
+ export { groundEvent, newGroundingState, collectContentAtoms, } from "./core/grounding.js";
36
+ export { loadSponsoConfig } from "./core/config-loader.js";
37
+ export { SessionLogger, rotateSessions } from "./core/session-log.js";
38
+ export { contract, ContractBuilder } from "./contract.js";
39
+ export { createJudge, LlmJudgeEvaluator, ToneEvaluator, RelevanceEvaluator, SemanticPiiFreeEvaluator, HallucinationFreeEvaluator, ScopeRespectEvaluator, MetricIntegrityEvaluator, InjectionFreeEvaluator, parseScore, } from "./core/sto.js";
40
+ /**
41
+ * Best-effort accessor for the agent-facing line. Prefers the
42
+ * structured ``agentMsg`` field when populated; falls back to
43
+ * ``message`` for adapters that haven't migrated yet. Mirrors the
44
+ * Python ``select_agent_message`` helper.
45
+ */
46
+ export function selectAgentMessage(violations, fallback = "Contract violation") {
47
+ for (const v of violations) {
48
+ if (v.agentMsg && v.agentMsg.length > 0) {
49
+ return v.agentMsg;
50
+ }
51
+ }
52
+ if (violations.length > 0) {
53
+ return violations[0].message;
54
+ }
55
+ return fallback;
56
+ }
57
+ export class Sponsio {
58
+ agentId;
59
+ mode;
60
+ _contracts;
61
+ _stoContracts;
62
+ _judge;
63
+ _judgeFallback;
64
+ _stoContext;
65
+ _trace;
66
+ _state;
67
+ _contentAtoms;
68
+ _violations;
69
+ _logger;
70
+ _turnSpans = [];
71
+ constructor(options = {}) {
72
+ this.agentId = options.agentId ?? "agent";
73
+ this._trace = [];
74
+ this._state = newGroundingState();
75
+ this._violations = [];
76
+ this._contracts = [];
77
+ this._stoContracts = [];
78
+ this._judge = null;
79
+ this._judgeFallback = "allow";
80
+ this._stoContext = {};
81
+ // ── Gather contracts + yaml-derived settings ────────────────────
82
+ let yamlMode;
83
+ let yamlSkipped = [];
84
+ let yamlJudge;
85
+ let yamlStoSpecs = [];
86
+ const sources = [];
87
+ if (options.config) {
88
+ const loaded = loadSponsoConfig(options.config, this.agentId);
89
+ for (const c of loaded.contracts)
90
+ sources.push(c);
91
+ yamlMode = loaded.mode;
92
+ yamlSkipped = loaded.skipped;
93
+ yamlJudge = loaded.judge;
94
+ yamlStoSpecs = loaded.stoSpecs;
95
+ }
96
+ for (const c of options.contracts ?? [])
97
+ sources.push(c);
98
+ // ── Resolve mode: env > ctor > yaml > default ────────────────────
99
+ this.mode = resolveMode(options.mode, yamlMode);
100
+ // ── Parse NL strings into det formulas ───────────────────────────
101
+ for (const c of sources) {
102
+ if (typeof c === "string") {
103
+ const parsed = parseNl(c);
104
+ if (parsed) {
105
+ this._contracts.push(parsed);
106
+ }
107
+ else {
108
+ console.warn(`[sponsio] Could not parse: "${c}"`);
109
+ }
110
+ }
111
+ else {
112
+ this._contracts.push(c);
113
+ }
114
+ }
115
+ // ── Sto pipeline is a Sponsio Cloud feature ──────────────────────
116
+ // The managed LLM-judge catalog (`tone` / `relevance` / `llm_judge`
117
+ // …) and the judge client live in `sponsio[cloud]`. The OSS
118
+ // engine logs-and-skips any yaml sto contracts and any inline
119
+ // `judge:` option, never constructs an evaluator, never contacts
120
+ // an LLM. The API surface (`guardAfter`, `setContext`, `judge`
121
+ // ctor option) is preserved so a shared yaml between Python+Cloud
122
+ // and TS+OSS doesn't refuse to load.
123
+ this._judge = null;
124
+ this._judgeFallback = "allow";
125
+ for (const spec of yamlStoSpecs) {
126
+ yamlSkipped.push({
127
+ kind: "sto-contract",
128
+ detail: `${spec.desc} (sto pipeline is a Sponsio Cloud feature)`,
129
+ });
130
+ }
131
+ if (options.judge) {
132
+ yamlSkipped.push({
133
+ kind: "sto-contract",
134
+ detail: "`judge:` option ignored (sto pipeline is a Sponsio Cloud feature; install sponsio[cloud])",
135
+ });
136
+ }
137
+ // Reference yamlJudge so unused-var lints don't fire — the field
138
+ // is parsed by the loader for shared-yaml compatibility but the
139
+ // OSS engine never builds a judge from it.
140
+ void yamlJudge;
141
+ // ── Warn once about yaml features the TS runtime can't handle ───
142
+ warnOnceAboutSkipped(yamlSkipped);
143
+ this._contentAtoms = collectContentAtoms(this._contracts.map((c) => c.formula));
144
+ // ── Session log ─────────────────────────────────────────────────
145
+ const wantLog = options.sessionLog ?? true;
146
+ this._logger = wantLog
147
+ ? new SessionLogger(this.agentId, { baseDir: options.sessionLogBaseDir })
148
+ : null;
149
+ }
150
+ /**
151
+ * Check a tool call against contracts before execution.
152
+ *
153
+ * On block, **all** mutations made by ``groundEvent`` are rolled back via a
154
+ * pre-call snapshot. Previously only ``callCounts[toolName]`` was undone,
155
+ * leaving ``consecutiveCounts``, ``lastTool``, ``callWithCounts``,
156
+ * ``tokenCounts``, and ``delegationDepth`` in a stale state; subsequent
157
+ * guards saw counts as if the blocked call had executed.
158
+ *
159
+ * In **observe mode**, violations are logged to the session JSONL
160
+ * but not reported as blocks — the method always returns ``allowed: true``.
161
+ * In **enforce mode**, the first violation blocks the call.
162
+ */
163
+ /** Read the human-readable descs of all compiled contracts (det only). */
164
+ contractDescs() {
165
+ return this._contracts.map((c) => c.desc);
166
+ }
167
+ guardBefore(toolName, args = {}) {
168
+ const event = { tool: toolName, args };
169
+ const snapshot = this._snapshotState();
170
+ const valuation = groundEvent(event, this._state, this._contentAtoms);
171
+ this._trace.push(valuation);
172
+ // Build a span tree for this turn (mirrors Python's RuntimeMonitor).
173
+ const collector = new SpanCollector(this.agentId, toolName);
174
+ // Stash args on the root for the renderer (it shows them in the trace).
175
+ collector.rootSpan().attributes.args = args;
176
+ const violations = [];
177
+ const violatedDescs = [];
178
+ const detViolations = [];
179
+ for (const contract of this._contracts) {
180
+ const checkSpan = new ContractCheckSpan(contract.desc, "hard");
181
+ collector.push(checkSpan);
182
+ const result = evaluate(contract.formula, this._trace);
183
+ // The TS evaluator is currently a single-pass deterministic
184
+ // check; it doesn't separately track assumption vs guarantee
185
+ // sub-formulas. Synthesise a guarantee span so the renderer can
186
+ // surface failed contracts without refactoring the evaluator.
187
+ const guaranteeSpan = new GuaranteeSpan(contract.desc, result);
188
+ collector.add(guaranteeSpan, result ? "ok" : "violated");
189
+ if (!result) {
190
+ const verb = this.mode === "observe" ? "WOULD-BLOCK" : "BLOCKED";
191
+ const msg = `${verb}: ${this.agentId}.${toolName} — det constraint violated: ${contract.desc}`;
192
+ violations.push(msg);
193
+ violatedDescs.push(contract.desc);
194
+ detViolations.push({
195
+ desc: contract.desc,
196
+ message: msg,
197
+ ruleId: contract.patternName || contract.desc,
198
+ agentMsg: `The action \`${toolName}\` was rejected by policy ` +
199
+ `(${contract.patternName || contract.desc}): ${contract.desc}. ` +
200
+ `Choose a different approach.`,
201
+ });
202
+ // Nest violation + enforcement spans under the failed
203
+ // guarantee so the renderer can pick up the verdict word.
204
+ const enforce = new EnforcementSpan("DetBlock", this.mode === "enforce" ? "blocked" : "blocked");
205
+ guaranteeSpan.children.push(enforce);
206
+ enforce.finish("violated");
207
+ }
208
+ collector.pop(result ? "ok" : "violated");
209
+ }
210
+ const hasViolations = violations.length > 0;
211
+ const blocked = hasViolations && this.mode === "enforce";
212
+ this._turnSpans.push(collector.finishRoot(blocked, this._contracts.length, violations.length));
213
+ if (blocked) {
214
+ this._trace.pop();
215
+ this._state = snapshot;
216
+ this._violations.push(...violations);
217
+ this._logViolations(toolName, violations, violatedDescs, "blocked");
218
+ return {
219
+ blocked: true,
220
+ allowed: false,
221
+ message: violations[0],
222
+ violations,
223
+ detViolations,
224
+ stoViolations: [],
225
+ };
226
+ }
227
+ // Either no violations, or observe mode: allow + log.
228
+ if (hasViolations) {
229
+ // observe mode: capture for summary(), but don't roll back.
230
+ this._violations.push(...violations);
231
+ this._logViolations(toolName, violations, violatedDescs, "observed");
232
+ }
233
+ else {
234
+ // Clean allow: one "allow" record per guardBefore so
235
+ // ``sponsio report`` sees a complete turn ledger.
236
+ this._logAllow(toolName);
237
+ }
238
+ return {
239
+ blocked: false,
240
+ allowed: true,
241
+ message: "",
242
+ violations: [],
243
+ detViolations,
244
+ stoViolations: [],
245
+ };
246
+ }
247
+ /**
248
+ * Snapshot of the per-turn span trees this guard has produced since
249
+ * construction (or the last ``resetSession``). One root
250
+ * ``AgentTurnSpan`` per ``guardBefore`` call, with nested
251
+ * ``ContractCheckSpan`` / ``GuaranteeSpan`` / ``EnforcementSpan``
252
+ * children. Mirrors Python's ``RuntimeMonitor.turn_spans``.
253
+ */
254
+ turnSpans() {
255
+ return [...this._turnSpans];
256
+ }
257
+ /** Drop accumulated turn spans (used between sessions in tests). */
258
+ resetSession() {
259
+ this._turnSpans = [];
260
+ }
261
+ /**
262
+ * Render the end-of-session view to ``out`` (defaults to stderr) —
263
+ * banner, contracts armed, trace tree, verdict, perf, CTA. Mirrors
264
+ * Python's ``RuntimeMonitor.finish_session`` + ``render_session``
265
+ * pipeline. Call this once at the end of the agent's run.
266
+ */
267
+ finishSession(opts = {}) {
268
+ renderSession({
269
+ agentId: this.agentId,
270
+ mode: this.mode,
271
+ contracts: this._contracts,
272
+ turnSpans: this._turnSpans,
273
+ ...opts,
274
+ });
275
+ }
276
+ /** Deep-copy the grounding state so it can be restored on a blocked call. */
277
+ _snapshotState() {
278
+ return {
279
+ callCounts: { ...this._state.callCounts },
280
+ callWithCounts: { ...this._state.callWithCounts },
281
+ lastTool: this._state.lastTool,
282
+ consecutiveCounts: { ...this._state.consecutiveCounts },
283
+ tokenCounts: { ...this._state.tokenCounts },
284
+ delegationDepth: this._state.delegationDepth,
285
+ };
286
+ }
287
+ _logViolations(toolName, messages, descs, action) {
288
+ if (!this._logger)
289
+ return;
290
+ const ts = Date.now() / 1000;
291
+ for (let i = 0; i < messages.length; i++) {
292
+ this._logger.log({
293
+ ts,
294
+ agent_id: this.agentId,
295
+ action,
296
+ pipeline: "det",
297
+ constraint: descs[i] ?? `${this.agentId}.${toolName}`,
298
+ result: { action, message: messages[i] },
299
+ });
300
+ }
301
+ }
302
+ _logAllow(toolName) {
303
+ if (!this._logger)
304
+ return;
305
+ this._logger.log({
306
+ ts: Date.now() / 1000,
307
+ agent_id: this.agentId,
308
+ action: "allowed",
309
+ pipeline: "det",
310
+ constraint: `${this.agentId}.${toolName}`,
311
+ result: { action: "allowed", message: "" },
312
+ });
313
+ }
314
+ /**
315
+ * Record tool output after execution and run the sto pipeline.
316
+ *
317
+ * Returns a ``CheckResult`` whose ``stoViolations`` carries any
318
+ * stochastic rule failures (``tone`` / ``llm_judge``). When no sto
319
+ * contracts are declared the method returns synchronously in
320
+ * effect (the ``Promise`` resolves on the microtask queue) and
321
+ * never contacts the judge LLM.
322
+ *
323
+ * In **observe mode** violations are logged but the method still
324
+ * reports ``allowed: true``. In **enforce mode** the first sto
325
+ * violation flips ``blocked: true`` — but the tool output has
326
+ * already executed, so the caller is responsible for routing the
327
+ * result (retry with feedback, redirect to safe, etc.).
328
+ */
329
+ async guardAfter(toolName, output = "") {
330
+ if (this._stoContracts.length === 0) {
331
+ return emptyAllow();
332
+ }
333
+ const stoViolations = [];
334
+ const flatMessages = [];
335
+ for (const sto of this._stoContracts) {
336
+ try {
337
+ const result = await sto.evaluator.evaluate({
338
+ toolName,
339
+ output,
340
+ context: this._stoContext,
341
+ });
342
+ if (result.passed) {
343
+ this._logSto(sto.desc, "allowed", result.score, result.evidence);
344
+ continue;
345
+ }
346
+ const verb = this.mode === "observe" ? "WOULD-BLOCK" : "BLOCKED";
347
+ const msg = `${verb}: ${this.agentId}.${toolName} — sto constraint ` +
348
+ `violated: ${sto.desc} (score=${result.score.toFixed(2)})`;
349
+ // Sto outcomes default to retry-style phrasing — the model
350
+ // is being asked to regenerate addressing the failed
351
+ // property, not to abandon the action altogether. retryHint
352
+ // carries the evaluator's suggestion when available.
353
+ stoViolations.push({
354
+ desc: sto.desc,
355
+ message: msg,
356
+ ruleId: sto.desc,
357
+ agentMsg: `Your output failed the \`${sto.desc}\` check ` +
358
+ `(score=${result.score.toFixed(2)}). Regenerate addressing the issue.`,
359
+ retryHint: result.evidence || undefined,
360
+ });
361
+ flatMessages.push(msg);
362
+ this._logSto(sto.desc, this.mode === "observe" ? "observed" : "blocked", result.score, result.evidence);
363
+ }
364
+ catch (err) {
365
+ const errMsg = err instanceof Error ? err.message : String(err);
366
+ const handling = this._judgeFallback;
367
+ if (handling === "skip") {
368
+ console.warn(`[sponsio] sto ${sto.desc}: judge error (${errMsg}) — skipping`);
369
+ continue;
370
+ }
371
+ const verb = this.mode === "observe" ? "WOULD-BLOCK" : "BLOCKED";
372
+ if (handling === "deny") {
373
+ const msg = `${verb}: ${this.agentId}.${toolName} — sto judge error ` +
374
+ `(${errMsg}); fallback_mode=deny`;
375
+ stoViolations.push({ desc: sto.desc, message: msg });
376
+ flatMessages.push(msg);
377
+ this._logSto(sto.desc, this.mode === "observe" ? "observed" : "blocked", undefined, `judge-error: ${errMsg}`);
378
+ }
379
+ else {
380
+ // allow (default) — log a pass so the operator can see the
381
+ // judge was exercised, but do not create a violation.
382
+ console.warn(`[sponsio] sto ${sto.desc}: judge error (${errMsg}) — allowing`);
383
+ this._logSto(sto.desc, "allowed", undefined, `judge-error-allowed: ${errMsg}`);
384
+ }
385
+ }
386
+ }
387
+ if (stoViolations.length === 0) {
388
+ return emptyAllow();
389
+ }
390
+ this._violations.push(...flatMessages);
391
+ if (this.mode === "enforce") {
392
+ return {
393
+ blocked: true,
394
+ allowed: false,
395
+ message: flatMessages[0],
396
+ violations: flatMessages,
397
+ detViolations: [],
398
+ stoViolations,
399
+ };
400
+ }
401
+ return {
402
+ blocked: false,
403
+ allowed: true,
404
+ message: "",
405
+ violations: [],
406
+ detViolations: [],
407
+ stoViolations,
408
+ };
409
+ }
410
+ _logSto(desc, action, score, evidence) {
411
+ if (!this._logger)
412
+ return;
413
+ const record = {
414
+ ts: Date.now() / 1000,
415
+ agent_id: this.agentId,
416
+ action,
417
+ pipeline: "sto",
418
+ constraint: desc,
419
+ result: {
420
+ action,
421
+ message: evidence ?? "",
422
+ },
423
+ };
424
+ if (score !== undefined) {
425
+ record.sto = evidence ? { score, evidence } : { score };
426
+ }
427
+ this._logger.log(record);
428
+ }
429
+ /**
430
+ * Reset guard state for a new session.
431
+ */
432
+ reset() {
433
+ this._trace = [];
434
+ this._state = newGroundingState();
435
+ this._violations = [];
436
+ this._stoContext = {};
437
+ this._contentAtoms = collectContentAtoms(this._contracts.map((c) => c.formula));
438
+ }
439
+ /**
440
+ * Stash per-turn context for the sto pipeline. Atoms that need
441
+ * grounding — ``relevance`` (``query``), ``hallucination_free``
442
+ * (``source``), ``scope_respect`` (``scope`` override),
443
+ * ``metric_integrity`` (``history``) — read from this snapshot on
444
+ * the next ``guardAfter`` call.
445
+ *
446
+ * Merges with any previously-set context; pass ``{ query: undefined }``
447
+ * to explicitly clear a field. ``reset()`` clears the whole snapshot.
448
+ */
449
+ setContext(ctx) {
450
+ this._stoContext = { ...this._stoContext, ...ctx };
451
+ }
452
+ /**
453
+ * Get all violations from this session.
454
+ */
455
+ get violations() {
456
+ return [...this._violations];
457
+ }
458
+ /**
459
+ * Get a summary string. Returns a formatted list of violations
460
+ * observed in this session, or ``"No violations"`` if clean.
461
+ */
462
+ summary() {
463
+ if (this._violations.length === 0)
464
+ return "No violations";
465
+ return this._violations.map((v) => `- ${v}`).join("\n");
466
+ }
467
+ /**
468
+ * Print the session summary to stdout — Python parity for
469
+ * ``guard.print_summary()``. Equivalent to
470
+ * ``console.log(guard.summary())``; exists so copy-pasted Python
471
+ * snippets compile (and so ad-hoc review in scripts reads the
472
+ * same way across both SDKs).
473
+ */
474
+ printSummary() {
475
+ console.log(this.summary());
476
+ }
477
+ }
478
+ /* -----------------------------------------------------------------
479
+ * helpers
480
+ * -----------------------------------------------------------------*/
481
+ /**
482
+ * Resolve the runtime mode with the same precedence as the Python
483
+ * SDK: ``SPONSIO_MODE`` env var wins over an explicit ctor arg so
484
+ * ops can flip enforcement in production without a code change.
485
+ */
486
+ function resolveMode(ctorMode, yamlMode) {
487
+ const envRaw = process.env.SPONSIO_MODE;
488
+ if (envRaw === "enforce" || envRaw === "observe")
489
+ return envRaw;
490
+ if (envRaw) {
491
+ console.warn(`[sponsio] ignoring unknown SPONSIO_MODE="${envRaw}" ` +
492
+ `(expected "enforce" | "observe")`);
493
+ }
494
+ if (ctorMode)
495
+ return ctorMode;
496
+ if (yamlMode)
497
+ return yamlMode;
498
+ return "observe";
499
+ }
500
+ let _skippedWarned = false;
501
+ // Note: ``resolveJudge`` / ``buildStoContract`` / ``isJudgeClient``
502
+ // helpers were removed when the sto pipeline became Sponsio Cloud-only.
503
+ // The OSS engine never constructs a judge or evaluator; yaml sto
504
+ // specs flow through the ``yamlSkipped`` warning path in the ctor.
505
+ function emptyAllow() {
506
+ return {
507
+ blocked: false,
508
+ allowed: true,
509
+ message: "",
510
+ violations: [],
511
+ detViolations: [],
512
+ stoViolations: [],
513
+ };
514
+ }
515
+ function warnOnceAboutSkipped(skipped) {
516
+ if (_skippedWarned || skipped.length === 0)
517
+ return;
518
+ _skippedWarned = true;
519
+ const packs = skipped.filter((s) => s.kind === "pack").map((s) => s.detail);
520
+ const structured = skipped.filter((s) => s.kind === "structured-contract").length;
521
+ const sto = skipped.filter((s) => s.kind === "sto-contract").length;
522
+ const unknown = skipped.filter((s) => s.kind === "unknown-contract").length;
523
+ const bits = [];
524
+ if (packs.length > 0) {
525
+ bits.push(`${packs.length} pack include(s) [${packs.join(", ")}]`);
526
+ }
527
+ if (structured > 0) {
528
+ bits.push(`${structured} structured pattern contract(s) (token_budget, loop_detection, …)`);
529
+ }
530
+ if (sto > 0) {
531
+ bits.push(`${sto} sto contract(s) (LLM-judged)`);
532
+ }
533
+ if (unknown > 0) {
534
+ bits.push(`${unknown} unrecognised contract entr${unknown === 1 ? "y" : "ies"}`);
535
+ }
536
+ console.warn("[sponsio] skipped unsupported yaml items: " +
537
+ bits.join("; ") +
538
+ ". These features are Python-only today; TS runtime will ship them in a future release.");
539
+ }
540
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,QAAQ,EAAkB,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EACL,WAAW,EACX,iBAAiB,EACjB,mBAAmB,GAGpB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC9C,OAAO,EACL,gBAAgB,GAIjB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAEL,iBAAiB,EACjB,eAAe,EACf,aAAa,EACb,aAAa,GACd,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAmBzD,aAAa;AACb,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAE/C,cAAc,mBAAmB,CAAC;AAClC,cAAc,oBAAoB,CAAC;AACnC,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EACL,WAAW,EACX,iBAAiB,EACj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EAAE,CAAC;IAC1B,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACrB,IAAI,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,qBAAqB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACrE,CAAC;IACD,IAAI,UAAU,GAAG,CAAC,EAAE,CAAC;QACnB,IAAI,CAAC,IAAI,CAAC,GAAG,UAAU,mEAAmE,CAAC,CAAC;IAC9F,CAAC;IACD,IAAI,GAAG,GAAG,CAAC,EAAE,CAAC;QACZ,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,+BAA+B,CAAC,CAAC;IACnD,CAAC;IACD,IAAI,OAAO,GAAG,CAAC,EAAE,CAAC;QAChB,IAAI,CAAC,IAAI,CAAC,GAAG,OAAO,8BAA8B,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;IACnF,CAAC;IAED,OAAO,CAAC,IAAI,CACV,4CAA4C;QAC1C,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;QACf,wFAAwF,CAC3F,CAAC;AACJ,CAAC"}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Claude Agent SDK integration — native TypeScript.
3
+ *
4
+ * Usage:
5
+ * import { Sponsio } from "@sponsio/sdk"
6
+ * import { sponsioHooks } from "@sponsio/sdk/claude-agent"
7
+ *
8
+ * const guard = new Sponsio({ contracts: [...] })
9
+ * const options = { hooks: sponsioHooks(guard) }
10
+ */
11
+ import type { Sponsio } from "../index.js";
12
+ export interface HookResult {
13
+ systemMessage?: string;
14
+ hookSpecificOutput?: {
15
+ hookEventName: string;
16
+ permissionDecision?: "allow" | "deny" | "ask";
17
+ permissionDecisionReason?: string;
18
+ additionalContext?: string;
19
+ };
20
+ }
21
+ export declare function sponsioHooks(guard: Sponsio): {
22
+ PreToolUse: {
23
+ hooks: ((input: Record<string, unknown>, _toolUseId: string | null, _context: unknown) => Promise<HookResult | Record<string, never>>)[];
24
+ }[];
25
+ PostToolUse: {
26
+ hooks: ((input: Record<string, unknown>, _toolUseId: string | null, _context: unknown) => Promise<Record<string, never>>)[];
27
+ }[];
28
+ };
29
+ //# sourceMappingURL=claude-agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude-agent.d.ts","sourceRoot":"","sources":["../../src/integrations/claude-agent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAE3C,MAAM,WAAW,UAAU;IACzB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,kBAAkB,CAAC,EAAE;QACnB,aAAa,EAAE,MAAM,CAAC;QACtB,kBAAkB,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,KAAK,CAAC;QAC9C,wBAAwB,CAAC,EAAE,MAAM,CAAC;QAClC,iBAAiB,CAAC,EAAE,MAAM,CAAC;KAC5B,CAAC;CACH;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO;;wBAEhC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,cAClB,MAAM,GAAG,IAAI,YACf,OAAO,KAChB,OAAO,CAAC,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;;;wBAuBrC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,cAClB,MAAM,GAAG,IAAI,YACf,OAAO,KAChB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;;EAWlC"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Claude Agent SDK integration — native TypeScript.
3
+ *
4
+ * Usage:
5
+ * import { Sponsio } from "@sponsio/sdk"
6
+ * import { sponsioHooks } from "@sponsio/sdk/claude-agent"
7
+ *
8
+ * const guard = new Sponsio({ contracts: [...] })
9
+ * const options = { hooks: sponsioHooks(guard) }
10
+ */
11
+ export function sponsioHooks(guard) {
12
+ async function preToolUse(input, _toolUseId, _context) {
13
+ const toolName = input.tool_name ?? "";
14
+ const toolInput = input.tool_input ?? {};
15
+ const result = guard.guardBefore(toolName, toolInput);
16
+ if (result.blocked) {
17
+ return {
18
+ systemMessage: `[Sponsio] Tool \`${toolName}\` was blocked: ${result.message}. ` +
19
+ `Please adjust your approach.`,
20
+ hookSpecificOutput: {
21
+ hookEventName: "PreToolUse",
22
+ permissionDecision: "deny",
23
+ permissionDecisionReason: `Sponsio: ${result.message}`,
24
+ },
25
+ };
26
+ }
27
+ return {};
28
+ }
29
+ async function postToolUse(input, _toolUseId, _context) {
30
+ const toolName = input.tool_name ?? "";
31
+ const toolResult = input.tool_result ?? "";
32
+ await guard.guardAfter(toolName, String(toolResult));
33
+ return {};
34
+ }
35
+ return {
36
+ PreToolUse: [{ hooks: [preToolUse] }],
37
+ PostToolUse: [{ hooks: [postToolUse] }],
38
+ };
39
+ }
40
+ //# sourceMappingURL=claude-agent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude-agent.js","sourceRoot":"","sources":["../../src/integrations/claude-agent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAcH,MAAM,UAAU,YAAY,CAAC,KAAc;IACzC,KAAK,UAAU,UAAU,CACvB,KAA8B,EAC9B,UAAyB,EACzB,QAAiB;QAEjB,MAAM,QAAQ,GAAI,KAAK,CAAC,SAAoB,IAAI,EAAE,CAAC;QACnD,MAAM,SAAS,GAAI,KAAK,CAAC,UAAsC,IAAI,EAAE,CAAC;QAEtE,MAAM,MAAM,GAAG,KAAK,CAAC,WAAW,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;QAEtD,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;YACnB,OAAO;gBACL,aAAa,EACX,oBAAoB,QAAQ,mBAAmB,MAAM,CAAC,OAAO,IAAI;oBACjE,8BAA8B;gBAChC,kBAAkB,EAAE;oBAClB,aAAa,EAAE,YAAY;oBAC3B,kBAAkB,EAAE,MAAM;oBA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