cap-shield 0.6.0__tar.gz → 0.6.2__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cap-shield
3
- Version: 0.6.0
3
+ Version: 0.6.2
4
4
  Summary: Context selection and compression for AI agents — measured, not estimated
5
5
  Project-URL: Homepage, https://cap-shield-robin.fly.dev
6
6
  Project-URL: Documentation, https://cap-shield-robin.fly.dev/docs/quickstart
@@ -70,20 +70,51 @@ svar = eskalera_om_behovs_v6(ctx, fraga, modell="openai",
70
70
  print(svar["svar"])
71
71
  ```
72
72
 
73
- Measured 2026-11-16 on LongMemEval-S, 500 questions, with `gpt-6-luna`
74
- answering: **96.6 %** correct, judged automatically (previous version
75
- 88.0 %); 98.6 % after a manual review of 10 answers, each listed in the
76
- document above. On 100 LoCoMo questions it was never tuned on, it scored
77
- the same as the previous version (80 and 81 of 100).
73
+ Measured on LongMemEval-S, 500 questions, with `gpt-6-luna` answering and
74
+ judged exactly as in the LongMemEval paper (GPT-4o as judge, the official
75
+ judge prompts): **481 of 500 correct (96.2 %)**. Our own automatic judging
76
+ of the same answers gives 96.6 % (previous helper version 88.0 %).
77
+
78
+ On 200 LoCoMo questions held out and never read during development,
79
+ v6.2 answered **170** correctly, against 148 for v6.1. The gain is on
80
+ questions about a person the conversation says nothing about: v6.2 checks
81
+ which speaker a fact belongs to before answering.
78
82
 
79
83
  Read those figures with three caveats. The rules in the helper were
80
- written against the same 500 questions. The judge is not the GPT-4o used
81
- in the LongMemEval paper, so the figures are not directly comparable to
82
- other published scores. And they depend on the answer model.
84
+ written against the same 500 LongMemEval questions. The answer model is
85
+ our own choice, so the judging is comparable with other published
86
+ LongMemEval scores but the setup is not identical. And the figures depend
87
+ on the answer model.
83
88
 
84
89
  `escalation_context()` returns the raw context, so you can also run your
85
90
  own model call on it instead of the helper.
86
91
 
92
+ ## Energy and time
93
+
94
+ A model spends energy and time on every token it reads. Measured
95
+ 2026-11-17 with the GPU's own energy counter (NVIDIA GeForce RTX 4070,
96
+ `llama3.2:1b`, idle power subtracted), 50 LongMemEval-S
97
+ questions, against the whole history (median 104 652 tokens):
98
+ **95 % less energy and 94.4 % less time** for the model to
99
+ read the context, with the selection at budget 32 000 and every
100
+ session holding the answer included in 90 % of questions.
101
+
102
+ | The model reads | Tokens (median) | Less energy | Less time | All evidence included |
103
+ |---|---:|---:|---:|---:|
104
+ | Selection, budget 32 000 | 18 248 | 95 % | 94.4 % | 90 % |
105
+ | Selection, budget 16 000 | 12 672 | 97.2 % | 96.5 % | 80 % |
106
+ | Selection, budget 8 000 | 6 158 | 98.7 % | 97.9 % | 50 % |
107
+ | Selection, budget 4 000 | 3 094 | 99.3 % | 98.5 % | 22 % |
108
+ | Selection, budget 2 000 | 1 080 | 99.7 % | 98.8 % | 14 %, 9 empty |
109
+ | Escalation context | 75 066 | 39.3 % | 37.4 % | 98 % |
110
+
111
+ Per reading of the context, on one GPU with a small model; larger models
112
+ have not been measured. A shorter history leaves less to remove. The
113
+ escalation helper reads its context at least twice per question. If the
114
+ budget is too small for the best match, the response says so in
115
+ `budget_warning` (in `context()` results: `.raw["budget_warning"]`) and
116
+ suggests a budget that fits it.
117
+
87
118
  ## What this does not do
88
119
 
89
120
  It does not call your model. `ctx.text` goes to Claude, GPT or whatever
@@ -128,8 +159,9 @@ Conflating them is the most common misunderstanding about this product.
128
159
 
129
160
  ## MCP server
130
161
 
131
- The package also contains an MCP server. Nine tools, no extra
132
- dependencies, and three of them work without an account.
162
+ The package also contains an MCP server. Fifteen tools, no extra
163
+ dependencies, and four of them work without an account
164
+ (`measure_traffic`, `list_packages`, `start_sandbox`, `verify_pass`).
133
165
 
134
166
  ```bash
135
167
  pip install cap-shield
@@ -149,8 +181,10 @@ pip install cap-shield
149
181
  }
150
182
  ```
151
183
 
152
- The `env` block is only needed for `remember` and `assemble_context`.
153
- Leave it out and `measure_traffic` and `list_packages` still work.
184
+ The `env` block is only needed for the tools that store or retrieve
185
+ memory, pack data or issue passes. Leave it out and `measure_traffic`,
186
+ `list_packages`, `start_sandbox` and `verify_pass` still work;
187
+ `start_sandbox` gives a 24-hour key for trying memory without an account.
154
188
 
155
189
  Source and docs: https://github.com/robinlidberg-dot/cap-shield-mcp
156
190
 
@@ -52,20 +52,51 @@ svar = eskalera_om_behovs_v6(ctx, fraga, modell="openai",
52
52
  print(svar["svar"])
53
53
  ```
54
54
 
55
- Measured 2026-11-16 on LongMemEval-S, 500 questions, with `gpt-6-luna`
56
- answering: **96.6 %** correct, judged automatically (previous version
57
- 88.0 %); 98.6 % after a manual review of 10 answers, each listed in the
58
- document above. On 100 LoCoMo questions it was never tuned on, it scored
59
- the same as the previous version (80 and 81 of 100).
55
+ Measured on LongMemEval-S, 500 questions, with `gpt-6-luna` answering and
56
+ judged exactly as in the LongMemEval paper (GPT-4o as judge, the official
57
+ judge prompts): **481 of 500 correct (96.2 %)**. Our own automatic judging
58
+ of the same answers gives 96.6 % (previous helper version 88.0 %).
59
+
60
+ On 200 LoCoMo questions held out and never read during development,
61
+ v6.2 answered **170** correctly, against 148 for v6.1. The gain is on
62
+ questions about a person the conversation says nothing about: v6.2 checks
63
+ which speaker a fact belongs to before answering.
60
64
 
61
65
  Read those figures with three caveats. The rules in the helper were
62
- written against the same 500 questions. The judge is not the GPT-4o used
63
- in the LongMemEval paper, so the figures are not directly comparable to
64
- other published scores. And they depend on the answer model.
66
+ written against the same 500 LongMemEval questions. The answer model is
67
+ our own choice, so the judging is comparable with other published
68
+ LongMemEval scores but the setup is not identical. And the figures depend
69
+ on the answer model.
65
70
 
66
71
  `escalation_context()` returns the raw context, so you can also run your
67
72
  own model call on it instead of the helper.
68
73
 
74
+ ## Energy and time
75
+
76
+ A model spends energy and time on every token it reads. Measured
77
+ 2026-11-17 with the GPU's own energy counter (NVIDIA GeForce RTX 4070,
78
+ `llama3.2:1b`, idle power subtracted), 50 LongMemEval-S
79
+ questions, against the whole history (median 104 652 tokens):
80
+ **95 % less energy and 94.4 % less time** for the model to
81
+ read the context, with the selection at budget 32 000 and every
82
+ session holding the answer included in 90 % of questions.
83
+
84
+ | The model reads | Tokens (median) | Less energy | Less time | All evidence included |
85
+ |---|---:|---:|---:|---:|
86
+ | Selection, budget 32 000 | 18 248 | 95 % | 94.4 % | 90 % |
87
+ | Selection, budget 16 000 | 12 672 | 97.2 % | 96.5 % | 80 % |
88
+ | Selection, budget 8 000 | 6 158 | 98.7 % | 97.9 % | 50 % |
89
+ | Selection, budget 4 000 | 3 094 | 99.3 % | 98.5 % | 22 % |
90
+ | Selection, budget 2 000 | 1 080 | 99.7 % | 98.8 % | 14 %, 9 empty |
91
+ | Escalation context | 75 066 | 39.3 % | 37.4 % | 98 % |
92
+
93
+ Per reading of the context, on one GPU with a small model; larger models
94
+ have not been measured. A shorter history leaves less to remove. The
95
+ escalation helper reads its context at least twice per question. If the
96
+ budget is too small for the best match, the response says so in
97
+ `budget_warning` (in `context()` results: `.raw["budget_warning"]`) and
98
+ suggests a budget that fits it.
99
+
69
100
  ## What this does not do
70
101
 
71
102
  It does not call your model. `ctx.text` goes to Claude, GPT or whatever
@@ -110,8 +141,9 @@ Conflating them is the most common misunderstanding about this product.
110
141
 
111
142
  ## MCP server
112
143
 
113
- The package also contains an MCP server. Nine tools, no extra
114
- dependencies, and three of them work without an account.
144
+ The package also contains an MCP server. Fifteen tools, no extra
145
+ dependencies, and four of them work without an account
146
+ (`measure_traffic`, `list_packages`, `start_sandbox`, `verify_pass`).
115
147
 
116
148
  ```bash
117
149
  pip install cap-shield
@@ -131,8 +163,10 @@ pip install cap-shield
131
163
  }
132
164
  ```
133
165
 
134
- The `env` block is only needed for `remember` and `assemble_context`.
135
- Leave it out and `measure_traffic` and `list_packages` still work.
166
+ The `env` block is only needed for the tools that store or retrieve
167
+ memory, pack data or issue passes. Leave it out and `measure_traffic`,
168
+ `list_packages`, `start_sandbox` and `verify_pass` still work;
169
+ `start_sandbox` gives a 24-hour key for trying memory without an account.
136
170
 
137
171
  Source and docs: https://github.com/robinlidberg-dot/cap-shield-mcp
138
172
 
@@ -770,6 +770,70 @@ def eskalera_om_behovs_v2(cap_svar: dict, fraga: str, modell: str = "claude",
770
770
  # ---------------------------------------------------------------------------
771
771
 
772
772
 
773
+ # ----------------------------------------------------------------------
774
+ # Steg 123: RÄTT PERSON.
775
+ #
776
+ # I samtal mellan två personer svarade modellen ofta med den ANDRA
777
+ # personens upplevelse: frågan gällde Calvins workshop, men det var Dave
778
+ # som blivit uttagen. Raderna i kontexten börjar med talarens namn, så
779
+ # informationen fanns -- modellen kontrollerade den bara inte.
780
+ #
781
+ # Regeln läggs till BARA när kandidaterna har talarrader och frågan nämner
782
+ # en av talarna. Annars returneras tom sträng och prompten blir exakt som
783
+ # förut. LongMemEval har inga talarrader i sina kontexter.
784
+ # ----------------------------------------------------------------------
785
+ _TALARRAD = re.compile(r"^([A-Z][a-zA-Z]{1,20}):\s", re.MULTILINE)
786
+ _INTE_TALARE = frozenset({
787
+ "User", "Assistant", "Note", "Question", "Answer", "Ingredients",
788
+ "Instructions", "Step", "Example", "Tip", "Summary", "Title", "Q", "A",
789
+ "SVAR", "Session", "USER", "ASSISTANT"})
790
+ _MIN_TALARRADER = 3
791
+
792
+
793
+ def _talare_i_fragan(kandidater: str, fraga: str) -> tuple[list[str], list[str]]:
794
+ """(alla talare i kandidaterna, de av dem som frågan nämner)."""
795
+ antal: dict[str, int] = {}
796
+ for namn in _TALARRAD.findall(kandidater or ""):
797
+ antal[namn] = antal.get(namn, 0) + 1
798
+ talare = sorted(n for n, k in antal.items()
799
+ if k >= _MIN_TALARRADER and n not in _INTE_TALARE)
800
+ i_fragan = [n for n in talare
801
+ if re.search(r"\b" + re.escape(n) + r"\b", fraga or "")]
802
+ return talare, i_fragan
803
+
804
+
805
+ def _ratt_person_regel(kandidater: str, fraga: str) -> str:
806
+ talare, i_fragan = _talare_i_fragan(kandidater, fraga)
807
+ if not i_fragan:
808
+ return ""
809
+ vem = " och ".join(i_fragan)
810
+ return (
811
+ "\nRÄTT PERSON-REGEL: kandidaterna är ett samtal mellan flera "
812
+ f"personer ({', '.join(talare)}), och varje rad börjar med vem som "
813
+ f"talar. Frågan gäller {vem}. Kontrollera vem uppgiften faktiskt "
814
+ f"gäller innan du svarar: det {vem} själv säger om sig själv, eller "
815
+ f"det någon annan uttryckligen säger om {vem}. Något som en ANNAN "
816
+ f"person berättar om sig själv gäller INTE {vem}, även om ämnet, "
817
+ "platsen eller tidpunkten stämmer exakt med frågan. Finns uppgiften "
818
+ f"bara om en annan person än {vem}: låt 'SVAR:'-raden vara exakt "
819
+ "'Not available in the provided selection.' Anta aldrig att båda "
820
+ "gjort samma sak.\n")
821
+
822
+
823
+ def _ratt_person_kontroll(kandidater: str, fraga: str) -> str:
824
+ _, i_fragan = _talare_i_fragan(kandidater, fraga)
825
+ if not i_fragan:
826
+ return ""
827
+ vem = " och ".join(i_fragan)
828
+ return (
829
+ f"- RÄTT PERSON: frågan gäller {vem}. Peka ut raden i kandidaterna "
830
+ "som stöder ditt svar och vem som säger den. Säger en ANNAN person "
831
+ f"den om sig själv, gäller uppgiften inte {vem}: byt till 'Not "
832
+ "available in the provided selection.' Omvänt: om raden visar att "
833
+ f"uppgiften gäller {vem} (hen säger det själv, eller någon säger det "
834
+ "om hen), behåll svaret.\n")
835
+
836
+
773
837
  def _prompt_v3(cap_svar: dict, fraga: str, dagens_datum: str | None = None) -> str:
774
838
  kandidater = cap_svar.get("context", "")
775
839
  datumrad = (f"\nFRÅGANS TIDPUNKT (använd denna som \"idag\" vid "
@@ -805,7 +869,8 @@ def _prompt_v3(cap_svar: dict, fraga: str, dagens_datum: str | None = None) -> s
805
869
  + "\n" + _BESKRIVANDE_SVAR_REGEL + "\n" + _INTE_KOMBINERA_REGEL
806
870
  + "\n" + _NOLL_TRAFFAR_REGEL + "\n" + _KATEGORI_BREDD_REGEL
807
871
  + "\n" + _NAMNGIVEN_SLUTPUNKT_UTESLUTS_REGEL
808
- + "\n" + _UNGEFARLIG_PERIOD_TROSKEL_REGEL +
872
+ + "\n" + _UNGEFARLIG_PERIOD_TROSKEL_REGEL
873
+ + _ratt_person_regel(kandidater, fraga) +
809
874
  "\nVIKTIGT OM SVARSFORMAT (så svaret går att jämföra mot ett facit):\n"
810
875
  "- Resonemang/uträkning får stå EN eller flera rader, men avsluta "
811
876
  "ALLTID med en sista rad som börjar exakt med 'SVAR: ' följt av "
@@ -908,7 +973,8 @@ def _prompt_verifiering_v3(fraga: str, kandidater: str, forsta_svar_ra: str) ->
908
973
  "ifrån din uträknade: kontrollera om det ändå är den enda "
909
974
  "rimliga matchningen — om så, byt till den i stället för 'Not "
910
975
  "available' (se flerstegs-ungefärliga-referenser-tillägget i "
911
- "närmaste-datum-regeln i din ursprungliga instruktion).\n\n"
976
+ "närmaste-datum-regeln i din ursprungliga instruktion).\n"
977
+ + _ratt_person_kontroll(kandidater, fraga) + "\n"
912
978
  f"FRÅGA: {fraga}\n\nKANDIDATER:\n{kandidater}\n\n"
913
979
  f"DITT FÖRSTA SVAR:\n{forsta_svar_ra}\n\n"
914
980
  "Skriv din dubbelkontroll kort (ett par rader räcker), och avsluta "
@@ -439,6 +439,31 @@ def prompt_tidsankare_bred(fraga: str, fragans_datum: str, ankare: dict,
439
439
  return "SECOND READING. " + bred
440
440
 
441
441
 
442
+ def _regel_ratt_person(fraga: str, text: str) -> str:
443
+ """Steg 123b: samma regel som i eskaleringshjälpens v3-prompt, på
444
+ engelska som resten av den här prompten. Tom sträng när texten saknar
445
+ talarrader eller frågan inte nämner någon av talarna -- då blir
446
+ prompten exakt som förut. Funktionen bor i cap_escalate_helper; den
447
+ importeras först här, så att modulerna inte importerar varandra vid
448
+ start."""
449
+ try:
450
+ from cap_escalate_helper import _talare_i_fragan
451
+ except ImportError:
452
+ return ""
453
+ talare, i_fragan = _talare_i_fragan(text, fraga)
454
+ if not i_fragan:
455
+ return ""
456
+ vem = " and ".join(i_fragan)
457
+ return (
458
+ "RULE P - the right person. These sessions are a conversation "
459
+ f"between several people ({', '.join(talare)}), and every line "
460
+ f"starts with who is speaking. The question is about {vem}. "
461
+ "Something another person says about themselves is NOT about "
462
+ f"{vem}, even if the topic, place or time matches the question "
463
+ f"exactly. If the fact exists only for someone other than {vem}, "
464
+ "the information is not available (treat it as case B2).\n\n")
465
+
466
+
442
467
  def prompt_avstaende(fraga: str, fragans_datum: str, text: str,
443
468
  antal: int) -> str:
444
469
  """Version 2 (2026-11-12). Version 1 bad modellen jämföra "namn och
@@ -501,6 +526,7 @@ def prompt_avstaende(fraga: str, fragans_datum: str, text: str,
501
526
  "session counts as the date it happened. Time expressions in "
502
527
  "the question (\"last Friday\", \"two weeks ago\") are counted "
503
528
  "from the question date.\n\n"
529
+ + _regel_ratt_person(fraga, text) +
504
530
  "Write a short reasoning (2-5 lines) that names the case (B1, "
505
531
  "B2 or B3), and finish with exactly one last line, either\n"
506
532
  "SVAR: <the short, concrete answer in English> [<what it "
@@ -40,6 +40,7 @@ kunna MÄTA innan någon registrerar sig.
40
40
 
41
41
  from __future__ import annotations
42
42
 
43
+ import contextvars
43
44
  import json
44
45
  import os
45
46
  import sys
@@ -47,7 +48,7 @@ from typing import Any
47
48
 
48
49
  BAS = os.environ.get("CAP_SHIELD_URL", "https://cap-shield-robin.fly.dev")
49
50
  PROTOKOLL = "2024-11-05"
50
- VERSION = "0.7.0" # 2026-11-15: + assemble_escalation_context (steg 101)
51
+ VERSION = "0.7.6" # 2026-11-25: + verify_pass (steg 134)
51
52
 
52
53
 
53
54
  # ----------------------------------------------------------------------
@@ -134,6 +135,100 @@ VERKTYG = [
134
135
  "required": ["namespace", "text"],
135
136
  },
136
137
  },
138
+ {
139
+ "name": "remember_batch",
140
+ "description": (
141
+ "Store up to 100 memory entries in ONE call. REQUIRES A KEY. "
142
+ "Counts as one call against the rate limit and one packet per "
143
+ "entry against the monthly quota, so prefer it over many "
144
+ "remember calls. All or nothing: duplicate ids or a blocked "
145
+ "entry reject the whole batch before anything is stored. "
146
+ "Does not call any language model."
147
+ ),
148
+ "inputSchema": {
149
+ "type": "object",
150
+ "properties": {
151
+ "namespace": {"type": "string",
152
+ "description": "Groups related memories."},
153
+ "items": {
154
+ "type": "array", "minItems": 1, "maxItems": 100,
155
+ "items": {
156
+ "type": "object",
157
+ "properties": {
158
+ "text": {"type": "string"},
159
+ "item_id": {
160
+ "type": "string",
161
+ "description": (
162
+ "Optional. a-z, 0-9, - and _, at most "
163
+ "64 characters. Same id overwrites. "
164
+ "Omit for a generated one.")},
165
+ "ttl_days": {"type": "integer"},
166
+ },
167
+ "required": ["text"],
168
+ },
169
+ },
170
+ },
171
+ "required": ["namespace", "items"],
172
+ },
173
+ },
174
+ {
175
+ "name": "list_memories",
176
+ "description": (
177
+ "List what is stored, newest first, with a short preview of "
178
+ "each entry and its item_id. REQUIRES A KEY. Omit namespace to "
179
+ "list your namespaces instead. Use the item_id with "
180
+ "update_memory or forget. Read-only."
181
+ ),
182
+ "inputSchema": {
183
+ "type": "object",
184
+ "properties": {
185
+ "namespace": {"type": "string",
186
+ "description": "Omit to list namespaces."},
187
+ "offset": {"type": "integer", "minimum": 0},
188
+ "limit": {"type": "integer", "minimum": 1, "maximum": 100,
189
+ "description": "Default 50."},
190
+ "tag": {"type": "string",
191
+ "description": "Only entries with this tag."},
192
+ },
193
+ },
194
+ },
195
+ {
196
+ "name": "update_memory",
197
+ "description": (
198
+ "Replace the text of an EXISTING memory entry. REQUIRES A KEY. "
199
+ "Fails with MEMORY_NOT_FOUND if the item_id does not exist "
200
+ "(use remember to create). The previous text is kept in the "
201
+ "entry's version history; created date and tags are kept."
202
+ ),
203
+ "inputSchema": {
204
+ "type": "object",
205
+ "properties": {
206
+ "namespace": {"type": "string"},
207
+ "item_id": {"type": "string"},
208
+ "text": {"type": "string"},
209
+ "ttl_days": {"type": "integer",
210
+ "description": "Optional. Omit to keep the current expiry."},
211
+ },
212
+ "required": ["namespace", "item_id", "text"],
213
+ },
214
+ },
215
+ {
216
+ "name": "forget",
217
+ "description": (
218
+ "Permanently delete up to 100 memory entries, including their "
219
+ "version history. REQUIRES A KEY. Cannot be undone. Unknown "
220
+ "ids are reported in not_found, not treated as an error."
221
+ ),
222
+ "inputSchema": {
223
+ "type": "object",
224
+ "properties": {
225
+ "namespace": {"type": "string"},
226
+ "item_ids": {"type": "array", "items": {"type": "string"},
227
+ "minItems": 1, "maxItems": 100},
228
+ },
229
+ "required": ["namespace", "item_ids"],
230
+ },
231
+ },
137
232
  {
138
233
  "name": "assemble_context",
139
234
  "description": (
@@ -143,7 +238,9 @@ VERKTYG = [
143
238
  "This does not call a model itself — it selects what to send. "
144
239
  "The budget is a ceiling, not a target: selection stops where "
145
240
  "relevance runs out, often well below it. The response says "
146
- "how many entries were left behind and why."
241
+ "how many entries were left behind and why. If the response "
242
+ "has a 'budget_warning', the best match did not fit: call "
243
+ "again with its suggested_token_budget."
147
244
  ),
148
245
  "inputSchema": {
149
246
  "type": "object",
@@ -219,6 +316,18 @@ VERKTYG = [
219
316
  "required": ["namespace", "query"],
220
317
  },
221
318
  },
319
+ {
320
+ "name": "start_sandbox",
321
+ "description": (
322
+ "Try memory WITHOUT an account. Returns a temporary "
323
+ "sandbox_key; pass it as the sandbox_key argument to remember, "
324
+ "remember_batch, assemble_context, list_memories, "
325
+ "update_memory or forget. Everything is deleted after 24 hours. "
326
+ "Limits: 200 entries, 1 MB of text. No email needed. Do not "
327
+ "store real personal data in a sandbox."
328
+ ),
329
+ "inputSchema": {"type": "object", "properties": {}},
330
+ },
222
331
  {
223
332
  "name": "get_account",
224
333
  "description": (
@@ -272,6 +381,31 @@ VERKTYG = [
272
381
  "required": ["acts_for"],
273
382
  },
274
383
  },
384
+ {
385
+ "name": "verify_pass",
386
+ "description": (
387
+ "Check a CAP-Shield pass you were given: signature against "
388
+ "CAP-Shield's published keys, issuer, expiry, and, if you give "
389
+ "them, audience and required scope. No key needed. Returns "
390
+ "valid true/false with the reason and the claims. It cannot "
391
+ "tell you whether acts_for is TRUE, only that a key holder "
392
+ "claimed it."
393
+ ),
394
+ "inputSchema": {
395
+ "type": "object",
396
+ "properties": {
397
+ "pass": {"type": "string",
398
+ "description": "The JWT from issue_pass."},
399
+ "audience": {"type": "string",
400
+ "description": ("Your own identifier. Omit "
401
+ "only if any audience is fine.")},
402
+ "required_scope": {"type": "object",
403
+ "description": ("Key/value pairs that "
404
+ "must be in cap_scope.")},
405
+ },
406
+ "required": ["pass"],
407
+ },
408
+ },
275
409
  {
276
410
  "name": "pack_batch",
277
411
  "description": (
@@ -339,6 +473,188 @@ VERKTYG = [
339
473
  },
340
474
  ]
341
475
 
476
+ # Steg 111: titel och beteendeanteckningar per verktyg (MCP ToolAnnotations).
477
+ # Claudes connectors-katalog och ChatGPT:s pluginkatalog kräver dem, och
478
+ # en klient använder dem för att avgöra vad som får köras utan att fråga.
479
+ # readOnlyHint: ändrar ingenting som användaren äger.
480
+ # destructiveHint: kan skriva över eller ta bort (gäller bara om inte
481
+ # readOnly). Steg 128: update_memory och forget är de enda som sätter
482
+ # den. remember med ett id som redan finns skriver också över, men
483
+ # utan id skapas alltid en ny post -- additivt som standard.
484
+ # openWorldHint: når andra än CAP-Shields egen tjänst. Inget gör det.
485
+ # Kvot och telemetri räknas upp av alla anrop; det räknas inte som att
486
+ # ändra användarens data.
487
+ # Steg 129: sandbox_key på alla minnesverktyg. Valfri; utan den gäller
488
+ # nyckeln ur miljön (stdio) eller Authorization-huvudet (/mcp).
489
+ SANDLADA_VERKTYG = ("remember", "remember_batch", "assemble_context",
490
+ "assemble_escalation_context", "list_memories",
491
+ "update_memory", "forget")
492
+ for _v in VERKTYG:
493
+ if _v["name"] in SANDLADA_VERKTYG:
494
+ _v["inputSchema"].setdefault("properties", {})["sandbox_key"] = {
495
+ "type": "string",
496
+ "description": ("Optional. A temporary key from start_sandbox, "
497
+ "for trying without an account.")}
498
+ _v["description"] = _v["description"].replace(
499
+ "REQUIRES A KEY.",
500
+ "REQUIRES A KEY (or a sandbox_key from start_sandbox).", 1)
501
+
502
+ # ----------------------------------------------------------------------
503
+ # Steg 132: outputSchema för verktygen vars svar agenten läser fält ur.
504
+ # Tillåtande med avsikt: bara det som alltid finns är required, och
505
+ # additionalProperties lämnas öppet. Se hantera() för structuredContent.
506
+ # ----------------------------------------------------------------------
507
+ _STR_ELLER_NULL = {"type": ["string", "null"]}
508
+ UTSCHEMAN = {
509
+ "remember": {
510
+ "type": "object",
511
+ "properties": {
512
+ "namespace": {"type": "string"},
513
+ "item_id": {"type": "string"},
514
+ "tokens_est": {"type": "integer"},
515
+ "raw_bytes": {"type": "integer"},
516
+ "wire_bytes": {"type": "integer"},
517
+ "expires_utc": _STR_ELLER_NULL,
518
+ },
519
+ "required": ["namespace", "item_id"],
520
+ },
521
+ "remember_batch": {
522
+ "type": "object",
523
+ "properties": {
524
+ "namespace": {"type": "string"},
525
+ "stored": {"type": "integer"},
526
+ "items": {"type": "array", "items": {
527
+ "type": "object",
528
+ "properties": {"item_id": {"type": "string"}},
529
+ "required": ["item_id"]}},
530
+ },
531
+ "required": ["namespace", "stored", "items"],
532
+ },
533
+ "list_memories": {
534
+ "type": "object",
535
+ "description": ("With a namespace: a page of entries. Without: "
536
+ "'namespaces' only."),
537
+ "properties": {
538
+ "namespaces": {"type": "array", "items": {
539
+ "type": "object",
540
+ "properties": {"namespace": {"type": "string"},
541
+ "items": {"type": "integer"}}}},
542
+ "namespace": {"type": "string"},
543
+ "total": {"type": "integer"},
544
+ "offset": {"type": "integer"},
545
+ "limit": {"type": "integer"},
546
+ "next_offset": {"type": ["integer", "null"]},
547
+ "items": {"type": "array", "items": {
548
+ "type": "object",
549
+ "properties": {
550
+ "item_id": {"type": "string"},
551
+ "created_utc": _STR_ELLER_NULL,
552
+ "updated_utc": _STR_ELLER_NULL,
553
+ "expires_utc": _STR_ELLER_NULL,
554
+ "expired": {"type": "boolean"},
555
+ "tags": {"type": "array", "items": {"type": "string"}},
556
+ "preview": _STR_ELLER_NULL,
557
+ },
558
+ "required": ["item_id"]}},
559
+ },
560
+ },
561
+ "update_memory": {
562
+ "type": "object",
563
+ "properties": {
564
+ "namespace": {"type": "string"},
565
+ "item_id": {"type": "string"},
566
+ "version": {"type": "integer"},
567
+ "previous_version": {"type": "integer"},
568
+ "created_utc": _STR_ELLER_NULL,
569
+ "updated_utc": _STR_ELLER_NULL,
570
+ "expires_utc": _STR_ELLER_NULL,
571
+ },
572
+ "required": ["namespace", "item_id", "version"],
573
+ },
574
+ "forget": {
575
+ "type": "object",
576
+ "properties": {
577
+ "namespace": {"type": "string"},
578
+ "forgotten": {"type": "array", "items": {"type": "string"}},
579
+ "not_found": {"type": "array", "items": {"type": "string"}},
580
+ },
581
+ "required": ["namespace", "forgotten", "not_found"],
582
+ },
583
+ "assemble_context": {
584
+ "type": "object",
585
+ "properties": {
586
+ "context": {"type": "string",
587
+ "description": "Send this to the model."},
588
+ "item_ids": {"type": "array", "items": {"type": "string"}},
589
+ "tokens_used_est": {"type": "integer"},
590
+ "escalate_recommended": {"type": "boolean"},
591
+ "budget_warning": {"type": ["object", "null"]},
592
+ "possible_conflicts": {"type": "array", "items": {
593
+ "type": "object",
594
+ "properties": {
595
+ "item_ids": {"type": "array", "items": {"type": "string"}},
596
+ "newer": _STR_ELLER_NULL,
597
+ "dates": {"type": "object"},
598
+ "only_in": {"type": "object"},
599
+ "in_context": {"type": "object"},
600
+ }}},
601
+ },
602
+ "required": ["context"],
603
+ },
604
+ "verify_pass": {
605
+ "type": "object",
606
+ "properties": {
607
+ "valid": {"type": "boolean"},
608
+ "reason": {"type": "string"},
609
+ "checks": {"type": "object"},
610
+ "claims": {"type": "object"},
611
+ "warning": {"type": "string"},
612
+ "note": {"type": "string"},
613
+ },
614
+ "required": ["valid", "checks"],
615
+ },
616
+ "start_sandbox": {
617
+ "type": "object",
618
+ "properties": {
619
+ "sandbox_key": {"type": "string"},
620
+ "expires_utc": {"type": "string"},
621
+ "limits": {"type": "object"},
622
+ },
623
+ "required": ["sandbox_key", "expires_utc"],
624
+ },
625
+ }
626
+ for _v in VERKTYG:
627
+ if _v["name"] in UTSCHEMAN:
628
+ _v["outputSchema"] = UTSCHEMAN[_v["name"]]
629
+
630
+ ANNOTERINGAR = {
631
+ "measure_traffic": ("Measure possible savings", True, True),
632
+ "list_packages": ("List compression packages", True, True),
633
+ "remember": ("Store a memory entry", False, False),
634
+ "remember_batch": ("Store many memory entries", False, False),
635
+ "list_memories": ("List stored memory", True, True),
636
+ "update_memory": ("Replace a memory entry", False, True, True),
637
+ "forget": ("Delete memory entries", False, True, True),
638
+ "assemble_context": ("Retrieve relevant memory", True, True),
639
+ "assemble_escalation_context": ("Retrieve wide dated memory", True, True),
640
+ "get_account": ("Create account and API key", False, False),
641
+ "start_sandbox": ("Start a 24-hour memory sandbox", False, False),
642
+ "issue_pass": ("Issue a signed agent pass", False, False),
643
+ "verify_pass": ("Verify a signed agent pass", True, True),
644
+ "pack_batch": ("Compress a batch of messages", True, True),
645
+ "unpack_batch": ("Decompress a batch packet", True, True),
646
+ }
647
+ for _v in VERKTYG:
648
+ _titel, _las, _idem, *_destr = ANNOTERINGAR[_v["name"]]
649
+ _v["title"] = _titel
650
+ _v["annotations"] = {
651
+ "title": _titel,
652
+ "readOnlyHint": _las,
653
+ "destructiveHint": bool(_destr and _destr[0]),
654
+ "idempotentHint": _idem,
655
+ "openWorldHint": False,
656
+ }
657
+
342
658
 
343
659
  def _nyckel() -> str:
344
660
  return os.environ.get("CAP_SHIELD_API_KEY", "").strip()
@@ -404,13 +720,15 @@ def _anrop(vag: str, kropp: dict | None = None, metod: str = "POST",
404
720
  miljön, som förut.
405
721
  """
406
722
  n = (nyckel if nyckel is not None
407
- else _NYCKEL_FOR_ANROP or _nyckel())
723
+ else _SANDLADA.get() or _NYCKEL_FOR_ANROP or _nyckel())
408
724
 
409
725
  if kraver_nyckel and not n:
410
726
  return {"error": (
411
727
  "No API key. Set CAP_SHIELD_API_KEY in the server's env, "
412
- "or call get_account to obtain one. The measure_traffic "
413
- "and list_packages tools work without a key.")}
728
+ "or call get_account to obtain one. To try memory without "
729
+ "an account, call start_sandbox and pass the returned "
730
+ "sandbox_key to this tool. measure_traffic, list_packages, "
731
+ "start_sandbox and verify_pass work without a key.")}
414
732
 
415
733
  if _UTFORARE is not None:
416
734
  try:
@@ -443,7 +761,23 @@ def _anrop(vag: str, kropp: dict | None = None, metod: str = "POST",
443
761
  return {"error": f"Could not reach {BAS}: {exc}"}
444
762
 
445
763
 
764
+ _SANDLADA = contextvars.ContextVar("cap_sandbox_key", default=None)
765
+
766
+
446
767
  def kor_verktyg(namn: str, arg: dict) -> dict:
768
+ # Steg 129: plocka ut sandbox_key och låt den gälla för anropet.
769
+ # Samma funktion anropas igen utan argumentet, med nyckeln satt.
770
+ if isinstance(arg, dict) and arg.get("sandbox_key"):
771
+ arg = dict(arg)
772
+ t = _SANDLADA.set(str(arg.pop("sandbox_key")).strip())
773
+ try:
774
+ return kor_verktyg(namn, arg)
775
+ finally:
776
+ _SANDLADA.reset(t)
777
+
778
+ if namn == "start_sandbox":
779
+ return _anrop("/api/v1/sandbox", {}, kraver_nyckel=False)
780
+
447
781
  if namn == "measure_traffic":
448
782
  kropp = {"texts": arg.get("texts", []),
449
783
  "dict_id": arg.get("dict_id", "finance")}
@@ -465,6 +799,35 @@ def kor_verktyg(namn: str, arg: dict) -> dict:
465
799
  kropp["ttl_days"] = arg["ttl_days"]
466
800
  return _anrop("/api/v1/memory/put", kropp)
467
801
 
802
+ if namn == "list_memories":
803
+ kropp = {k: arg[k] for k in ("namespace", "offset", "limit", "tag")
804
+ if arg.get(k) is not None}
805
+ return _anrop("/api/v1/memory/list", kropp)
806
+
807
+ if namn == "update_memory":
808
+ kropp = {"namespace": arg["namespace"], "item_id": arg["item_id"],
809
+ "text": arg["text"]}
810
+ if arg.get("ttl_days"):
811
+ kropp["ttl_days"] = arg["ttl_days"]
812
+ return _anrop("/api/v1/memory/update", kropp)
813
+
814
+ if namn == "forget":
815
+ return _anrop("/api/v1/memory/forget",
816
+ {"namespace": arg["namespace"],
817
+ "item_ids": list(arg.get("item_ids") or [])})
818
+
819
+ if namn == "remember_batch":
820
+ import uuid
821
+ poster = []
822
+ for p in arg.get("items") or []:
823
+ post = {"item_id": p.get("item_id") or uuid.uuid4().hex[:16],
824
+ "text": p.get("text", "")}
825
+ if p.get("ttl_days"):
826
+ post["ttl_days"] = p["ttl_days"]
827
+ poster.append(post)
828
+ return _anrop("/api/v1/memory/put-batch",
829
+ {"namespace": arg["namespace"], "items": poster})
830
+
468
831
  if namn == "assemble_context":
469
832
  kropp = {
470
833
  "namespace": arg["namespace"], "query": arg["query"],
@@ -494,6 +857,14 @@ def kor_verktyg(namn: str, arg: dict) -> dict:
494
857
  kropp["traffic"] = arg["traffic"]
495
858
  return _anrop("/api/v1/beta-signup", kropp, kraver_nyckel=False)
496
859
 
860
+ if namn == "verify_pass":
861
+ kropp = {"pass": arg["pass"]}
862
+ if arg.get("audience"):
863
+ kropp["audience"] = arg["audience"]
864
+ if arg.get("required_scope"):
865
+ kropp["required_scope"] = arg["required_scope"]
866
+ return _anrop("/api/v1/pass/verify", kropp, kraver_nyckel=False)
867
+
497
868
  if namn == "issue_pass":
498
869
  kropp = {"acts_for": arg["acts_for"]}
499
870
  if arg.get("audience"):
@@ -547,9 +918,18 @@ def hantera(begaran: dict) -> dict | None:
547
918
  resultat = {"error": f"Missing required argument: {exc}"}
548
919
  except Exception as exc:
549
920
  resultat = {"error": f"{type(exc).__name__}: {exc}"}
550
- return _svar(rid, {"content": [
921
+ # Steg 132: fel markeras som fel, och verktyg med outputSchema
922
+ # får sitt resultat även som structuredContent. Texten finns
923
+ # kvar för klienter som inte läser det.
924
+ fel = isinstance(resultat, dict) and "error" in resultat
925
+ ut = {"content": [
551
926
  {"type": "text",
552
- "text": json.dumps(resultat, ensure_ascii=False, indent=2)}]})
927
+ "text": json.dumps(resultat, ensure_ascii=False, indent=2)}],
928
+ "isError": fel}
929
+ if (not fel and isinstance(resultat, dict)
930
+ and p.get("name") in UTSCHEMAN):
931
+ ut["structuredContent"] = resultat
932
+ return _svar(rid, ut)
553
933
 
554
934
  if rid is None:
555
935
  return None # okänd notifiering — tig
@@ -34,7 +34,7 @@ import os
34
34
  from dataclasses import dataclass, field
35
35
  from typing import Any, Iterable
36
36
 
37
- __version__ = "0.6.0"
37
+ __version__ = "0.6.2"
38
38
  BAS = "https://cap-shield-robin.fly.dev"
39
39
  TIMEOUT = 30.0
40
40
 
File without changes
File without changes