akanjs 3.2.0-rc.20 → 3.2.0-rc.21

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 (40) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/common/index.ts +2 -0
  3. package/common/mcpExposure.ts +12 -2
  4. package/fetch/client/fetchClient.ts +2 -2
  5. package/package.json +1 -1
  6. package/server/mcp/AgentTools.ts +1 -0
  7. package/service/agentLoop/agentLoop.ts +49 -6
  8. package/service/agentLoop/agentLoopTypes.ts +25 -3
  9. package/service/agentLoop/loopCompaction.ts +8 -2
  10. package/service/agentLoop/loopRequest.ts +34 -1
  11. package/service/agentLoop/loopToolkits.ts +107 -0
  12. package/service/predefinedAdaptor/agentTools.adaptor.ts +3 -2
  13. package/service/predefinedAdaptor/llm.adaptor.ts +2 -0
  14. package/signal/index.ts +1 -0
  15. package/signal/mcp/McpDocument.ts +8 -1
  16. package/signal/serializer/fetch.serializer.ts +12 -5
  17. package/signal/slice.ts +22 -19
  18. package/signal/types.ts +17 -5
  19. package/types/common/index.d.ts +1 -1
  20. package/types/common/mcpExposure.d.ts +7 -2
  21. package/types/dictionary/base.dictionary.d.ts +1 -1
  22. package/types/dictionary/dictionary.d.ts +8 -8
  23. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  24. package/types/service/agentLoop/agentLoopTypes.d.ts +24 -2
  25. package/types/service/agentLoop/loopCompaction.d.ts +1 -1
  26. package/types/service/agentLoop/loopRequest.d.ts +1 -1
  27. package/types/service/agentLoop/loopToolkits.d.ts +14 -0
  28. package/types/service/predefinedAdaptor/agentTools.adaptor.d.ts +3 -2
  29. package/types/service/predefinedAdaptor/llm.adaptor.d.ts +2 -0
  30. package/types/signal/index.d.ts +1 -1
  31. package/types/signal/mcp/McpDocument.d.ts +2 -0
  32. package/types/signal/slice.d.ts +15 -13
  33. package/types/signal/types.d.ts +16 -5
  34. package/types/ui/index.d.ts +1 -1
  35. package/types/vendor/use-agentic/AgentClientTools.d.ts +19 -0
  36. package/types/vendor/use-agentic/index.d.ts +1 -0
  37. package/ui/index.ts +4 -0
  38. package/vendor/use-agentic/AgentClientTools.ts +33 -0
  39. package/vendor/use-agentic/CHANGELOG.md +16 -1
  40. package/vendor/use-agentic/index.ts +1 -0
package/CHANGELOG.md CHANGED
@@ -21,6 +21,29 @@
21
21
 
22
22
  **Upgrading.** An `AgentChat` override that types `title` as `string` must take `ReactNode`. A modal an app mounted beside the Chat and opened from the panel's `header` still opens under the panel; mount it inside `header` to bring it above.
23
23
 
24
+ - dcddea0: `agentService.loop` can now call the tools of a screen the member has open, without running them on the server. The run parks each such call, the way an approval parks one, until the page answers it.
25
+
26
+ - **Server.** `clientTools` takes the definitions the open page sent over the app's own transport. They are listed beside the endpoint tools.
27
+ - They are client input. Each definition is rebuilt from `name`, `description`, `parameters`, `readOnly` and `needsConfirm`. A name an endpoint tool holds is dropped, in a closed toolkit too, and so is `openToolkit`.
28
+ - `approve` is still asked about each call. With no approver, a definition that is not `readOnly` counts as a write, and a `needsConfirm` one is refused.
29
+ - An allowed call ends the run as `awaiting`, with `client: true` on the event. Calls written before it in the same batch have already run; calls written after it wait for the resume.
30
+ - The run never waits on a socket. The app delivers the call to the page, appends the page's result to the stored messages (or its own error when no page answers), and resumes. A resume without that result parks the call again. A resume without `clientTools` answers it as an unknown tool.
31
+ - **Browser.** `AgentClientTools` is new in `use-agentic` and re-exported from `akanjs/ui`, along with the `ToolRunnerHost` and `ToolApprovalRequest` types.
32
+ - `new AgentClientTools(surface?, host?).list()` gives the open screen's tools in the shape `clientTools` takes, each with `readOnly: false`.
33
+ - `run(call)` answers a parked call through the same `ToolRunner` as the in-page chat. A `confirm` still asks through `host.approve` and is refused without one, a card tool needs `host.card`, and the answer is clipped and fenced as the chat's would be.
34
+
35
+ Both are new and optional, so no upgrade step is needed.
36
+
37
+ - 2da2adc: `agentService.loop` takes `toolkits`, so a run over a large catalogue no longer sends every tool definition every round.
38
+
39
+ - **Shape.** `toolkits: { calendar: { description: "Read and edit the org calendar", tools: ["eventListInOrg", "updateEvent"] } }` groups names of `allow`. A tool in no toolkit is the core and is listed every round. `allow` still caps every toolkit.
40
+ - **Opening.** With toolkits set, the run lists one more tool, `openToolkit({ name })`. Its description names each toolkit that has a tool the account may see, with its `description`. The call is answered inside the loop with `{ opened, tools }`, and those tools are listed from the next round on. It never reaches `approve` or `untrusted`, and it does not count toward `budget.toolCalls`.
41
+ - **Refusals.** A call to a tool whose toolkit is closed is answered with an error that names the toolkit to open, with code `toolkitClosed`. An unknown toolkit name gets code `unknownToolkit`. A tool outside `allow` is still an unknown tool.
42
+ - **Resume and compaction.** A resumed run reopens every toolkit a stored `openToolkit` call opened without an error. A compaction summary now carries `toolkits`, which is new and optional on `AgentWireMessage`. Store messages whole, as you already do for `tainted`.
43
+ - **Validation.** A malformed `toolkits`, or an `allow` that names a tool `openToolkit` while toolkits are set, is an `error` before any model call.
44
+
45
+ `toolkits` is optional and changes nothing for a run without it, so no upgrade step is needed.
46
+
24
47
  - e9a2c7f: `this.agentService.loop(request)` runs a model over the `/mcp` tool catalogue in-process until it answers. It needs no browser, so a queued task, a scheduled run or a reply to a mention can use it.
25
48
 
26
49
  - **Events.** It returns an async iterable of `text`, `toolCall`, `toolResult`, `usage`, `compacted` and `awaiting` events. The stream ends with exactly one `done { stop, rounds }` or `error`. `stop` is one of `end`, `maxRounds`, `budget`, `aborted`, `length`, `quota`, `unauthorized` or `awaiting`. The loop waits for the consumer at every event.
@@ -50,6 +73,15 @@
50
73
 
51
74
  The `AgentTurnContext` fields are optional and the moved classes are still exported from `akanjs/signal`, so no upgrade step is needed.
52
75
 
76
+ - 6ffb8ef: `mcp: "agent"` keeps an entry off `/mcp` and leaves it to the in-process agent. `AgentToolsRole`'s `listAs` and `callAs`, and so `agentService.loop`, still list and run it. `/mcp` neither lists nor runs it, and `listingCost` leaves it out. An app whose `/mcp` listing is near its size budget can now give a server agent more tools without growing that listing.
77
+
78
+ - **Where it goes.** It goes wherever `mcp: false` goes: an endpoint, a slice's `init()`, the bare `slice()` value, or one key of its map (`mcp: { cru: "agent" }`). It is curation, not authorization. Guards, person-only guards (`static agents = false`), `readOnly` and `setMcp({ excludeSignals, excludeEndpoints })` still apply to both catalogues, and HTTP is unchanged.
79
+ - **Lib slices.** An app slice that declares no `mcp` map now keeps the narrowest value its lib slices set: `false`, then `"agent"`, then listed.
80
+ - **MCP Apps.** A rendered view may still call an `mcp: "agent"` entry, as it may call an `mcp: false` one.
81
+ - **Types.** `McpShelf` (`boolean | "agent"`) and `narrowestMcpShelf` are new in `akanjs/common`. `SerializedSignalShelf` is new in `akanjs/signal`. `McpDocumentOptions` and `McpExposureOption` gain `agent`.
82
+
83
+ Upgrade: code that reads `SliceCls.mcp`, a serialized endpoint's `mcp` or a serialized signal's `mcp` map as a boolean must now compare it with `false` or `true`. `"agent"` is truthy, and it means "not on `/mcp`". Code that only declares `mcp: false` or `mcp: true` needs no change.
84
+
53
85
  - eb88032: A service can now run the `/mcp` tool catalogue in-process, as a given account, with `plug(AgentToolsRole)`.
54
86
 
55
87
  - **`listAs(account, { allow })`** returns the tools that account may see on `/mcp`, with the same names, descriptions, input schemas and guard filtering. Each tool also carries `readOnly`. `allow` narrows the list by tool name and never widens it.
package/common/index.ts CHANGED
@@ -168,9 +168,11 @@ export {
168
168
  isMcpDescribableArg,
169
169
  type McpExposureEndpoint,
170
170
  type McpExposureOption,
171
+ type McpShelf,
171
172
  mcpBaseVerbOf,
172
173
  mcpHintsOf,
173
174
  mcpRefusalOf,
175
+ narrowestMcpShelf,
174
176
  } from "./mcpExposure";
175
177
  export { MCP_FAILURE_META, type McpFailure } from "./mcpFailure";
176
178
  export { deepObjectify, objectify, plainFieldsOf } from "./objectify";
@@ -1,12 +1,18 @@
1
1
  import { modelNames } from "./akanNames";
2
2
 
3
+ /** `"agent"` lists it to the in-process agent (`AgentToolsRole`, `agentService.loop`) and keeps it off `/mcp`. */
4
+ export type McpShelf = boolean | "agent";
5
+
6
+ export const narrowestMcpShelf = (shelves: readonly McpShelf[]): McpShelf =>
7
+ shelves.includes(false) ? false : shelves.includes("agent") ? "agent" : true;
8
+
3
9
  export interface McpExposureEndpoint {
4
10
  type: string;
5
11
  returns: { refName: string };
6
12
  args: { name: string; refName: string; type: string; arrDepth?: number; nullable?: boolean }[];
7
13
  guards?: string[];
8
14
  fileUpload?: boolean;
9
- mcp?: boolean;
15
+ mcp?: McpShelf;
10
16
  /** `false` when a guard declares `static agents = false`: no model may ever pass, whatever else the guards say. */
11
17
  agents?: boolean;
12
18
  destructive?: boolean;
@@ -19,6 +25,8 @@ export interface McpExposureOption {
19
25
  readOnly?: boolean;
20
26
  /** MCP Apps: judges what a rendered view may call, which lifts the two refusals that only curate a model's shelf. */
21
27
  view?: boolean;
28
+ /** The in-process agent catalogue, which also lists an endpoint declared `mcp: "agent"`. */
29
+ agent?: boolean;
22
30
  }
23
31
 
24
32
  /** `Any` publishes as the empty schema, which tells a model nothing, so it is left out. */
@@ -49,10 +57,12 @@ export const mcpHintsOf = (key: string, endpoint: { type: string; destructive?:
49
57
 
50
58
  export const mcpRefusalOf = (
51
59
  endpoint: McpExposureEndpoint,
52
- { refName, key, readOnly, view }: McpExposureOption,
60
+ { refName, key, readOnly, view, agent }: McpExposureOption,
53
61
  ): string | null => {
54
62
  if (endpoint.mcp === false && !view)
55
63
  return "it declares `mcp: false`, so it is deliberately off the agent shelf. HTTP still serves it.";
64
+ if (endpoint.mcp === "agent" && !agent && !view)
65
+ return 'it declares `mcp: "agent"`, so only the in-process agent lists it, never `/mcp`. HTTP still serves it.';
56
66
 
57
67
  if (endpoint.agents === false)
58
68
  return `its guards (${(endpoint.guards ?? []).join(", ")}) admit no agent — an act reserved for a person, so it is off the agent shelf. HTTP still serves it.`;
@@ -595,7 +595,7 @@ export class FetchClient {
595
595
  const removeGuards = mountedGuards(signal, "remove");
596
596
 
597
597
  const mcp = (verb: keyof NonNullable<SerializedSignal["mcp"]>) => ({
598
- ...(signal.mcp?.[verb] === false ? { mcp: false as const } : {}),
598
+ ...(signal.mcp?.[verb] !== undefined ? { mcp: signal.mcp[verb] } : {}),
599
599
  ...(signal.agents?.[verb] === false ? { agents: false as const } : {}),
600
600
  });
601
601
  const endpoint: { [key: string]: SerializedEndpoint } = {};
@@ -794,7 +794,7 @@ export class FetchClient {
794
794
  const names = sliceNames(refName, suffix).endpoint;
795
795
 
796
796
  const mcp = {
797
- ...(slice.mcp === false ? { mcp: false as const } : {}),
797
+ ...(slice.mcp !== undefined ? { mcp: slice.mcp } : {}),
798
798
  ...(slice.agents === false ? { agents: false as const } : {}),
799
799
  };
800
800
  const endpoint: { [key: string]: SerializedEndpoint } = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.2.0-rc.20",
3
+ "version": "3.2.0-rc.21",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -140,6 +140,7 @@ export class AgentTools extends adapt("agentTools") implements AgentToolsAdaptor
140
140
  this.#document = new McpDocument(FetchSerializer.serializeRegistry(this.#props.live).signal, {
141
141
  resolveDescription: (key) => lookup.text(key),
142
142
  readOnly: this.#props.readOnly,
143
+ agent: true,
143
144
  excludeSignals: this.#props.excludeSignals,
144
145
  excludeEndpoints: this.#props.excludeEndpoints,
145
146
  });
@@ -16,6 +16,7 @@ import type { AgentLoopApproval, AgentLoopEvent, AgentLoopRequest, AgentLoopStop
16
16
  import { DeltaStream } from "./deltaStream";
17
17
  import { LoopCompaction } from "./loopCompaction";
18
18
  import { LoopRequest } from "./loopRequest";
19
+ import { LoopToolkits } from "./loopToolkits";
19
20
  import { LoopToolOutput } from "./loopToolOutput";
20
21
  import { LoopTranscript } from "./loopTranscript";
21
22
 
@@ -59,6 +60,8 @@ export class AgentLoop {
59
60
 
60
61
  readonly #wall = new DOMException("The run's wallMs ran out.", "AbortError");
61
62
  readonly #signal: AbortSignal;
63
+ readonly #toolkits: LoopToolkits;
64
+ #clientNames = new Set<string>();
62
65
  #account: unknown = null;
63
66
  #round = 0;
64
67
  #tokens = 0;
@@ -71,6 +74,7 @@ export class AgentLoop {
71
74
  this.#request = request;
72
75
  this.#messages = Array.isArray(request.messages) ? [...request.messages] : [];
73
76
  this.#signal = request.signal ? AbortSignal.any([request.signal, this.#halt.signal]) : this.#halt.signal;
77
+ this.#toolkits = new LoopToolkits(request.toolkits);
74
78
  }
75
79
 
76
80
  async *run(): Events<void> {
@@ -98,6 +102,7 @@ export class AgentLoop {
98
102
  }
99
103
 
100
104
  async *#drive(): Events<AgentLoopStop> {
105
+ this.#toolkits.restore(this.#messages);
101
106
  this.#tainted = LoopTranscript.markedTainted(this.#messages, !!this.#request.untrusted);
102
107
  for (const result of LoopTranscript.results(this.#messages)) this.#taintBy(result);
103
108
  const pending = LoopTranscript.pending(this.#messages);
@@ -144,7 +149,27 @@ export class AgentLoop {
144
149
  }
145
150
 
146
151
  async #listTools() {
147
- return await this.#port.tools.listAs(this.#account, { allow: this.#request.allow });
152
+ const visible = await this.#port.tools.listAs(this.#account, { allow: this.#request.allow });
153
+ const listed = this.#toolkits.listed(visible);
154
+ const taken = new Set(visible.map((tool) => tool.name));
155
+
156
+ const client = (this.#request.clientTools ?? []).filter((tool) => {
157
+ if (taken.has(tool.name) || this.#toolkits.isMeta(tool.name)) return false;
158
+ taken.add(tool.name);
159
+ return true;
160
+ });
161
+ this.#clientNames = new Set(client.map((tool) => tool.name));
162
+ return [...listed, ...client.map(AgentLoop.#clientTool)];
163
+ }
164
+
165
+ static #clientTool({ name, description, parameters, readOnly, needsConfirm }: AgentTool): AgentTool {
166
+ return {
167
+ name,
168
+ ...(description ? { description } : {}),
169
+ ...(parameters ? { parameters } : {}),
170
+ readOnly: readOnly === true,
171
+ needsConfirm: needsConfirm === true,
172
+ };
148
173
  }
149
174
 
150
175
  async *#ask(tools: AgentTool[]): Events<AgentLoopAnswer> {
@@ -215,7 +240,11 @@ export class AgentLoop {
215
240
  return;
216
241
  }
217
242
  if (!text) return;
218
- const summary = LoopCompaction.message(text, this.#tainted || untrusted ? this.#tainted : undefined);
243
+ const summary = LoopCompaction.message(
244
+ text,
245
+ this.#tainted || untrusted ? this.#tainted : undefined,
246
+ this.#toolkits.opened,
247
+ );
219
248
  this.#messages.splice(0, at, summary);
220
249
  const after = LoopCompaction.tokensOf(this.#messages);
221
250
 
@@ -240,13 +269,21 @@ export class AgentLoop {
240
269
  try {
241
270
  for (const [at, call] of calls.entries()) {
242
271
  const verdict = verdicts[at] ?? { deny: AgentLoop.unjudged };
243
- stop = this.#haltStop() ?? (verdict === "allow" ? this.#callBudgetStop() : null);
272
+ const meta = this.#toolkits.isMeta(call.name);
273
+ stop = this.#haltStop() ?? (verdict === "allow" && !meta ? this.#callBudgetStop() : null);
244
274
  if (stop) break;
245
- const whole = await this.#execute(call, verdict);
275
+
276
+ if (verdict === "allow" && this.#clientNames.has(call.name)) {
277
+ this.#toolCalls += 1;
278
+ yield { type: "awaiting", call, client: true };
279
+ stop = "awaiting";
280
+ break;
281
+ }
282
+ const whole = meta ? this.#toolkits.open(call) : await this.#execute(call, verdict);
246
283
  const result = LoopToolOutput.clipped(whole);
247
284
  results.push(result);
248
285
 
249
- this.#taintBy(whole);
286
+ if (!meta) this.#taintBy(whole);
250
287
  yield { type: "toolResult", result, round };
251
288
  }
252
289
  } finally {
@@ -258,8 +295,14 @@ export class AgentLoop {
258
295
  }
259
296
 
260
297
  async #verdictOf(call: AgentWireToolCall, tool: AgentTool | undefined): Promise<Verdict> {
298
+ if (this.#toolkits.isMeta(call.name)) return "allow";
261
299
 
262
- if (!tool) return { deny: `Unknown tool: ${call.name}.`, code: "unknownTool" };
300
+ if (!tool) {
301
+ const closed = this.#toolkits.refusalOf(call.name);
302
+ return closed
303
+ ? { deny: closed, code: "toolkitClosed" }
304
+ : { deny: `Unknown tool: ${call.name}.`, code: "unknownTool" };
305
+ }
263
306
  const { approve } = this.#request;
264
307
  if (approve) return AgentLoop.#judged(await this.#untilHalted(approve(call, { tainted: this.#tainted, tool })));
265
308
  if (tool.needsConfirm) return { deny: AgentLoop.needsPerson };
@@ -16,6 +16,12 @@ export type AgentLoopApprove = (
16
16
  state: { tainted: boolean; tool: AgentTool },
17
17
  ) => PromiseOrObject<AgentLoopApproval>;
18
18
 
19
+ /** `description` is the one line the model reads, in `openToolkit`'s own description, to decide whether to open it. */
20
+ export interface AgentLoopToolkit {
21
+ description: string;
22
+ tools: readonly string[];
23
+ }
24
+
19
25
  export interface AgentLoopBudget {
20
26
  /** Input and output tokens summed over this run's model calls, compactions included. */
21
27
  tokens?: number;
@@ -28,7 +34,10 @@ export interface AgentLoopBudget {
28
34
  wallMs?: number;
29
35
  }
30
36
 
31
- /** `awaiting`: `approve` deferred a call; resume with the messages `onMessage` stored and it is asked again. */
37
+ /**
38
+ * `awaiting`: `approve` deferred a call, and a resume with the messages `onMessage` stored asks it again; or a client
39
+ * tool was called, and a resume with its result appended runs on from it.
40
+ */
32
41
  export type AgentLoopStop =
33
42
  | "end"
34
43
  | "maxRounds"
@@ -40,7 +49,7 @@ export type AgentLoopStop =
40
49
  | "awaiting";
41
50
 
42
51
  export interface AgentLoopOptions {
43
- /** Tool names; the run sees only those the account may also see on `/mcp`. */
52
+ /** Tool names; the run sees only those `AgentToolsRole` lists to the account: `/mcp`'s, plus `mcp: "agent"` ones. */
44
53
  allow: readonly string[];
45
54
  /** The transcript so far, ending in a user message for a new ask or in unanswered calls for a resumed run. */
46
55
  messages: AgentWireMessage[];
@@ -52,6 +61,19 @@ export interface AgentLoopOptions {
52
61
  model?: string;
53
62
  maxRounds?: number;
54
63
  budget?: AgentLoopBudget;
64
+ /**
65
+ * Named groups of `allow` the model adds with `openToolkit({ name })`, a tool this run lists beside them; a tool in no
66
+ * toolkit is listed every round. An opened toolkit's tools are listed from the next round on, `allow` still capping
67
+ * them, and stay open across a resume and a compaction. `openToolkit` is never asked about and counts as no tool call.
68
+ */
69
+ toolkits?: Record<string, AgentLoopToolkit>;
70
+ /**
71
+ * The tools of a screen a connected browser has open (`AgentClientTools.list()` in `akanjs/ui`): client input,
72
+ * listed beside the endpoint tools and never run here. `approve` is still asked. An allowed call ends the run as
73
+ * `awaiting` with `client: true`; append the browser's result, or an error when no page answers, and resume. A name
74
+ * an endpoint tool or `openToolkit` holds is dropped.
75
+ */
76
+ clientTools?: AgentTool[];
55
77
  /** Summarizes all but the last `keep` messages (6) once the transcript is estimated at `at` tokens. */
56
78
  compact?: { at: number; keep?: number };
57
79
  /** Asked before every call; without it a `needsConfirm` tool is refused, and so is any write once tainted. */
@@ -85,6 +107,6 @@ export type AgentLoopEvent =
85
107
  * whole: its `tainted` carries the run's taint across a resume.
86
108
  */
87
109
  | { type: "compacted"; replaced: number; summary: AgentWireMessage }
88
- | { type: "awaiting"; call: AgentWireToolCall }
110
+ | { type: "awaiting"; call: AgentWireToolCall; client?: true }
89
111
  | { type: "done"; stop: AgentLoopStop; rounds: number }
90
112
  | { type: "error"; message: string; error: unknown };
@@ -97,8 +97,14 @@ export class LoopCompaction {
97
97
  return [...head, `[... ${high - low + 1} messages omitted ...]`, ...tail].join("\n");
98
98
  }
99
99
 
100
- static message(summary: string, tainted?: boolean): AgentWireMessage {
101
- return { role: "user", text: summary, summary: true, ...(tainted === undefined ? {} : { tainted }) };
100
+ static message(summary: string, tainted?: boolean, toolkits: string[] = []): AgentWireMessage {
101
+ return {
102
+ role: "user",
103
+ text: summary,
104
+ summary: true,
105
+ ...(tainted === undefined ? {} : { tainted }),
106
+ ...(toolkits.length ? { toolkits } : {}),
107
+ };
102
108
  }
103
109
 
104
110
  static #line(message: AgentWireMessage): string {
@@ -1,14 +1,17 @@
1
1
  import { Err } from "akanjs/dictionary";
2
2
  import type { AgentLoopRequest } from "./agentLoopTypes";
3
+ import { LoopToolkits } from "./loopToolkits";
3
4
 
4
5
  export class LoopRequest {
5
6
 
6
7
  static readonly maxWallMs = 2 ** 31 - 1;
7
8
 
8
- static assertValid({ allow, messages, maxRounds, budget, compact }: AgentLoopRequest) {
9
+ static assertValid({ allow, messages, maxRounds, budget, compact, toolkits, clientTools }: AgentLoopRequest) {
9
10
 
10
11
  if (!Array.isArray(allow)) LoopRequest.#refuse("allow");
11
12
  if (!Array.isArray(messages)) LoopRequest.#refuse("messages");
13
+ LoopRequest.#assertToolkits(toolkits, allow);
14
+ LoopRequest.#assertClientTools(clientTools);
12
15
  LoopRequest.#assertCount("maxRounds", maxRounds);
13
16
  LoopRequest.#assertCount("compact.at", compact?.at);
14
17
  LoopRequest.#assertCount("compact.keep", compact?.keep);
@@ -19,6 +22,36 @@ export class LoopRequest {
19
22
  LoopRequest.#refuse("budget.wallMs");
20
23
  }
21
24
 
25
+ static #assertToolkits(toolkits: AgentLoopRequest["toolkits"], allow: readonly string[]) {
26
+ if (toolkits === undefined) return;
27
+ if (typeof toolkits !== "object" || Array.isArray(toolkits)) LoopRequest.#refuse("toolkits");
28
+ for (const [name, kit] of Object.entries(toolkits)) {
29
+ const tools = (kit as { tools?: unknown } | null)?.tools;
30
+ const valid =
31
+ !!name &&
32
+ typeof kit?.description === "string" &&
33
+ Array.isArray(tools) &&
34
+ tools.every((tool) => typeof tool === "string");
35
+ if (!valid) LoopRequest.#refuse(`toolkits.${name}`);
36
+ }
37
+
38
+ if (allow.includes(LoopToolkits.toolName)) LoopRequest.#refuse("allow");
39
+ }
40
+
41
+ static #assertClientTools(clientTools: AgentLoopRequest["clientTools"]) {
42
+ if (clientTools === undefined) return;
43
+ if (!Array.isArray(clientTools)) LoopRequest.#refuse("clientTools");
44
+ for (const tool of clientTools as unknown[]) {
45
+ const { name, description, parameters } = (tool ?? {}) as Record<string, unknown>;
46
+ const valid =
47
+ typeof name === "string" &&
48
+ !!name &&
49
+ (description === undefined || typeof description === "string") &&
50
+ (parameters === undefined || (typeof parameters === "object" && parameters !== null));
51
+ if (!valid) LoopRequest.#refuse("clientTools");
52
+ }
53
+ }
54
+
22
55
  static #assertCount(name: string, value: number | undefined) {
23
56
  if (value !== undefined && !(Number.isSafeInteger(value) && value >= 0)) LoopRequest.#refuse(name);
24
57
  }
@@ -0,0 +1,107 @@
1
+ import type { AgentTool } from "../predefinedAdaptor/agentTools.adaptor";
2
+ import type { AgentWireMessage, AgentWireToolCall, AgentWireToolResult } from "../predefinedAdaptor/llm.adaptor";
3
+ import type { AgentLoopToolkit } from "./agentLoopTypes";
4
+ import { LoopTranscript } from "./loopTranscript";
5
+
6
+ export class LoopToolkits {
7
+ static readonly toolName = "openToolkit";
8
+
9
+ readonly #kits: ReadonlyMap<string, AgentLoopToolkit>;
10
+ readonly #open = new Set<string>();
11
+ #visible: AgentTool[] = [];
12
+
13
+ constructor(kits: Record<string, AgentLoopToolkit> | undefined) {
14
+ this.#kits = new Map(Object.entries(kits ?? {}));
15
+ }
16
+
17
+ get opened(): string[] {
18
+ return [...this.#open];
19
+ }
20
+
21
+ isMeta(name: string): boolean {
22
+ return this.#kits.size > 0 && name === LoopToolkits.toolName;
23
+ }
24
+
25
+ listed(visible: AgentTool[]): AgentTool[] {
26
+ this.#visible = visible;
27
+ if (!this.#kits.size) return visible;
28
+ const shown = visible.filter((tool) => this.#isOn(tool.name));
29
+ const closed = this.#closed();
30
+ return closed.length ? [...shown, this.#metaTool(closed)] : shown;
31
+ }
32
+
33
+ refusalOf(name: string): string | null {
34
+ if (!this.#kits.size || !this.#visible.some((tool) => tool.name === name)) return null;
35
+ const kit = [...this.#kits].find(([kitName, { tools }]) => !this.#open.has(kitName) && tools.includes(name))?.[0];
36
+ if (!kit) return null;
37
+ return `Not run: ${name} is in the "${kit}" toolkit, which was not open when this call was written. Open it with ${LoopToolkits.toolName}, then call ${name} again.`;
38
+ }
39
+
40
+ open({ id, name, args }: AgentWireToolCall): AgentWireToolResult {
41
+ const kit = typeof args.name === "string" ? args.name : "";
42
+ const tools = this.#toolsOf(kit);
43
+ if (!tools.length) {
44
+ const known = this.#closed().join(", ");
45
+ return {
46
+ id,
47
+ name,
48
+ error: `No toolkit named "${kit}".${known ? ` Open one of: ${known}.` : " Every toolkit is already open."}`,
49
+ code: "unknownToolkit",
50
+ };
51
+ }
52
+ this.#open.add(kit);
53
+ return { id, name, result: { opened: kit, tools } };
54
+ }
55
+
56
+ #isOn(name: string): boolean {
57
+ let inKit = false;
58
+ for (const [kitName, { tools }] of this.#kits) {
59
+ if (!tools.includes(name)) continue;
60
+ if (this.#open.has(kitName)) return true;
61
+ inKit = true;
62
+ }
63
+ return !inKit;
64
+ }
65
+
66
+ #toolsOf(kit: string): string[] {
67
+ const tools = this.#kits.get(kit)?.tools ?? [];
68
+ return this.#visible.filter((tool) => tools.includes(tool.name)).map((tool) => tool.name);
69
+ }
70
+
71
+ #closed(): string[] {
72
+ return [...this.#kits.keys()].filter((kit) => !this.#open.has(kit) && this.#toolsOf(kit).length);
73
+ }
74
+
75
+ #metaTool(closed: string[]): AgentTool {
76
+ const lines = closed.map((kit) => `- ${kit}: ${this.#kits.get(kit)?.description ?? ""}`.trimEnd());
77
+ return {
78
+ name: LoopToolkits.toolName,
79
+ description: [
80
+ "Adds a toolkit's tools to the ones listed to you, from your next step on. Open a toolkit only when the request needs its tools.",
81
+ "Toolkits:",
82
+ ...lines,
83
+ ].join("\n"),
84
+ parameters: {
85
+ type: "object",
86
+ properties: { name: { type: "string", enum: closed } },
87
+ required: ["name"],
88
+ additionalProperties: false,
89
+ },
90
+ readOnly: true,
91
+ };
92
+ }
93
+
94
+ restore(messages: readonly AgentWireMessage[]) {
95
+ if (!this.#kits.size) return;
96
+ const answered = new Map(LoopTranscript.results(messages).map((result) => [result.id, result]));
97
+ for (const message of messages) {
98
+ for (const kit of message.summary ? (message.toolkits ?? []) : []) if (this.#kits.has(kit)) this.#open.add(kit);
99
+ for (const call of message.toolCalls ?? []) {
100
+ if (call.name !== LoopToolkits.toolName) continue;
101
+ const result = answered.get(call.id);
102
+ const kit = call.args.name;
103
+ if (result && !result.error && typeof kit === "string" && this.#kits.has(kit)) this.#open.add(kit);
104
+ }
105
+ }
106
+ }
107
+ }
@@ -19,8 +19,9 @@ export interface AgentTool extends AgentWireTool {
19
19
 
20
20
  /**
21
21
  * The `/mcp` tool catalogue run in-process as a given account, with the same refusals, masking and error text and
22
- * `origin` "mcp". Built from the DI registry, so a batch server without `/mcp` has it too. Covers the endpoint tools
23
- * only: a page's `page().app()` tool is listed on `/mcp` but absent here, and `callAs` answers it as an unknown tool.
22
+ * `origin` "mcp", plus every endpoint declared `mcp: "agent"`, which `/mcp` never lists. Built from the DI registry,
23
+ * so a batch server without `/mcp` has it too. Covers the endpoint tools only: a page's `page().app()` tool is listed
24
+ * on `/mcp` but absent here, and `callAs` answers it as an unknown tool.
24
25
  * Security: `account` is put on the call after the middleware chain, unchecked — pass one the server resolved, never
25
26
  * client input, and resolve a stored one again before reusing it, as a revoked session is not noticed here. Its
26
27
  * `machine` field is removed, since only a verified machine token may set one. Both methods throw `InjectError`
@@ -58,6 +58,8 @@ export interface AgentWireMessage {
58
58
  * Absent on a summary, nothing judged what it replaced, so a resumed run with `untrusted` counts it as tainted.
59
59
  */
60
60
  tainted?: boolean;
61
+ /** On a summary `agentService.loop` wrote: the toolkits its run had opened, which the messages it replaced recorded. */
62
+ toolkits?: string[];
61
63
  }
62
64
 
63
65
  export interface AgentWireTool {
package/signal/index.ts CHANGED
@@ -282,6 +282,7 @@ export {
282
282
  type SerializedReturns,
283
283
  type SerializedSignal,
284
284
  type SerializedSignalMcp,
285
+ type SerializedSignalShelf,
285
286
  type SerializedSlice,
286
287
  type SignalOption,
287
288
  type SignalType,
@@ -25,6 +25,8 @@ export interface McpDocumentOptions {
25
25
  * refusal still holds.
26
26
  */
27
27
  apps?: boolean;
28
+ /** The in-process agent's catalogue (`AgentToolsRole`), which also lists an endpoint declared `mcp: "agent"`. */
29
+ agent?: boolean;
28
30
  }
29
31
 
30
32
  export type McpOutputSchemaMode = "full" | "shallow" | "none";
@@ -154,7 +156,12 @@ export class McpDocument {
154
156
  this.#catalogue.refuse(key, excluded);
155
157
  continue;
156
158
  }
157
- const reason = mcpRefusalOf(endpoint, { refName, key, readOnly: this.#options.readOnly });
159
+ const reason = mcpRefusalOf(endpoint, {
160
+ refName,
161
+ key,
162
+ readOnly: this.#options.readOnly,
163
+ agent: this.#options.agent,
164
+ });
158
165
  if (reason && this.#isAppOnly(item)) {
159
166
  appOnly.push({ ...item, reason });
160
167
  continue;
@@ -1,5 +1,5 @@
1
1
  import { type Cls, ENDPOINT_META, PrimitiveRegistry, type PrimitiveScalar, SLICE_META } from "akanjs/base";
2
- import { Logger } from "akanjs/common";
2
+ import { Logger, type McpShelf } from "akanjs/common";
3
3
  import { ConstantRegistry, type ConstantType } from "akanjs/constant";
4
4
  import { type FilterArgInfo, getFilterArgInfos, getFilterMeta } from "akanjs/document";
5
5
  import type { LiveRegistry } from "akanjs/service";
@@ -16,6 +16,7 @@ import type {
16
16
  SerializedReturns,
17
17
  SerializedSignal,
18
18
  SerializedSignalMcp,
19
+ SerializedSignalShelf,
19
20
  SerializedSlice,
20
21
  } from "../types";
21
22
 
@@ -74,7 +75,7 @@ export class FetchSerializer {
74
75
  ...(endpointInfo.signalOption.timeout ? { timeout: endpointInfo.signalOption.timeout } : {}),
75
76
  ...(endpointInfo.signalOption.errors ? { errors: endpointInfo.signalOption.errors } : {}),
76
77
  ...(guards?.length ? { guards } : {}),
77
- ...(endpointInfo.signalOption.mcp === false ? { mcp: false as const } : {}),
78
+ ...FetchSerializer.#shelfOf(endpointInfo.signalOption.mcp),
78
79
  ...(refusesAgents(endpointInfo.signalOption.guards) ? { agents: false as const } : {}),
79
80
  ...(endpointInfo.signalOption.destructive !== undefined
80
81
  ? { destructive: endpointInfo.signalOption.destructive }
@@ -113,7 +114,7 @@ export class FetchSerializer {
113
114
  args: sliceInfo.args.map(FetchSerializer.#serializeArg),
114
115
  ...(sliceInfo.signalOption.path ? { path: sliceInfo.signalOption.path } : {}),
115
116
  ...(guards?.length ? { guards } : {}),
116
- ...(sliceInfo.signalOption.mcp === false ? { mcp: false as const } : {}),
117
+ ...FetchSerializer.#shelfOf(sliceInfo.signalOption.mcp),
117
118
  ...(refusesAgents(sliceInfo.signalOption.guards) ? { agents: false as const } : {}),
118
119
  ...(sliceInfo.liveOption
119
120
  ? {
@@ -189,11 +190,17 @@ export class FetchSerializer {
189
190
  return Object.keys(agents).length ? { agents } : {};
190
191
  }
191
192
 
192
- static #serializeSliceMcp(sliceCls: SliceCls): { mcp?: SerializedSignalMcp } {
193
- const mcp = FetchSerializer.#offVerbs(sliceCls.mcp);
193
+ static #serializeSliceMcp(sliceCls: SliceCls): { mcp?: SerializedSignalShelf } {
194
+ const mcp = Object.fromEntries(
195
+ Object.entries(sliceCls.mcp).filter(([, shelf]) => shelf !== true),
196
+ ) as SerializedSignalShelf;
194
197
  return Object.keys(mcp).length ? { mcp } : {};
195
198
  }
196
199
 
200
+ static #shelfOf(mcp: McpShelf | undefined): { mcp?: false | "agent" } {
201
+ return mcp === false || mcp === "agent" ? { mcp } : {};
202
+ }
203
+
197
204
  static #serializeSliceCrud(sliceCls: SliceCls): { crud?: SerializedSignalMcp } {
198
205
  const crud = FetchSerializer.#offVerbs(sliceCls.crud);
199
206
  return Object.keys(crud).length ? { crud } : {};