tokensafe 4.15.1 → 4.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.15.1",
2
+ "version": "4.16.0",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * ACP (Agent Client Protocol) entry point for editors that spawn a Node command.
5
+ *
6
+ * The protocol server itself is Python (src/acp/server.py): it owns the session
7
+ * kernel, the tool guard and the permission prompts. This shim exists only so an
8
+ * editor config can name a Node executable — it reuses the main launcher's
9
+ * runtime resolution (system CPython, ~/.tokensafe/venv, then the pinned managed
10
+ * runtime) and forwards stdio unchanged, so JSON-RPC never passes through JS.
11
+ *
12
+ * tokensafe acp --print-command # prints: node "/abs/path/bin/tokensafe-acp.js"
13
+ */
14
+
15
+ const { spawn } = require('child_process');
16
+ const path = require('path');
17
+
18
+ const ROOT_DIR = path.resolve(__dirname, '..');
19
+ const launcher = path.join(__dirname, 'tokensafe.js');
20
+
21
+ const child = spawn(process.execPath, [launcher, 'acp', ...process.argv.slice(2)], {
22
+ stdio: 'inherit',
23
+ cwd: ROOT_DIR,
24
+ env: process.env,
25
+ });
26
+
27
+ child.on('error', (err) => {
28
+ console.error(`❌ TokenSafe ACP: failed to start the engine: ${err.message}`);
29
+ process.exit(1);
30
+ });
31
+
32
+ child.on('exit', (code, signal) => {
33
+ if (signal) {
34
+ process.kill(process.pid, signal);
35
+ return;
36
+ }
37
+ process.exit(code === null ? 1 : code);
38
+ });
@@ -214,6 +214,16 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
214
214
  except Exception:
215
215
  pass
216
216
 
217
+ # Delegated task digest: the child already read these files (one injection
218
+ # per delegation; the digest file is consumed on read).
219
+ try:
220
+ from src.delegation import render as _render_delegation, take as _take_delegation
221
+ _delegated = _take_delegation(session_id)
222
+ if _delegated:
223
+ parts.append(_render_delegation(_delegated))
224
+ except Exception:
225
+ pass
226
+
217
227
  if parts:
218
228
  return {
219
229
  "hookSpecificOutput": {
@@ -273,6 +283,14 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
273
283
  FileState.record_seen(track_fp)
274
284
  except Exception:
275
285
  pass
286
+ # A delegated task returned: fold the child's rollout into a digest for the
287
+ # next turn instead of letting the orchestrator re-read its files.
288
+ try:
289
+ from src.delegation import is_agent_tool, record_from_hook
290
+ if is_agent_tool(tool):
291
+ record_from_hook(payload)
292
+ except Exception:
293
+ pass
276
294
  return {}
277
295
 
278
296
  if event == "Stop":
@@ -302,6 +320,14 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
302
320
  )
303
321
  except Exception:
304
322
  pass
323
+ # Output usage ledger: incremental offset read, provider-reported only.
324
+ try:
325
+ usage_tp = str(payload.get("transcript_path") or "")
326
+ if usage_tp and session_id:
327
+ from src.usage_ledger import update_from_transcript
328
+ update_from_transcript(usage_tp, agent=agent, session_id=session_id)
329
+ except Exception:
330
+ pass
305
331
  return {}
306
332
 
307
333
  return {}
@@ -65,6 +65,16 @@ def main():
65
65
  from src.file_state import FileState
66
66
  FileState.record_seen(tracked_path)
67
67
 
68
+ # A delegated task returned: fold the child's own rollout into a digest
69
+ # for the next turn instead of letting the orchestrator re-read its
70
+ # files (the largest measured leak in the burn audit).
71
+ try:
72
+ from src.delegation import is_agent_tool, record_from_hook
73
+ if is_agent_tool(tool_name):
74
+ record_from_hook(payload)
75
+ except Exception:
76
+ pass
77
+
68
78
  # Anti-Stuck Failure Tracking: record command or test failure
69
79
  if tool_name in ("run_command", "Bash", "ExecuteCommand", "terminal"):
70
80
  tool_res = (
@@ -262,13 +262,16 @@ def _handle(payload: dict) -> dict:
262
262
  try:
263
263
  budget = kernel.estimate_budget(
264
264
  tracker, session_id=conversation_id,
265
- model=_model_name(payload),
265
+ model=_model_name(payload) or resolve_event_model(transcript_path, conversation_id),
266
266
  history_tokens=history_mass,
267
267
  transcript_path=transcript_path
268
268
  )
269
- used_pct = budget.get("used_pct")
269
+ # The warning follows the fold budget (min(70% of the window, ceiling)),
270
+ # not the window percentage: on a 1M window 80% is 800k of paid context.
271
+ budget_pct = budget.get("budget_pct")
270
272
  if (budget.get("measurement") == "measured"
271
- and used_pct is not None and used_pct >= 80):
273
+ and budget_pct is not None
274
+ and budget.get("threshold") in ("warning", "critical")):
272
275
  already = recent_events.get("BUDGET_WARNING")
273
276
  if not already:
274
277
  if transcript_path:
@@ -278,8 +281,9 @@ def _handle(payload: dict) -> dict:
278
281
  action = budget["recommendation"]
279
282
  token_count = budget.get("used_tokens") or budget.get("used_estimated") or 0
280
283
  warn = (
281
- f"🧠 **Context Budget:** ~{used_pct}% of the window measured "
282
- f"({token_count:,}/{budget['window_tokens']:,} prompt tokens). {action}"
284
+ f"🧠 **Context Budget:** ~{budget_pct}% of the fold budget measured "
285
+ f"({token_count:,}/{budget.get('effective_limit_tokens', budget['window_tokens']):,} tokens; "
286
+ f"window {budget['window_tokens']:,}). {action}"
283
287
  )
284
288
  inject_steps.append({
285
289
  "systemMessage": {
@@ -292,7 +296,9 @@ def _handle(payload: dict) -> dict:
292
296
  event_type="BUDGET_WARNING",
293
297
  original_tokens=0,
294
298
  optimized_tokens=0,
295
- details={"used_pct": used_pct, "window": budget["window_tokens"],
299
+ details={"used_pct": budget.get("used_pct"), "budget_pct": budget_pct,
300
+ "effective_limit": budget.get("effective_limit_tokens"),
301
+ "window": budget["window_tokens"],
296
302
  "measurement": budget.get("measurement")}
297
303
  )
298
304
  except Exception:
@@ -325,6 +331,20 @@ def _handle(payload: dict) -> dict:
325
331
  except Exception:
326
332
  pass
327
333
 
334
+ # 5.6 Delegated result digest: consume once per delegation.
335
+ try:
336
+ from src.delegation import render as _render_delegation, take as _take_delegation
337
+ _delegated = _take_delegation(conversation_id)
338
+ if _delegated:
339
+ inject_steps.append({
340
+ "systemMessage": {
341
+ "systemMessage": "",
342
+ "metadata": {"user_markdown": _render_delegation(_delegated)}
343
+ }
344
+ })
345
+ except Exception:
346
+ pass
347
+
328
348
  # 6. Multi-Agent Live Burn Monitor (rate-limited, only fires on real burn spikes)
329
349
  if invocation_num >= 2 or transcript_path:
330
350
  try:
@@ -99,7 +99,14 @@ def _handle(payload: dict) -> dict:
99
99
 
100
100
  # Search/list/other tools only ever answer "allow"; quota checks and event
101
101
  # recording are skipped for them. The guarded set is read/write/edit/bash.
102
- if canon_tool not in ("read", "write", "edit", "bash"):
102
+ if canon_tool not in ("read", "write", "edit", "bash", "batch_edit"):
103
+ return response
104
+
105
+ if canon_tool == "batch_edit":
106
+ from src.adapter_core import guard_batch_payload
107
+ verdict = guard_batch_payload(args, "antigravity", conversation_id)
108
+ if verdict["decision"] == "deny":
109
+ return {"decision": "deny", "reason": verdict["reason"]}
103
110
  return response
104
111
 
105
112
  tracker = MetricsTracker()
@@ -142,6 +149,20 @@ def _handle(payload: dict) -> dict:
142
149
  except Exception:
143
150
  pass
144
151
 
152
+ # 1.6 Edit-rewrite guard: an Edit that re-emits most of a file costs the
153
+ # same as a wholesale Write. Ask, never deny. Kill switch:
154
+ # TOKENSAFE_EDIT_REWRITE_GUARD=0.
155
+ if canon_tool == "edit":
156
+ try:
157
+ from src.adapter_core import guard_edit_rewrite
158
+ raw_path = str(args.get("Path") or args.get("TargetFile") or args.get("path") or args.get("file_path") or "")
159
+ verdict = guard_edit_rewrite(_resolve_hook_path(raw_path, hook_cwd), args, "antigravity", conversation_id)
160
+ if verdict["decision"] == "ask":
161
+ _trigger_bg_sync()
162
+ return {"decision": "force_ask", "reason": verdict["reason"]}
163
+ except Exception:
164
+ pass
165
+
145
166
  # 2. TokenSafe Guard: Inspect file writes and edits for security violations
146
167
  if canon_tool in ("write", "edit"):
147
168
  from src.guard import TokenSafeGuard
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.15.1",
3
+ "version": "4.16.0",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
6
  "license": "Apache-2.0",
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.15.1",
4
+ "version": "4.16.0",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
8
- "tokensafe": "bin/tokensafe.js"
8
+ "tokensafe": "bin/tokensafe.js",
9
+ "tokensafe-acp": "bin/tokensafe-acp.js"
9
10
  },
10
11
  "files": [
11
12
  "bin/tokensafe.js",
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.15.1",
4
+ "version": "4.16.0",
5
5
  "license": "Apache-2.0",
6
6
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
7
7
  "logo": "assets/logo.png",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.15.1",
6
+ "version": "4.16.0",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.15.1",
26
+ "version": "4.16.0",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.15.1",
42
+ "version": "4.16.0",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -17,7 +17,7 @@ import sys
17
17
  import re
18
18
  import json
19
19
  import time
20
- from typing import Dict, Any, Optional, Tuple
20
+ from typing import Dict, Any, List, Optional, Tuple
21
21
 
22
22
  from src.tokenizer import count_tokens
23
23
 
@@ -38,6 +38,7 @@ TOKENSAFE_DIRECTIVES = (
38
38
  "• Deduplication & Cache Pointers: Never re-read unchanged files repeatedly; reuse earlier context or pointer references.\n"
39
39
  "• Zero-Fluff Egress: Omit conversational filler, courtesy preambles, and wrap-ups. Format responses in dense, technical prose.\n"
40
40
  "• Surgical Code Diffs: Never reprint full unmodified files or lengthy boilerplate; cite line ranges and provide targeted diffs (use apply_edits for multi-file edits and run_helper for sanitize/guard/deps/web/expand/image).\n"
41
+ "• apply_edits already runs the project's own test command and returns the verdict in the same call; do not re-read the edited file or run the suite again unless strict_verify=true was used.\n"
41
42
  "• Compact Test Execution: Run unit tests with concise flags or via 'tokensafe tests [cmd]' so passing suites emit a 1-line summary.\n"
42
43
  "• Mandatory Architecture Graph & God Nodes: For any codebase inquiry, navigation, or multi-component work, ALWAYS inspect God Nodes via 'tokensafe:repo_map(view=\"graph\", project_path=...)' first before diving into files (pass target project's absolute path in multi-repo setups).\n"
43
44
  "• To inspect all exported types/interfaces or directory trees: call 'tokensafe:repo_map(view=\"api\"|\"tree\", project_path=...)'.\n"
@@ -431,6 +432,141 @@ def guard_write(file_path: str, content: str, append: bool = False, agent: str =
431
432
  )
432
433
 
433
434
 
435
+ def _env_int(name: str, default: int) -> int:
436
+ try:
437
+ return int(os.environ.get(name, str(default)))
438
+ except (TypeError, ValueError):
439
+ return default
440
+
441
+
442
+ def _edit_replacements(tool_input: Dict[str, Any]) -> List[str]:
443
+ """Collects the replacement text of Edit-like payloads (Edit/MultiEdit/
444
+ apply_edits/apply_patch-normalized shapes)."""
445
+ keys = ("new_string", "new_text", "replacement", "new_content", "content", "Content")
446
+ reps: List[str] = []
447
+
448
+ def _take(obj: Dict[str, Any]) -> None:
449
+ for key in keys:
450
+ val = obj.get(key)
451
+ if isinstance(val, str) and val:
452
+ reps.append(val)
453
+ return
454
+
455
+ _take(tool_input)
456
+ items = tool_input.get("edits")
457
+ if isinstance(items, list):
458
+ for item in items:
459
+ if isinstance(item, dict):
460
+ _take(item)
461
+ return reps
462
+
463
+
464
+ def guard_edit_rewrite(
465
+ file_path: str,
466
+ tool_input: Dict[str, Any],
467
+ agent: str = "",
468
+ session_id: str = "",
469
+ transcript_path: str = "",
470
+ ) -> Dict[str, Any]:
471
+ """Edit-path twin of guard_write: an Edit that re-emits most of an existing
472
+ file costs the same output tokens as a wholesale Write, so it earns the same
473
+ ask. Only asks; never denies. Kill switch: TOKENSAFE_EDIT_REWRITE_GUARD=0."""
474
+ result = {"decision": "allow", "reason": "", "saved_tokens": 0}
475
+ if os.environ.get("TOKENSAFE_EDIT_REWRITE_GUARD", "1").strip().lower() in ("0", "false", "no"):
476
+ return result
477
+ if not file_path or not os.path.isfile(file_path):
478
+ return result
479
+ replacements = _edit_replacements(tool_input)
480
+ if not replacements:
481
+ return result
482
+ try:
483
+ with open(file_path, "r", encoding="utf-8", errors="replace") as f:
484
+ existing_text = f.read()
485
+ except Exception:
486
+ return result
487
+ existing_lines = existing_text.splitlines()
488
+ if len(existing_lines) < _env_int("TOKENSAFE_EDIT_REWRITE_MIN_LINES", 40):
489
+ return result
490
+
491
+ replacement = "\n".join(replacements)
492
+ replacement_tokens = max(1, count_tokens(replacement))
493
+ file_tokens = max(1, count_tokens(existing_text))
494
+ ratio = replacement_tokens / file_tokens
495
+ if ratio < float(os.environ.get("TOKENSAFE_EDIT_REWRITE_RATIO", "0.6")):
496
+ return result
497
+
498
+ tracker = _get_tracker()
499
+ if tracker:
500
+ try:
501
+ tracker.record_event(
502
+ session_id=session_id or f"hook_{agent}",
503
+ event_type="OUTPUT_GUARD",
504
+ original_tokens=replacement_tokens,
505
+ optimized_tokens=max(1, replacement_tokens // 4),
506
+ details={
507
+ "agent": agent,
508
+ "target_file": os.path.basename(file_path),
509
+ "existing_lines": len(existing_lines),
510
+ "ratio": round(ratio, 2),
511
+ "decision": "ask_edit_rewrite",
512
+ "model": resolve_event_model(transcript_path, session_id),
513
+ },
514
+ )
515
+ except Exception:
516
+ pass
517
+ return {
518
+ "decision": "ask",
519
+ "reason": (
520
+ f"TokenSafe Output Guard: this Edit re-emits ~{ratio:.0%} of '{os.path.basename(file_path)}' "
521
+ f"({replacement_tokens} vs {file_tokens} tokens). Prefer apply_edits with narrow hunks "
522
+ f"(target + replacement); use a true rewrite only when the file really changes wholesale."
523
+ ),
524
+ "saved_tokens": max(0, replacement_tokens - max(1, replacement_tokens // 4)),
525
+ }
526
+
527
+
528
+ def guard_batch_payload(
529
+ tool_input: Dict[str, Any],
530
+ agent: str = "",
531
+ session_id: str = "",
532
+ transcript_path: str = "",
533
+ ) -> Dict[str, Any]:
534
+ """PreToolUse cap for apply_edits/apply_patch payloads (defense in depth:
535
+ batch_editor enforces the same limits at execution time)."""
536
+ result = {"decision": "allow", "reason": ""}
537
+ max_chars = _env_int("TOKENSAFE_MAX_BATCH_CHARS", 600_000)
538
+ max_replacement = _env_int("TOKENSAFE_MAX_REPLACEMENT_CHARS", 200_000)
539
+ max_hunks = _env_int("TOKENSAFE_MAX_HUNKS_PER_FILE", 200)
540
+
541
+ patch = tool_input.get("patch") or tool_input.get("input")
542
+ if isinstance(patch, str) and len(patch) > max_chars:
543
+ return {"decision": "deny", "reason": f"TokenSafe Output Guard: patch payload is {len(patch):,} chars (cap {max_chars:,})."}
544
+
545
+ items = tool_input.get("edits")
546
+ if not isinstance(items, list):
547
+ return result
548
+ total = 0
549
+ for item in items:
550
+ if not isinstance(item, dict):
551
+ continue
552
+ path = str(item.get("path") or "?")
553
+ create = item.get("create")
554
+ if isinstance(create, str):
555
+ if len(create) > max_replacement:
556
+ return {"decision": "deny", "reason": f"TokenSafe Output Guard: 'create' for {path} is {len(create):,} chars (cap {max_replacement:,})."}
557
+ total += len(create)
558
+ hunks = item.get("hunks")
559
+ if isinstance(hunks, list):
560
+ if len(hunks) > max_hunks:
561
+ return {"decision": "deny", "reason": f"TokenSafe Output Guard: {len(hunks)} hunks for {path} (cap {max_hunks})."}
562
+ for hunk in hunks:
563
+ if isinstance(hunk, dict):
564
+ total += len(str(hunk.get("target") or "")) + len(str(hunk.get("replacement") or ""))
565
+ if total > max_chars:
566
+ return {"decision": "deny", "reason": f"TokenSafe Output Guard: batch payload exceeds {max_chars:,} chars."}
567
+ return result
568
+
569
+
434
570
  _CODE_EXTS = {
435
571
  ".py", ".ts", ".tsx", ".js", ".jsx", ".go", ".rs", ".java", ".kt", ".swift",
436
572
  ".c", ".cpp", ".h", ".hpp", ".cs", ".rb", ".php", ".vue", ".svelte",
@@ -448,6 +584,11 @@ def canonical_tool_name(name: str) -> str:
448
584
  return "edit"
449
585
  if t in ("Read", "read_file", "view_file", "view_file_outline"):
450
586
  return "read"
587
+ if t.lower() in (
588
+ "apply_edits", "tokensafe:apply_edits", "mcp__tokensafe__apply_edits",
589
+ "apply_patch", "applypatch",
590
+ ):
591
+ return "batch_edit"
451
592
  return t.lower()
452
593
 
453
594
 
@@ -691,6 +832,9 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
691
832
  )
692
833
  except Exception:
693
834
  pass
835
+ rewrite = guard_edit_rewrite(file_path, tool_input, agent, session_id, transcript_path=tp)
836
+ if rewrite["decision"] == "ask":
837
+ return _cc_decision("ask", rewrite["reason"])
694
838
  # Advisory only, and only for hosts whose PreToolUse schema documents
695
839
  # additionalContext (Claude Code): omitting permissionDecision keeps the
696
840
  # normal permission flow, while returning "allow" used to auto-approve edits.
@@ -706,6 +850,12 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
706
850
  }
707
851
  return {}
708
852
 
853
+ if canon == "batch_edit":
854
+ verdict = guard_batch_payload(tool_input, agent, session_id, transcript_path=tp)
855
+ if verdict["decision"] == "deny":
856
+ return _cc_decision("deny", verdict["reason"])
857
+ return {}
858
+
709
859
  if canon == "read":
710
860
  file_path = _extract_path(tool_input)
711
861
  verdict = guard_read(file_path, agent, session_id, transcript_path=tp)
@@ -0,0 +1,181 @@
1
+ """Angular CLI injection: point a workspace's `serve` target at the TokenSafe builder.
2
+
3
+ `ng serve` is the only way into an Angular app that is not on Vite, and it has no
4
+ third-party plugin slot. What it does have is a configurable builder per project:
5
+ `projects.<name>.architect.serve.builder`. This module rewrites that value to
6
+ `@tokensafe-ui/angular-builder:dev-server` and records the previous value so
7
+ `tokensafe inject --revert` restores byte-for-byte what was there.
8
+
9
+ Refusals are deliberate:
10
+ - no `angular.json` / no `architect.serve` → nothing to point at;
11
+ - the builder package is not installed in the workspace → `ng serve` would fail
12
+ while `tokensafe` claimed the app was wired, so the inject reports the install
13
+ command instead of writing a builder it cannot resolve.
14
+ """
15
+
16
+ import json
17
+ import os
18
+ from typing import Any, Dict, Optional
19
+
20
+ BUILDER_ID = "@tokensafe-ui/angular-builder:dev-server"
21
+ INSTALL_COMMAND = "npm install --save-dev @tokensafe-ui/angular-builder"
22
+ STATE_REL_PATH = os.path.join(".tokensafe", "angular-cli.json")
23
+
24
+
25
+ def _angular_json(app_root: str) -> str:
26
+ return os.path.join(app_root, "angular.json")
27
+
28
+
29
+ def _state_path(workspace: str) -> str:
30
+ return os.path.join(workspace, STATE_REL_PATH)
31
+
32
+
33
+ def _load_state(workspace: str) -> Dict[str, Any]:
34
+ try:
35
+ with open(_state_path(workspace), "r", encoding="utf-8") as handle:
36
+ data = json.load(handle)
37
+ return data if isinstance(data, dict) else {}
38
+ except Exception:
39
+ return {}
40
+
41
+
42
+ def _save_state(workspace: str, state: Dict[str, Any]) -> None:
43
+ from src.atomic_io import write_text_atomic
44
+
45
+ path = _state_path(workspace)
46
+ os.makedirs(os.path.dirname(path), exist_ok=True)
47
+ write_text_atomic(path, json.dumps(state, indent=2, ensure_ascii=False))
48
+
49
+
50
+ def _read_angular_json(app_root: str) -> Optional[Dict[str, Any]]:
51
+ try:
52
+ with open(_angular_json(app_root), "r", encoding="utf-8") as handle:
53
+ data = json.load(handle)
54
+ return data if isinstance(data, dict) else None
55
+ except Exception:
56
+ return None
57
+
58
+
59
+ def _ensure_tokensafe_gitignored(app_root: str) -> None:
60
+ try:
61
+ from src.paths import ensure_tokensafe_gitignore
62
+
63
+ ensure_tokensafe_gitignore(app_root)
64
+ except Exception:
65
+ pass
66
+
67
+
68
+ def package_installed(app_root: str) -> bool:
69
+ """The builder must be resolvable from the workspace or `ng serve` cannot load it."""
70
+ marker = os.path.join(app_root, "node_modules", "@tokensafe-ui", "angular-builder", "package.json")
71
+ return os.path.isfile(marker)
72
+
73
+
74
+ def serve_targets(data: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
75
+ """Project name → its `architect.serve` block (Angular keeps it under `architect`)."""
76
+ out: Dict[str, Dict[str, Any]] = {}
77
+ for name, project in (data.get("projects") or {}).items():
78
+ if not isinstance(project, dict):
79
+ continue
80
+ architect = project.get("architect") if isinstance(project.get("architect"), dict) else {}
81
+ serve = architect.get("serve") if isinstance(architect.get("serve"), dict) else {}
82
+ if serve:
83
+ out[name] = serve
84
+ return out
85
+
86
+
87
+ def patch_state(app_root: str) -> Dict[str, Any]:
88
+ """What `apply` would find: is there a target, is it already patched, is the package installed."""
89
+ data = _read_angular_json(app_root)
90
+ if data is None:
91
+ return {"patched": False, "projects": [], "reason": f"no readable angular.json in {app_root}"}
92
+ targets = serve_targets(data)
93
+ if not targets:
94
+ return {"patched": False, "projects": [], "reason": "angular.json has no architect.serve target"}
95
+ already = [name for name, serve in targets.items() if str(serve.get("builder") or "") == BUILDER_ID]
96
+ return {
97
+ "patched": len(already) == len(targets),
98
+ "projects": sorted(targets),
99
+ "patched_projects": sorted(already),
100
+ "installed": package_installed(app_root),
101
+ }
102
+
103
+
104
+ def apply(workspace: str, app_root: str, dry_run: bool = False) -> Dict[str, Any]:
105
+ """Rewrites `architect.serve.builder` for every project in the app."""
106
+ state = patch_state(app_root)
107
+ if state.get("reason"):
108
+ return {"status": "skipped", "kind": "angular_cli_builder", "reason": state["reason"]}
109
+ if not state.get("installed"):
110
+ return {
111
+ "status": "skipped",
112
+ "kind": "angular_cli_builder",
113
+ "reason": "the TokenSafe Angular builder is not installed in this workspace, so ng serve could not load it",
114
+ "install": INSTALL_COMMAND,
115
+ }
116
+ data = _read_angular_json(app_root) or {}
117
+ targets = serve_targets(data)
118
+ previous: Dict[str, str] = {}
119
+ for name, serve in targets.items():
120
+ previous[name] = str(serve.get("builder") or "")
121
+ serve["builder"] = BUILDER_ID
122
+
123
+ if not dry_run:
124
+ from src.atomic_io import write_text_atomic
125
+
126
+ write_text_atomic(_angular_json(app_root), json.dumps(data, indent=2, ensure_ascii=False) + "\n")
127
+ recorded = _load_state(workspace)
128
+ apps = recorded.get("apps") if isinstance(recorded.get("apps"), dict) else {}
129
+ apps[os.path.abspath(app_root)] = previous
130
+ recorded["apps"] = apps
131
+ _save_state(workspace, recorded)
132
+ _ensure_tokensafe_gitignored(app_root)
133
+
134
+ return {
135
+ "status": "ready",
136
+ "kind": "angular_cli_builder",
137
+ "builder": BUILDER_ID,
138
+ "projects": sorted(previous),
139
+ "previous": previous,
140
+ "dry_run": dry_run,
141
+ "run": "ng serve",
142
+ "note": "the bridge is served by the builder; no source file is touched",
143
+ }
144
+
145
+
146
+ def revert_all(workspace: str) -> Dict[str, Any]:
147
+ """Restores every recorded builder value and removes the state file."""
148
+ recorded = _load_state(workspace)
149
+ apps = recorded.get("apps") if isinstance(recorded.get("apps"), dict) else {}
150
+ restored: Dict[str, Any] = {}
151
+ for app_root, previous in apps.items():
152
+ if not isinstance(previous, dict):
153
+ continue
154
+ data = _read_angular_json(app_root)
155
+ if data is None:
156
+ restored[app_root] = {"status": "skipped", "reason": "angular.json is missing"}
157
+ continue
158
+ targets = serve_targets(data)
159
+ changed = []
160
+ for name, builder in previous.items():
161
+ serve = targets.get(name)
162
+ if not serve:
163
+ continue
164
+ if str(serve.get("builder") or "") != BUILDER_ID:
165
+ # Someone changed it after the inject: leave their value alone.
166
+ continue
167
+ serve["builder"] = builder
168
+ changed.append(name)
169
+ if changed:
170
+ from src.atomic_io import write_text_atomic
171
+
172
+ write_text_atomic(_angular_json(app_root), json.dumps(data, indent=2, ensure_ascii=False) + "\n")
173
+ restored[app_root] = {"status": "reverted", "projects": changed}
174
+ try:
175
+ if os.path.isfile(_state_path(workspace)):
176
+ os.unlink(_state_path(workspace))
177
+ except OSError:
178
+ pass
179
+ if not restored:
180
+ return {"status": "nothing-to-revert"}
181
+ return {"status": "reverted", "apps": restored}