akanjs 3.2.0-rc.20 → 3.2.0-rc.22

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 (43) hide show
  1. package/CHANGELOG.md +36 -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/server/resolver/signal.resolver.ts +3 -39
  8. package/server/resolver/sliceCrud.ts +63 -0
  9. package/service/agentLoop/agentLoop.ts +49 -6
  10. package/service/agentLoop/agentLoopTypes.ts +25 -3
  11. package/service/agentLoop/loopCompaction.ts +8 -2
  12. package/service/agentLoop/loopRequest.ts +34 -1
  13. package/service/agentLoop/loopToolkits.ts +107 -0
  14. package/service/predefinedAdaptor/agentTools.adaptor.ts +3 -2
  15. package/service/predefinedAdaptor/llm.adaptor.ts +2 -0
  16. package/signal/index.ts +1 -0
  17. package/signal/mcp/McpDocument.ts +8 -1
  18. package/signal/serializer/fetch.serializer.ts +12 -5
  19. package/signal/slice.ts +22 -19
  20. package/signal/types.ts +17 -5
  21. package/types/common/index.d.ts +1 -1
  22. package/types/common/mcpExposure.d.ts +7 -2
  23. package/types/dictionary/base.dictionary.d.ts +1 -1
  24. package/types/dictionary/dictionary.d.ts +8 -8
  25. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  26. package/types/server/resolver/sliceCrud.d.ts +8 -0
  27. package/types/service/agentLoop/agentLoopTypes.d.ts +24 -2
  28. package/types/service/agentLoop/loopCompaction.d.ts +1 -1
  29. package/types/service/agentLoop/loopRequest.d.ts +1 -1
  30. package/types/service/agentLoop/loopToolkits.d.ts +14 -0
  31. package/types/service/predefinedAdaptor/agentTools.adaptor.d.ts +3 -2
  32. package/types/service/predefinedAdaptor/llm.adaptor.d.ts +2 -0
  33. package/types/signal/index.d.ts +1 -1
  34. package/types/signal/mcp/McpDocument.d.ts +2 -0
  35. package/types/signal/slice.d.ts +15 -13
  36. package/types/signal/types.d.ts +16 -5
  37. package/types/ui/index.d.ts +1 -1
  38. package/types/vendor/use-agentic/AgentClientTools.d.ts +19 -0
  39. package/types/vendor/use-agentic/index.d.ts +1 -0
  40. package/ui/index.ts +4 -0
  41. package/vendor/use-agentic/AgentClientTools.ts +33 -0
  42. package/vendor/use-agentic/CHANGELOG.md +16 -1
  43. 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 `mcp` (an endpoint's `signalOption.mcp`, `SliceCls.mcp`, a serialized endpoint's `mcp` or a serialized signal's `mcp` map) to decide whether an entry is on `/mcp` must test for listed, `(mcp ?? true) === true`. A check of `mcp !== false`, or a truthiness test, now lets `"agent"` through as listed. A workspace's copied `libs/shared` `AccountMiddleware` had exactly that check, which let an MCP client's OAuth token reach an `mcp: "agent"` endpoint over HTTP, so port its fix. 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.
@@ -219,6 +251,10 @@
219
251
  - **The `akan-service` skill** carries a recipe for pages backed by an external HTTP API: an `adapt()` adapter in `srvkit/` that reads its base URL at boot, a `lib/_<service>` service, a `Public` `query(Any, { nullable: true })` endpoint and its dictionary label, and the page that calls it.
220
252
  - **The README's "Inside an existing repository"** runs the creator through `npx -y bun@1.4.4 x …` on a host with only Node and npm, so nothing global is written. It also gives copy-ready `build` and `start` scripts, says a fresh clone builds without a committed env file, and says which environment a `.env`-less build is for and what a deployed host sets instead.
221
253
 
254
+ - cc59b93: A slice's per-verb `mcp` value now reaches the endpoints it generates. `mcp: { cru: false }` or `mcp: { get: "agent" }` used to be read only where `/mcp` builds its listing. Each generated `get`, `create`, `update` and `remove` endpoint now carries its own verb's value in its `signalOption.mcp`, as a slice's list already did. This lets server code that reads `signalOption.mcp`, such as `libs/shared`'s `AccountMiddleware`, refuse an MCP client's OAuth token there over HTTP as well.
255
+
256
+ `libs/shared`'s `AccountMiddleware` now refuses such a token at an `mcp: "agent"` endpoint, as it does at an `mcp: false` one. A workspace that copied `libs/shared` should port the one-line check in `srvkit/accountMiddleware.ts` (`(signalOption?.mcp ?? true) === true`).
257
+
222
258
  - 61fbd7d: `get_graph` takes `since`, a git revision, and returns the Change Map: the Akan Graph of what changed since HEAD forked from that revision, working tree and untracked files included. Every node, field and edge is marked `added`, `removed` or `changed`. The unchanged nodes a changed one calls, or is called by, stay in as context, and `unmapped` lists the changed files under `apps/` or `libs/` that no node covers, each marked the same way. `since: "HEAD"` maps uncommitted work only. Files `.gitignore` covers stay out, a renamed file reads as removed and added, and a CRLF checkout of an unchanged file reads as unchanged. A revision git does not know returns a `graph-since-unknown` diagnostic, and so does one HEAD shares no commit with (a shallow clone, say) instead of comparing with its tip. A revision that starts with `-` also returns it and never reaches git.
223
259
 
224
260
  - **`AkanGraphDiff.between(base, head)`** in `@akanjs/language` diffs two graphs. `index.graph(readText, { digests: true })` gives each member, query, component and field a hash of its body text, so an edit inside a method, or to a field's options, marks it changed and moving it does not.
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.22",
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
  });
@@ -14,7 +14,7 @@ import {
14
14
  type PromiseOrObject,
15
15
  SLICE_META,
16
16
  } from "akanjs/base";
17
- import { capitalize, Logger, modelNames, moduleNames, sliceNames } from "akanjs/common";
17
+ import { capitalize, Logger, moduleNames, sliceNames } from "akanjs/common";
18
18
  import {
19
19
  type ConstantField,
20
20
  deserialize,
@@ -34,7 +34,6 @@ import type {
34
34
  LiveRegistry,
35
35
  WebsocketAdaptor,
36
36
  } from "akanjs/service";
37
- import { ByIdRead } from "../../signal/byIdRead";
38
37
  import { type Endpoint, type EndpointCls, sliceEndpoint } from "../../signal/endpoint";
39
38
  import { EndpointErrorContract } from "../../signal/endpointErrorContract";
40
39
  import type { EndpointInfo } from "../../signal/endpointInfo";
@@ -60,6 +59,7 @@ import type { HttpRoutes, LocalPublish, SignalRoutes, WebsocketRoutes } from "..
60
59
  import { invalidSignal as invalid } from "./invalidSignal";
61
60
  import { LivePause } from "./livePause";
62
61
  import { PendingSubscribes } from "./PendingSubscribes";
62
+ import { SliceCrud } from "./sliceCrud";
63
63
  import { websocketOf } from "./websocketOf";
64
64
 
65
65
  type LiveChangeListener = (doc: unknown, type: unknown, previous?: unknown) => void;
@@ -391,7 +391,6 @@ export class SignalResolver {
391
391
  if (!cnst) throw invalid("Constant is not set for slice");
392
392
  const refName = cnst.refName;
393
393
  const serviceName = moduleNames(refName).service;
394
- const names = modelNames(refName);
395
394
 
396
395
  const assertSliceQuery = (query: unknown, key: string) => {
397
396
  if (Array.isArray(query))
@@ -489,42 +488,7 @@ export class SignalResolver {
489
488
  });
490
489
  });
491
490
 
492
- if (sliceCls.crud.get)
493
- for (const key of [names.model, names.lightModel])
494
- endpointObj[key] = ByIdRead.mark(
495
- refName,
496
- (builder as any)
497
- .query(key === names.model ? cnst.full : cnst.light, { guards: sliceCls.getGuards })
498
- .param(names.modelId, ID)
499
- .exec(async function (this: any, id: string) {
500
- return await this[serviceName][names.getModel](id);
501
- }),
502
- );
503
-
504
- if (sliceCls.crud.create)
505
- endpointObj[names.createModel] = (builder as any)
506
- .mutation(cnst.full, { guards: sliceCls.createGuards })
507
- .body("data", cnst.input)
508
- .exec(async function (this: any, data: any) {
509
- return await this[serviceName].__create(data);
510
- });
511
-
512
- if (sliceCls.crud.update)
513
- endpointObj[names.updateModel] = (builder as any)
514
- .mutation(cnst.full, { guards: sliceCls.updateGuards })
515
- .param(names.modelId, ID)
516
- .body("data", cnst.input)
517
- .exec(async function (this: any, id: string, data: any) {
518
- return await this[serviceName].__update(id, data);
519
- });
520
-
521
- if (sliceCls.crud.remove)
522
- endpointObj[names.removeModel] = (builder as any)
523
- .mutation(cnst.full, { guards: sliceCls.removeGuards })
524
- .param(names.modelId, ID)
525
- .exec(async function (this: any, id: string) {
526
- return await this[serviceName].__remove(id);
527
- });
491
+ Object.assign(endpointObj, SliceCrud.endpoints(builder, sliceCls, cnst));
528
492
  return endpointObj;
529
493
  }) {}
530
494
  return SliceEndpoint;
@@ -0,0 +1,63 @@
1
+ import { ID } from "akanjs/base";
2
+ import { type McpShelf, modelNames, moduleNames } from "akanjs/common";
3
+ import { ByIdRead } from "../../signal/byIdRead";
4
+ import type { EndpointInfo } from "../../signal/endpointInfo";
5
+ import type { SliceCls } from "../../signal/slice";
6
+
7
+ export class SliceCrud {
8
+
9
+ static #shelf(mcp: McpShelf) {
10
+ return mcp === true ? {} : { mcp };
11
+ }
12
+
13
+ static endpoints(
14
+ builder: unknown,
15
+ sliceCls: SliceCls,
16
+ cnst: NonNullable<SliceCls["srv"]["cnst"]>,
17
+ ): { [key: string]: EndpointInfo } {
18
+ const refName = cnst.refName;
19
+ const serviceName = moduleNames(refName).service;
20
+ const names = modelNames(refName);
21
+ const endpointObj: { [key: string]: EndpointInfo } = {};
22
+ if (sliceCls.crud.get)
23
+ for (const key of [names.model, names.lightModel])
24
+ endpointObj[key] = ByIdRead.mark(
25
+ refName,
26
+ (builder as any)
27
+ .query(key === names.model ? cnst.full : cnst.light, {
28
+ guards: sliceCls.getGuards,
29
+ ...SliceCrud.#shelf(sliceCls.mcp.get),
30
+ })
31
+ .param(names.modelId, ID)
32
+ .exec(async function (this: any, id: string) {
33
+ return await this[serviceName][names.getModel](id);
34
+ }),
35
+ );
36
+
37
+ if (sliceCls.crud.create)
38
+ endpointObj[names.createModel] = (builder as any)
39
+ .mutation(cnst.full, { guards: sliceCls.createGuards, ...SliceCrud.#shelf(sliceCls.mcp.create) })
40
+ .body("data", cnst.input)
41
+ .exec(async function (this: any, data: any) {
42
+ return await this[serviceName].__create(data);
43
+ });
44
+
45
+ if (sliceCls.crud.update)
46
+ endpointObj[names.updateModel] = (builder as any)
47
+ .mutation(cnst.full, { guards: sliceCls.updateGuards, ...SliceCrud.#shelf(sliceCls.mcp.update) })
48
+ .param(names.modelId, ID)
49
+ .body("data", cnst.input)
50
+ .exec(async function (this: any, id: string, data: any) {
51
+ return await this[serviceName].__update(id, data);
52
+ });
53
+
54
+ if (sliceCls.crud.remove)
55
+ endpointObj[names.removeModel] = (builder as any)
56
+ .mutation(cnst.full, { guards: sliceCls.removeGuards, ...SliceCrud.#shelf(sliceCls.mcp.remove) })
57
+ .param(names.modelId, ID)
58
+ .exec(async function (this: any, id: string) {
59
+ return await this[serviceName].__remove(id);
60
+ });
61
+ return endpointObj;
62
+ }
63
+ }
@@ -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
+ }