@zvada/agent-server 0.3.26 → 0.3.28

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 (262) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +7 -5
  3. package/dist/client/client.js +27 -11
  4. package/dist/client/connection.js +35 -3
  5. package/dist/core/agents/acp/account.js +111 -0
  6. package/dist/core/agents/acp/acp-agent.js +247 -158
  7. package/dist/core/agents/acp/adapter.js +103 -34
  8. package/dist/core/agents/acp/client.js +169 -42
  9. package/dist/core/agents/acp/known-agents.js +12 -5
  10. package/dist/core/agents/acp/mappings.js +84 -20
  11. package/dist/core/agents/acp/models.js +59 -0
  12. package/dist/core/agents/acp/profile.js +36 -0
  13. package/dist/core/agents/acp/prompts.js +248 -0
  14. package/dist/core/agents/acp/requests.js +4 -4
  15. package/dist/core/agents/claude-code/approvals.js +1 -1
  16. package/dist/core/agents/claude-code/login.js +4 -1
  17. package/dist/core/agents/claude-code/session.js +38 -10
  18. package/dist/core/agents/claude-code/spawn.js +0 -26
  19. package/dist/core/agents/codex-app-server/client.js +12 -13
  20. package/dist/core/agents/codex-app-server/login.js +4 -1
  21. package/dist/core/agents/codex-app-server/plan-approval.js +1 -1
  22. package/dist/core/agents/gemini/failures.js +133 -0
  23. package/dist/core/agents/gemini/login.js +173 -0
  24. package/dist/core/agents/gemini/profile.js +137 -0
  25. package/dist/core/agents/gemini/tools.js +91 -0
  26. package/dist/core/agents/login.js +8 -6
  27. package/dist/core/agents/scripted/scripted-agent.js +30 -3
  28. package/dist/core/agents/stderr-tail.js +5 -2
  29. package/dist/core/presets.js +17 -1
  30. package/dist/core/processes/native-processes.js +23 -1
  31. package/dist/core/provision/install-build.js +70 -26
  32. package/dist/core/provision/pins.js +5 -0
  33. package/dist/core/provision/provisioner.js +39 -16
  34. package/dist/core/provision/releases.js +39 -1
  35. package/dist/core/provision/tools.js +87 -28
  36. package/dist/core/runtime/agent-runtime.js +15 -5
  37. package/dist/core/runtime/event-processor.js +13 -8
  38. package/dist/core/runtime/origin-line.js +42 -0
  39. package/dist/core/runtime/request-broker.js +2 -1
  40. package/dist/core/runtime/steering.js +4 -3
  41. package/dist/core/runtime/turn.js +6 -4
  42. package/dist/operator/errors.js +97 -0
  43. package/dist/operator/index.js +10 -5
  44. package/dist/operator/mcp.js +7 -12
  45. package/dist/operator/operator.js +1431 -378
  46. package/dist/operator/refs.js +59 -0
  47. package/dist/operator/render.js +199 -94
  48. package/dist/operator/session-tools.js +88 -0
  49. package/dist/operator/types.js +30 -0
  50. package/dist/operator/view.js +82 -27
  51. package/dist/protocol/account.js +5 -1
  52. package/dist/protocol/auth.js +5 -1
  53. package/dist/protocol/config.js +12 -5
  54. package/dist/protocol/conversation.js +3 -0
  55. package/dist/protocol/credentials.js +9 -1
  56. package/dist/protocol/harness.js +9 -1
  57. package/dist/protocol/history.js +2 -1
  58. package/dist/protocol/index.js +1 -0
  59. package/dist/protocol/lifecycle.js +19 -0
  60. package/dist/protocol/origin.js +39 -0
  61. package/dist/protocol/reduce.js +2 -0
  62. package/dist/protocol/wire.js +17 -0
  63. package/dist/server/bin.js +22 -7
  64. package/dist/server/install.js +6 -4
  65. package/dist/server/routes.js +15 -5
  66. package/dist/types/client/client.d.ts.map +1 -1
  67. package/dist/types/client/connection.d.ts +14 -2
  68. package/dist/types/client/connection.d.ts.map +1 -1
  69. package/dist/types/client/turns.d.ts +2 -2
  70. package/dist/types/client/turns.d.ts.map +1 -1
  71. package/dist/types/core/agents/acp/account.d.ts +55 -0
  72. package/dist/types/core/agents/acp/account.d.ts.map +1 -0
  73. package/dist/types/core/agents/acp/acp-agent.d.ts +65 -36
  74. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -1
  75. package/dist/types/core/agents/acp/adapter.d.ts +28 -3
  76. package/dist/types/core/agents/acp/adapter.d.ts.map +1 -1
  77. package/dist/types/core/agents/acp/client.d.ts +66 -4
  78. package/dist/types/core/agents/acp/client.d.ts.map +1 -1
  79. package/dist/types/core/agents/acp/known-agents.d.ts +4 -2
  80. package/dist/types/core/agents/acp/known-agents.d.ts.map +1 -1
  81. package/dist/types/core/agents/acp/mappings.d.ts +53 -7
  82. package/dist/types/core/agents/acp/mappings.d.ts.map +1 -1
  83. package/dist/types/core/agents/acp/models.d.ts +22 -0
  84. package/dist/types/core/agents/acp/models.d.ts.map +1 -0
  85. package/dist/types/core/agents/acp/profile.d.ts +92 -0
  86. package/dist/types/core/agents/acp/profile.d.ts.map +1 -0
  87. package/dist/types/core/agents/acp/prompts.d.ts +108 -0
  88. package/dist/types/core/agents/acp/prompts.d.ts.map +1 -0
  89. package/dist/types/core/agents/acp/requests.d.ts +7 -1
  90. package/dist/types/core/agents/acp/requests.d.ts.map +1 -1
  91. package/dist/types/core/agents/base.d.ts +2 -0
  92. package/dist/types/core/agents/base.d.ts.map +1 -1
  93. package/dist/types/core/agents/claude-code/login.d.ts.map +1 -1
  94. package/dist/types/core/agents/claude-code/session.d.ts +3 -0
  95. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  96. package/dist/types/core/agents/claude-code/spawn.d.ts +0 -8
  97. package/dist/types/core/agents/claude-code/spawn.d.ts.map +1 -1
  98. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  99. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  100. package/dist/types/core/agents/gemini/failures.d.ts +25 -0
  101. package/dist/types/core/agents/gemini/failures.d.ts.map +1 -0
  102. package/dist/types/core/agents/gemini/login.d.ts +28 -0
  103. package/dist/types/core/agents/gemini/login.d.ts.map +1 -0
  104. package/dist/types/core/agents/gemini/profile.d.ts +30 -0
  105. package/dist/types/core/agents/gemini/profile.d.ts.map +1 -0
  106. package/dist/types/core/agents/gemini/tools.d.ts +18 -0
  107. package/dist/types/core/agents/gemini/tools.d.ts.map +1 -0
  108. package/dist/types/core/agents/login.d.ts +15 -5
  109. package/dist/types/core/agents/login.d.ts.map +1 -1
  110. package/dist/types/core/agents/scripted/scripted-agent.d.ts +14 -1
  111. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  112. package/dist/types/core/agents/stderr-tail.d.ts +1 -1
  113. package/dist/types/core/agents/stderr-tail.d.ts.map +1 -1
  114. package/dist/types/core/presets.d.ts +2 -2
  115. package/dist/types/core/presets.d.ts.map +1 -1
  116. package/dist/types/core/processes/native-processes.d.ts +6 -0
  117. package/dist/types/core/processes/native-processes.d.ts.map +1 -1
  118. package/dist/types/core/provision/checksums.d.ts +7 -1
  119. package/dist/types/core/provision/checksums.d.ts.map +1 -1
  120. package/dist/types/core/provision/install-build.d.ts +32 -6
  121. package/dist/types/core/provision/install-build.d.ts.map +1 -1
  122. package/dist/types/core/provision/pins.d.ts +4 -0
  123. package/dist/types/core/provision/pins.d.ts.map +1 -1
  124. package/dist/types/core/provision/provisioner.d.ts +18 -7
  125. package/dist/types/core/provision/provisioner.d.ts.map +1 -1
  126. package/dist/types/core/provision/releases.d.ts +2 -1
  127. package/dist/types/core/provision/releases.d.ts.map +1 -1
  128. package/dist/types/core/provision/tools.d.ts +36 -7
  129. package/dist/types/core/provision/tools.d.ts.map +1 -1
  130. package/dist/types/core/runtime/agent-runtime.d.ts +4 -2
  131. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  132. package/dist/types/core/runtime/event-processor.d.ts +2 -2
  133. package/dist/types/core/runtime/event-processor.d.ts.map +1 -1
  134. package/dist/types/core/runtime/origin-line.d.ts +15 -0
  135. package/dist/types/core/runtime/origin-line.d.ts.map +1 -0
  136. package/dist/types/core/runtime/request-broker.d.ts +1 -1
  137. package/dist/types/core/runtime/request-broker.d.ts.map +1 -1
  138. package/dist/types/core/runtime/steering.d.ts +7 -4
  139. package/dist/types/core/runtime/steering.d.ts.map +1 -1
  140. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  141. package/dist/types/operator/errors.d.ts +87 -0
  142. package/dist/types/operator/errors.d.ts.map +1 -0
  143. package/dist/types/operator/index.d.ts +10 -5
  144. package/dist/types/operator/index.d.ts.map +1 -1
  145. package/dist/types/operator/mcp.d.ts +1 -1
  146. package/dist/types/operator/mcp.d.ts.map +1 -1
  147. package/dist/types/operator/operator.d.ts +15 -197
  148. package/dist/types/operator/operator.d.ts.map +1 -1
  149. package/dist/types/operator/refs.d.ts +25 -0
  150. package/dist/types/operator/refs.d.ts.map +1 -0
  151. package/dist/types/operator/render.d.ts +67 -22
  152. package/dist/types/operator/render.d.ts.map +1 -1
  153. package/dist/types/operator/session-tools.d.ts +61 -0
  154. package/dist/types/operator/session-tools.d.ts.map +1 -0
  155. package/dist/types/operator/types.d.ts +442 -0
  156. package/dist/types/operator/types.d.ts.map +1 -0
  157. package/dist/types/operator/view.d.ts +19 -29
  158. package/dist/types/operator/view.d.ts.map +1 -1
  159. package/dist/types/protocol/account.d.ts +4 -2
  160. package/dist/types/protocol/account.d.ts.map +1 -1
  161. package/dist/types/protocol/auth.d.ts +10 -7
  162. package/dist/types/protocol/auth.d.ts.map +1 -1
  163. package/dist/types/protocol/clis.d.ts +4 -3
  164. package/dist/types/protocol/clis.d.ts.map +1 -1
  165. package/dist/types/protocol/config.d.ts +22 -5
  166. package/dist/types/protocol/config.d.ts.map +1 -1
  167. package/dist/types/protocol/conversation.d.ts +47 -6
  168. package/dist/types/protocol/conversation.d.ts.map +1 -1
  169. package/dist/types/protocol/credentials.d.ts +8 -0
  170. package/dist/types/protocol/credentials.d.ts.map +1 -1
  171. package/dist/types/protocol/execution.d.ts +1 -1
  172. package/dist/types/protocol/harness.d.ts +5 -2
  173. package/dist/types/protocol/harness.d.ts.map +1 -1
  174. package/dist/types/protocol/history.d.ts +1 -1
  175. package/dist/types/protocol/history.d.ts.map +1 -1
  176. package/dist/types/protocol/index.d.ts +1 -0
  177. package/dist/types/protocol/index.d.ts.map +1 -1
  178. package/dist/types/protocol/lifecycle.d.ts +48 -10
  179. package/dist/types/protocol/lifecycle.d.ts.map +1 -1
  180. package/dist/types/protocol/models.d.ts +3 -0
  181. package/dist/types/protocol/models.d.ts.map +1 -1
  182. package/dist/types/protocol/origin.d.ts +49 -0
  183. package/dist/types/protocol/origin.d.ts.map +1 -0
  184. package/dist/types/protocol/reduce.d.ts.map +1 -1
  185. package/dist/types/protocol/wire-api.d.ts +78 -30
  186. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  187. package/dist/types/protocol/wire.d.ts +78 -12
  188. package/dist/types/protocol/wire.d.ts.map +1 -1
  189. package/dist/types/server/install.d.ts +2 -1
  190. package/dist/types/server/install.d.ts.map +1 -1
  191. package/dist/types/server/routes.d.ts.map +1 -1
  192. package/docs/consuming.md +62 -121
  193. package/docs/deploy.md +17 -8
  194. package/docs/harnesses.md +166 -44
  195. package/docs/sync-history.md +2 -1
  196. package/package.json +1 -1
  197. package/src/client/client.ts +36 -9
  198. package/src/client/connection.ts +31 -1
  199. package/src/client/turns.ts +2 -1
  200. package/src/core/agents/acp/account.ts +158 -0
  201. package/src/core/agents/acp/acp-agent.ts +288 -178
  202. package/src/core/agents/acp/adapter.ts +126 -35
  203. package/src/core/agents/acp/client.ts +196 -49
  204. package/src/core/agents/acp/known-agents.ts +14 -5
  205. package/src/core/agents/acp/mappings.ts +112 -21
  206. package/src/core/agents/acp/models.ts +72 -0
  207. package/src/core/agents/acp/profile.ts +127 -0
  208. package/src/core/agents/acp/prompts.ts +287 -0
  209. package/src/core/agents/acp/requests.ts +16 -9
  210. package/src/core/agents/base.ts +2 -0
  211. package/src/core/agents/claude-code/approvals.ts +2 -2
  212. package/src/core/agents/claude-code/login.ts +4 -1
  213. package/src/core/agents/claude-code/session.ts +38 -8
  214. package/src/core/agents/claude-code/spawn.ts +0 -26
  215. package/src/core/agents/codex-app-server/client.ts +11 -18
  216. package/src/core/agents/codex-app-server/login.ts +4 -5
  217. package/src/core/agents/codex-app-server/plan-approval.ts +1 -1
  218. package/src/core/agents/gemini/failures.ts +148 -0
  219. package/src/core/agents/gemini/login.ts +188 -0
  220. package/src/core/agents/gemini/profile.ts +162 -0
  221. package/src/core/agents/gemini/tools.ts +99 -0
  222. package/src/core/agents/login.ts +14 -8
  223. package/src/core/agents/scripted/scripted-agent.ts +42 -3
  224. package/src/core/agents/stderr-tail.ts +5 -2
  225. package/src/core/presets.ts +19 -3
  226. package/src/core/processes/native-processes.ts +32 -1
  227. package/src/core/provision/checksums.ts +12 -2
  228. package/src/core/provision/install-build.ts +122 -55
  229. package/src/core/provision/pins.ts +5 -0
  230. package/src/core/provision/provisioner.ts +62 -27
  231. package/src/core/provision/releases.ts +47 -1
  232. package/src/core/provision/tools.ts +124 -31
  233. package/src/core/runtime/agent-runtime.ts +31 -7
  234. package/src/core/runtime/event-processor.ts +13 -6
  235. package/src/core/runtime/origin-line.ts +43 -0
  236. package/src/core/runtime/request-broker.ts +2 -0
  237. package/src/core/runtime/steering.ts +8 -4
  238. package/src/core/runtime/turn.ts +11 -4
  239. package/src/operator/errors.ts +221 -0
  240. package/src/operator/index.ts +18 -23
  241. package/src/operator/mcp.ts +7 -16
  242. package/src/operator/operator.ts +1684 -610
  243. package/src/operator/refs.ts +75 -0
  244. package/src/operator/render.ts +260 -118
  245. package/src/operator/session-tools.ts +127 -0
  246. package/src/operator/types.ts +506 -0
  247. package/src/operator/view.ts +93 -42
  248. package/src/protocol/account.ts +5 -2
  249. package/src/protocol/auth.ts +5 -1
  250. package/src/protocol/config.ts +14 -6
  251. package/src/protocol/conversation.ts +3 -0
  252. package/src/protocol/credentials.ts +11 -2
  253. package/src/protocol/harness.ts +9 -1
  254. package/src/protocol/history.ts +2 -1
  255. package/src/protocol/index.ts +1 -0
  256. package/src/protocol/lifecycle.ts +21 -0
  257. package/src/protocol/origin.ts +47 -0
  258. package/src/protocol/reduce.ts +4 -0
  259. package/src/protocol/wire.ts +18 -0
  260. package/src/server/bin.ts +20 -6
  261. package/src/server/install.ts +6 -3
  262. package/src/server/routes.ts +16 -5
@@ -0,0 +1,75 @@
1
+ /**
2
+ * References a model types: `id / [project "/"] workspace [":" chat]`. What
3
+ * the tools print is always explicit (`workspace:N`, or the session's id when
4
+ * the host numbers no chats), so a printed reference never moves to another
5
+ * chat.
6
+ */
7
+
8
+ // @ref LLP 0019#references — the grammar, resolved over everything the caller may see, archived included
9
+
10
+ import type { Entry } from "./types.ts";
11
+
12
+ /** How the tools print an entry: `[project/]workspace:N`, or its id when it has no number. */
13
+ export function refOf(entry: Entry, all: readonly Entry[]): string {
14
+ if (entry.chat === undefined) return entry.id;
15
+ const shared = all.some(
16
+ (other) =>
17
+ other.workspace.id !== entry.workspace.id &&
18
+ other.workspace.name.toLowerCase() === entry.workspace.name.toLowerCase(),
19
+ );
20
+ const project = shared && entry.project ? `${entry.project.name}/` : "";
21
+ return `${project}${entry.workspace.name}:${entry.chat}`;
22
+ }
23
+
24
+ /** What a reference resolved to: one entry, several, or none. */
25
+ export type Resolved = { found: Entry } | { ambiguous: Entry[] } | { missing: true };
26
+
27
+ /**
28
+ * The entry `ref` names among `all` (everything the caller may see, archived
29
+ * included). An id is exact: a session's, or a workspace's (its current
30
+ * chat). A name is case-insensitive; a bare workspace means its current chat,
31
+ * resolved now.
32
+ */
33
+ export function resolve(ref: string, all: readonly Entry[]): Resolved {
34
+ const wanted = ref.trim();
35
+ const byId = all.find((entry) => entry.id === wanted);
36
+ if (byId) return { found: byId };
37
+ const inWorkspace = all.filter((entry) => entry.workspace.id === wanted);
38
+ if (inWorkspace.length) return pick(inWorkspace, undefined);
39
+ const slash = wanted.lastIndexOf("/");
40
+ const project = slash >= 0 ? wanted.slice(0, slash).toLowerCase() : undefined;
41
+ const rest = slash >= 0 ? wanted.slice(slash + 1) : wanted;
42
+ const colon = rest.lastIndexOf(":");
43
+ const number = colon >= 0 ? Number(rest.slice(colon + 1)) : undefined;
44
+ const chat = number !== undefined && Number.isInteger(number) && number > 0 ? number : undefined;
45
+ const workspace = (chat !== undefined ? rest.slice(0, colon) : rest).toLowerCase();
46
+ const named = all.filter(
47
+ (entry) =>
48
+ entry.workspace.name.toLowerCase() === workspace &&
49
+ (project === undefined || entry.project?.name.toLowerCase() === project),
50
+ );
51
+ const workspaces = [...new Set(named.map((entry) => entry.workspace.id))];
52
+ if (workspaces.length > 1)
53
+ return {
54
+ ambiguous: workspaces.map(
55
+ (id) =>
56
+ (named.find((e) => e.workspace.id === id && e.current) ??
57
+ named.find((e) => e.workspace.id === id)) as Entry,
58
+ ),
59
+ };
60
+ if (!named.length) return { missing: true };
61
+ return pick(named, chat);
62
+ }
63
+
64
+ /** In one workspace's entries: chat `chat`, else its current chat. */
65
+ function pick(entries: readonly Entry[], chat: number | undefined): Resolved {
66
+ if (chat !== undefined) {
67
+ const hit = entries.find((entry) => (entry.chat ?? 1) === chat);
68
+ return hit ? { found: hit } : { missing: true };
69
+ }
70
+ const current =
71
+ entries.find((entry) => entry.current && entry.status !== "archived") ??
72
+ entries.find((entry) => entry.current) ??
73
+ (entries.length === 1 ? entries[0] : undefined);
74
+ return current ? { found: current } : { ambiguous: [...entries] };
75
+ }
@@ -7,16 +7,12 @@
7
7
  */
8
8
 
9
9
  import type { ElicitationOutcome, PermissionOutcome } from "../protocol/lifecycle.ts";
10
+ import type { Origin, ReportedOrigin } from "../protocol/origin.ts";
10
11
  import type { Part, UnknownPart } from "../protocol/parts.ts";
11
12
  import { PLAN_OPTION_IDS } from "../protocol/plan.ts";
12
- import {
13
- type DecisionRequest,
14
- type SessionView,
15
- type ViewMessage,
16
- type Waiting,
17
- isPlan,
18
- phaseOf,
19
- } from "./view.ts";
13
+ import type { Hint } from "./errors.ts";
14
+ import type { SessionView, ViewTurn, Waiting } from "./types.ts";
15
+ import type { DecisionRequest, ViewMessage } from "./view.ts";
20
16
 
21
17
  const clip = (text: string, limit: number) =>
22
18
  text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
@@ -39,6 +35,8 @@ const UNSAFE_IN_JSON = new RegExp(`${BREAKS.source}|${CONTROLS.source}`, "g");
39
35
 
40
36
  /** The most messages `read_session` reads. */
41
37
  export const MAX_LAST = 100;
38
+ /** A full read fits in one tool result, its continuation included. */
39
+ export const FULL_READ_LIMIT = 20_000;
42
40
 
43
41
  /** Untrusted text as one line: no line breaks or controls, runs of space collapsed. */
44
42
  export function oneLine(text: string): string {
@@ -47,11 +45,7 @@ export function oneLine(text: string): string {
47
45
 
48
46
  /** Untrusted text as a block: each of its lines carried after `QUOTE`. */
49
47
  export function quote(text: string): string {
50
- return text
51
- .replace(CONTROLS, "")
52
- .split(BREAKS)
53
- .map((line) => `${QUOTE}${line}`.trimEnd())
54
- .join("\n");
48
+ return QUOTE + text.replace(CONTROLS, "").replace(BREAKS, `\n${QUOTE}`);
55
49
  }
56
50
 
57
51
  /** Untrusted text named in prose (a session, a project, an option): one JSON-quoted line. */
@@ -63,26 +57,47 @@ const block = (label: string, text: string) => `${label}\n${quote(text)}`;
63
57
  const textOf = (parts: readonly (Part | UnknownPart)[]) =>
64
58
  parts
65
59
  .flatMap((part) => (part.type === "text" && "text" in part ? [String(part.text)] : []))
66
- .join("")
67
- .trim();
60
+ .join("");
68
61
 
69
62
  /**
70
63
  * The next step, as the tool call that takes it:
71
64
  * `-> answer_request(session: "voyager", answer: "<your answer>")`.
72
65
  */
73
- export function callHint(
74
- tool: string,
75
- args: Record<string, string | number | boolean> = {},
76
- ): string {
77
- // `\uXXXX` for what JSON leaves raw (U+2028, C1, bidi controls): the value reads back the same.
78
- const json = (value: string | number | boolean) =>
79
- JSON.stringify(value).replace(UNSAFE_IN_JSON, (found) =>
80
- [...found].map((c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`).join(""),
81
- );
82
- const named = Object.entries(args).map(([key, value]) => `${key}: ${json(value)}`);
66
+ // @ref LLP 0014#untrusted-text — every value a line names goes through `json`
67
+ /**
68
+ * A value as JSON on one line, losslessly: `\uXXXX` for what JSON leaves raw
69
+ * (U+2028, C1, bidi controls), so it reads back the same and breaks no line.
70
+ */
71
+ export const json = (value: unknown): string =>
72
+ JSON.stringify(value).replace(UNSAFE_IN_JSON, (found) =>
73
+ [...found].map((c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`).join(""),
74
+ );
75
+
76
+ export function callHint(tool: string, args: Record<string, unknown> = {}): string {
77
+ const named = Object.entries(args)
78
+ .filter(([, value]) => value !== undefined)
79
+ .map(([key, value]) => `${key}: ${json(value)}`);
83
80
  return `-> ${tool}(${named.join(", ")})`;
84
81
  }
85
82
 
83
+ type Selection = { after?: string; last?: number };
84
+
85
+ /** A message preview and, if clipped, a read selecting its full text. */
86
+ function messageBlock(
87
+ label: string,
88
+ text: string,
89
+ limit: number,
90
+ context: WaitingContext,
91
+ selection: Selection,
92
+ ) {
93
+ const shown = block(label, clip(text, limit));
94
+ if (text.length <= limit) return shown;
95
+ if (selection.last !== undefined && selection.last > MAX_LAST)
96
+ return `${shown}\nmessage clipped. This reply is older than the last ${MAX_LAST} messages read_session can select.`;
97
+ const read = context.hint("read_session", { session: context.ref, ...selection, full: true });
98
+ return `${shown}\nmessage clipped.${read ? `\n ${read}` : ""}`;
99
+ }
100
+
86
101
  /** A choice's labels on one line: `options: "USD", "EUR"`. */
87
102
  const optionsLine = (labels: readonly string[]) => `options: ${labels.map(quoted).join(", ")}`;
88
103
 
@@ -267,16 +282,51 @@ function aboutLines(toolCall: DecisionRequest["toolCall"], root: string): string
267
282
  }
268
283
 
269
284
  /**
270
- * What the agent waits on, and the exact call that answers it. What only the
271
- * person can answer (`personOnly`) is one line, with no call. Paths under
272
- * `root` read relative to it.
285
+ * One request's context: named by the broker's own id when more than one
286
+ * waits, and offered the answer only when this caller may give that one.
273
287
  */
274
- export function describeWaiting(waiting: Waiting, ref: string, root = ""): string {
288
+ export function perRequest<C extends WaitingContext>(context: C, waiting: Waiting): C {
289
+ const id = waiting.request.requestId;
290
+ return {
291
+ ...context,
292
+ // Its id in every hint, one request or many: a hint followed late cannot reach a replacement.
293
+ handle: id,
294
+ ...(context.answerable ? { canAnswer: context.answerable.has(id) } : {}),
295
+ };
296
+ }
297
+
298
+ /** What a request waiting in a session is, in the words a model reads. */
299
+ export interface WaitingContext {
300
+ /** How hints name the session. */
301
+ ref: string;
302
+ /** The request's handle, said when the session waits on more than one. */
303
+ handle?: string;
304
+ /** Whether this caller may answer it: the answer hint is offered only then. */
305
+ canAnswer?: boolean;
306
+ /** Whether this caller may answer each waiting request, by the one rule the write uses. */
307
+ answerable?: ReadonlySet<string>;
308
+ /** Paths under it read relative to it. */
309
+ root?: string;
310
+ hint: Hint;
311
+ }
312
+
313
+ /**
314
+ * What the agent waits on, and the call that answers it, when that tool is
315
+ * installed. What only the person can answer (`personOnly`) is one line, with
316
+ * no call.
317
+ */
318
+ export function describeWaiting(waiting: Waiting, context: WaitingContext): string {
319
+ const { ref, handle, root = "", hint } = context;
275
320
  const only = waiting.kind === "question" && personOnly(waiting);
276
321
  if (only) {
277
322
  return `only the person can answer this, where the session runs (${only}): ${quoted(clip(waiting.request.message, 300))}`;
278
323
  }
279
- const answer = (text: string) => callHint("answer_request", { session: ref, answer: text });
324
+ const named = handle ? ` (request ${quoted(handle)})` : "";
325
+ const answer = (text: string) => {
326
+ if (context.canAnswer === false) return "";
327
+ const call = hint("answer_request", { session: ref, request: handle, answer: text });
328
+ return call ? `\n ${call}` : "";
329
+ };
280
330
  const options = (labels: readonly string[], ownWords = false) =>
281
331
  labels.length ? `\n${optionsLine(labels)}${ownWords ? " (or your own words)" : ""}` : "";
282
332
  if (waiting.kind === "question") {
@@ -285,127 +335,219 @@ export function describeWaiting(waiting: Waiting, ref: string, root = ""): strin
285
335
  ? questions
286
336
  .map(
287
337
  (q) =>
288
- `${block("question:", q.question)}${options(
338
+ `${block(`question${named}:`, q.question)}${options(
289
339
  (q.options ?? []).map((o) => o.label),
290
340
  true,
291
341
  )}`,
292
342
  )
293
343
  .join("\n")
294
- : block("question:", waiting.request.message);
344
+ : block(`question${named}:`, waiting.request.message);
295
345
  const form =
296
346
  questions.length > 1 ? "<one answer per question, separated by ; >" : "<your answer>";
297
- return `${asked}\n ${answer(form)}`;
347
+ return `${asked}${answer(form)}`;
298
348
  }
299
- if (isPlan(waiting.request)) {
300
- const approve = ` ${answer("approve")} (or answer: "<what to change>")`;
349
+ if (waiting.kind === "plan") {
350
+ const approve = answer("approve");
351
+ const or = approve ? ` (or answer: "<what to change>")` : "";
301
352
  // Never approved unseen: the plan itself, or the call that shows it.
302
353
  const plan = waiting.request.toolCall?.rawInput?.plan;
303
- return typeof plan === "string" && plan.trim()
304
- ? `plan waiting for approval:\n${quote(clip(plan, 800))}\n${approve}`
305
- : `plan waiting for approval; read it before answering\n ${callHint("read_session", { session: ref })}\n${approve}`;
354
+ if (typeof plan === "string" && plan.trim())
355
+ return `plan waiting for approval${named}:\n${quote(clip(plan, 800))}${approve}${or}`;
356
+ const read = hint("read_session", { session: ref });
357
+ return `plan waiting for approval${named}; read it before answering${read ? `\n ${read}` : ""}${approve}${or}`;
306
358
  }
307
- const named = waiting.request.options.map((option) => option.name);
359
+ const choices = waiting.request.options.map((option) => option.name);
308
360
  const about = aboutLines(waiting.request.toolCall, root);
309
- return `${block("permission:", waiting.request.title)}${about}${options(named)}\n ${answer("allow")} (or answer: "deny")`;
361
+ const allow = answer("allow");
362
+ return `${block(`permission${named}:`, waiting.request.title)}${about}${options(choices)}${allow}${allow ? ` (or answer: "deny")` : ""}`;
310
363
  }
311
364
 
312
- /** The agent's words since the person last spoke. */
313
- export function lastReply(messages: readonly ViewMessage[]): string {
314
- // A loop, not `findLastIndex`: consumers compile this source with their own `lib`.
315
- let lastUser = messages.length - 1;
316
- while (lastUser >= 0 && messages[lastUser]?.role !== "user") lastUser--;
317
- return messages
318
- .slice(lastUser + 1)
319
- .filter((message) => message.role === "assistant" && !message.nested)
320
- .map((message) => textOf(message.parts))
321
- .filter(Boolean)
322
- .join("\n");
365
+ /** The latest top-level reply since the sender spoke, and its position for a full read. */
366
+ function lastReply(messages: readonly ViewMessage[], newer: number) {
367
+ for (let i = messages.length - 1; i >= 0; i--) {
368
+ const message = messages[i];
369
+ if (message?.role !== "assistant") break;
370
+ if (message.nested) continue;
371
+ const text = textOf(message.parts);
372
+ if (text.trim()) return { text, last: newer + messages.length - i };
373
+ }
374
+ }
375
+
376
+ /** Every message of a view, oldest first. */
377
+ export const messagesOf = (view: Pick<SessionView, "turns">): ViewMessage[] =>
378
+ view.turns.flatMap((turn) => turn.messages);
379
+
380
+ /** How a status reads in an outcome. */
381
+ const STATUS_WORDS: Record<string, string> = {
382
+ idle: "done",
383
+ stopped: "stopped",
384
+ error: "error",
385
+ needs_input: "needs_input",
386
+ archived: "archived",
387
+ };
388
+
389
+ /** How the waits and outcomes word a view; `waited` is how long the call waited. */
390
+ export interface OutcomeContext extends WaitingContext {
391
+ waited?: number;
392
+ /** The host's line of facts for a settled turn. */
393
+ note?: string;
394
+ /** Messages after the turn this outcome follows, when it already has a successor. */
395
+ newer?: number;
323
396
  }
324
397
 
325
398
  /**
326
- * How a turn stands: finished, waiting on the person, failed, or still going.
327
- * `waitedSeconds` is how long this call waited; `note` is the host's line of
328
- * facts for a turn that is not working any more; paths under `root` in what it
329
- * waits on read relative to it.
399
+ * How a session stands: done, stopped, waiting on someone, failed, or still
400
+ * going. Each request it waits on is said with the call that answers it.
330
401
  */
331
- export function renderOutcome(
332
- view: SessionView,
333
- ref: string,
334
- waitedSeconds?: number,
335
- note?: string,
336
- root?: string,
337
- ): string {
338
- const phase = phaseOf(view);
339
- if (phase === "working") {
340
- // No messages at all: it is being set up, or its first turn has not shown yet.
402
+ export function renderOutcome(view: SessionView, context: OutcomeContext): string {
403
+ const { ref, hint } = context;
404
+ if (view.status === "working" || view.status === "setting_up") {
405
+ const messages = messagesOf(view);
341
406
  const detail = [
342
- view.messages.length ? "" : "starting up, no messages yet",
343
- waitedSeconds ? `still running after ${waitedSeconds}s` : "",
407
+ view.status === "setting_up"
408
+ ? "being set up"
409
+ : messages.length
410
+ ? ""
411
+ : "starting, no messages yet",
412
+ context.waited ? `still running after ${context.waited}s` : "",
344
413
  ].filter(Boolean);
345
- return `status: working${detail.length ? ` (${detail.join("; ")})` : ""}\n ${callHint("wait_for_session", { session: ref })}`;
414
+ const next = hint("wait_for_sessions", { sessions: [ref] });
415
+ return `status: working${detail.length ? ` (${detail.join("; ")})` : ""}${next ? `\n ${next}` : ""}`;
416
+ }
417
+ const messages = messagesOf(view);
418
+ const fresh = view.status === "idle" && !messages.length;
419
+ const lines = [
420
+ `status: ${fresh ? "idle (no messages yet)" : (STATUS_WORDS[view.status] ?? view.status)}`,
421
+ ];
422
+ const reply = lastReply(messages, context.newer ?? 0);
423
+ if (reply)
424
+ lines.push(messageBlock("agent said:", reply.text, 1500, context, { last: reply.last }));
425
+ for (const waiting of view.waiting)
426
+ lines.push(describeWaiting(waiting, perRequest(context, waiting)));
427
+ if (view.status === "error") {
428
+ const failed = view.turns.at(-1)?.error;
429
+ lines.push(block("error:", failed ?? "the turn failed"));
346
430
  }
347
- const fresh = phase === "idle" && !view.messages.length;
348
- const lines = [`status: ${fresh ? "idle (no messages yet)" : phase === "idle" ? "done" : phase}`];
349
- const reply = lastReply(view.messages);
350
- if (reply) lines.push(block("agent said:", clip(reply, 1500)));
351
- for (const waiting of view.waiting) lines.push(describeWaiting(waiting, ref, root));
352
- if (phase === "error") lines.push(block("error:", view.error ?? "the turn failed"));
353
- if (note) lines.push(oneLine(note));
354
- if (phase === "error" || reply.length > 1500) {
355
- lines.push(` ${callHint("read_session", { session: ref })}`);
431
+ if (context.note) lines.push(oneLine(context.note));
432
+ if (view.status === "error") {
433
+ const read = hint("read_session", { session: ref });
434
+ if (read) lines.push(` ${read}`);
356
435
  }
357
436
  return lines.join("\n");
358
437
  }
359
438
 
360
- export interface RenderOptions {
361
- /** How many recent messages (default 10). */
362
- last?: number;
363
- /** Paths in tool lines are shown relative to this folder. */
364
- root?: string;
439
+ /** Who a user message is from, as `read_session` labels it; `you` is the caller's own origin. */
440
+ export function senderLabel(origin: ReportedOrigin | undefined, you: Origin): string {
441
+ if (!origin || origin.kind === "person") return you.kind === "person" ? "[you]" : "[the person]";
442
+ if (sameOrigin(origin, you)) return "[you]";
443
+ if (origin.kind === "session") {
444
+ const { name, sessionId } = origin as { name?: string; sessionId: string };
445
+ return `[${quoted(name ?? sessionId)}]`;
446
+ }
447
+ if (origin.kind === "assistant") return `[assistant ${quoted(String(origin.name))}]`;
448
+ return `[${quoted(origin.kind)}]`;
449
+ }
450
+
451
+ /** Whether two origins are the same sender. */
452
+ export function sameOrigin(a: ReportedOrigin | undefined, b: ReportedOrigin | undefined): boolean {
453
+ const key = (o: ReportedOrigin | undefined) =>
454
+ !o || o.kind === "person"
455
+ ? "person"
456
+ : o.kind === "session"
457
+ ? `session:${(o as { sessionId: string }).sessionId}`
458
+ : o.kind === "assistant"
459
+ ? `assistant:${(o as { id: string }).id}`
460
+ : JSON.stringify(o);
461
+ return key(a) === key(b);
462
+ }
463
+
464
+ /** How a turn that is over ended, after its messages. */
465
+ function endOf(turn: ViewTurn, you: Origin): string | undefined {
466
+ if (turn.outcome === "running") return undefined;
467
+ if (turn.outcome === "done") return "— turn done";
468
+ if (turn.outcome === "cancelled") {
469
+ const by = turn.cancelledBy ? ` by ${senderLabel(turn.cancelledBy, you).slice(1, -1)}` : "";
470
+ return `— turn cancelled${by}`;
471
+ }
472
+ return block("— turn failed:", turn.error ?? "the turn failed");
473
+ }
474
+
475
+ export interface RenderOptions extends WaitingContext, Selection {
476
+ full?: boolean;
477
+ /** The caller's own origin: its messages read `[you]`. */
478
+ you: Origin;
479
+ /** The header line (the session, its id, who started it). */
480
+ header?: string;
365
481
  }
366
482
 
367
483
  /**
368
- * The conversation, condensed: what was asked, what the agent said, which
369
- * tools it ran, and under a call that asked the person its questions and
370
- * what the agent was told (or its plan).
484
+ * The conversation, condensed: each user message under its own sender, what
485
+ * the agent said, which tools it ran (with what a call asked the person),
486
+ * how each turn ended, and what the session waits on.
371
487
  */
372
- export function renderConversation(
373
- view: SessionView,
374
- ref: string,
375
- options: RenderOptions = {},
376
- ): string {
377
- const lines: string[] = [];
378
- // The host was asked for `last`; a host that gives more is cut here.
379
- const shown = view.messages.slice(-Math.max(1, options.last ?? 10));
380
- // A tool awaiting approval is open in a working turn; one an ended turn left open was interrupted.
381
- const working = view.status === "working";
382
- for (const message of shown) {
383
- const text = textOf(message.parts);
384
- if (message.role === "user") {
385
- lines.push(block("[you]", clip(text, 800)));
386
- continue;
387
- }
388
- for (const part of message.parts) {
389
- const line = toolLine(part, options.root, working);
390
- if (!line) continue;
391
- lines.push(` · ${line}`);
392
- // Under the call's line, aligned with its name.
393
- for (const asked of askedLines(part, options.root)) {
394
- lines.push(asked.replace(/^/gm, " "));
488
+ export function renderConversation(view: SessionView, options: RenderOptions): string {
489
+ const { root, you } = options;
490
+ const lines: string[] = options.header ? [options.header] : [];
491
+ const limit = options.after ? Number.POSITIVE_INFINITY : (options.last ?? 10);
492
+ const selection = options.after ? { after: options.after } : { last: limit };
493
+ let count = 0;
494
+ const shownTurns: { turn: ViewTurn; messages: ViewMessage[] }[] = [];
495
+ for (let t = view.turns.length - 1; t >= 0 && count < limit; t--) {
496
+ const turn = view.turns[t] as ViewTurn;
497
+ const messages = turn.messages.slice(-(limit - count));
498
+ count += messages.length;
499
+ shownTurns.unshift({ turn, messages });
500
+ }
501
+ const working = view.status === "working" || view.status === "needs_input";
502
+ for (const { turn, messages } of shownTurns) {
503
+ for (const message of messages) {
504
+ const text = textOf(message.parts);
505
+ if (message.role === "user") {
506
+ lines.push(
507
+ messageBlock(
508
+ senderLabel(message.origin, you),
509
+ text,
510
+ options.full ? Number.POSITIVE_INFINITY : 800,
511
+ options,
512
+ selection,
513
+ ),
514
+ );
515
+ continue;
395
516
  }
517
+ for (const part of message.parts) {
518
+ const line = toolLine(part, root, working && turn.outcome === "running");
519
+ if (!line) continue;
520
+ lines.push(` · ${line}`);
521
+ for (const asked of askedLines(part, root)) lines.push(asked.replace(/^/gm, " "));
522
+ }
523
+ if (text)
524
+ lines.push(
525
+ messageBlock(
526
+ "[agent]",
527
+ text,
528
+ options.full ? Number.POSITIVE_INFINITY : 1200,
529
+ options,
530
+ selection,
531
+ ),
532
+ );
396
533
  }
397
- if (text) lines.push(block("[agent]", clip(text, 1200)));
534
+ const end = endOf(turn, you);
535
+ if (end) lines.push(end);
398
536
  }
399
- if (!shown.length) lines.push("(no messages yet)");
400
- const cut = view.older || shown.length < view.messages.length;
401
- lines.push(`(status: ${phaseOf(view)})`);
402
- if (view.error && phaseOf(view) === "error") lines.push(block("error:", view.error));
403
- for (const waiting of view.waiting) lines.push(describeWaiting(waiting, ref, options.root));
404
- if (cut) {
537
+ if (!count && !view.turns.length) lines.push("(no messages yet)");
538
+ lines.push(`(status: ${view.status})`);
539
+ for (const waiting of view.waiting)
540
+ lines.push(describeWaiting(waiting, perRequest(options, waiting)));
541
+ const total = view.turns.reduce((sum, turn) => sum + turn.messages.length, 0);
542
+ if (view.older || count < total) {
543
+ const more = options.hint("read_session", {
544
+ session: options.ref,
545
+ last: Math.min(count + 10, MAX_LAST),
546
+ });
405
547
  lines.push(
406
- shown.length >= MAX_LAST
548
+ count >= MAX_LAST || !more
407
549
  ? `older messages exist; read_session shows at most the last ${MAX_LAST}.`
408
- : `older messages exist: ${callHint("read_session", { session: ref, last: Math.min(shown.length + 10, MAX_LAST) })}`,
550
+ : `older messages exist: ${more}`,
409
551
  );
410
552
  }
411
553
  return lines.join("\n");
@@ -458,7 +600,7 @@ export function answerFor(waiting: Waiting, text: string): Answer {
458
600
  requestId,
459
601
  outcome: { outcome: "selected", optionId, ...(message ? { message } : {}) },
460
602
  });
461
- if (isPlan(waiting.request)) {
603
+ if (waiting.kind === "plan") {
462
604
  // Approving starts the work with edits still asked for; anything else is what to change.
463
605
  return YES.test(said)
464
606
  ? pick(PLAN_OPTION_IDS.approve)