@zvada/agent-server 0.3.25 → 0.3.27

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 (256) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/README.md +4 -1
  3. package/dist/client/client.js +27 -11
  4. package/dist/client/connection.js +35 -3
  5. package/dist/core/agents/acp/acp-agent.js +91 -14
  6. package/dist/core/agents/acp/mappings.js +5 -1
  7. package/dist/core/agents/claude-code/approvals.js +3 -2
  8. package/dist/core/agents/claude-code/claude-agent.js +12 -2
  9. package/dist/core/agents/claude-code/mcp.js +9 -1
  10. package/dist/core/agents/claude-code/models.js +16 -10
  11. package/dist/core/agents/claude-code/options.js +23 -2
  12. package/dist/core/agents/claude-code/session.js +21 -1
  13. package/dist/core/agents/claude-code/tools.js +9 -4
  14. package/dist/core/agents/claude-code/turn.js +2 -0
  15. package/dist/core/agents/codex-app-server/adapter.js +2 -0
  16. package/dist/core/agents/codex-app-server/client.js +8 -5
  17. package/dist/core/agents/codex-app-server/codex-agent.js +35 -2
  18. package/dist/core/agents/codex-app-server/effort.js +13 -6
  19. package/dist/core/agents/codex-app-server/mcp.js +35 -18
  20. package/dist/core/agents/codex-app-server/models.js +10 -10
  21. package/dist/core/agents/codex-app-server/options.js +11 -2
  22. package/dist/core/agents/codex-app-server/plan-approval.js +1 -1
  23. package/dist/core/agents/codex-app-server/session.js +11 -4
  24. package/dist/core/agents/codex-app-server/thread-settings.js +30 -11
  25. package/dist/core/agents/host-tools.js +493 -0
  26. package/dist/core/agents/mcp-config.js +6 -2
  27. package/dist/core/agents/scripted/scripted-agent.js +39 -6
  28. package/dist/core/agents/scripted/steps.js +5 -1
  29. package/dist/core/agents/session-agent.js +70 -2
  30. package/dist/core/agents/thinking-levels.js +8 -5
  31. package/dist/core/index.js +1 -0
  32. package/dist/core/presets.js +16 -3
  33. package/dist/core/processes/lifeline.js +9 -5
  34. package/dist/core/provision/pins.js +7 -16
  35. package/dist/core/provision/releases.js +25 -25
  36. package/dist/core/proxy/loopback.js +22 -4
  37. package/dist/core/runtime/agent-runtime.js +15 -5
  38. package/dist/core/runtime/event-processor.js +13 -8
  39. package/dist/core/runtime/origin-line.js +42 -0
  40. package/dist/core/runtime/request-broker.js +2 -1
  41. package/dist/core/runtime/steering.js +4 -3
  42. package/dist/core/runtime/turn.js +6 -4
  43. package/dist/operator/errors.js +97 -0
  44. package/dist/operator/index.js +10 -5
  45. package/dist/operator/mcp.js +7 -12
  46. package/dist/operator/operator.js +1336 -380
  47. package/dist/operator/refs.js +59 -0
  48. package/dist/operator/render.js +171 -74
  49. package/dist/operator/session-tools.js +87 -0
  50. package/dist/operator/types.js +30 -0
  51. package/dist/operator/view.js +82 -27
  52. package/dist/protocol/config.js +33 -6
  53. package/dist/protocol/conversation.js +3 -0
  54. package/dist/protocol/history.js +2 -1
  55. package/dist/protocol/index.js +1 -0
  56. package/dist/protocol/lifecycle.js +19 -0
  57. package/dist/protocol/model-catalog.js +58 -18
  58. package/dist/protocol/models.js +6 -27
  59. package/dist/protocol/origin.js +39 -0
  60. package/dist/protocol/reduce.js +2 -0
  61. package/dist/protocol/thinking.js +22 -9
  62. package/dist/protocol/wire-api.js +2 -2
  63. package/dist/protocol/wire.js +17 -0
  64. package/dist/server/bin.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/acp-agent.d.ts +15 -0
  72. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -1
  73. package/dist/types/core/agents/acp/mappings.d.ts +5 -1
  74. package/dist/types/core/agents/acp/mappings.d.ts.map +1 -1
  75. package/dist/types/core/agents/acp/requests.d.ts +2 -0
  76. package/dist/types/core/agents/acp/requests.d.ts.map +1 -1
  77. package/dist/types/core/agents/base.d.ts +2 -0
  78. package/dist/types/core/agents/base.d.ts.map +1 -1
  79. package/dist/types/core/agents/claude-code/approvals.d.ts +2 -1
  80. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  81. package/dist/types/core/agents/claude-code/claude-agent.d.ts +1 -0
  82. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  83. package/dist/types/core/agents/claude-code/mcp.d.ts +8 -1
  84. package/dist/types/core/agents/claude-code/mcp.d.ts.map +1 -1
  85. package/dist/types/core/agents/claude-code/models.d.ts +9 -5
  86. package/dist/types/core/agents/claude-code/models.d.ts.map +1 -1
  87. package/dist/types/core/agents/claude-code/options.d.ts +10 -1
  88. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  89. package/dist/types/core/agents/claude-code/session.d.ts +2 -0
  90. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  91. package/dist/types/core/agents/claude-code/tools.d.ts.map +1 -1
  92. package/dist/types/core/agents/claude-code/turn.d.ts +3 -0
  93. package/dist/types/core/agents/claude-code/turn.d.ts.map +1 -1
  94. package/dist/types/core/agents/codex-app-server/adapter.d.ts.map +1 -1
  95. package/dist/types/core/agents/codex-app-server/client.d.ts +2 -0
  96. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  97. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts +11 -0
  98. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts.map +1 -1
  99. package/dist/types/core/agents/codex-app-server/effort.d.ts +7 -7
  100. package/dist/types/core/agents/codex-app-server/effort.d.ts.map +1 -1
  101. package/dist/types/core/agents/codex-app-server/mcp.d.ts +11 -3
  102. package/dist/types/core/agents/codex-app-server/mcp.d.ts.map +1 -1
  103. package/dist/types/core/agents/codex-app-server/models.d.ts +4 -1
  104. package/dist/types/core/agents/codex-app-server/models.d.ts.map +1 -1
  105. package/dist/types/core/agents/codex-app-server/options.d.ts +9 -2
  106. package/dist/types/core/agents/codex-app-server/options.d.ts.map +1 -1
  107. package/dist/types/core/agents/codex-app-server/requests.d.ts +2 -0
  108. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  109. package/dist/types/core/agents/codex-app-server/session.d.ts +6 -3
  110. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  111. package/dist/types/core/agents/codex-app-server/thread-settings.d.ts.map +1 -1
  112. package/dist/types/core/agents/host-tools.d.ts +162 -0
  113. package/dist/types/core/agents/host-tools.d.ts.map +1 -0
  114. package/dist/types/core/agents/mcp-config.d.ts +11 -2
  115. package/dist/types/core/agents/mcp-config.d.ts.map +1 -1
  116. package/dist/types/core/agents/scripted/scripted-agent.d.ts +14 -1
  117. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  118. package/dist/types/core/agents/scripted/steps.d.ts.map +1 -1
  119. package/dist/types/core/agents/session-agent.d.ts +2 -7
  120. package/dist/types/core/agents/session-agent.d.ts.map +1 -1
  121. package/dist/types/core/agents/thinking-levels.d.ts +7 -3
  122. package/dist/types/core/agents/thinking-levels.d.ts.map +1 -1
  123. package/dist/types/core/index.d.ts +1 -0
  124. package/dist/types/core/index.d.ts.map +1 -1
  125. package/dist/types/core/presets.d.ts +11 -1
  126. package/dist/types/core/presets.d.ts.map +1 -1
  127. package/dist/types/core/processes/lifeline.d.ts.map +1 -1
  128. package/dist/types/core/provision/pins.d.ts +5 -4
  129. package/dist/types/core/provision/pins.d.ts.map +1 -1
  130. package/dist/types/core/proxy/loopback.d.ts.map +1 -1
  131. package/dist/types/core/runtime/agent-runtime.d.ts +4 -2
  132. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  133. package/dist/types/core/runtime/event-processor.d.ts +2 -2
  134. package/dist/types/core/runtime/event-processor.d.ts.map +1 -1
  135. package/dist/types/core/runtime/origin-line.d.ts +15 -0
  136. package/dist/types/core/runtime/origin-line.d.ts.map +1 -0
  137. package/dist/types/core/runtime/request-broker.d.ts +1 -1
  138. package/dist/types/core/runtime/request-broker.d.ts.map +1 -1
  139. package/dist/types/core/runtime/steering.d.ts +7 -4
  140. package/dist/types/core/runtime/steering.d.ts.map +1 -1
  141. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  142. package/dist/types/operator/errors.d.ts +83 -0
  143. package/dist/types/operator/errors.d.ts.map +1 -0
  144. package/dist/types/operator/index.d.ts +10 -5
  145. package/dist/types/operator/index.d.ts.map +1 -1
  146. package/dist/types/operator/mcp.d.ts +1 -1
  147. package/dist/types/operator/mcp.d.ts.map +1 -1
  148. package/dist/types/operator/operator.d.ts +15 -197
  149. package/dist/types/operator/operator.d.ts.map +1 -1
  150. package/dist/types/operator/refs.d.ts +25 -0
  151. package/dist/types/operator/refs.d.ts.map +1 -0
  152. package/dist/types/operator/render.d.ts +59 -19
  153. package/dist/types/operator/render.d.ts.map +1 -1
  154. package/dist/types/operator/session-tools.d.ts +61 -0
  155. package/dist/types/operator/session-tools.d.ts.map +1 -0
  156. package/dist/types/operator/types.d.ts +441 -0
  157. package/dist/types/operator/types.d.ts.map +1 -0
  158. package/dist/types/operator/view.d.ts +19 -29
  159. package/dist/types/operator/view.d.ts.map +1 -1
  160. package/dist/types/protocol/config.d.ts +32 -24
  161. package/dist/types/protocol/config.d.ts.map +1 -1
  162. package/dist/types/protocol/conversation.d.ts +48 -39
  163. package/dist/types/protocol/conversation.d.ts.map +1 -1
  164. package/dist/types/protocol/execution.d.ts +2 -18
  165. package/dist/types/protocol/execution.d.ts.map +1 -1
  166. package/dist/types/protocol/history.d.ts +1 -1
  167. package/dist/types/protocol/history.d.ts.map +1 -1
  168. package/dist/types/protocol/index.d.ts +1 -0
  169. package/dist/types/protocol/index.d.ts.map +1 -1
  170. package/dist/types/protocol/lifecycle.d.ts +48 -74
  171. package/dist/types/protocol/lifecycle.d.ts.map +1 -1
  172. package/dist/types/protocol/model-catalog.d.ts.map +1 -1
  173. package/dist/types/protocol/models.d.ts +4 -42
  174. package/dist/types/protocol/models.d.ts.map +1 -1
  175. package/dist/types/protocol/origin.d.ts +49 -0
  176. package/dist/types/protocol/origin.d.ts.map +1 -0
  177. package/dist/types/protocol/reduce.d.ts.map +1 -1
  178. package/dist/types/protocol/thinking.d.ts +19 -19
  179. package/dist/types/protocol/thinking.d.ts.map +1 -1
  180. package/dist/types/protocol/wire-api.d.ts +59 -106
  181. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  182. package/dist/types/protocol/wire.d.ts +81 -119
  183. package/dist/types/protocol/wire.d.ts.map +1 -1
  184. package/dist/types/server/routes.d.ts.map +1 -1
  185. package/docs/consuming.md +124 -132
  186. package/docs/deploy.md +6 -5
  187. package/docs/harnesses.md +79 -31
  188. package/docs/sync-history.md +2 -1
  189. package/package.json +4 -4
  190. package/src/client/client.ts +36 -9
  191. package/src/client/connection.ts +31 -1
  192. package/src/client/turns.ts +2 -1
  193. package/src/core/agents/acp/acp-agent.ts +123 -17
  194. package/src/core/agents/acp/mappings.ts +5 -1
  195. package/src/core/agents/acp/requests.ts +2 -0
  196. package/src/core/agents/base.ts +2 -0
  197. package/src/core/agents/claude-code/approvals.ts +4 -3
  198. package/src/core/agents/claude-code/claude-agent.ts +14 -2
  199. package/src/core/agents/claude-code/mcp.ts +11 -1
  200. package/src/core/agents/claude-code/models.ts +15 -10
  201. package/src/core/agents/claude-code/options.ts +33 -3
  202. package/src/core/agents/claude-code/session.ts +26 -1
  203. package/src/core/agents/claude-code/tools.ts +10 -4
  204. package/src/core/agents/claude-code/turn.ts +4 -0
  205. package/src/core/agents/codex-app-server/adapter.ts +2 -0
  206. package/src/core/agents/codex-app-server/client.ts +11 -5
  207. package/src/core/agents/codex-app-server/codex-agent.ts +45 -1
  208. package/src/core/agents/codex-app-server/effort.ts +15 -20
  209. package/src/core/agents/codex-app-server/mcp.ts +46 -23
  210. package/src/core/agents/codex-app-server/models.ts +10 -10
  211. package/src/core/agents/codex-app-server/options.ts +16 -2
  212. package/src/core/agents/codex-app-server/plan-approval.ts +1 -1
  213. package/src/core/agents/codex-app-server/requests.ts +2 -0
  214. package/src/core/agents/codex-app-server/session.ts +19 -4
  215. package/src/core/agents/codex-app-server/thread-settings.ts +31 -11
  216. package/src/core/agents/host-tools.ts +649 -0
  217. package/src/core/agents/mcp-config.ts +15 -3
  218. package/src/core/agents/scripted/scripted-agent.ts +51 -5
  219. package/src/core/agents/scripted/steps.ts +5 -1
  220. package/src/core/agents/session-agent.ts +78 -2
  221. package/src/core/agents/thinking-levels.ts +9 -6
  222. package/src/core/index.ts +9 -0
  223. package/src/core/presets.ts +28 -4
  224. package/src/core/processes/lifeline.ts +9 -5
  225. package/src/core/provision/pins.ts +7 -16
  226. package/src/core/provision/releases.ts +25 -25
  227. package/src/core/proxy/loopback.ts +25 -4
  228. package/src/core/runtime/agent-runtime.ts +31 -7
  229. package/src/core/runtime/event-processor.ts +13 -6
  230. package/src/core/runtime/origin-line.ts +43 -0
  231. package/src/core/runtime/request-broker.ts +2 -0
  232. package/src/core/runtime/steering.ts +8 -4
  233. package/src/core/runtime/turn.ts +11 -4
  234. package/src/operator/errors.ts +218 -0
  235. package/src/operator/index.ts +18 -23
  236. package/src/operator/mcp.ts +7 -16
  237. package/src/operator/operator.ts +1583 -613
  238. package/src/operator/refs.ts +75 -0
  239. package/src/operator/render.ts +208 -98
  240. package/src/operator/session-tools.ts +126 -0
  241. package/src/operator/types.ts +505 -0
  242. package/src/operator/view.ts +93 -42
  243. package/src/protocol/config.ts +36 -7
  244. package/src/protocol/conversation.ts +3 -0
  245. package/src/protocol/history.ts +2 -1
  246. package/src/protocol/index.ts +1 -0
  247. package/src/protocol/lifecycle.ts +21 -0
  248. package/src/protocol/model-catalog.ts +58 -18
  249. package/src/protocol/models.ts +6 -26
  250. package/src/protocol/origin.ts +47 -0
  251. package/src/protocol/reduce.ts +4 -0
  252. package/src/protocol/thinking.ts +27 -14
  253. package/src/protocol/wire-api.ts +2 -2
  254. package/src/protocol/wire.ts +18 -0
  255. package/src/server/bin.ts +6 -4
  256. 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;
@@ -70,16 +66,20 @@ const textOf = (parts: readonly (Part | UnknownPart)[]) =>
70
66
  * The next step, as the tool call that takes it:
71
67
  * `-> answer_request(session: "voyager", answer: "<your answer>")`.
72
68
  */
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)}`);
69
+ // @ref LLP 0014#untrusted-text — every value a line names goes through `json`
70
+ /**
71
+ * A value as JSON on one line, losslessly: `\uXXXX` for what JSON leaves raw
72
+ * (U+2028, C1, bidi controls), so it reads back the same and breaks no line.
73
+ */
74
+ export const json = (value: unknown): string =>
75
+ JSON.stringify(value).replace(UNSAFE_IN_JSON, (found) =>
76
+ [...found].map((c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`).join(""),
77
+ );
78
+
79
+ export function callHint(tool: string, args: Record<string, unknown> = {}): string {
80
+ const named = Object.entries(args)
81
+ .filter(([, value]) => value !== undefined)
82
+ .map(([key, value]) => `${key}: ${json(value)}`);
83
83
  return `-> ${tool}(${named.join(", ")})`;
84
84
  }
85
85
 
@@ -267,16 +267,51 @@ function aboutLines(toolCall: DecisionRequest["toolCall"], root: string): string
267
267
  }
268
268
 
269
269
  /**
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.
270
+ * One request's context: named by the broker's own id when more than one
271
+ * waits, and offered the answer only when this caller may give that one.
273
272
  */
274
- export function describeWaiting(waiting: Waiting, ref: string, root = ""): string {
273
+ export function perRequest<C extends WaitingContext>(context: C, waiting: Waiting): C {
274
+ const id = waiting.request.requestId;
275
+ return {
276
+ ...context,
277
+ // Its id in every hint, one request or many: a hint followed late cannot reach a replacement.
278
+ handle: id,
279
+ ...(context.answerable ? { canAnswer: context.answerable.has(id) } : {}),
280
+ };
281
+ }
282
+
283
+ /** What a request waiting in a session is, in the words a model reads. */
284
+ export interface WaitingContext {
285
+ /** How hints name the session. */
286
+ ref: string;
287
+ /** The request's handle, said when the session waits on more than one. */
288
+ handle?: string;
289
+ /** Whether this caller may answer it: the answer hint is offered only then. */
290
+ canAnswer?: boolean;
291
+ /** Whether this caller may answer each waiting request, by the one rule the write uses. */
292
+ answerable?: ReadonlySet<string>;
293
+ /** Paths under it read relative to it. */
294
+ root?: string;
295
+ hint: Hint;
296
+ }
297
+
298
+ /**
299
+ * What the agent waits on, and the call that answers it, when that tool is
300
+ * installed. What only the person can answer (`personOnly`) is one line, with
301
+ * no call.
302
+ */
303
+ export function describeWaiting(waiting: Waiting, context: WaitingContext): string {
304
+ const { ref, handle, root = "", hint } = context;
275
305
  const only = waiting.kind === "question" && personOnly(waiting);
276
306
  if (only) {
277
307
  return `only the person can answer this, where the session runs (${only}): ${quoted(clip(waiting.request.message, 300))}`;
278
308
  }
279
- const answer = (text: string) => callHint("answer_request", { session: ref, answer: text });
309
+ const named = handle ? ` (request ${quoted(handle)})` : "";
310
+ const answer = (text: string) => {
311
+ if (context.canAnswer === false) return "";
312
+ const call = hint("answer_request", { session: ref, request: handle, answer: text });
313
+ return call ? `\n ${call}` : "";
314
+ };
280
315
  const options = (labels: readonly string[], ownWords = false) =>
281
316
  labels.length ? `\n${optionsLine(labels)}${ownWords ? " (or your own words)" : ""}` : "";
282
317
  if (waiting.kind === "question") {
@@ -285,28 +320,31 @@ export function describeWaiting(waiting: Waiting, ref: string, root = ""): strin
285
320
  ? questions
286
321
  .map(
287
322
  (q) =>
288
- `${block("question:", q.question)}${options(
323
+ `${block(`question${named}:`, q.question)}${options(
289
324
  (q.options ?? []).map((o) => o.label),
290
325
  true,
291
326
  )}`,
292
327
  )
293
328
  .join("\n")
294
- : block("question:", waiting.request.message);
329
+ : block(`question${named}:`, waiting.request.message);
295
330
  const form =
296
331
  questions.length > 1 ? "<one answer per question, separated by ; >" : "<your answer>";
297
- return `${asked}\n ${answer(form)}`;
332
+ return `${asked}${answer(form)}`;
298
333
  }
299
- if (isPlan(waiting.request)) {
300
- const approve = ` ${answer("approve")} (or answer: "<what to change>")`;
334
+ if (waiting.kind === "plan") {
335
+ const approve = answer("approve");
336
+ const or = approve ? ` (or answer: "<what to change>")` : "";
301
337
  // Never approved unseen: the plan itself, or the call that shows it.
302
338
  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}`;
339
+ if (typeof plan === "string" && plan.trim())
340
+ return `plan waiting for approval${named}:\n${quote(clip(plan, 800))}${approve}${or}`;
341
+ const read = hint("read_session", { session: ref });
342
+ return `plan waiting for approval${named}; read it before answering${read ? `\n ${read}` : ""}${approve}${or}`;
306
343
  }
307
- const named = waiting.request.options.map((option) => option.name);
344
+ const choices = waiting.request.options.map((option) => option.name);
308
345
  const about = aboutLines(waiting.request.toolCall, root);
309
- return `${block("permission:", waiting.request.title)}${about}${options(named)}\n ${answer("allow")} (or answer: "deny")`;
346
+ const allow = answer("allow");
347
+ return `${block(`permission${named}:`, waiting.request.title)}${about}${options(choices)}${allow}${allow ? ` (or answer: "deny")` : ""}`;
310
348
  }
311
349
 
312
350
  /** The agent's words since the person last spoke. */
@@ -322,90 +360,162 @@ export function lastReply(messages: readonly ViewMessage[]): string {
322
360
  .join("\n");
323
361
  }
324
362
 
363
+ /** Every message of a view, oldest first. */
364
+ export const messagesOf = (view: Pick<SessionView, "turns">): ViewMessage[] =>
365
+ view.turns.flatMap((turn) => turn.messages);
366
+
367
+ /** How a status reads in an outcome. */
368
+ const STATUS_WORDS: Record<string, string> = {
369
+ idle: "done",
370
+ stopped: "stopped",
371
+ error: "error",
372
+ needs_input: "needs_input",
373
+ archived: "archived",
374
+ };
375
+
376
+ /** How the waits and outcomes word a view; `waited` is how long the call waited. */
377
+ export interface OutcomeContext extends WaitingContext {
378
+ waited?: number;
379
+ /** The host's line of facts for a settled turn. */
380
+ note?: string;
381
+ }
382
+
325
383
  /**
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.
384
+ * How a session stands: done, stopped, waiting on someone, failed, or still
385
+ * going. Each request it waits on is said with the call that answers it.
330
386
  */
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.
387
+ export function renderOutcome(view: SessionView, context: OutcomeContext): string {
388
+ const { ref, hint } = context;
389
+ if (view.status === "working" || view.status === "setting_up") {
390
+ const messages = messagesOf(view);
341
391
  const detail = [
342
- view.messages.length ? "" : "starting up, no messages yet",
343
- waitedSeconds ? `still running after ${waitedSeconds}s` : "",
392
+ view.status === "setting_up"
393
+ ? "being set up"
394
+ : messages.length
395
+ ? ""
396
+ : "starting, no messages yet",
397
+ context.waited ? `still running after ${context.waited}s` : "",
344
398
  ].filter(Boolean);
345
- return `status: working${detail.length ? ` (${detail.join("; ")})` : ""}\n ${callHint("wait_for_session", { session: ref })}`;
399
+ const next = hint("wait_for_sessions", { sessions: [ref] });
400
+ return `status: working${detail.length ? ` (${detail.join("; ")})` : ""}${next ? `\n ${next}` : ""}`;
346
401
  }
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);
402
+ const messages = messagesOf(view);
403
+ const fresh = view.status === "idle" && !messages.length;
404
+ const lines = [
405
+ `status: ${fresh ? "idle (no messages yet)" : (STATUS_WORDS[view.status] ?? view.status)}`,
406
+ ];
407
+ const reply = lastReply(messages);
350
408
  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 })}`);
409
+ for (const waiting of view.waiting)
410
+ lines.push(describeWaiting(waiting, perRequest(context, waiting)));
411
+ if (view.status === "error") {
412
+ const failed = view.turns.at(-1)?.error;
413
+ lines.push(block("error:", failed ?? "the turn failed"));
414
+ }
415
+ if (context.note) lines.push(oneLine(context.note));
416
+ if (view.status === "error" || reply.length > 1500) {
417
+ const read = hint("read_session", { session: ref });
418
+ if (read) lines.push(` ${read}`);
356
419
  }
357
420
  return lines.join("\n");
358
421
  }
359
422
 
360
- export interface RenderOptions {
361
- /** How many recent messages (default 10). */
423
+ /** Who a user message is from, as `read_session` labels it; `you` is the caller's own origin. */
424
+ export function senderLabel(origin: ReportedOrigin | undefined, you: Origin): string {
425
+ if (!origin || origin.kind === "person") return you.kind === "person" ? "[you]" : "[the person]";
426
+ if (sameOrigin(origin, you)) return "[you]";
427
+ if (origin.kind === "session") {
428
+ const { name, sessionId } = origin as { name?: string; sessionId: string };
429
+ return `[${quoted(name ?? sessionId)}]`;
430
+ }
431
+ if (origin.kind === "assistant") return `[assistant ${quoted(String(origin.name))}]`;
432
+ return `[${quoted(origin.kind)}]`;
433
+ }
434
+
435
+ /** Whether two origins are the same sender. */
436
+ export function sameOrigin(a: ReportedOrigin | undefined, b: ReportedOrigin | undefined): boolean {
437
+ const key = (o: ReportedOrigin | undefined) =>
438
+ !o || o.kind === "person"
439
+ ? "person"
440
+ : o.kind === "session"
441
+ ? `session:${(o as { sessionId: string }).sessionId}`
442
+ : o.kind === "assistant"
443
+ ? `assistant:${(o as { id: string }).id}`
444
+ : JSON.stringify(o);
445
+ return key(a) === key(b);
446
+ }
447
+
448
+ /** How a turn that is over ended, after its messages. */
449
+ function endOf(turn: ViewTurn, you: Origin): string | undefined {
450
+ if (turn.outcome === "running") return undefined;
451
+ if (turn.outcome === "done") return "— turn done";
452
+ if (turn.outcome === "cancelled") {
453
+ const by = turn.cancelledBy ? ` by ${senderLabel(turn.cancelledBy, you).slice(1, -1)}` : "";
454
+ return `— turn cancelled${by}`;
455
+ }
456
+ return block("— turn failed:", turn.error ?? "the turn failed");
457
+ }
458
+
459
+ export interface RenderOptions extends WaitingContext {
460
+ /** How many recent messages (default 10); with `all`, every message the host gave (a cursor's page). */
362
461
  last?: number;
363
- /** Paths in tool lines are shown relative to this folder. */
364
- root?: string;
462
+ all?: boolean;
463
+ /** The caller's own origin: its messages read `[you]`. */
464
+ you: Origin;
465
+ /** The header line (the session, its id, who started it). */
466
+ header?: string;
365
467
  }
366
468
 
367
469
  /**
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).
470
+ * The conversation, condensed: each user message under its own sender, what
471
+ * the agent said, which tools it ran (with what a call asked the person),
472
+ * how each turn ended, and what the session waits on.
371
473
  */
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, " "));
474
+ export function renderConversation(view: SessionView, options: RenderOptions): string {
475
+ const { root, you } = options;
476
+ const lines: string[] = options.header ? [options.header] : [];
477
+ const limit = options.all ? Number.POSITIVE_INFINITY : Math.max(1, options.last ?? 10);
478
+ let count = 0;
479
+ const shownTurns: { turn: ViewTurn; messages: ViewMessage[] }[] = [];
480
+ for (let t = view.turns.length - 1; t >= 0 && count < limit; t--) {
481
+ const turn = view.turns[t] as ViewTurn;
482
+ const messages = turn.messages.slice(-(limit - count));
483
+ count += messages.length;
484
+ shownTurns.unshift({ turn, messages });
485
+ }
486
+ const working = view.status === "working" || view.status === "needs_input";
487
+ for (const { turn, messages } of shownTurns) {
488
+ for (const message of messages) {
489
+ const text = textOf(message.parts);
490
+ if (message.role === "user") {
491
+ lines.push(block(senderLabel(message.origin, you), clip(text, 800)));
492
+ continue;
395
493
  }
494
+ for (const part of message.parts) {
495
+ const line = toolLine(part, root, working && turn.outcome === "running");
496
+ if (!line) continue;
497
+ lines.push(` · ${line}`);
498
+ for (const asked of askedLines(part, root)) lines.push(asked.replace(/^/gm, " "));
499
+ }
500
+ if (text) lines.push(block("[agent]", clip(text, 1200)));
396
501
  }
397
- if (text) lines.push(block("[agent]", clip(text, 1200)));
502
+ const end = endOf(turn, you);
503
+ if (end) lines.push(end);
398
504
  }
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) {
505
+ if (!count && !view.turns.length) lines.push("(no messages yet)");
506
+ lines.push(`(status: ${view.status})`);
507
+ for (const waiting of view.waiting)
508
+ lines.push(describeWaiting(waiting, perRequest(options, waiting)));
509
+ const total = view.turns.reduce((sum, turn) => sum + turn.messages.length, 0);
510
+ if (view.older || count < total) {
511
+ const more = options.hint("read_session", {
512
+ session: options.ref,
513
+ last: Math.min(count + 10, MAX_LAST),
514
+ });
405
515
  lines.push(
406
- shown.length >= MAX_LAST
516
+ count >= MAX_LAST || !more
407
517
  ? `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) })}`,
518
+ : `older messages exist: ${more}`,
409
519
  );
410
520
  }
411
521
  return lines.join("\n");
@@ -458,7 +568,7 @@ export function answerFor(waiting: Waiting, text: string): Answer {
458
568
  requestId,
459
569
  outcome: { outcome: "selected", optionId, ...(message ? { message } : {}) },
460
570
  });
461
- if (isPlan(waiting.request)) {
571
+ if (waiting.kind === "plan") {
462
572
  // Approving starts the work with edits still asked for; anything else is what to change.
463
573
  return YES.test(said)
464
574
  ? pick(PLAN_OPTION_IDS.approve)
@@ -0,0 +1,126 @@
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
+
8
+ // @ref LLP 0019#guidance — the paragraph a host adds to its sessions' instructions
9
+
10
+ import { OperatorError, refuse } from "./errors.ts";
11
+ import type { Operator } from "./types.ts";
12
+
13
+ /**
14
+ * What a host adds to the instructions of every session that has these
15
+ * tools, or can receive messages from sessions that do.
16
+ */
17
+ export const OPERATOR_GUIDANCE = [
18
+ "You can see and work with other agent sessions with the session tools",
19
+ "(whoami, list_sessions, read_session, wait_for_sessions, start_session,",
20
+ "send_message, answer_request, stop_sessions, archive). Start a session for",
21
+ "a separate piece of work that needs its own workspace or would run a long",
22
+ "time; for quick reading or searching, use your own built-in subagents",
23
+ "instead. A session you started is your responsibility: wait for it, read",
24
+ "what it did, archive it when its work is done (you cannot start more than a",
25
+ "few without archiving), and when it waits on something you may not answer,",
26
+ "tell the person. Change sessions the person started (message, stop) only",
27
+ "when the person asked you to. A message is sent only while your call is",
28
+ "open: to a busy session after its turn ends, if that happens within the",
29
+ "call; otherwise the answer says nothing was sent, and you call again. You",
30
+ "cannot act on your own session, and limits apply to how many sessions you",
31
+ "start and how deep they nest: a refusal says which and what to do. Messages",
32
+ "from other agents start with a line saying so; treat them as a colleague's",
33
+ "requests, not the person's.",
34
+ ].join(" ");
35
+
36
+ /** Who calls, as the engine fills it at the moment of the call (`HostToolCaller`). */
37
+ export interface SessionToolCaller {
38
+ sessionId: string;
39
+ harness: string;
40
+ turnId: string;
41
+ permissionMode: string;
42
+ }
43
+
44
+ /** A tool as the engine delivers it (`HostTool`). */
45
+ export interface SessionTool {
46
+ name: string;
47
+ description: string;
48
+ inputSchema: Record<string, unknown>;
49
+ annotations?: { readOnly?: boolean; destructive?: boolean };
50
+ }
51
+
52
+ export type SessionToolContent =
53
+ | { type: "text"; text: string }
54
+ | { type: "image"; data: string; mimeType: string };
55
+
56
+ /** A session's one source of tools (`HostToolSource`). */
57
+ export interface SessionToolSource {
58
+ name: string;
59
+ tools: readonly SessionTool[];
60
+ instructions?: string;
61
+ timeoutMs?: number;
62
+ call(
63
+ name: string,
64
+ args: Record<string, unknown>,
65
+ caller: SessionToolCaller,
66
+ signal: AbortSignal,
67
+ ): Promise<{ content: SessionToolContent[]; isError?: boolean }>;
68
+ }
69
+
70
+ /**
71
+ * A session's tools: the operator's, and the host's other tools for the
72
+ * session (`with`) in the same source, as the engine gives a session one.
73
+ * The caller is the engine's, so no model can name another; a refusal is an
74
+ * `isError` result in its words, any other failure `refused (failed)` with
75
+ * none of its text; a call the agent gives up ends its wait.
76
+ */
77
+ export function operatorSessionTools<Auth>(
78
+ operator: Operator<Auth>,
79
+ options: { name: string; with?: SessionToolSource; instructions?: string },
80
+ ): SessionToolSource {
81
+ const own: SessionTool[] = operator.tools().map((tool) => ({
82
+ name: tool.name,
83
+ description: tool.description,
84
+ inputSchema: tool.inputSchema as Record<string, unknown>,
85
+ // Only what is so: a read says it reads, a destructive tool says so, a write says neither.
86
+ annotations: tool.readOnly ? { readOnly: true } : tool.destructive ? { destructive: true } : {},
87
+ }));
88
+ const other = options.with;
89
+ const theirs = new Set(other?.tools.map((tool) => tool.name));
90
+ const clash = own.find((tool) => theirs.has(tool.name));
91
+ if (clash) throw new Error(`The host's tools and the operator's both have ${clash.name}`);
92
+ const instructions = [options.instructions ?? OPERATOR_GUIDANCE, other?.instructions]
93
+ .filter(Boolean)
94
+ .join("\n\n");
95
+ return {
96
+ name: options.name,
97
+ tools: [...own, ...(other?.tools ?? [])],
98
+ instructions,
99
+ ...(other?.timeoutMs !== undefined ? { timeoutMs: other.timeoutMs } : {}),
100
+ async call(name, args, caller, signal) {
101
+ // One boundary for both: plan mode reads only, and no failure's text gets out.
102
+ try {
103
+ // A call the agent gave up runs nothing.
104
+ if (signal.aborted)
105
+ throw refuse.unsupported("The call was given up before it ran. Nothing was done.");
106
+ if (other && theirs.has(name)) {
107
+ const writes = !other.tools.find((t) => t.name === name)?.annotations?.readOnly;
108
+ if (writes && caller.permissionMode === "plan") throw refuse.readOnly();
109
+ return await other.call(name, args, caller, signal);
110
+ }
111
+ const text = await operator.call(name, args, {
112
+ kind: "session",
113
+ sessionId: caller.sessionId,
114
+ turnId: caller.turnId,
115
+ harness: caller.harness as never,
116
+ permissionMode: caller.permissionMode,
117
+ signal,
118
+ });
119
+ return { content: [{ type: "text", text }] };
120
+ } catch (error) {
121
+ const said = error instanceof OperatorError ? error.message : refuse.failed().message;
122
+ return { content: [{ type: "text", text: said }], isError: true };
123
+ }
124
+ },
125
+ };
126
+ }