agent-bios 0.19.2 → 0.19.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 (46) hide show
  1. package/DEPENDENCIES.md +32 -4
  2. package/README.md +54 -4
  3. package/claude/guides/cli-multi-model-workflow.md +1 -1
  4. package/claude/guides/coding-staged-workflow.md +17 -0
  5. package/claude/guides/llm-capability-boundary.md +7 -1
  6. package/claude/guides/tooling-gotchas.md +20 -1
  7. package/claude/guides/ui-design/visual-direction.md +88 -0
  8. package/claude/guides/ui-design.md +90 -0
  9. package/claude/guides/verification-discipline.md +10 -1
  10. package/claude/hooks/tooling-gotchas-hook.py +41 -0
  11. package/codex/guides/cli-multi-model-workflow.md +1 -1
  12. package/codex/guides/coding-staged-workflow.md +17 -0
  13. package/codex/guides/llm-capability-boundary.md +7 -1
  14. package/codex/guides/tooling-gotchas.md +20 -1
  15. package/codex/guides/ui-design/visual-direction.md +88 -0
  16. package/codex/guides/ui-design.md +90 -0
  17. package/codex/guides/verification-discipline.md +10 -1
  18. package/compose/app_bridge/scripts/bridge.py +23 -6
  19. package/compose/app_desktop/server.py +250 -0
  20. package/compose/domains.json +1 -0
  21. package/compose/host_platform.py +121 -0
  22. package/compose/instructions-state.py +5 -2
  23. package/compose/instructions_app.py +281 -48
  24. package/compose/instructions_catalog.py +2 -2
  25. package/compose/instructions_import.py +19 -11
  26. package/compose/instructions_install.py +77 -11
  27. package/compose/instructions_session.py +6 -6
  28. package/compose/instructions_setup.py +41 -4
  29. package/compose/instructions_setup_cli.py +31 -10
  30. package/compose/instructions_setup_i18n.py +3 -0
  31. package/compose/instructions_store.py +6 -6
  32. package/compose/instructions_transaction.py +8 -6
  33. package/compose/instructions_ui_runtime.py +2 -1
  34. package/compose/native_cli.py +52 -0
  35. package/compose/runtime_entry.py +58 -0
  36. package/compose/windows_deploy.py +719 -0
  37. package/docs/instructions.md +1 -0
  38. package/docs/releases/0.19.3.md +107 -0
  39. package/docs/session-model.md +8 -0
  40. package/docs/setup.md +36 -0
  41. package/docs/windows.md +99 -0
  42. package/install.sh +1 -0
  43. package/launch/agent-launch.py +12 -4
  44. package/launch/agent-launch.zsh +11 -1
  45. package/package.json +8 -3
  46. package/provenance.json +1 -1
@@ -0,0 +1,88 @@
1
+ ---
2
+ language: en
3
+ status: active
4
+ ---
5
+
6
+ # Choosing a visual direction for an operational interface
7
+
8
+ Use when a new visual direction or a material arrangement decision remains
9
+ unresolved in the requested work. For an established direction or a bounded copy
10
+ correction, use the existing system and verify the affected result proportionately.
11
+
12
+ ## Start from the task and supported system
13
+
14
+ Identify the content people must read, compare, select, edit or act on. Preserve
15
+ the working scope, authority and state distinctions that matter to that task.
16
+ Inspect the project's existing components and tokens before introducing a new
17
+ visual vocabulary. An external reference does not itself justify replacing the
18
+ project's framework or component library.
19
+
20
+ Consult a reference when it helps resolve the remaining visual decision; reuse
21
+ sufficient existing evidence. Research more when the decision needs it or the
22
+ user requests research. Prefer task-relevant product views or official pattern
23
+ documentation. Distinguish live observations, release screenshots, historical
24
+ images and explanatory artwork. Record the source and date, what it informs,
25
+ and its applicability limits in the ordinary design note. Do not infer token
26
+ values or usability from an image alone.
27
+
28
+ ## Choose only the patterns the task needs
29
+
30
+ | Task | Useful arrangement | Meaning to preserve |
31
+ | --- | --- | --- |
32
+ | Reading and review | Give the artifact sufficient space; keep necessary evidence nearby when switching would obstruct comparison | The artifact, source, applicable conditions and review target |
33
+ | Repeated record comparison | Align comparable values; distinguish whole-list, selected-set and individual-record actions | Units, comparison basis, exceptions and each action's scope |
34
+ | Selection-driven editing | Keep relevant properties bound to the selected object | Selection, draft and resulting changes remain attached to the same target |
35
+ | Input and result confirmation | Keep input, consequential effects and results close enough to follow | Entered, saved, approved and actually executed states stay distinct |
36
+
37
+ These are conditional patterns, not a required navigation structure or panel
38
+ count. Choose persistent supporting panels or transient overlays according to
39
+ their role. Give prose a readable measure and comparisons sufficient width.
40
+ Adapt the arrangement to the supported viewport while preserving the current
41
+ selection, return context, reading order and keyboard focus order. Compact
42
+ navigation when needed to keep the main task reachable on a narrow screen.
43
+
44
+ ## Define roles before values
45
+
46
+ Explain the proposed reading order, emphasis, density and grouping briefly.
47
+ Map foregrounds, surfaces, action states, spacing relationships and any required
48
+ depth to the existing semantic tokens. Keep focus, selection, feedback and
49
+ disabled states distinct even when values initially coincide. Add a pattern
50
+ token only when it represents an independent decision. The role of a token
51
+ must survive theme changes; check its actual foreground/background pairing.
52
+
53
+ For information-dense operational work, start with typography, alignment and
54
+ spacing to organize content; add containers, color or elevation when they
55
+ communicate a needed relationship or interaction. Large introductory areas,
56
+ repeated summary cards, badges and icon backgrounds need a task or brand purpose.
57
+ Ordinary content need not look raised. Use depth when it clarifies a floating,
58
+ movable or otherwise distinct object. Preserve useful brand and user preferences.
59
+
60
+ Do not impose a reference palette, fixed pixel scale, permanently dim navigation,
61
+ universal card ban or identical layout across tasks. When no system exists, mark
62
+ initial values as project proposals. Define consistent text roles and spacing
63
+ within and between groups, then check the resulting density. Resolve crowded
64
+ content through grouping, widths and wrapping before shrinking text. Keep words
65
+ and meaningful phrases together where the language permits, with a fallback for
66
+ unbroken strings. Check representative Korean text when the product uses Korean.
67
+
68
+ ## Compare only enough to resolve the decision
69
+
70
+ Use representative content, long labels, important exceptions and relevant
71
+ states at the target sizes. Keep task, content and capability constant while
72
+ comparing visual alternatives; use a credible baseline. Distinguish token
73
+ changes from changes to regions, information order and grouping. Typography
74
+ and spacing can still alter wrapping and geometry. Where narrow layouts
75
+ converge, do not claim a difference the user cannot see.
76
+
77
+ Inspect the actual rendered result when appearance is being judged. Check
78
+ contrast, clipping, wrapping, state distinctions, action targets and focus
79
+ visibility under the applicable accessibility requirements. Verify that
80
+ rearrangement preserves semantic reading and keyboard order. For interactive
81
+ changes, exercise selection, draft retention and the relevant failure/recovery
82
+ paths; styling does not establish permission or execution.
83
+
84
+ Record visual preference separately from observed task performance. Rendered
85
+ samples support visual inspection; interaction and user-performance claims need
86
+ their own evidence. Preserve the result and remaining uncertainty in ordinary
87
+ team artifacts. No prescribed number of variants or new research report is
88
+ needed for every task.
@@ -0,0 +1,90 @@
1
+ ---
2
+ guide_id: ui-design
3
+ language: en
4
+ status: active
5
+ description: For designing, reviewing, or changing task flows, information layout, visual hierarchy, or interaction in operational user interfaces; keep bounded corrections proportionate.
6
+ use_when:
7
+ - designing or reviewing a work application, operations tool, or interactive work surface
8
+ - changing information arrangement, visual hierarchy, design tokens, or interaction states
9
+ - preserving scope, evidence, authority, and continuity through a user interface
10
+ ---
11
+
12
+ # Operational interface design and delivery
13
+
14
+ Use for interfaces where people inspect evidence, compose work, make decisions
15
+ or act on records. Match the deliverable to the user's requested stage and scope.
16
+ A clear text correction needs that correction and a proportionate check.
17
+
18
+ 1. **Establish what the sources mean now.** Separate implemented behavior,
19
+ accepted requirements, proposed design choices and illustrative states.
20
+ Reconcile amendments and decisions before reusing an older screen. A newer
21
+ date alone does not establish authority. Keep material contradictions and
22
+ unknowns visible instead of silently choosing a convenient interpretation.
23
+
24
+ 2. **Preserve requested coverage; bound the work at the right level.** Identify
25
+ the operator, outcome and evidence that would complete this deliverable.
26
+ Distinguish people consuming work context from those authoring or managing
27
+ it; do not invent their visit frequency or force a common starting screen.
28
+ For a complete design request, cover the required operations even when their
29
+ backend is not built; specify their subjects, inputs, effects, dependencies
30
+ and recovery rather than claiming implementation. For a bounded change,
31
+ complete the requested path before expanding neighboring features. Include
32
+ adjacent repairs when that path depends on them or this change causes a
33
+ regression, and state why. An unavailable implementation does not erase a
34
+ requested design contract.
35
+
36
+ 3. **Organize around a meaningful next decision.** Show the working scope,
37
+ evidence to compare, current state, available action and resulting next step
38
+ together. Internal modules or protocol phases are not automatically menus
39
+ or buttons. Combine preparation steps behind one authorized intent when no
40
+ user choice is needed, while keeping distinct outcomes understandable. Use
41
+ the team's visual language to assign emphasis according to the task, and
42
+ make typography, spacing, color and boundaries express meaningful
43
+ relationships. Test whether actual task content is prominent at the target
44
+ size; decorative summaries must earn their space. When layout uncertainty
45
+ matters, compare arrangements at the lowest useful fidelity, explaining the
46
+ task tradeoff and what evidence would change the choice.
47
+
48
+ When a new visual direction or a material arrangement decision remains
49
+ unresolved, use
50
+ `${CODEX_HOME:-$HOME/.codex}/guides/ui-design/visual-direction.md`.
51
+ An established direction or a bounded correction does not require new
52
+ reference research or multiple designs.
53
+
54
+ 4. **Keep qualifications with the thing they qualify.** Preserve applicable
55
+ conditions, exceptions, units, source/version, time meaning and affected
56
+ scope through summaries, edits, comparisons and exports. Keep independent
57
+ dimensions separate. Missing evidence is not an empty result or a zero, and
58
+ an index or relationship view is not proof of its underlying body or meaning.
59
+ Expand technical detail when useful without hiding a consequential limit.
60
+
61
+ 5. **Make each action's authority and effect precise.** Name the exact target,
62
+ base and changed content when reviewing a change. Recheck a changed base or
63
+ permission instead of carrying approval onto different input. Distinguish
64
+ selection, saved draft, approval, execution and recipient use as applicable;
65
+ one positive state does not prove the next. Preserve request identity when
66
+ an outcome is uncertain and reconcile its actual result before retrying.
67
+ UI controls reflect the existing authoritative policy; they do not create it.
68
+ If policy is unsettled, label proposed choices and the responsible decision
69
+ owner rather than implying permission or omitting the required design.
70
+
71
+ 6. **Carry the same work across views and people.** Preserve the draft, target,
72
+ review/request identity and return context when moving between surfaces.
73
+ Equivalent outcomes need suitable representations, not identical layouts or
74
+ duplicated business rules. Provide keyboard and structured alternatives for
75
+ necessary spatial interactions. Verify evidence for the actual recipient;
76
+ another worker's receipt does not establish their access or delivery.
77
+
78
+ 7. **Verify this deliverable, then finish it.** Walk a design's concrete scenario
79
+ and relevant exceptions against its sources; inspect its proposed composition.
80
+ For working changes, exercise the changed runtime path, relevant failures,
81
+ keyboard and recovery. When a visual change is material, inspect the affected
82
+ composition with representative content and relevant states at the target
83
+ size, distinguishing token changes from changes to information arrangement.
84
+ Check that visual, reading and focus order remain coherent across layouts.
85
+ Report visual preference separately from observed task performance. Keep
86
+ simulation, observed runtime and user evidence distinct. Once the required
87
+ checks are complete, leave the result, material decisions, source bindings
88
+ and remaining work in ordinary team artifacts. Keep private facts within
89
+ their permitted boundary. Choose dependencies only when a requirement
90
+ demands a decision, using the supported environment first.
@@ -77,6 +77,7 @@ cheapest one to write.
77
77
  - A/B or on/off measurements: before accepting a null result, verify the arms actually received different treatment in the mechanism under test — a shared default or unconditional upstream step can silently apply the treatment to both arms.
78
78
  - Multi-stage pipelines with nondeterministic stages: a final-output diff cannot attribute an effect or a regression to a stage — it conflates the change with run-to-run variance. Persist every stage's output, tabulate what each creates, may edit, and only guards, restrict the suspects to the stages that edit the content in question, and find the first stage where the intended effect disappears or the defect appears. Fix there, preferring a structural recheck over another prompt-level instruction that already failed.
79
79
  - Before/after comparisons: pin the input to an immutable copy — a snapshot or versioned artifact — and run both arms against it, because a live artifact (a growing log, a regenerated upstream stage) drifts between runs and any diff over it, a matching one included, is evidence of nothing; when the arms are metered, restore the baseline's exact upstream inputs and re-run only the changed stage. This is input identity, not the separate unit-and-denominator basis rule.
80
+ - Cost figures from provider usage records: before pricing, map every provider's token fields onto one schema — uncached input, cache read, cache write, output. Some providers report input as a total that already includes cached tokens: treating that total as uncached input and then adding the cache-read field again counts the cached portion twice, while charging the inclusive total once at the full rate misprices that portion instead. Other providers exclude cached tokens from the input field. When a provider reports or prices cache writes separately, keep them in their own field. Confirm each provider's field meaning against its own usage documentation or a known sample, never by analogy with another provider, and derive the cache hit rate from the normalized fields.
80
81
  - Model-behavior guardrails: verify by changed behavior, not recitation — a staged battery from named-trigger cases through disguised, deconfounded, category-wide, and single-variable framings; a clean pass means "no known defect", so re-run the battery when the model changes.
81
82
  - Branch/version test builds against real data: explicitly separate every state sink the app touches (files, DB, OS-level stores that ignore env overrides), confirm the launch path propagates the isolation to child processes, and back up live data before the first run — a mismatched schema that drops unknown fields on write is data loss, not a no-op.
82
83
  - Sandbox, replay, or re-adjudication runs on production-derived config: enumerate every outbound channel the stage can reach — publish, upload, notify, external write — and disable or redirect each one before the run, proving each disarm fires as you would prove a path guard; a guard on the input or target path alone leaves egress armed. Fingerprint every external destination before the run and diff it after, so an escaped write is caught by the run rather than by a recipient.
@@ -151,6 +152,11 @@ produce a green with no evidence behind it:
151
152
  - **The suspiciously fast or empty run.** When a check goes green unexpectedly quickly, or reports
152
153
  nothing at all, dump what it actually ran over before believing it. A harness that crashed early
153
154
  and one that found nothing produce the same exit code.
155
+ - **The verdict that ran before its checks.** If a runner computes or prints its overall verdict
156
+ before all checks finish, later failures cannot change it. Accumulate one failure count across
157
+ every check, then compute the verdict and exit status once, after the last check. Read a
158
+ multi-check run from that final count and an exit status verified to derive from it — never from
159
+ `tail` or collapsed last lines, which hide failures printed earlier.
154
160
  - **The control that failed by crashing.** A negative control is evidence only when it fails
155
161
  through the assertion it names: a traceback and a caught violation share an exit code, and an
156
162
  early crash can pre-empt every control after it. Treat each traceback in a control run as a
@@ -173,7 +179,10 @@ produce a green with no evidence behind it:
173
179
  - **The mutant that never ran.** A mutation verdict counts only if the mutant is valid: it
174
180
  compiled, sits on a path the exercised test traverses, and changes the guarded behavior, not
175
181
  healed downstream or coinciding with a default. The runner must report build failure,
176
- unreachable, and equivalent distinctly from KILLED and SURVIVED, and halt on a moved anchor.
182
+ unreachable, equivalent, and timed out distinctly from KILLED and SURVIVED, and halt on a moved
183
+ anchor. A timeout is not a kill: it moves with machine load, so set the limit well above the
184
+ unmutated suite's runtime and accept a verdict only when repeated runs agree on which mutants
185
+ timed out.
177
186
  More tests red than the mutation should touch indicts it; classify a survivor (rebuild,
178
187
  discard, genuine gap) before writing a test. **Equivalent is a verdict about the probe as
179
188
  much as the mutant**: a probe that is dead or returns a constant reports every mutant as
@@ -10,9 +10,13 @@ import sys
10
10
 
11
11
 
12
12
  def main() -> int:
13
+ # A Windows PowerShell 5.1 caller may prefix piped input with a UTF-8 BOM.
14
+ for stream, encoding in ((sys.stdin, "utf-8-sig"), (sys.stdout, "utf-8"), (sys.stderr, "utf-8")):
15
+ if hasattr(stream, "reconfigure"):
16
+ stream.reconfigure(encoding=encoding, errors="strict")
13
17
  root = Path(__file__).resolve().parents[1]
14
18
  expected = {"SKILL.md", "agents/openai.yaml", "scripts/bridge.py",
15
- "scripts/instructions_transaction.py", "bridge.json"}
19
+ "scripts/instructions_transaction.py", "scripts/host_platform.py", "bridge.json"}
16
20
  try:
17
21
  paths = list(root.rglob("*"))
18
22
  if any(path.is_symlink() for path in paths):
@@ -32,6 +36,8 @@ def main() -> int:
32
36
  if not isinstance(config.get(key), str) or not Path(config[key]).is_absolute():
33
37
  raise RuntimeError("registered bridge needs absolute private roots")
34
38
  sys.dont_write_bytecode = True
39
+ sys.path.insert(0, str(root / "scripts"))
40
+ from host_platform import cli_argv, python_argv, runtime_environment
35
41
  from instructions_transaction import confirmed_release, guard_pending, reject_symlink_ancestors
36
42
  state = Path(config["state_root"])
37
43
  reject_symlink_ancestors(state)
@@ -52,27 +58,38 @@ def main() -> int:
52
58
  if not isinstance(value, str) or (value and not Path(value).is_absolute()):
53
59
  raise RuntimeError("registered bridge has an invalid managed runtime path")
54
60
  env["AGENT_LAUNCH_VENV"] = value
61
+ if "python_binding" in config:
62
+ bound = config["python_binding"]
63
+ if not isinstance(bound, dict):
64
+ raise RuntimeError('registered Python binding must be an object')
65
+ env.update(runtime_environment(bound))
55
66
  args = sys.argv[1:]
56
67
  command = args[0] if args else "session"
57
68
  tail = args[1:] if args else ["status", "--json"]
58
69
  if command == "bootstrap":
59
- print((release / "compose/bootstrap/SKILL.md").read_text(encoding="utf-8"), end="")
70
+ text = (release / "compose/bootstrap/SKILL.md").read_text(encoding="utf-8")
71
+ if os.name == "nt":
72
+ prefix = "& '" + sys.executable.replace("'", "''") + "' '" + str(root / "scripts/bridge.py").replace("'", "''") + "' instructions"
73
+ text = text.replace('bash "$AGENT_BIOS_PACKAGE_ROOT/install.sh" instructions', prefix).replace('agent-bios instructions', prefix)
74
+ print(text, end="")
60
75
  return 0
61
76
  if command == "tui":
62
77
  operation = "instructions" if (release / "compose/instructions.py").is_file() else "corpus"
63
- argv = ["/bin/bash", str(release / "install.sh"), operation, *tail]
78
+ argv = python_argv(release / 'compose/native_cli.py', operation, *tail, environ=env) if os.name == 'nt' else cli_argv(release, operation, *tail)
64
79
  elif command in {"setup", "instructions", "corpus", "import", "learn"}:
65
80
  if command == "instructions" and not (release / "compose/instructions.py").is_file():
66
81
  command = "corpus"
67
- argv = ["/bin/bash", str(release / "install.sh"), command, *tail]
82
+ argv = python_argv(release / 'compose/native_cli.py', command, *tail, environ=env) if os.name == 'nt' else cli_argv(release, command, *tail)
68
83
  elif command == "session":
69
84
  manager = release / "compose/instructions_app.py"
70
85
  if not manager.is_file():
71
86
  manager = release / "compose/corpus_app.py"
72
- argv = [sys.executable, str(manager), "--repo", str(release),
73
- "--state-dir", config["state_root"], "--user-dir", config["user_root"], "session", *tail]
87
+ argv = python_argv(manager, "--repo", str(release), "--state-dir", config["state_root"], "--user-dir", config["user_root"], "session", *tail, environ=env)
74
88
  else:
75
89
  raise RuntimeError("bridge supports setup, session, instructions, import, learn, bootstrap and tui")
90
+ if os.name == "nt":
91
+ import subprocess
92
+ return subprocess.call(argv, env=env)
76
93
  os.execve(argv[0], argv, env)
77
94
  except (OSError, RuntimeError, ValueError, KeyError) as exc:
78
95
  print(f"agent-bios app bridge: {exc}", file=sys.stderr)
@@ -0,0 +1,250 @@
1
+ #!/usr/bin/env python3
2
+ """Claude Desktop MCP server for explicit agent-bios instructions delivery.
3
+
4
+ It is a transport at the same layer as `compose/app_bridge/scripts/bridge.py`: it
5
+ owns no selection, ContentRef, receipt or identifier. Each tool call resolves the
6
+ confirmed private release again and runs that release's
7
+ `compose/instructions_app.py session <op> --host claude-desktop` in a child
8
+ process, so a package update answers from the next call and this long-lived
9
+ process holds nothing across requests.
10
+
11
+ Protocol 2025-11-25 over stdio, the revision Desktop speaks; a call that arrives
12
+ without a handshake is still answered, because nothing here depends on one.
13
+ Standard library only; stdout carries protocol messages and nothing else.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ from pathlib import Path
20
+ import subprocess
21
+ import sys
22
+ from typing import Any
23
+
24
+ HERE = Path(__file__).resolve().parent
25
+ PROTOCOL = "2025-11-25"
26
+ KNOWN_PROTOCOLS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05")
27
+ CALL_TIMEOUT = 120
28
+
29
+ _SESSION_ID = {"type": "string", "description": "The session_id an earlier preview or use returned in this conversation."}
30
+ _DOMAINS = {"type": "array", "items": {"type": "string"},
31
+ "description": "Only when the user names a selection; omit to use their saved installation selection."}
32
+ # One owner: the bundle builder reads this list for the manifest.
33
+ TOOLS = [
34
+ {"name": "status",
35
+ "description": "Show whether agent-bios instructions were delivered to this conversation. After reading a "
36
+ "delivery to its last line, call this with end_marker_seen set to that line.",
37
+ "inputSchema": {"type": "object", "properties": {
38
+ "session_id": _SESSION_ID,
39
+ "end_marker_seen": {"type": "string", "description": "The delivery's last line, exactly as read."}},
40
+ "required": ["session_id"]}},
41
+ {"name": "preview",
42
+ "description": "Describe the agent-bios work environment use would return, without delivering it. "
43
+ "Call only when the user asks for their agent-bios instructions or environment.",
44
+ "inputSchema": {"type": "object", "properties": {"session_id": _SESSION_ID, "domains": _DOMAINS}}},
45
+ {"name": "use",
46
+ "description": "Return the user's selected agent-bios work environment as context for this conversation. "
47
+ "Call only when the user asks for it.",
48
+ "inputSchema": {"type": "object", "properties": {
49
+ "session_id": _SESSION_ID, "domains": _DOMAINS,
50
+ "expected_content_ref": {"type": "string", "description": "The content_ref preview returned, to refuse a changed snapshot."}}}},
51
+ {"name": "off",
52
+ "description": "Stop agent-bios delivery in this conversation. Text already returned stays in context.",
53
+ "inputSchema": {"type": "object", "properties": {"session_id": _SESSION_ID}, "required": ["session_id"]}},
54
+ ]
55
+
56
+
57
+ class ToolError(RuntimeError):
58
+ pass
59
+
60
+
61
+ def _config() -> dict[str, Any]:
62
+ config = json.loads((HERE / "desktop.json").read_text(encoding="utf-8"))
63
+ if config.get("schema_version") != 1:
64
+ raise ToolError("this agent-bios Desktop bundle has an unsupported configuration; generate it again with agent-bios app desktop")
65
+ for key in ("home", "state_root", "user_root"):
66
+ if not isinstance(config.get(key), str) or not Path(config[key]).is_absolute():
67
+ raise ToolError("this agent-bios Desktop bundle needs absolute private roots")
68
+ return config
69
+
70
+
71
+ def _string(arguments: dict[str, Any], key: str) -> str | None:
72
+ value = arguments.get(key)
73
+ if value is None:
74
+ return None
75
+ if not isinstance(value, str) or not value.strip():
76
+ raise ToolError(f"{key} must be a nonempty string")
77
+ return value.strip()
78
+
79
+
80
+ def _argv(operation: str, arguments: dict[str, Any]) -> list[str]:
81
+ tail = ["--host", "claude-desktop"]
82
+ session = _string(arguments, "session_id")
83
+ if session is not None:
84
+ tail += ["--session", session]
85
+ if operation in {"preview", "use"} and arguments.get("domains") is not None:
86
+ domains = arguments["domains"]
87
+ if not isinstance(domains, list) or not domains or not all(isinstance(v, str) and v.strip() for v in domains):
88
+ raise ToolError("domains must be a nonempty list of selection names")
89
+ tail += ["--domains", ",".join(v.strip() for v in domains)]
90
+ if operation == "use" and (ref := _string(arguments, "expected_content_ref")) is not None:
91
+ tail += ["--expected-content-ref", ref]
92
+ if operation == "status" and (marker := _string(arguments, "end_marker_seen")) is not None:
93
+ tail += ["--end-marker-seen", marker]
94
+ return tail
95
+
96
+
97
+ def run_session(operation: str, arguments: dict[str, Any]) -> dict[str, Any]:
98
+ config = _config()
99
+ sys.dont_write_bytecode = True
100
+ sys.path.insert(0, str(HERE))
101
+ from host_platform import python_argv, runtime_environment
102
+ from instructions_transaction import confirmed_release, guard_pending, reject_symlink_ancestors
103
+ state = Path(config["state_root"])
104
+ reject_symlink_ancestors(state)
105
+ reject_symlink_ancestors(Path(config["user_root"]))
106
+ guard_pending(state)
107
+ release = confirmed_release(state)
108
+ reject_symlink_ancestors(release)
109
+ env = dict(os.environ)
110
+ env.update({"HOME": config["home"], "AGENT_BIOS_STATE_DIR": config["state_root"],
111
+ "AGENT_BIOS_INSTRUCTIONS_DIR": config["user_root"], "AGENT_BIOS_CORPUS_DIR": config["user_root"],
112
+ "AGENT_BIOS_PACKAGE_ROOT": str(release), "AGENT_BIOS_PRIVATE_INSTRUCTIONS": "1",
113
+ "AGENT_BIOS_PRIVATE_CORPUS": "1", "AGENT_BIOS_LEGACY_INSTALL": "0",
114
+ "PYTHONDONTWRITEBYTECODE": "1"})
115
+ if "python_binding" in config:
116
+ if not isinstance(config["python_binding"], dict):
117
+ raise ToolError("the bundle's Python binding must be an object")
118
+ env.update(runtime_environment(config["python_binding"]))
119
+ manager = release / "compose/instructions_app.py"
120
+ argv = python_argv(manager, "--repo", str(release), "--state-dir", config["state_root"],
121
+ "--user-dir", config["user_root"], "--json", "session", operation,
122
+ *_argv(operation, arguments), environ=env)
123
+ try:
124
+ done = subprocess.run(argv, env=env, stdin=subprocess.DEVNULL, capture_output=True,
125
+ text=True, encoding="utf-8", timeout=CALL_TIMEOUT)
126
+ except subprocess.TimeoutExpired as exc:
127
+ raise ToolError(f"agent-bios did not answer within {CALL_TIMEOUT} seconds") from exc
128
+ if done.returncode != 0:
129
+ raise ToolError(done.stderr.strip() or f"agent-bios session {operation} failed")
130
+ try:
131
+ return json.loads(done.stdout)
132
+ except ValueError as exc:
133
+ raise ToolError("agent-bios returned an unreadable session result") from exc
134
+
135
+
136
+ def _scope(result: dict[str, Any]) -> str:
137
+ return ("Project scope: none. Desktop names no project, so project-scoped imported "
138
+ "instructions are not included.") if result.get("project_scope") == "none" else ""
139
+
140
+
141
+ def _size_note(result: dict[str, Any]) -> str:
142
+ if not result.get("host_may_save_to_file"):
143
+ return ""
144
+ return (f"{result['instruction_bytes']} bytes is above the smallest limit Desktop has kept inline; "
145
+ "Desktop may save this result to a file instead of showing it.")
146
+
147
+
148
+ def _unavailable(result: dict[str, Any]) -> str:
149
+ items = result.get("unavailable") or []
150
+ names = [f"{item.get('ref')} ({item.get('reason')})" if isinstance(item, dict) else str(item) for item in items]
151
+ return "Not included: " + "; ".join(names) if names else ""
152
+
153
+
154
+ def render(operation: str, result: dict[str, Any]) -> str:
155
+ session = result.get("session_id")
156
+ if operation == "use" and isinstance(result.get("instruction_text"), str):
157
+ lines = [f"agent-bios session_id: {session} — pass it to status, off and use in this conversation.",
158
+ f"content_ref: {result['content_ref']}", _scope(result), _size_note(result)]
159
+ if result.get("repeat"):
160
+ lines.append("Same snapshot as this conversation's latest delivery; returned again with its existing receipt.")
161
+ lines.append(_unavailable(result))
162
+ lines.append("The text below ends with a line beginning 'agent-bios end'. After reading to it, "
163
+ "call status with that whole line as end_marker_seen.")
164
+ header = "\n".join(line for line in lines if line)
165
+ return f"{header}\n\n{result['instruction_text'].rstrip()}\n\n{result['end_marker']}"
166
+ if operation == "preview":
167
+ if result.get("selection_mode") == "none":
168
+ return f"agent-bios session_id: {session}\nNo instructions are selected; use would return nothing."
169
+ lines = [f"agent-bios session_id: {session} — pass it to use, status and off in this conversation.",
170
+ f"content_ref: {result['content_ref']}",
171
+ f"Size: {result.get('instruction_characters')} characters, {result.get('instruction_bytes')} bytes.",
172
+ _scope(result), _size_note(result),
173
+ _unavailable(result),
174
+ "Nothing was delivered. Call use to return this text."]
175
+ return "\n".join(line for line in lines if line)
176
+ lines = [f"agent-bios session_id: {session}",
177
+ f"Delivery: {'on' if result.get('enabled') else 'off'}; "
178
+ f"deliveries recorded: {len(result.get('deliveries', []))}.",
179
+ f"Latest delivery read to its end: {'yes' if result.get('latest_end_confirmed') else 'no'}."
180
+ if result.get("ever_delivered") else "",
181
+ result.get("message", "")]
182
+ return "\n".join(line for line in lines if line)
183
+
184
+
185
+ def call_tool(params: dict[str, Any]) -> dict[str, Any]:
186
+ name = params.get("name")
187
+ arguments = params.get("arguments") or {}
188
+ if name not in {tool["name"] for tool in TOOLS}:
189
+ return {"content": [{"type": "text", "text": f"unknown tool: {name}"}], "isError": True}
190
+ if not isinstance(arguments, dict):
191
+ return {"content": [{"type": "text", "text": "arguments must be an object"}], "isError": True}
192
+ try:
193
+ text = render(name, run_session(name, arguments))
194
+ return {"content": [{"type": "text", "text": text}], "isError": False}
195
+ except (ToolError, OSError, RuntimeError, ValueError, KeyError) as exc:
196
+ return {"content": [{"type": "text", "text": f"agent-bios: {exc}"}], "isError": True}
197
+
198
+
199
+ def respond(message: Any) -> dict[str, Any] | None:
200
+ if not isinstance(message, dict):
201
+ return {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "expected one JSON-RPC request object"}}
202
+ method, ident = message.get("method"), message.get("id")
203
+ params = message.get("params") if isinstance(message.get("params"), dict) else {}
204
+ if method == "initialize":
205
+ asked = params.get("protocolVersion")
206
+ result: dict[str, Any] = {"protocolVersion": asked if asked in KNOWN_PROTOCOLS else PROTOCOL,
207
+ "capabilities": {"tools": {}},
208
+ "serverInfo": {"name": "agent-bios", "version": _version()}}
209
+ elif method == "ping":
210
+ result = {}
211
+ elif method == "tools/list":
212
+ result = {"tools": TOOLS}
213
+ elif method == "tools/call":
214
+ result = call_tool(params)
215
+ elif ident is None:
216
+ return None
217
+ else:
218
+ return {"jsonrpc": "2.0", "id": ident, "error": {"code": -32601, "message": f"method not supported: {method}"}}
219
+ return None if ident is None else {"jsonrpc": "2.0", "id": ident, "result": result}
220
+
221
+
222
+ def _version() -> str:
223
+ try:
224
+ return str(json.loads((HERE.parent / "manifest.json").read_text(encoding="utf-8"))["version"])
225
+ except (OSError, ValueError, KeyError):
226
+ return "unknown"
227
+
228
+
229
+ def main() -> int:
230
+ for stream in (sys.stdin, sys.stdout):
231
+ if hasattr(stream, "reconfigure"):
232
+ stream.reconfigure(encoding="utf-8")
233
+ for line in sys.stdin:
234
+ if not line.strip():
235
+ continue
236
+ try:
237
+ message = json.loads(line)
238
+ except ValueError:
239
+ reply: dict[str, Any] | None = {"jsonrpc": "2.0", "id": None,
240
+ "error": {"code": -32700, "message": "parse error"}}
241
+ else:
242
+ reply = respond(message)
243
+ if reply is not None:
244
+ sys.stdout.write(json.dumps(reply, ensure_ascii=False) + "\n")
245
+ sys.stdout.flush()
246
+ return 0
247
+
248
+
249
+ if __name__ == "__main__":
250
+ raise SystemExit(main())
@@ -108,6 +108,7 @@
108
108
  "slide-writing.md": {"tier": "domain", "domains": ["office-work", "visualization-docs"], "item_id": "skill-slide-writing"},
109
109
  "verification-discipline.md": {"tier": "domain", "domains": ["builder-base"], "item_id": "guide-verification-discipline"},
110
110
  "tooling-gotchas.md": {"tier": "domain", "domains": ["builder-base"], "item_id": "guide-tooling-gotchas"},
111
+ "ui-design.md": {"tier": "domain", "domains": ["builder-base"], "item_id": "guide-ui-design"},
111
112
  "korean-writing.md": {"tier": "core", "domains": [], "item_id": "korean-writing"}
112
113
  },
113
114
  "hooks": {