quireai 0.1.0__py3-none-any.whl

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 (147) hide show
  1. quire/__init__.py +1 -0
  2. quire/__main__.py +14 -0
  3. quire/agent/__init__.py +1 -0
  4. quire/agent/arms.py +292 -0
  5. quire/agent/attachments.py +58 -0
  6. quire/agent/backends/__init__.py +1 -0
  7. quire/agent/backends/base.py +161 -0
  8. quire/agent/backends/claude.py +238 -0
  9. quire/agent/backends/codex.py +380 -0
  10. quire/agent/backends/opencode.py +364 -0
  11. quire/agent/backends/rpc.py +167 -0
  12. quire/agent/bridge.py +203 -0
  13. quire/agent/conversation.py +311 -0
  14. quire/agent/prompt.py +157 -0
  15. quire/agent/session.py +486 -0
  16. quire/agent/sidecar.py +113 -0
  17. quire/agent/tools.py +483 -0
  18. quire/app.py +249 -0
  19. quire/auth.py +35 -0
  20. quire/cli.py +81 -0
  21. quire/context/__init__.py +1 -0
  22. quire/context/graph.py +121 -0
  23. quire/context/inventory.py +128 -0
  24. quire/context/ledger.py +77 -0
  25. quire/context/packet.py +281 -0
  26. quire/context/tokens.py +24 -0
  27. quire/context/variables.py +61 -0
  28. quire/debugging.py +81 -0
  29. quire/doc/__init__.py +1 -0
  30. quire/doc/arms.py +259 -0
  31. quire/doc/checkpoint.py +148 -0
  32. quire/doc/ipynb.py +138 -0
  33. quire/doc/model.py +62 -0
  34. quire/doc/ops.py +204 -0
  35. quire/doc/store.py +121 -0
  36. quire/doc/strip.py +61 -0
  37. quire/file_api.py +219 -0
  38. quire/files.py +84 -0
  39. quire/git.py +575 -0
  40. quire/git_api.py +176 -0
  41. quire/hub.py +514 -0
  42. quire/kernel/__init__.py +1 -0
  43. quire/kernel/code_help.py +91 -0
  44. quire/kernel/debugger.py +346 -0
  45. quire/kernel/executor.py +348 -0
  46. quire/kernel/interpreter.py +76 -0
  47. quire/kernel/kernel_helper.py +845 -0
  48. quire/kernel/outputs.py +166 -0
  49. quire/kernel/session.py +394 -0
  50. quire/kernel/table_helper.py +591 -0
  51. quire/kernel/variable_view.py +332 -0
  52. quire/kernel/widgets.py +354 -0
  53. quire/protocol.py +797 -0
  54. quire/shell_child.py +16 -0
  55. quire/static/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  56. quire/static/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  57. quire/static/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  58. quire/static/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  59. quire/static/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  60. quire/static/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  61. quire/static/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  62. quire/static/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  63. quire/static/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  64. quire/static/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  65. quire/static/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  66. quire/static/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  67. quire/static/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  68. quire/static/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  69. quire/static/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  70. quire/static/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  71. quire/static/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  72. quire/static/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  73. quire/static/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  74. quire/static/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  75. quire/static/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  76. quire/static/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  77. quire/static/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  78. quire/static/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  79. quire/static/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  80. quire/static/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  81. quire/static/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  82. quire/static/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  83. quire/static/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  84. quire/static/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  85. quire/static/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  86. quire/static/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  87. quire/static/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  88. quire/static/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  89. quire/static/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  90. quire/static/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  91. quire/static/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  92. quire/static/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  93. quire/static/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  94. quire/static/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  95. quire/static/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  96. quire/static/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  97. quire/static/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  98. quire/static/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  99. quire/static/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  100. quire/static/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  101. quire/static/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  102. quire/static/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  103. quire/static/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  104. quire/static/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  105. quire/static/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  106. quire/static/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  107. quire/static/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  108. quire/static/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  109. quire/static/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  110. quire/static/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  111. quire/static/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  112. quire/static/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  113. quire/static/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  114. quire/static/assets/TerminalPane-Bro4TU3o.css +1 -0
  115. quire/static/assets/TerminalPane-v20mOnlF.js +18 -0
  116. quire/static/assets/auto-render-BiUk-CzN.js +257 -0
  117. quire/static/assets/download-wAs-UBGo.js +766 -0
  118. quire/static/assets/index-D0vadP_b.css +1 -0
  119. quire/static/assets/index-Yk83QJ9J.js +420 -0
  120. quire/static/assets/instrument-serif-latin-400-italic-DKMiL14s.woff2 +0 -0
  121. quire/static/assets/instrument-serif-latin-400-italic-u__WvvIK.woff +0 -0
  122. quire/static/assets/instrument-serif-latin-400-normal-BVbkICAY.woff +0 -0
  123. quire/static/assets/instrument-serif-latin-400-normal-DnYpCC2O.woff2 +0 -0
  124. quire/static/assets/inter-cyrillic-ext-opsz-normal-CfYZpDVp.woff2 +0 -0
  125. quire/static/assets/inter-cyrillic-opsz-normal-BFQXbQ-f.woff2 +0 -0
  126. quire/static/assets/inter-greek-ext-opsz-normal-BmPQvyvo.woff2 +0 -0
  127. quire/static/assets/inter-greek-opsz-normal-BM0NlUE_.woff2 +0 -0
  128. quire/static/assets/inter-latin-ext-opsz-normal-DpK-iCPk.woff2 +0 -0
  129. quire/static/assets/inter-latin-opsz-normal-BwkfbSeq.woff2 +0 -0
  130. quire/static/assets/inter-vietnamese-opsz-normal-Ci9T9ieq.woff2 +0 -0
  131. quire/static/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  132. quire/static/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  133. quire/static/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  134. quire/static/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  135. quire/static/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  136. quire/static/assets/mermaid.min-CDSj-a4E.js +4330 -0
  137. quire/static/assets/plotly.min-CaWywiwD.js +3620 -0
  138. quire/static/assets/widgetLibrary-C3QXBEFI.js +36 -0
  139. quire/static/assets/widgetLibrary-C88Z8tk3.css +1 -0
  140. quire/static/index.html +24 -0
  141. quire/table_protocol.py +113 -0
  142. quire/terminal.py +197 -0
  143. quireai-0.1.0.dist-info/METADATA +598 -0
  144. quireai-0.1.0.dist-info/RECORD +147 -0
  145. quireai-0.1.0.dist-info/WHEEL +4 -0
  146. quireai-0.1.0.dist-info/entry_points.txt +3 -0
  147. quireai-0.1.0.dist-info/licenses/LICENSE +21 -0
quire/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Quire: a notebook where Claude is a cell."""
quire/__main__.py ADDED
@@ -0,0 +1,14 @@
1
+ """`python -m quire`: the same as the `quire` command.
2
+
3
+ `strip` is picked out first, so that Git's clean filter, which runs it for each notebook, does not load
4
+ the server and the agents.
5
+ """
6
+
7
+ import sys
8
+
9
+ if sys.argv[1:] == ["strip"]:
10
+ from .doc.strip import main
11
+ else:
12
+ from .cli import main
13
+
14
+ main()
@@ -0,0 +1 @@
1
+ """Claude inside the notebook: one Claude Code session per notebook, with notebook tools."""
quire/agent/arms.py ADDED
@@ -0,0 +1,292 @@
1
+ """The arms of a notebook: starts a block, runs one Claude per arm, and applies the user's decision.
2
+
3
+ An arm is its own conversation with Claude (a fresh session: the context packet is a valid cold start),
4
+ with tools that only change the arm's own cells and use the arm's own copy of the variables. The arms of
5
+ a block work at the same time; their cell runs take turns on the one kernel. How a block sits in the
6
+ document is in quire.doc.arms; how an arm's variables live in the kernel is in quire.kernel.
7
+
8
+ The work of an arm is a Turn with `arm` set. It is kept in memory only: after a restart of Quire the
9
+ block still shows each arm's cells, outputs and verdict, which are in the notebook file.
10
+ """
11
+
12
+ import asyncio
13
+ import contextlib
14
+ import time
15
+ import uuid
16
+ from collections.abc import Callable
17
+ from dataclasses import dataclass
18
+ from typing import TYPE_CHECKING, Any
19
+
20
+ from .. import protocol as p
21
+ from ..context.ledger import Ledger
22
+ from ..context.tokens import clip
23
+ from ..doc import arms
24
+ from ..doc.checkpoint import TurnCheckpoint
25
+ from ..doc.model import QUIRE, Cell
26
+ from ..doc.ops import CellDelete, CellInsert, CellMeta, CellSource, OpError
27
+ from ..kernel.session import EvaluationError, KernelDied
28
+ from .backends.base import Backend, BackendError
29
+ from .conversation import Conversation, Verdict, packet_for
30
+ from .prompt import ARM_PROMPT
31
+ from .tools import ARM_SPECS, Kind, NotebookTools, ToolError
32
+
33
+ if TYPE_CHECKING:
34
+ from ..hub import Room
35
+
36
+ LETTERS = "abcd"
37
+ VERDICT_TOKENS = 400 # an arm's verdict is cut to this in the block's summary
38
+ STOP_SECONDS = 10.0 # how long a stopped arm gets to end by itself
39
+
40
+
41
+ @dataclass
42
+ class _Run:
43
+ group: str
44
+ arm: str
45
+ turn: p.Turn
46
+ conversation: Conversation
47
+ task: asyncio.Task[None] | None = None
48
+ stopped: bool = False
49
+
50
+ @property
51
+ def working(self) -> bool:
52
+ return self.task is not None and not self.task.done()
53
+
54
+
55
+ class Arms:
56
+ def __init__(
57
+ self,
58
+ room: "Room",
59
+ *,
60
+ backend: Callable[[], Backend],
61
+ model: Callable[[], str | None],
62
+ mode: Callable[[], p.PermissionMode],
63
+ note: Callable[[str | None, str | None, str], None],
64
+ ) -> None:
65
+ self.room = room
66
+ self._backend = backend # the backend of the chat that starts a block: its arms run on it too
67
+ self._model = model
68
+ self._mode = mode
69
+ self._note = note # (asking cell, asking turn, text): adds a line to the answer that started a block
70
+ self._runs: dict[str, _Run] = {} # arm key -> its work, for the blocks started since Quire started
71
+ self._asked_in: dict[str, str | None] = {} # block id -> the turn that started it
72
+
73
+ @property
74
+ def turns(self) -> list[p.Turn]:
75
+ return [run.turn for run in self._runs.values()]
76
+
77
+ # ---- starting ----
78
+ async def start(self, goal: str, listed: Any, *, origin: str | None, turn: str | None) -> str:
79
+ """Makes a block below the asking cell and starts its arms. Returns what Claude is told."""
80
+ if any(run.working for run in self._runs.values()):
81
+ raise ToolError(
82
+ "Arms are still working in this notebook. Wait until they end, or the user stops them."
83
+ )
84
+ if not isinstance(listed, list) or not arms.MIN_ARMS <= len(listed) <= arms.MAX_ARMS:
85
+ raise ToolError(f"Give {arms.MIN_ARMS} to {arms.MAX_ARMS} arms.")
86
+ entries = []
87
+ for letter, item in zip(LETTERS, listed, strict=False):
88
+ fields = item if isinstance(item, dict) else {}
89
+ title, instruction = (
90
+ str(fields.get("title", "")).strip(),
91
+ str(fields.get("instruction", "")).strip(),
92
+ )
93
+ if not title or not instruction:
94
+ raise ToolError("Every arm needs a title and an instruction.")
95
+ entries.append(arms.Arm(id=letter, title=title, instruction=instruction))
96
+ await self.room.ensure_kernel()
97
+ executor = self.room.executor
98
+ assert executor is not None
99
+ block = arms.Block(id=uuid.uuid4().hex[:8], goal=str(goal).strip(), origin=origin, arms=entries)
100
+ store = self.room.store
101
+ after = origin is not None and store.nb.has(origin)
102
+ index = arms.end_of(store.nb.cells, store.nb.index_of(origin)) + 1 if after else len(store.nb.cells)
103
+ header = Cell(
104
+ kind="markdown", source=arms.render(block), metadata={QUIRE: {arms.ARMS: block.model_dump()}}
105
+ )
106
+ store.apply([CellInsert(index=index, cell=header)], "agent", actor=turn)
107
+ try:
108
+ await executor.fork([arms.key(block.id, arm.id) for arm in block.arms])
109
+ except (KernelDied, EvaluationError) as error:
110
+ store.apply([CellDelete(id=header.id)], "agent", actor=turn)
111
+ raise ToolError(f"The arms could not start: {error}") from None
112
+ self._asked_in[block.id] = turn
113
+ for arm in block.arms:
114
+ self._launch(block, arm)
115
+ position = next(
116
+ n for n, cell in enumerate(arms.main_view(store.nb.cells), start=1) if cell.id == header.id
117
+ )
118
+ names = ", ".join(f"{arm.id.upper()} · {arm.title}" for arm in block.arms)
119
+ return (
120
+ f"Started {len(block.arms)} arms in block #{position}: {names}.\n"
121
+ "They work on their own from now on, and the block shows each one's result when it ends. "
122
+ "End your turn: tell the user in one line that the arms started."
123
+ )
124
+
125
+ def _launch(self, block: arms.Block, arm: arms.Arm) -> None:
126
+ turn = p.Turn(
127
+ id=uuid.uuid4().hex[:10],
128
+ prompt=arm.instruction,
129
+ arm=p.ArmRef(group=block.id, id=arm.id),
130
+ status="running",
131
+ started_at=time.time(),
132
+ )
133
+ tools = NotebookTools(self.room, arm=(block.id, arm.id))
134
+ tools.begin(None, TurnCheckpoint(self.room.store, turn.id, {arms.ARM: arms.tag(block.id, arm.id)}))
135
+ conversation = Conversation(
136
+ self.room,
137
+ tools,
138
+ backend=self._backend(),
139
+ system_prompt=ARM_PROMPT,
140
+ specs=ARM_SPECS,
141
+ policy=self._policy,
142
+ after_change=self._publish,
143
+ )
144
+ conversation.model = self._model()
145
+ run = _Run(block.id, arm.id, turn, conversation)
146
+ self._runs[arms.key(block.id, arm.id)] = run
147
+ self._publish(turn)
148
+ run.task = asyncio.get_running_loop().create_task(self._work(run, block, arm))
149
+
150
+ def _policy(self, kind: Kind) -> Verdict:
151
+ """The user approved the block when it started: an arm then works inside it without asking."""
152
+ return "allow" if kind == "read" or self._mode() != "read" else "deny"
153
+
154
+ def _publish(self, turn: p.Turn) -> None:
155
+ self.room.broadcast(p.TurnMessage(turn=turn))
156
+
157
+ async def _work(self, run: _Run, block: arms.Block, arm: arms.Arm) -> None:
158
+ turn, conversation = run.turn, run.conversation
159
+ started = time.monotonic()
160
+ name = arm.id.upper()
161
+ try:
162
+ packet, report = await packet_for(
163
+ self.room, turn, conversation.tools, Ledger(), arm=f"{name} ({arm.title})"
164
+ )
165
+ turn.context_tokens = report.tokens
166
+ self.room.broadcast(p.ContextMessage(report=report))
167
+ task = (
168
+ f'<arm name="{name}" of="{len(block.arms)}" title="{arm.title}">\n'
169
+ f"Goal of all arms: {block.goal}\nYour approach: {arm.instruction}\n</arm>"
170
+ )
171
+ await conversation.exchange(turn, f"{packet}\n\n{task}")
172
+ except BackendError as error:
173
+ turn.error = conversation.backend.fix(str(error))
174
+ except (OSError, OpError) as error: # OpError: the block went away meanwhile
175
+ turn.error = conversation.backend.fix(f"{type(error).__name__}: {error}")
176
+ finally:
177
+ stopped = run.stopped or conversation.interrupted
178
+ turn.status = "interrupted" if stopped else "error" if turn.error else "done"
179
+ turn.seconds = time.monotonic() - started
180
+ self._summarize(run)
181
+ self._publish(turn)
182
+ await conversation.drop()
183
+
184
+ def _summarize(self, run: _Run) -> None:
185
+ """Writes how an arm ended into its block's header: state, verdict, what it changed in place."""
186
+ store = self.room.store
187
+ try:
188
+ header = store.nb.cells[arms.header_index(store.nb.cells, run.group)]
189
+ except OpError:
190
+ return # the block was kept or discarded while the arm was ending
191
+ block = arms.block_of(header)
192
+ assert block is not None
193
+ entry = block.arm(run.arm)
194
+ turn = run.turn
195
+ entry.status = "stopped" if turn.status == "interrupted" else "error" if turn.error else "done"
196
+ verdict = turn.answer[run.conversation.verdict_from :].strip() or turn.error or ""
197
+ entry.verdict = clip(verdict, VERDICT_TOKENS, "The arm's tab has all of it.")
198
+ entry.leaked = sorted(run.conversation.tools.leaked)
199
+ ops = [
200
+ CellMeta(id=header.id, patch={arms.ARMS: block.model_dump()}),
201
+ CellSource(id=header.id, source=arms.render(block)),
202
+ ]
203
+ store.apply(ops, "agent", actor=turn.id)
204
+
205
+ # ---- the user's decisions ----
206
+ async def decide(self, action: str, group: str, arm: str | None) -> None:
207
+ if action == "stop":
208
+ await self.stop(group, arm)
209
+ elif action == "discard":
210
+ await self._discard(group)
211
+ elif arm is not None:
212
+ await self._keep(group, arm)
213
+
214
+ async def stop(self, group: str | None = None, arm: str | None = None) -> None:
215
+ """Stops arms that are working: one arm, the arms of one block, or every arm."""
216
+ runs = [
217
+ run
218
+ for run in self._runs.values()
219
+ if run.working and group in (None, run.group) and arm in (None, run.arm)
220
+ ]
221
+ for run in runs:
222
+ run.stopped = True
223
+ if run.conversation.turn is not None and run.conversation.connected:
224
+ await run.conversation.interrupt()
225
+ elif run.task is not None:
226
+ run.task.cancel() # it has not reached Claude yet
227
+ if self.room.executor is not None:
228
+ await self.room.executor.stop_arm(arms.key(run.group, run.arm))
229
+ tasks = [run.task for run in runs if run.task is not None]
230
+ if tasks:
231
+ _, late = await asyncio.wait(tasks, timeout=STOP_SECONDS)
232
+ for task in late:
233
+ task.cancel()
234
+ if late:
235
+ await asyncio.wait(late)
236
+
237
+ def _block(self, group: str) -> arms.Block | None:
238
+ cells = self.room.store.nb.cells
239
+ try:
240
+ return arms.block_of(cells[arms.header_index(cells, group)])
241
+ except OpError:
242
+ self.room.notice("That block of arms is no longer in the notebook.")
243
+ return None
244
+
245
+ async def _keep(self, group: str, arm: str) -> None:
246
+ block = self._block(group)
247
+ if block is None or all(entry.id != arm for entry in block.arms):
248
+ return
249
+ await self.stop(group)
250
+ store, executor = self.room.store, self.room.executor
251
+ key = arms.key(group, arm)
252
+ changed: dict[str, list[str]] | None = None
253
+ if executor is not None and key in executor.arms:
254
+ changed = await executor.adopt(key)
255
+ kept = [cell.id for cell in store.nb.cells if arms.member_of(cell) == (group, arm)]
256
+ store.apply(arms.keep_ops(store.nb.cells, group, arm), "user")
257
+ await self._forget(block)
258
+ self.room.kept(kept, [] if changed is None else changed["bound"])
259
+ name = f"{arm.upper()} · {block.arm(arm).title}"
260
+ self._note(block.origin, self._asked_in.pop(group, None), f"Kept arm {name}.")
261
+ if changed is None:
262
+ self.room.notice(
263
+ f"Kept the cells of arm {name}. Its variables were gone (the kernel was restarted since): "
264
+ "run the cells to make them again."
265
+ )
266
+ elif changed["overwritten"]:
267
+ names = ", ".join(changed["overwritten"])
268
+ self.room.notice(f"Arm {name} replaced variables that changed after the arms started: {names}.")
269
+
270
+ async def _discard(self, group: str) -> None:
271
+ block = self._block(group)
272
+ if block is None:
273
+ return
274
+ await self.stop(group)
275
+ store = self.room.store
276
+ store.apply(arms.discard_ops(store.nb.cells, group), "user")
277
+ await self._forget(block)
278
+ self._note(block.origin, self._asked_in.pop(group, None), f"Discarded the {len(block.arms)} arms.")
279
+
280
+ async def _forget(self, block: arms.Block) -> None:
281
+ keys = [arms.key(block.id, arm.id) for arm in block.arms]
282
+ if self.room.executor is not None:
283
+ with contextlib.suppress(KernelDied, EvaluationError): # the variables are gone either way
284
+ await self.room.executor.drop(keys)
285
+ for key in keys:
286
+ self._runs.pop(key, None)
287
+
288
+ async def close(self) -> None:
289
+ for run in self._runs.values():
290
+ if run.task is not None:
291
+ run.task.cancel()
292
+ await run.conversation.drop()
@@ -0,0 +1,58 @@
1
+ """Files attached to a panel message: Claude gets an image as an image and a text file as text.
2
+
3
+ Quire does not keep the files. They go to Claude with the turn, and the turn records their names. If the
4
+ Claude session is later replaced (context full, resume failed), Claude no longer has them.
5
+ """
6
+
7
+ import base64
8
+ import binascii
9
+ from typing import Any
10
+
11
+ from .. import protocol as p
12
+ from ..context.tokens import clip
13
+
14
+ IMAGE_TYPES = frozenset({"image/png", "image/jpeg", "image/gif", "image/webp"})
15
+ MAX_BYTES = 5 * 1024 * 1024 # one file; also the most Claude takes for one image
16
+ MAX_TOTAL_BYTES = 10 * 1024 * 1024 # one message: as base64 it must fit a 16 MB WebSocket frame
17
+ TEXT_TOKENS = 20_000 # a text file longer than this is cut: head and tail stay
18
+
19
+
20
+ class AttachmentError(ValueError):
21
+ """The user attached something Quire cannot send. The message is shown to them."""
22
+
23
+
24
+ def to_blocks(attachments: list[p.Attachment]) -> tuple[list[dict[str, Any]], list[p.AttachmentInfo]]:
25
+ """The content blocks to send to Claude, and what the turn records about each file."""
26
+ blocks: list[dict[str, Any]] = []
27
+ infos: list[p.AttachmentInfo] = []
28
+ total = 0
29
+ for attachment in attachments:
30
+ name = attachment.name
31
+ try:
32
+ raw = base64.b64decode(attachment.data, validate=True)
33
+ except binascii.Error as error:
34
+ raise AttachmentError(f"{name} did not arrive whole. Attach it again.") from error
35
+ total += len(raw)
36
+ if len(raw) > MAX_BYTES:
37
+ raise AttachmentError(f"{name} is larger than 5 MB.")
38
+ if total > MAX_TOTAL_BYTES:
39
+ raise AttachmentError("The attached files are larger than 10 MB together.")
40
+ if attachment.media_type in IMAGE_TYPES:
41
+ source = {"type": "base64", "media_type": attachment.media_type, "data": attachment.data}
42
+ blocks.append({"type": "image", "source": source})
43
+ else:
44
+ blocks.append({"type": "text", "text": _as_text(name, raw)})
45
+ infos.append(p.AttachmentInfo(name=name, media_type=attachment.media_type, size=len(raw)))
46
+ return blocks, infos
47
+
48
+
49
+ def _as_text(name: str, raw: bytes) -> str:
50
+ try:
51
+ text = raw.decode("utf-8")
52
+ except UnicodeDecodeError as error:
53
+ raise AttachmentError(f"{name} is not an image (PNG, JPEG, GIF, WebP) or a text file.") from error
54
+ if "\x00" in text:
55
+ raise AttachmentError(f"{name} is not an image (PNG, JPEG, GIF, WebP) or a text file.")
56
+ body = clip(text, TEXT_TOKENS, "The user attached a longer file: ask them for the part you need.")
57
+ label = name.replace('"', "'").replace("\n", " ")
58
+ return f'<attached-file name="{label}">\n{body}\n</attached-file>'
@@ -0,0 +1 @@
1
+ """The agents a chat can run on: each is a local CLI with its own login (quire.agent.backends.base)."""
@@ -0,0 +1,161 @@
1
+ """What a chat needs from an agent CLI, whichever one it is.
2
+
3
+ A backend opens sessions. A session is one conversation with the CLI: it sends one user message at a
4
+ time and turns the CLI's output into the events below, in order, ending with `Ended`. The conversation
5
+ (quire.agent.conversation) turns those events into the turn the UI shows; it is the `ToolHost` that runs
6
+ the notebook tools and decides what they may do.
7
+
8
+ How the tools reach the CLI depends on the CLI: Claude gets them in process through its SDK, and asks
9
+ `permit` before each call; the other CLIs reach them over MCP (quire.agent.bridge), and `serve_tool`
10
+ decides and runs in one step.
11
+
12
+ Quire never holds keys: every CLI runs with its own login.
13
+ """
14
+
15
+ import os
16
+ import shutil
17
+ from collections.abc import AsyncIterator
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from typing import Any, Protocol
21
+
22
+ from ... import protocol as p
23
+ from ..tools import Spec, ToolResult
24
+
25
+ # A user message: plain text, or content blocks in Claude's form (text, and base64 images).
26
+ Content = str | list[dict[str, Any]]
27
+
28
+
29
+ def find_cli(name: str) -> str | None:
30
+ """Where a CLI is: on PATH, else in ~/.local/bin, where CLIs are often installed and which the PATH
31
+ of a non-login shell (a tmux session, a service) may lack."""
32
+ found = shutil.which(name)
33
+ if found is not None:
34
+ return found
35
+ local = Path.home() / ".local" / "bin" / name
36
+ return str(local) if local.is_file() and os.access(local, os.X_OK) else None
37
+
38
+
39
+ class BackendError(Exception):
40
+ """The CLI failed or could not start. The message is shown to the user."""
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Started:
45
+ """The CLI says what runs: the model id and how it is signed in, when it tells."""
46
+
47
+ model: str | None
48
+ login: str | None
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class TextStarted:
53
+ """A new block of answer text begins (after a tool call it starts a new paragraph)."""
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Text:
58
+ text: str
59
+ thinking: bool = False
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class ToolStarted:
64
+ """The CLI calls a tool. Calls of the notebook tools that go over MCP are recorded by the tool host
65
+ instead, so a session reports only the calls it sees in its own stream."""
66
+
67
+ id: str
68
+ name: str
69
+ input: dict[str, Any]
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class ToolEnded:
74
+ id: str
75
+ error: bool
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class Ended:
80
+ """The answer is complete. `error` is set when the turn failed; an interrupted turn has none."""
81
+
82
+ session_id: str | None
83
+ usage: p.Usage | None = None
84
+ error: str | None = None
85
+ context_used: int | None = None # tokens in the context window after this turn
86
+ context_max: int | None = None
87
+
88
+
89
+ Event = Started | TextStarted | Text | ToolStarted | ToolEnded | Ended
90
+
91
+
92
+ class ToolHost(Protocol):
93
+ """The conversation, as a session sees it."""
94
+
95
+ async def call_tool(self, name: str, arguments: dict[str, Any]) -> ToolResult:
96
+ """Runs a notebook tool that was allowed, and records the result in the turn."""
97
+ ...
98
+
99
+ async def permit(self, name: str, arguments: dict[str, Any], call_id: str) -> tuple[bool, str | None]:
100
+ """May this call run? Asks the user when the mode says so. (allowed, message for the agent)"""
101
+ ...
102
+
103
+ async def serve_tool(self, name: str, arguments: dict[str, Any]) -> ToolResult:
104
+ """`permit` and `call_tool` in one step, for a call that arrives over MCP."""
105
+ ...
106
+
107
+
108
+ @dataclass(frozen=True)
109
+ class SessionSpec:
110
+ system_prompt: str
111
+ model: str | None # None: the CLI's own default
112
+ resume: str | None # the session id of an earlier session to go on with
113
+ cwd: Path
114
+ specs: list[Spec] # the notebook tools of this conversation
115
+ host: ToolHost
116
+
117
+
118
+ def prompt_for(label: str, system_prompt: str) -> str:
119
+ """The system prompt for an agent that is not Claude.
120
+
121
+ The prompt is one text for every agent. It is written for Claude and the user may have edited it, so
122
+ it is not rewritten: a first line says who reads it.
123
+ """
124
+ return (
125
+ f"You are {label}, not Claude. The instructions below were written for Claude: "
126
+ f"where they say Claude, they mean you.\n\n{system_prompt}"
127
+ )
128
+
129
+
130
+ class Session(Protocol):
131
+ def send(self, content: Content) -> AsyncIterator[Event]:
132
+ """Sends one user message and streams the answer. Raises BackendError when the CLI fails."""
133
+ ...
134
+
135
+ async def interrupt(self) -> None:
136
+ """Stops the answer being streamed: the stream then ends with `Ended` and no error."""
137
+ ...
138
+
139
+ async def close(self) -> None:
140
+ """Ends the CLI process. The session can be resumed later by its id."""
141
+ ...
142
+
143
+
144
+ class Backend(Protocol):
145
+ id: p.BackendId
146
+ label: str
147
+
148
+ @property
149
+ def info(self) -> p.BackendInfo:
150
+ """Whether it can run here, why not, and the models its CLI lists."""
151
+ ...
152
+
153
+ async def refresh(self) -> None:
154
+ """Checks the CLI again: the user may have installed it or logged in since."""
155
+ ...
156
+
157
+ def open(self, spec: SessionSpec) -> Session: ...
158
+
159
+ def fix(self, error: str) -> str:
160
+ """Adds what to do to an error the user can fix."""
161
+ ...