@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,59 @@
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
+ /** How the tools print an entry: `[project/]workspace:N`, or its id when it has no number. */
8
+ export function refOf(entry, all) {
9
+ if (entry.chat === undefined)
10
+ return entry.id;
11
+ const shared = all.some((other) => other.workspace.id !== entry.workspace.id &&
12
+ other.workspace.name.toLowerCase() === entry.workspace.name.toLowerCase());
13
+ const project = shared && entry.project ? `${entry.project.name}/` : "";
14
+ return `${project}${entry.workspace.name}:${entry.chat}`;
15
+ }
16
+ /**
17
+ * The entry `ref` names among `all` (everything the caller may see, archived
18
+ * included). An id is exact: a session's, or a workspace's (its current
19
+ * chat). A name is case-insensitive; a bare workspace means its current chat,
20
+ * resolved now.
21
+ */
22
+ export function resolve(ref, all) {
23
+ const wanted = ref.trim();
24
+ const byId = all.find((entry) => entry.id === wanted);
25
+ if (byId)
26
+ return { found: byId };
27
+ const inWorkspace = all.filter((entry) => entry.workspace.id === wanted);
28
+ if (inWorkspace.length)
29
+ return pick(inWorkspace, undefined);
30
+ const slash = wanted.lastIndexOf("/");
31
+ const project = slash >= 0 ? wanted.slice(0, slash).toLowerCase() : undefined;
32
+ const rest = slash >= 0 ? wanted.slice(slash + 1) : wanted;
33
+ const colon = rest.lastIndexOf(":");
34
+ const number = colon >= 0 ? Number(rest.slice(colon + 1)) : undefined;
35
+ const chat = number !== undefined && Number.isInteger(number) && number > 0 ? number : undefined;
36
+ const workspace = (chat !== undefined ? rest.slice(0, colon) : rest).toLowerCase();
37
+ const named = all.filter((entry) => entry.workspace.name.toLowerCase() === workspace &&
38
+ (project === undefined || entry.project?.name.toLowerCase() === project));
39
+ const workspaces = [...new Set(named.map((entry) => entry.workspace.id))];
40
+ if (workspaces.length > 1)
41
+ return {
42
+ ambiguous: workspaces.map((id) => (named.find((e) => e.workspace.id === id && e.current) ??
43
+ named.find((e) => e.workspace.id === id))),
44
+ };
45
+ if (!named.length)
46
+ return { missing: true };
47
+ return pick(named, chat);
48
+ }
49
+ /** In one workspace's entries: chat `chat`, else its current chat. */
50
+ function pick(entries, chat) {
51
+ if (chat !== undefined) {
52
+ const hit = entries.find((entry) => (entry.chat ?? 1) === chat);
53
+ return hit ? { found: hit } : { missing: true };
54
+ }
55
+ const current = entries.find((entry) => entry.current && entry.status !== "archived") ??
56
+ entries.find((entry) => entry.current) ??
57
+ (entries.length === 1 ? entries[0] : undefined);
58
+ return current ? { found: current } : { ambiguous: [...entries] };
59
+ }
@@ -6,7 +6,6 @@
6
6
  * name alone is ambiguous.
7
7
  */
8
8
  import { PLAN_OPTION_IDS } from "../protocol/plan.js";
9
- import { isPlan, phaseOf, } from "./view.js";
10
9
  const clip = (text, limit) => text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
11
10
  // @ref LLP 0014#untrusted-text — text an agent wrote or a repository holds never starts a line
12
11
  // Untrusted text (what an agent or a person wrote, a question, an option, an
@@ -23,17 +22,15 @@ const CONTROLS = /[\u0000-\u0008\u000e-\u001f\u007f-\u009f\u200e\u200f\u202a-\u2
23
22
  const UNSAFE_IN_JSON = new RegExp(`${BREAKS.source}|${CONTROLS.source}`, "g");
24
23
  /** The most messages `read_session` reads. */
25
24
  export const MAX_LAST = 100;
25
+ /** A full read fits in one tool result, its continuation included. */
26
+ export const FULL_READ_LIMIT = 20_000;
26
27
  /** Untrusted text as one line: no line breaks or controls, runs of space collapsed. */
27
28
  export function oneLine(text) {
28
29
  return text.replace(BREAKS, " ").replace(CONTROLS, "").replace(/\s+/g, " ").trim();
29
30
  }
30
31
  /** Untrusted text as a block: each of its lines carried after `QUOTE`. */
31
32
  export function quote(text) {
32
- return text
33
- .replace(CONTROLS, "")
34
- .split(BREAKS)
35
- .map((line) => `${QUOTE}${line}`.trimEnd())
36
- .join("\n");
33
+ return QUOTE + text.replace(CONTROLS, "").replace(BREAKS, `\n${QUOTE}`);
37
34
  }
38
35
  /** Untrusted text named in prose (a session, a project, an option): one JSON-quoted line. */
39
36
  export const quoted = (text) => JSON.stringify(oneLine(text));
@@ -41,18 +38,33 @@ export const quoted = (text) => JSON.stringify(oneLine(text));
41
38
  const block = (label, text) => `${label}\n${quote(text)}`;
42
39
  const textOf = (parts) => parts
43
40
  .flatMap((part) => (part.type === "text" && "text" in part ? [String(part.text)] : []))
44
- .join("")
45
- .trim();
41
+ .join("");
46
42
  /**
47
43
  * The next step, as the tool call that takes it:
48
44
  * `-> answer_request(session: "voyager", answer: "<your answer>")`.
49
45
  */
46
+ // @ref LLP 0014#untrusted-text — every value a line names goes through `json`
47
+ /**
48
+ * A value as JSON on one line, losslessly: `\uXXXX` for what JSON leaves raw
49
+ * (U+2028, C1, bidi controls), so it reads back the same and breaks no line.
50
+ */
51
+ export const json = (value) => JSON.stringify(value).replace(UNSAFE_IN_JSON, (found) => [...found].map((c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`).join(""));
50
52
  export function callHint(tool, args = {}) {
51
- // `\uXXXX` for what JSON leaves raw (U+2028, C1, bidi controls): the value reads back the same.
52
- const json = (value) => JSON.stringify(value).replace(UNSAFE_IN_JSON, (found) => [...found].map((c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`).join(""));
53
- const named = Object.entries(args).map(([key, value]) => `${key}: ${json(value)}`);
53
+ const named = Object.entries(args)
54
+ .filter(([, value]) => value !== undefined)
55
+ .map(([key, value]) => `${key}: ${json(value)}`);
54
56
  return `-> ${tool}(${named.join(", ")})`;
55
57
  }
58
+ /** A message preview and, if clipped, a read selecting its full text. */
59
+ function messageBlock(label, text, limit, context, selection) {
60
+ const shown = block(label, clip(text, limit));
61
+ if (text.length <= limit)
62
+ return shown;
63
+ if (selection.last !== undefined && selection.last > MAX_LAST)
64
+ return `${shown}\nmessage clipped. This reply is older than the last ${MAX_LAST} messages read_session can select.`;
65
+ const read = context.hint("read_session", { session: context.ref, ...selection, full: true });
66
+ return `${shown}\nmessage clipped.${read ? `\n ${read}` : ""}`;
67
+ }
56
68
  /** A choice's labels on one line: `options: "USD", "EUR"`. */
57
69
  const optionsLine = (labels) => `options: ${labels.map(quoted).join(", ")}`;
58
70
  /** What ends a path in a command: a space, a quote, or the shell's punctuation. */
@@ -226,126 +238,219 @@ function aboutLines(toolCall, root) {
226
238
  .join("");
227
239
  }
228
240
  /**
229
- * What the agent waits on, and the exact call that answers it. What only the
230
- * person can answer (`personOnly`) is one line, with no call. Paths under
231
- * `root` read relative to it.
241
+ * One request's context: named by the broker's own id when more than one
242
+ * waits, and offered the answer only when this caller may give that one.
243
+ */
244
+ export function perRequest(context, waiting) {
245
+ const id = waiting.request.requestId;
246
+ return {
247
+ ...context,
248
+ // Its id in every hint, one request or many: a hint followed late cannot reach a replacement.
249
+ handle: id,
250
+ ...(context.answerable ? { canAnswer: context.answerable.has(id) } : {}),
251
+ };
252
+ }
253
+ /**
254
+ * What the agent waits on, and the call that answers it, when that tool is
255
+ * installed. What only the person can answer (`personOnly`) is one line, with
256
+ * no call.
232
257
  */
233
- export function describeWaiting(waiting, ref, root = "") {
258
+ export function describeWaiting(waiting, context) {
259
+ const { ref, handle, root = "", hint } = context;
234
260
  const only = waiting.kind === "question" && personOnly(waiting);
235
261
  if (only) {
236
262
  return `only the person can answer this, where the session runs (${only}): ${quoted(clip(waiting.request.message, 300))}`;
237
263
  }
238
- const answer = (text) => callHint("answer_request", { session: ref, answer: text });
264
+ const named = handle ? ` (request ${quoted(handle)})` : "";
265
+ const answer = (text) => {
266
+ if (context.canAnswer === false)
267
+ return "";
268
+ const call = hint("answer_request", { session: ref, request: handle, answer: text });
269
+ return call ? `\n ${call}` : "";
270
+ };
239
271
  const options = (labels, ownWords = false) => labels.length ? `\n${optionsLine(labels)}${ownWords ? " (or your own words)" : ""}` : "";
240
272
  if (waiting.kind === "question") {
241
273
  const questions = waiting.request.questions ?? [];
242
274
  const asked = questions.length
243
275
  ? questions
244
- .map((q) => `${block("question:", q.question)}${options((q.options ?? []).map((o) => o.label), true)}`)
276
+ .map((q) => `${block(`question${named}:`, q.question)}${options((q.options ?? []).map((o) => o.label), true)}`)
245
277
  .join("\n")
246
- : block("question:", waiting.request.message);
278
+ : block(`question${named}:`, waiting.request.message);
247
279
  const form = questions.length > 1 ? "<one answer per question, separated by ; >" : "<your answer>";
248
- return `${asked}\n ${answer(form)}`;
280
+ return `${asked}${answer(form)}`;
249
281
  }
250
- if (isPlan(waiting.request)) {
251
- const approve = ` ${answer("approve")} (or answer: "<what to change>")`;
282
+ if (waiting.kind === "plan") {
283
+ const approve = answer("approve");
284
+ const or = approve ? ` (or answer: "<what to change>")` : "";
252
285
  // Never approved unseen: the plan itself, or the call that shows it.
253
286
  const plan = waiting.request.toolCall?.rawInput?.plan;
254
- return typeof plan === "string" && plan.trim()
255
- ? `plan waiting for approval:\n${quote(clip(plan, 800))}\n${approve}`
256
- : `plan waiting for approval; read it before answering\n ${callHint("read_session", { session: ref })}\n${approve}`;
287
+ if (typeof plan === "string" && plan.trim())
288
+ return `plan waiting for approval${named}:\n${quote(clip(plan, 800))}${approve}${or}`;
289
+ const read = hint("read_session", { session: ref });
290
+ return `plan waiting for approval${named}; read it before answering${read ? `\n ${read}` : ""}${approve}${or}`;
257
291
  }
258
- const named = waiting.request.options.map((option) => option.name);
292
+ const choices = waiting.request.options.map((option) => option.name);
259
293
  const about = aboutLines(waiting.request.toolCall, root);
260
- return `${block("permission:", waiting.request.title)}${about}${options(named)}\n ${answer("allow")} (or answer: "deny")`;
294
+ const allow = answer("allow");
295
+ return `${block(`permission${named}:`, waiting.request.title)}${about}${options(choices)}${allow}${allow ? ` (or answer: "deny")` : ""}`;
261
296
  }
262
- /** The agent's words since the person last spoke. */
263
- export function lastReply(messages) {
264
- // A loop, not `findLastIndex`: consumers compile this source with their own `lib`.
265
- let lastUser = messages.length - 1;
266
- while (lastUser >= 0 && messages[lastUser]?.role !== "user")
267
- lastUser--;
268
- return messages
269
- .slice(lastUser + 1)
270
- .filter((message) => message.role === "assistant" && !message.nested)
271
- .map((message) => textOf(message.parts))
272
- .filter(Boolean)
273
- .join("\n");
297
+ /** The latest top-level reply since the sender spoke, and its position for a full read. */
298
+ function lastReply(messages, newer) {
299
+ for (let i = messages.length - 1; i >= 0; i--) {
300
+ const message = messages[i];
301
+ if (message?.role !== "assistant")
302
+ break;
303
+ if (message.nested)
304
+ continue;
305
+ const text = textOf(message.parts);
306
+ if (text.trim())
307
+ return { text, last: newer + messages.length - i };
308
+ }
274
309
  }
310
+ /** Every message of a view, oldest first. */
311
+ export const messagesOf = (view) => view.turns.flatMap((turn) => turn.messages);
312
+ /** How a status reads in an outcome. */
313
+ const STATUS_WORDS = {
314
+ idle: "done",
315
+ stopped: "stopped",
316
+ error: "error",
317
+ needs_input: "needs_input",
318
+ archived: "archived",
319
+ };
275
320
  /**
276
- * How a turn stands: finished, waiting on the person, failed, or still going.
277
- * `waitedSeconds` is how long this call waited; `note` is the host's line of
278
- * facts for a turn that is not working any more; paths under `root` in what it
279
- * waits on read relative to it.
321
+ * How a session stands: done, stopped, waiting on someone, failed, or still
322
+ * going. Each request it waits on is said with the call that answers it.
280
323
  */
281
- export function renderOutcome(view, ref, waitedSeconds, note, root) {
282
- const phase = phaseOf(view);
283
- if (phase === "working") {
284
- // No messages at all: it is being set up, or its first turn has not shown yet.
324
+ export function renderOutcome(view, context) {
325
+ const { ref, hint } = context;
326
+ if (view.status === "working" || view.status === "setting_up") {
327
+ const messages = messagesOf(view);
285
328
  const detail = [
286
- view.messages.length ? "" : "starting up, no messages yet",
287
- waitedSeconds ? `still running after ${waitedSeconds}s` : "",
329
+ view.status === "setting_up"
330
+ ? "being set up"
331
+ : messages.length
332
+ ? ""
333
+ : "starting, no messages yet",
334
+ context.waited ? `still running after ${context.waited}s` : "",
288
335
  ].filter(Boolean);
289
- return `status: working${detail.length ? ` (${detail.join("; ")})` : ""}\n ${callHint("wait_for_session", { session: ref })}`;
336
+ const next = hint("wait_for_sessions", { sessions: [ref] });
337
+ return `status: working${detail.length ? ` (${detail.join("; ")})` : ""}${next ? `\n ${next}` : ""}`;
290
338
  }
291
- const fresh = phase === "idle" && !view.messages.length;
292
- const lines = [`status: ${fresh ? "idle (no messages yet)" : phase === "idle" ? "done" : phase}`];
293
- const reply = lastReply(view.messages);
339
+ const messages = messagesOf(view);
340
+ const fresh = view.status === "idle" && !messages.length;
341
+ const lines = [
342
+ `status: ${fresh ? "idle (no messages yet)" : (STATUS_WORDS[view.status] ?? view.status)}`,
343
+ ];
344
+ const reply = lastReply(messages, context.newer ?? 0);
294
345
  if (reply)
295
- lines.push(block("agent said:", clip(reply, 1500)));
346
+ lines.push(messageBlock("agent said:", reply.text, 1500, context, { last: reply.last }));
296
347
  for (const waiting of view.waiting)
297
- lines.push(describeWaiting(waiting, ref, root));
298
- if (phase === "error")
299
- lines.push(block("error:", view.error ?? "the turn failed"));
300
- if (note)
301
- lines.push(oneLine(note));
302
- if (phase === "error" || reply.length > 1500) {
303
- lines.push(` ${callHint("read_session", { session: ref })}`);
348
+ lines.push(describeWaiting(waiting, perRequest(context, waiting)));
349
+ if (view.status === "error") {
350
+ const failed = view.turns.at(-1)?.error;
351
+ lines.push(block("error:", failed ?? "the turn failed"));
352
+ }
353
+ if (context.note)
354
+ lines.push(oneLine(context.note));
355
+ if (view.status === "error") {
356
+ const read = hint("read_session", { session: ref });
357
+ if (read)
358
+ lines.push(` ${read}`);
304
359
  }
305
360
  return lines.join("\n");
306
361
  }
362
+ /** Who a user message is from, as `read_session` labels it; `you` is the caller's own origin. */
363
+ export function senderLabel(origin, you) {
364
+ if (!origin || origin.kind === "person")
365
+ return you.kind === "person" ? "[you]" : "[the person]";
366
+ if (sameOrigin(origin, you))
367
+ return "[you]";
368
+ if (origin.kind === "session") {
369
+ const { name, sessionId } = origin;
370
+ return `[${quoted(name ?? sessionId)}]`;
371
+ }
372
+ if (origin.kind === "assistant")
373
+ return `[assistant ${quoted(String(origin.name))}]`;
374
+ return `[${quoted(origin.kind)}]`;
375
+ }
376
+ /** Whether two origins are the same sender. */
377
+ export function sameOrigin(a, b) {
378
+ const key = (o) => !o || o.kind === "person"
379
+ ? "person"
380
+ : o.kind === "session"
381
+ ? `session:${o.sessionId}`
382
+ : o.kind === "assistant"
383
+ ? `assistant:${o.id}`
384
+ : JSON.stringify(o);
385
+ return key(a) === key(b);
386
+ }
387
+ /** How a turn that is over ended, after its messages. */
388
+ function endOf(turn, you) {
389
+ if (turn.outcome === "running")
390
+ return undefined;
391
+ if (turn.outcome === "done")
392
+ return "— turn done";
393
+ if (turn.outcome === "cancelled") {
394
+ const by = turn.cancelledBy ? ` by ${senderLabel(turn.cancelledBy, you).slice(1, -1)}` : "";
395
+ return `— turn cancelled${by}`;
396
+ }
397
+ return block("— turn failed:", turn.error ?? "the turn failed");
398
+ }
307
399
  /**
308
- * The conversation, condensed: what was asked, what the agent said, which
309
- * tools it ran, and under a call that asked the person its questions and
310
- * what the agent was told (or its plan).
400
+ * The conversation, condensed: each user message under its own sender, what
401
+ * the agent said, which tools it ran (with what a call asked the person),
402
+ * how each turn ended, and what the session waits on.
311
403
  */
312
- export function renderConversation(view, ref, options = {}) {
313
- const lines = [];
314
- // The host was asked for `last`; a host that gives more is cut here.
315
- const shown = view.messages.slice(-Math.max(1, options.last ?? 10));
316
- // A tool awaiting approval is open in a working turn; one an ended turn left open was interrupted.
317
- const working = view.status === "working";
318
- for (const message of shown) {
319
- const text = textOf(message.parts);
320
- if (message.role === "user") {
321
- lines.push(block("[you]", clip(text, 800)));
322
- continue;
323
- }
324
- for (const part of message.parts) {
325
- const line = toolLine(part, options.root, working);
326
- if (!line)
404
+ export function renderConversation(view, options) {
405
+ const { root, you } = options;
406
+ const lines = options.header ? [options.header] : [];
407
+ const limit = options.after ? Number.POSITIVE_INFINITY : (options.last ?? 10);
408
+ const selection = options.after ? { after: options.after } : { last: limit };
409
+ let count = 0;
410
+ const shownTurns = [];
411
+ for (let t = view.turns.length - 1; t >= 0 && count < limit; t--) {
412
+ const turn = view.turns[t];
413
+ const messages = turn.messages.slice(-(limit - count));
414
+ count += messages.length;
415
+ shownTurns.unshift({ turn, messages });
416
+ }
417
+ const working = view.status === "working" || view.status === "needs_input";
418
+ for (const { turn, messages } of shownTurns) {
419
+ for (const message of messages) {
420
+ const text = textOf(message.parts);
421
+ if (message.role === "user") {
422
+ lines.push(messageBlock(senderLabel(message.origin, you), text, options.full ? Number.POSITIVE_INFINITY : 800, options, selection));
327
423
  continue;
328
- lines.push(` · ${line}`);
329
- // Under the call's line, aligned with its name.
330
- for (const asked of askedLines(part, options.root)) {
331
- lines.push(asked.replace(/^/gm, " "));
332
424
  }
425
+ for (const part of message.parts) {
426
+ const line = toolLine(part, root, working && turn.outcome === "running");
427
+ if (!line)
428
+ continue;
429
+ lines.push(` · ${line}`);
430
+ for (const asked of askedLines(part, root))
431
+ lines.push(asked.replace(/^/gm, " "));
432
+ }
433
+ if (text)
434
+ lines.push(messageBlock("[agent]", text, options.full ? Number.POSITIVE_INFINITY : 1200, options, selection));
333
435
  }
334
- if (text)
335
- lines.push(block("[agent]", clip(text, 1200)));
436
+ const end = endOf(turn, you);
437
+ if (end)
438
+ lines.push(end);
336
439
  }
337
- if (!shown.length)
440
+ if (!count && !view.turns.length)
338
441
  lines.push("(no messages yet)");
339
- const cut = view.older || shown.length < view.messages.length;
340
- lines.push(`(status: ${phaseOf(view)})`);
341
- if (view.error && phaseOf(view) === "error")
342
- lines.push(block("error:", view.error));
442
+ lines.push(`(status: ${view.status})`);
343
443
  for (const waiting of view.waiting)
344
- lines.push(describeWaiting(waiting, ref, options.root));
345
- if (cut) {
346
- lines.push(shown.length >= MAX_LAST
444
+ lines.push(describeWaiting(waiting, perRequest(options, waiting)));
445
+ const total = view.turns.reduce((sum, turn) => sum + turn.messages.length, 0);
446
+ if (view.older || count < total) {
447
+ const more = options.hint("read_session", {
448
+ session: options.ref,
449
+ last: Math.min(count + 10, MAX_LAST),
450
+ });
451
+ lines.push(count >= MAX_LAST || !more
347
452
  ? `older messages exist; read_session shows at most the last ${MAX_LAST}.`
348
- : `older messages exist: ${callHint("read_session", { session: ref, last: Math.min(shown.length + 10, MAX_LAST) })}`);
453
+ : `older messages exist: ${more}`);
349
454
  }
350
455
  return lines.join("\n");
351
456
  }
@@ -391,7 +496,7 @@ export function answerFor(waiting, text) {
391
496
  requestId,
392
497
  outcome: { outcome: "selected", optionId, ...(message ? { message } : {}) },
393
498
  });
394
- if (isPlan(waiting.request)) {
499
+ if (waiting.kind === "plan") {
395
500
  // Approving starts the work with edits still asked for; anything else is what to change.
396
501
  return YES.test(said)
397
502
  ? pick(PLAN_OPTION_IDS.approve)
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The operator as a session's own tools: what a host returns from the
3
+ * engine's `hostTools` (LLP 0018 (host tools)), its other tools for the
4
+ * session in the same one source. The shapes are the engine's, said here by
5
+ * structure: the operator imports nothing of the engine's core.
6
+ */
7
+ // @ref LLP 0019#guidance — the paragraph a host adds to its sessions' instructions
8
+ import { OperatorError, refuse } from "./errors.js";
9
+ /**
10
+ * What a host adds to the instructions of every session that has these
11
+ * tools, or can receive messages from sessions that do.
12
+ */
13
+ export const OPERATOR_GUIDANCE = [
14
+ "You can see and work with other agent sessions with the session tools",
15
+ "(whoami, list_sessions, read_session, wait_for_sessions, start_session,",
16
+ "send_message, answer_request, stop_sessions, archive). Start a session for",
17
+ "a separate piece of work that needs its own workspace or would run a long",
18
+ "time; for quick reading or searching, use your own built-in subagents",
19
+ "instead. A session you started is your responsibility: wait for it, read",
20
+ "what it did, archive it when its work is done (you cannot start more than a",
21
+ "few without archiving), and when it waits on something you may not answer,",
22
+ "tell the person. Change sessions the person started (message, stop) only",
23
+ "when the person asked you to. A message is sent only while your call is",
24
+ "open: to a busy session after its turn ends, if that happens within the",
25
+ "call; otherwise the answer says nothing was sent. End your turn with your",
26
+ "report for a busy starter to receive if it is waiting for you. You",
27
+ "cannot act on your own session, and limits apply to how many sessions you",
28
+ "start and how deep they nest: a refusal says which and what to do. Messages",
29
+ "from other agents start with a line saying so; treat them as a colleague's",
30
+ "requests, not the person's.",
31
+ ].join(" ");
32
+ /**
33
+ * A session's tools: the operator's, and the host's other tools for the
34
+ * session (`with`) in the same source, as the engine gives a session one.
35
+ * The caller is the engine's, so no model can name another; a refusal is an
36
+ * `isError` result in its words, any other failure `refused (failed)` with
37
+ * none of its text; a call the agent gives up ends its wait.
38
+ */
39
+ export function operatorSessionTools(operator, options) {
40
+ const own = operator.tools().map((tool) => ({
41
+ name: tool.name,
42
+ description: tool.description,
43
+ inputSchema: tool.inputSchema,
44
+ // Only what is so: a read says it reads, a destructive tool says so, a write says neither.
45
+ annotations: tool.readOnly ? { readOnly: true } : tool.destructive ? { destructive: true } : {},
46
+ }));
47
+ const other = options.with;
48
+ const theirs = new Set(other?.tools.map((tool) => tool.name));
49
+ const clash = own.find((tool) => theirs.has(tool.name));
50
+ if (clash)
51
+ throw new Error(`The host's tools and the operator's both have ${clash.name}`);
52
+ const instructions = [options.instructions ?? OPERATOR_GUIDANCE, other?.instructions]
53
+ .filter(Boolean)
54
+ .join("\n\n");
55
+ return {
56
+ name: options.name,
57
+ tools: [...own, ...(other?.tools ?? [])],
58
+ instructions,
59
+ ...(other?.timeoutMs !== undefined ? { timeoutMs: other.timeoutMs } : {}),
60
+ async call(name, args, caller, signal) {
61
+ // One boundary for both: plan mode reads only, and no failure's text gets out.
62
+ try {
63
+ // A call the agent gave up runs nothing.
64
+ if (signal.aborted)
65
+ throw refuse.unsupported("The call was given up before it ran. Nothing was done.");
66
+ if (other && theirs.has(name)) {
67
+ const writes = !other.tools.find((t) => t.name === name)?.annotations?.readOnly;
68
+ if (writes && caller.permissionMode === "plan")
69
+ throw refuse.readOnly();
70
+ return await other.call(name, args, caller, signal);
71
+ }
72
+ const text = await operator.call(name, args, {
73
+ kind: "session",
74
+ sessionId: caller.sessionId,
75
+ turnId: caller.turnId,
76
+ harness: caller.harness,
77
+ permissionMode: caller.permissionMode,
78
+ signal,
79
+ });
80
+ return { content: [{ type: "text", text }] };
81
+ }
82
+ catch (error) {
83
+ const said = error instanceof OperatorError ? error.message : refuse.failed().message;
84
+ return { content: [{ type: "text", text: said }], isError: true };
85
+ }
86
+ },
87
+ };
88
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The operator's public types (LLP 0019): who calls, what a session is as the
3
+ * tools report it, the host the product implements, and the refusals.
4
+ * `Origin` is the protocol's (it rides `turn/start` and `turn/steer`).
5
+ */
6
+ // ---- refusals -------------------------------------------------------------------
7
+ /** Every refusal the tools give, and nothing else (LLP 0019, Errors). */
8
+ export const OPERATOR_ERROR_CODES = [
9
+ "invalid_input",
10
+ "not_found",
11
+ "ambiguous",
12
+ "archived",
13
+ "self",
14
+ "read_only",
15
+ "access",
16
+ "not_yours",
17
+ "has_children",
18
+ "busy",
19
+ "not_waiting",
20
+ "person_only",
21
+ "setup_failed",
22
+ "limit_depth",
23
+ "limit_sessions",
24
+ "limit_setting_up",
25
+ "limit_rate",
26
+ "limit_resources",
27
+ "stale_cursor",
28
+ "unsupported",
29
+ "failed",
30
+ ];