akanjs 3.2.0-rc.21 → 3.2.0-rc.23
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.
- package/CHANGELOG.md +34 -1
- package/package.json +1 -1
- package/server/resolver/signal.resolver.ts +3 -39
- package/server/resolver/sliceCrud.ts +63 -0
- package/service/agentLoop/agentLoop.ts +18 -6
- package/service/agentLoop/agentLoopTypes.ts +9 -2
- package/service/agentLoop/loopAsk.ts +44 -0
- package/service/agentLoop/loopRequest.ts +4 -1
- package/types/server/logging/rotatingLogWriter.d.ts +1 -1
- package/types/server/resolver/sliceCrud.d.ts +8 -0
- package/types/service/agentLoop/agentLoopTypes.d.ts +9 -1
- package/types/service/agentLoop/loopAsk.d.ts +12 -0
- package/types/service/agentLoop/loopRequest.d.ts +1 -1
- package/types/ui/Agent/ToolRow.d.ts +13 -0
- package/types/ui/UiOverride/UiOverride.d.ts +2 -0
- package/types/ui/index.d.ts +1 -0
- package/types/vendor/use-agentic/SessionQuestion.d.ts +26 -0
- package/types/vendor/use-agentic/Transcript.d.ts +1 -1
- package/ui/Agent/Bubble.tsx +4 -118
- package/ui/Agent/ToolRow.tsx +117 -0
- package/ui/UiOverride/UiOverride.tsx +2 -0
- package/ui/index.ts +1 -0
- package/vendor/use-agentic/AgentSession.ts +18 -54
- package/vendor/use-agentic/CHANGELOG.md +10 -0
- package/vendor/use-agentic/SessionQuestion.ts +99 -0
- package/vendor/use-agentic/Transcript.ts +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -21,6 +21,17 @@
|
|
|
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
|
+
- 4538737: `agentService.loop` can now ask the member a question and wait for the answer between runs, the way the in-page chat's `askUser` does.
|
|
25
|
+
|
|
26
|
+
- `ask: true` lists `askUser({ question, choices?, multiple? })`, with the in-page chat's own description and parameters.
|
|
27
|
+
- A call ends the run as `awaiting`, with `question: true` on the event. Calls written before it in the same batch have already run; calls written after it wait for the resume.
|
|
28
|
+
- Put the question to the member over your own transport. Append `{ id, name: "askUser", result }`, or an `error` when they dismiss it, and resume. A resume without the answer parks the call again. A resume without `ask` answers it as an unknown tool.
|
|
29
|
+
- `askUser` never reaches `approve` and counts as no tool call. `untrusted` never sees the answer, which is the member's own input.
|
|
30
|
+
- A call with no question is answered with an error and the run goes on.
|
|
31
|
+
- With `ask: true`, a `clientTools` entry named `askUser` is dropped, and an `allow` naming `askUser` is refused as an invalid argument.
|
|
32
|
+
|
|
33
|
+
The option is new and off by default, so no upgrade step is needed.
|
|
34
|
+
|
|
24
35
|
- 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
36
|
|
|
26
37
|
- **Server.** `clientTools` takes the definitions the open page sent over the app's own transport. They are listed beside the endpoint tools.
|
|
@@ -80,7 +91,15 @@
|
|
|
80
91
|
- **MCP Apps.** A rendered view may still call an `mcp: "agent"` entry, as it may call an `mcp: false` one.
|
|
81
92
|
- **Types.** `McpShelf` (`boolean | "agent"`) and `narrowestMcpShelf` are new in `akanjs/common`. `SerializedSignalShelf` is new in `akanjs/signal`. `McpDocumentOptions` and `McpExposureOption` gain `agent`.
|
|
82
93
|
|
|
83
|
-
Upgrade: code that reads `SliceCls.mcp`, a serialized endpoint's `mcp` or a serialized signal's `mcp` map
|
|
94
|
+
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.
|
|
95
|
+
|
|
96
|
+
- 278f8e4: The row a chat message draws for each tool call is now its own override slot, `AgentToolRow`, so an app can re-skin a tool call without replacing the whole `AgentBubble`.
|
|
97
|
+
|
|
98
|
+
- A component bound to `AgentToolRow` in `_overrides.tsx` gets `{ className?, name, args?, result?, progress? }`. `result` is absent while the call runs. `progress` is what a running call last reported about itself.
|
|
99
|
+
- The slot draws the calls in an assistant message and the results in a tool message. An `askUser` call is still drawn as its question.
|
|
100
|
+
- `DefaultToolRow` and `ToolRowProps` are exported from `akanjs/ui`, so a replacement can wrap the default.
|
|
101
|
+
|
|
102
|
+
The default row is unchanged, so no upgrade step is needed.
|
|
84
103
|
|
|
85
104
|
- eb88032: A service can now run the `/mcp` tool catalogue in-process, as a given account, with `plug(AgentToolsRole)`.
|
|
86
105
|
|
|
@@ -251,6 +270,20 @@
|
|
|
251
270
|
- **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.
|
|
252
271
|
- **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.
|
|
253
272
|
|
|
273
|
+
- f5d1e63: A restored chat transcript that ends on an unanswered `askUser` call now opens on that question instead of closing it. This covers a server run that parked on a question while no chat was open, and a page reloaded mid-question.
|
|
274
|
+
|
|
275
|
+
- The session's `pendingQuestion` holds the question, so `Agent.Chat` draws its card and the composer answers it as usual.
|
|
276
|
+
- Answering or dismissing it appends the `askUser` result (or the dismissal's error) and runs a turn through the runner, which carries the answer back to wherever the question came from.
|
|
277
|
+
- A turn started first, `reset()` and `compact()` take the question down. The call is then closed as unanswered on the wire, as before.
|
|
278
|
+
- Only the first unanswered call of the last batch reopens, and only when it asks something. Calls after it are closed as unanswered when the transcript is restored.
|
|
279
|
+
- `Transcript.sanitize(messages, openCallId?)` takes the id of one call to leave unanswered.
|
|
280
|
+
|
|
281
|
+
Before this, a reload in the middle of a question closed the call as stopped. It now asks again, so no upgrade step is needed.
|
|
282
|
+
|
|
283
|
+
- 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.
|
|
284
|
+
|
|
285
|
+
`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`).
|
|
286
|
+
|
|
254
287
|
- 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.
|
|
255
288
|
|
|
256
289
|
- **`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/package.json
CHANGED
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
type PromiseOrObject,
|
|
15
15
|
SLICE_META,
|
|
16
16
|
} from "akanjs/base";
|
|
17
|
-
import { capitalize, Logger,
|
|
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
|
-
|
|
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
|
+
}
|
|
@@ -14,6 +14,7 @@ import type {
|
|
|
14
14
|
} from "../predefinedAdaptor/llm.adaptor";
|
|
15
15
|
import type { AgentLoopApproval, AgentLoopEvent, AgentLoopRequest, AgentLoopStop } from "./agentLoopTypes";
|
|
16
16
|
import { DeltaStream } from "./deltaStream";
|
|
17
|
+
import { LoopAsk } from "./loopAsk";
|
|
17
18
|
import { LoopCompaction } from "./loopCompaction";
|
|
18
19
|
import { LoopRequest } from "./loopRequest";
|
|
19
20
|
import { LoopToolkits } from "./loopToolkits";
|
|
@@ -61,6 +62,7 @@ export class AgentLoop {
|
|
|
61
62
|
readonly #wall = new DOMException("The run's wallMs ran out.", "AbortError");
|
|
62
63
|
readonly #signal: AbortSignal;
|
|
63
64
|
readonly #toolkits: LoopToolkits;
|
|
65
|
+
readonly #askUser: LoopAsk;
|
|
64
66
|
#clientNames = new Set<string>();
|
|
65
67
|
#account: unknown = null;
|
|
66
68
|
#round = 0;
|
|
@@ -75,6 +77,7 @@ export class AgentLoop {
|
|
|
75
77
|
this.#messages = Array.isArray(request.messages) ? [...request.messages] : [];
|
|
76
78
|
this.#signal = request.signal ? AbortSignal.any([request.signal, this.#halt.signal]) : this.#halt.signal;
|
|
77
79
|
this.#toolkits = new LoopToolkits(request.toolkits);
|
|
80
|
+
this.#askUser = new LoopAsk(request.ask);
|
|
78
81
|
}
|
|
79
82
|
|
|
80
83
|
async *run(): Events<void> {
|
|
@@ -104,7 +107,9 @@ export class AgentLoop {
|
|
|
104
107
|
async *#drive(): Events<AgentLoopStop> {
|
|
105
108
|
this.#toolkits.restore(this.#messages);
|
|
106
109
|
this.#tainted = LoopTranscript.markedTainted(this.#messages, !!this.#request.untrusted);
|
|
107
|
-
|
|
110
|
+
|
|
111
|
+
for (const result of LoopTranscript.results(this.#messages))
|
|
112
|
+
if (!this.#askUser.isMeta(result.name)) this.#taintBy(result);
|
|
108
113
|
const pending = LoopTranscript.pending(this.#messages);
|
|
109
114
|
if (pending.length) {
|
|
110
115
|
if (!(await this.#authorize())) return "unauthorized";
|
|
@@ -154,12 +159,12 @@ export class AgentLoop {
|
|
|
154
159
|
const taken = new Set(visible.map((tool) => tool.name));
|
|
155
160
|
|
|
156
161
|
const client = (this.#request.clientTools ?? []).filter((tool) => {
|
|
157
|
-
if (taken.has(tool.name) || this.#toolkits.isMeta(tool.name)) return false;
|
|
162
|
+
if (taken.has(tool.name) || this.#toolkits.isMeta(tool.name) || this.#askUser.isMeta(tool.name)) return false;
|
|
158
163
|
taken.add(tool.name);
|
|
159
164
|
return true;
|
|
160
165
|
});
|
|
161
166
|
this.#clientNames = new Set(client.map((tool) => tool.name));
|
|
162
|
-
return [...listed, ...client.map(AgentLoop.#clientTool)];
|
|
167
|
+
return [...listed, ...client.map(AgentLoop.#clientTool), ...this.#askUser.listed()];
|
|
163
168
|
}
|
|
164
169
|
|
|
165
170
|
static #clientTool({ name, description, parameters, readOnly, needsConfirm }: AgentTool): AgentTool {
|
|
@@ -269,17 +274,24 @@ export class AgentLoop {
|
|
|
269
274
|
try {
|
|
270
275
|
for (const [at, call] of calls.entries()) {
|
|
271
276
|
const verdict = verdicts[at] ?? { deny: AgentLoop.unjudged };
|
|
272
|
-
const
|
|
277
|
+
const asked = this.#askUser.isMeta(call.name);
|
|
278
|
+
const meta = asked || this.#toolkits.isMeta(call.name);
|
|
273
279
|
stop = this.#haltStop() ?? (verdict === "allow" && !meta ? this.#callBudgetStop() : null);
|
|
274
280
|
if (stop) break;
|
|
281
|
+
const unasked = asked ? LoopAsk.refusalOf(call) : null;
|
|
275
282
|
|
|
283
|
+
if (asked && !unasked) {
|
|
284
|
+
yield { type: "awaiting", call, question: true };
|
|
285
|
+
stop = "awaiting";
|
|
286
|
+
break;
|
|
287
|
+
}
|
|
276
288
|
if (verdict === "allow" && this.#clientNames.has(call.name)) {
|
|
277
289
|
this.#toolCalls += 1;
|
|
278
290
|
yield { type: "awaiting", call, client: true };
|
|
279
291
|
stop = "awaiting";
|
|
280
292
|
break;
|
|
281
293
|
}
|
|
282
|
-
const whole = meta ? this.#toolkits.open(call) : await this.#execute(call, verdict);
|
|
294
|
+
const whole = unasked ?? (meta ? this.#toolkits.open(call) : await this.#execute(call, verdict));
|
|
283
295
|
const result = LoopToolOutput.clipped(whole);
|
|
284
296
|
results.push(result);
|
|
285
297
|
|
|
@@ -295,7 +307,7 @@ export class AgentLoop {
|
|
|
295
307
|
}
|
|
296
308
|
|
|
297
309
|
async #verdictOf(call: AgentWireToolCall, tool: AgentTool | undefined): Promise<Verdict> {
|
|
298
|
-
if (this.#toolkits.isMeta(call.name)) return "allow";
|
|
310
|
+
if (this.#toolkits.isMeta(call.name) || this.#askUser.isMeta(call.name)) return "allow";
|
|
299
311
|
|
|
300
312
|
if (!tool) {
|
|
301
313
|
const closed = this.#toolkits.refusalOf(call.name);
|
|
@@ -36,7 +36,7 @@ export interface AgentLoopBudget {
|
|
|
36
36
|
|
|
37
37
|
/**
|
|
38
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.
|
|
39
|
+
* tool or `askUser` was called, and a resume with its result appended runs on from it.
|
|
40
40
|
*/
|
|
41
41
|
export type AgentLoopStop =
|
|
42
42
|
| "end"
|
|
@@ -74,6 +74,13 @@ export interface AgentLoopOptions {
|
|
|
74
74
|
* an endpoint tool or `openToolkit` holds is dropped.
|
|
75
75
|
*/
|
|
76
76
|
clientTools?: AgentTool[];
|
|
77
|
+
/**
|
|
78
|
+
* Lists `askUser({ question, choices?, multiple? })`, the in-page chat's own tool. A call ends the run as `awaiting`
|
|
79
|
+
* with `question: true`; append the person's `{ id, name: "askUser", result }`, or an `error` when they dismiss it,
|
|
80
|
+
* and resume. It never reaches `approve`, counts as no tool call, and `untrusted` never sees its answer. A call with
|
|
81
|
+
* no question is answered with an error instead. A `clientTools` entry by that name is dropped.
|
|
82
|
+
*/
|
|
83
|
+
ask?: boolean;
|
|
77
84
|
/** Summarizes all but the last `keep` messages (6) once the transcript is estimated at `at` tokens. */
|
|
78
85
|
compact?: { at: number; keep?: number };
|
|
79
86
|
/** Asked before every call; without it a `needsConfirm` tool is refused, and so is any write once tainted. */
|
|
@@ -107,6 +114,6 @@ export type AgentLoopEvent =
|
|
|
107
114
|
* whole: its `tainted` carries the run's taint across a resume.
|
|
108
115
|
*/
|
|
109
116
|
| { type: "compacted"; replaced: number; summary: AgentWireMessage }
|
|
110
|
-
| { type: "awaiting"; call: AgentWireToolCall; client?: true }
|
|
117
|
+
| { type: "awaiting"; call: AgentWireToolCall; client?: true; question?: true }
|
|
111
118
|
| { type: "done"; stop: AgentLoopStop; rounds: number }
|
|
112
119
|
| { type: "error"; message: string; error: unknown };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { AgentTool } from "../predefinedAdaptor/agentTools.adaptor";
|
|
2
|
+
import type { AgentWireToolCall, AgentWireToolResult } from "../predefinedAdaptor/llm.adaptor";
|
|
3
|
+
|
|
4
|
+
export class LoopAsk {
|
|
5
|
+
static readonly toolName = "askUser";
|
|
6
|
+
|
|
7
|
+
static readonly tool: AgentTool = {
|
|
8
|
+
name: LoopAsk.toolName,
|
|
9
|
+
description:
|
|
10
|
+
"Ask the user to decide something that is theirs to decide — an ambiguous request, a missing value, a choice between paths. Use it instead of guessing. Pass `choices` to offer options, or omit them for a free-text answer; the user may answer off-list either way. Returns what they chose or wrote, and errors if they dismiss it.",
|
|
11
|
+
parameters: {
|
|
12
|
+
type: "object",
|
|
13
|
+
properties: {
|
|
14
|
+
question: { type: "string", description: "What to ask, in one sentence." },
|
|
15
|
+
choices: { type: "array", items: { type: "string" }, description: "The options to offer, as short labels." },
|
|
16
|
+
multiple: { type: "boolean", description: "Let the user pick several choices. Ignored without choices." },
|
|
17
|
+
},
|
|
18
|
+
required: ["question"],
|
|
19
|
+
additionalProperties: false,
|
|
20
|
+
},
|
|
21
|
+
readOnly: true,
|
|
22
|
+
needsConfirm: false,
|
|
23
|
+
};
|
|
24
|
+
static readonly noQuestion = "askUser needs a question to ask.";
|
|
25
|
+
|
|
26
|
+
readonly #on: boolean;
|
|
27
|
+
|
|
28
|
+
constructor(on: boolean | undefined) {
|
|
29
|
+
this.#on = on === true;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
isMeta(name: string): boolean {
|
|
33
|
+
return this.#on && name === LoopAsk.toolName;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
listed(): AgentTool[] {
|
|
37
|
+
return this.#on ? [LoopAsk.tool] : [];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
static refusalOf({ id, name, args }: AgentWireToolCall): AgentWireToolResult | null {
|
|
41
|
+
const question = typeof args.question === "string" ? args.question.trim() : "";
|
|
42
|
+
return question ? null : { id, name, error: LoopAsk.noQuestion };
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -1,16 +1,19 @@
|
|
|
1
1
|
import { Err } from "akanjs/dictionary";
|
|
2
2
|
import type { AgentLoopRequest } from "./agentLoopTypes";
|
|
3
|
+
import { LoopAsk } from "./loopAsk";
|
|
3
4
|
import { LoopToolkits } from "./loopToolkits";
|
|
4
5
|
|
|
5
6
|
export class LoopRequest {
|
|
6
7
|
|
|
7
8
|
static readonly maxWallMs = 2 ** 31 - 1;
|
|
8
9
|
|
|
9
|
-
static assertValid({ allow, messages, maxRounds, budget, compact, toolkits, clientTools }: AgentLoopRequest) {
|
|
10
|
+
static assertValid({ allow, messages, maxRounds, budget, compact, toolkits, clientTools, ask }: AgentLoopRequest) {
|
|
10
11
|
|
|
11
12
|
if (!Array.isArray(allow)) LoopRequest.#refuse("allow");
|
|
12
13
|
if (!Array.isArray(messages)) LoopRequest.#refuse("messages");
|
|
13
14
|
LoopRequest.#assertToolkits(toolkits, allow);
|
|
15
|
+
if (ask !== undefined && typeof ask !== "boolean") LoopRequest.#refuse("ask");
|
|
16
|
+
if (ask && allow.includes(LoopAsk.toolName)) LoopRequest.#refuse("allow");
|
|
14
17
|
LoopRequest.#assertClientTools(clientTools);
|
|
15
18
|
LoopRequest.#assertCount("maxRounds", maxRounds);
|
|
16
19
|
LoopRequest.#assertCount("compact.at", compact?.at);
|
|
@@ -19,5 +19,5 @@ export declare class RotatingLogWriter {
|
|
|
19
19
|
static sanitizeFilePart(value: string): string;
|
|
20
20
|
write(processKey: string, chunk: string): void;
|
|
21
21
|
close(): Promise<void>;
|
|
22
|
-
static fileMode(value?: string | undefined, warn?: typeof RotatingLogWriter.__#
|
|
22
|
+
static fileMode(value?: string | undefined, warn?: typeof RotatingLogWriter.__#154@#defaultWarn): number;
|
|
23
23
|
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { EndpointInfo } from "../../signal/endpointInfo.d.ts";
|
|
2
|
+
import type { SliceCls } from "../../signal/slice.d.ts";
|
|
3
|
+
export declare class SliceCrud {
|
|
4
|
+
#private;
|
|
5
|
+
static endpoints(builder: unknown, sliceCls: SliceCls, cnst: NonNullable<SliceCls["srv"]["cnst"]>): {
|
|
6
|
+
[key: string]: EndpointInfo;
|
|
7
|
+
};
|
|
8
|
+
}
|
|
@@ -27,7 +27,7 @@ export interface AgentLoopBudget {
|
|
|
27
27
|
}
|
|
28
28
|
/**
|
|
29
29
|
* `awaiting`: `approve` deferred a call, and a resume with the messages `onMessage` stored asks it again; or a client
|
|
30
|
-
* tool was called, and a resume with its result appended runs on from it.
|
|
30
|
+
* tool or `askUser` was called, and a resume with its result appended runs on from it.
|
|
31
31
|
*/
|
|
32
32
|
export type AgentLoopStop = "end" | "maxRounds" | "budget" | "aborted" | "length" | "quota" | "unauthorized" | "awaiting";
|
|
33
33
|
export interface AgentLoopOptions {
|
|
@@ -56,6 +56,13 @@ export interface AgentLoopOptions {
|
|
|
56
56
|
* an endpoint tool or `openToolkit` holds is dropped.
|
|
57
57
|
*/
|
|
58
58
|
clientTools?: AgentTool[];
|
|
59
|
+
/**
|
|
60
|
+
* Lists `askUser({ question, choices?, multiple? })`, the in-page chat's own tool. A call ends the run as `awaiting`
|
|
61
|
+
* with `question: true`; append the person's `{ id, name: "askUser", result }`, or an `error` when they dismiss it,
|
|
62
|
+
* and resume. It never reaches `approve`, counts as no tool call, and `untrusted` never sees its answer. A call with
|
|
63
|
+
* no question is answered with an error instead. A `clientTools` entry by that name is dropped.
|
|
64
|
+
*/
|
|
65
|
+
ask?: boolean;
|
|
59
66
|
/** Summarizes all but the last `keep` messages (6) once the transcript is estimated at `at` tokens. */
|
|
60
67
|
compact?: {
|
|
61
68
|
at: number;
|
|
@@ -115,6 +122,7 @@ export type AgentLoopEvent = {
|
|
|
115
122
|
type: "awaiting";
|
|
116
123
|
call: AgentWireToolCall;
|
|
117
124
|
client?: true;
|
|
125
|
+
question?: true;
|
|
118
126
|
} | {
|
|
119
127
|
type: "done";
|
|
120
128
|
stop: AgentLoopStop;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { AgentTool } from "../predefinedAdaptor/agentTools.adaptor";
|
|
2
|
+
import type { AgentWireToolCall, AgentWireToolResult } from "../predefinedAdaptor/llm.adaptor";
|
|
3
|
+
export declare class LoopAsk {
|
|
4
|
+
#private;
|
|
5
|
+
static readonly toolName = "askUser";
|
|
6
|
+
static readonly tool: AgentTool;
|
|
7
|
+
static readonly noQuestion = "askUser needs a question to ask.";
|
|
8
|
+
constructor(on: boolean | undefined);
|
|
9
|
+
isMeta(name: string): boolean;
|
|
10
|
+
listed(): AgentTool[];
|
|
11
|
+
static refusalOf({ id, name, args }: AgentWireToolCall): AgentWireToolResult | null;
|
|
12
|
+
}
|
|
@@ -2,5 +2,5 @@ import type { AgentLoopRequest } from "./agentLoopTypes.d.ts";
|
|
|
2
2
|
export declare class LoopRequest {
|
|
3
3
|
#private;
|
|
4
4
|
static readonly maxWallMs: number;
|
|
5
|
-
static assertValid({ allow, messages, maxRounds, budget, compact, toolkits, clientTools }: AgentLoopRequest): void;
|
|
5
|
+
static assertValid({ allow, messages, maxRounds, budget, compact, toolkits, clientTools, ask }: AgentLoopRequest): void;
|
|
6
6
|
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type AgentProgressReport, type ToolCallResult } from "../../vendor/use-agentic.d.ts";
|
|
2
|
+
export interface ToolRowProps {
|
|
3
|
+
className?: string;
|
|
4
|
+
name: string;
|
|
5
|
+
args?: Record<string, unknown>;
|
|
6
|
+
/** Absent while the call runs. */
|
|
7
|
+
result?: ToolCallResult;
|
|
8
|
+
/** What the running call last reported about itself; never set once it has a result. */
|
|
9
|
+
progress?: AgentProgressReport | null;
|
|
10
|
+
}
|
|
11
|
+
export declare const DefaultToolRow: ({ className, name, args, result, progress }: ToolRowProps) => import("react").JSX.Element;
|
|
12
|
+
declare const _default: import("react").ComponentType<ToolRowProps>;
|
|
13
|
+
export default _default;
|
|
@@ -11,6 +11,7 @@ import type { QuestionProps as AgentQuestionProps } from "../Agent/Question.d.ts
|
|
|
11
11
|
import type { QueuedProps as AgentQueuedProps } from "../Agent/Queued.d.ts";
|
|
12
12
|
import type { StepsProps as AgentStepsProps } from "../Agent/Steps.d.ts";
|
|
13
13
|
import type { ToolCardProps as AgentToolCardProps } from "../Agent/ToolCard.d.ts";
|
|
14
|
+
import type { ToolRowProps as AgentToolRowProps } from "../Agent/ToolRow.d.ts";
|
|
14
15
|
import type { BadgeProps } from "../Badge.d.ts";
|
|
15
16
|
import type { ButtonProps } from "../Button.d.ts";
|
|
16
17
|
import type { DatePickerProps, RangePickerProps, TimePickerProps } from "../DatePicker.d.ts";
|
|
@@ -57,6 +58,7 @@ export interface AkanUiOverrides {
|
|
|
57
58
|
AgentMenu: ComponentType<AgentMenuProps>;
|
|
58
59
|
AgentMarkdown: ComponentType<AgentMarkdownProps>;
|
|
59
60
|
AgentToolCard: ComponentType<AgentToolCardProps>;
|
|
61
|
+
AgentToolRow: ComponentType<AgentToolRowProps>;
|
|
60
62
|
AgentCode: ComponentType<AgentCodeProps>;
|
|
61
63
|
Button: ComponentType<ButtonProps<unknown>>;
|
|
62
64
|
Select: ComponentType<SelectProps<string | number | boolean | null | undefined>>;
|
package/types/ui/index.d.ts
CHANGED
|
@@ -19,6 +19,7 @@ export { DefaultQueued, type QueuedProps } from "./Agent/Queued.d.ts";
|
|
|
19
19
|
export { ReferenceChips as AgentReferences, type ReferenceChipsProps as AgentReferencesProps, } from "./Agent/Refer.d.ts";
|
|
20
20
|
export { DefaultSteps, type StepsProps } from "./Agent/Steps.d.ts";
|
|
21
21
|
export { DefaultToolCard, type ToolCardProps } from "./Agent/ToolCard.d.ts";
|
|
22
|
+
export { DefaultToolRow, type ToolRowProps } from "./Agent/ToolRow.d.ts";
|
|
22
23
|
export { tokenCount } from "./Agent/tokenCount.d.ts";
|
|
23
24
|
export type { QueuedMessage } from "./Agent/useChatQueue.d.ts";
|
|
24
25
|
export type { ReferenceCandidate, ReferenceSource } from "./Agent/useReferenceMenu.d.ts";
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { PendingQuestion } from "./AgentSession.d.ts";
|
|
2
|
+
import type { ChatMessage, ToolCallRequest, ToolCallResult } from "./types.d.ts";
|
|
3
|
+
type Settled = {
|
|
4
|
+
result: string | string[];
|
|
5
|
+
} | {
|
|
6
|
+
error: string;
|
|
7
|
+
};
|
|
8
|
+
type Asked = Pick<PendingQuestion, "question" | "choices" | "multiple">;
|
|
9
|
+
export declare class SessionQuestion {
|
|
10
|
+
#private;
|
|
11
|
+
static readonly toolName = "askUser";
|
|
12
|
+
static readonly dismissed = "The user dismissed the question without answering it.";
|
|
13
|
+
constructor(changed: () => void);
|
|
14
|
+
get pending(): PendingQuestion | null;
|
|
15
|
+
clear(): void;
|
|
16
|
+
/** No surface call and so no diff to report: the only thing this changes is what the model knows. */
|
|
17
|
+
ask(call: ToolCallRequest, signal: AbortSignal): Promise<ToolCallResult>;
|
|
18
|
+
wait(callId: string, asked: Asked, signal: AbortSignal): Promise<Settled>;
|
|
19
|
+
/**
|
|
20
|
+
* Puts back a question a restored transcript ends on, which a run asked while no chat was open; settling it hands
|
|
21
|
+
* the result to `resume` once, and a turn that starts first takes it down, leaving the call to the wire's closing.
|
|
22
|
+
*/
|
|
23
|
+
reopen(messages: readonly ChatMessage[], resume: (result: ToolCallResult) => void): void;
|
|
24
|
+
static openCall(messages: readonly ChatMessage[]): ToolCallRequest | null;
|
|
25
|
+
}
|
|
26
|
+
export {};
|
|
@@ -22,7 +22,7 @@ export declare class Transcript {
|
|
|
22
22
|
static seen(messages: readonly ChatMessage[]): ChatMessage[];
|
|
23
23
|
/** A message without the provider's count for its turn — what the wire carries and what a compaction keeps. */
|
|
24
24
|
static unmeasured(message: ChatMessage): ChatMessage;
|
|
25
|
-
static sanitize(messages: readonly ChatMessage[]): ChatMessage[];
|
|
25
|
+
static sanitize(messages: readonly ChatMessage[], openCallId?: string): ChatMessage[];
|
|
26
26
|
/** An empty assistant message is a draft a reload or an abort caught before it said anything. */
|
|
27
27
|
static carries(message: ChatMessage): boolean;
|
|
28
28
|
}
|
package/ui/Agent/Bubble.tsx
CHANGED
|
@@ -1,19 +1,12 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { cn, usePage } from "akanjs/client";
|
|
3
3
|
import { memo } from "react";
|
|
4
|
-
import {
|
|
5
|
-
type AgentProgressReport,
|
|
6
|
-
type AgentProgressStep,
|
|
7
|
-
AgentSession,
|
|
8
|
-
type ChatMessage,
|
|
9
|
-
type ToolCallResult,
|
|
10
|
-
ToolOutput,
|
|
11
|
-
} from "../../vendor/use-agentic";
|
|
4
|
+
import { type AgentProgressReport, AgentSession, type ChatMessage, type ToolCallResult } from "../../vendor/use-agentic";
|
|
12
5
|
import { createOverridable } from "../UiOverride";
|
|
13
6
|
import { Chips } from "./Attach";
|
|
14
7
|
import Markdown from "./Markdown";
|
|
15
8
|
import { ReferenceChips } from "./Refer";
|
|
16
|
-
import
|
|
9
|
+
import ToolRow from "./ToolRow";
|
|
17
10
|
|
|
18
11
|
export interface BubbleProps {
|
|
19
12
|
className?: string;
|
|
@@ -24,113 +17,6 @@ export interface BubbleProps {
|
|
|
24
17
|
results?: ReadonlyMap<string, ToolCallResult>;
|
|
25
18
|
}
|
|
26
19
|
|
|
27
|
-
interface RowProps {
|
|
28
|
-
name: string;
|
|
29
|
-
args?: Record<string, unknown>;
|
|
30
|
-
result?: ToolCallResult;
|
|
31
|
-
progress?: AgentProgressReport | null;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
const payloadOf = ({ result, changes, error }: ToolCallResult) => ({
|
|
35
|
-
...(result !== undefined ? { result } : {}),
|
|
36
|
-
...(changes?.length ? { changes } : {}),
|
|
37
|
-
...(error ? { error } : {}),
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
const stepGlyph = { pending: "○", running: "●", done: "✓", error: "✕" } as const;
|
|
41
|
-
const stepTone = {
|
|
42
|
-
pending: "text-foreground/40",
|
|
43
|
-
running: "animate-pulse text-warning",
|
|
44
|
-
done: "text-success",
|
|
45
|
-
error: "text-destructive",
|
|
46
|
-
} as const;
|
|
47
|
-
|
|
48
|
-
interface StepListProps {
|
|
49
|
-
steps: AgentProgressStep[];
|
|
50
|
-
}
|
|
51
|
-
const StepList = ({ steps }: StepListProps) => {
|
|
52
|
-
const settled = steps.filter((step) => step.status === "done" || step.status === "error").length;
|
|
53
|
-
return (
|
|
54
|
-
<details className="px-2 pb-1">
|
|
55
|
-
<summary className="cursor-pointer font-mono text-[10px] text-foreground/50">
|
|
56
|
-
{settled}/{steps.length}
|
|
57
|
-
</summary>
|
|
58
|
-
<ul className="mt-1 flex flex-col gap-0.5">
|
|
59
|
-
{steps.map((step) => (
|
|
60
|
-
<li className="flex items-baseline gap-2 text-[10px]" key={step.id}>
|
|
61
|
-
<span className={cn("shrink-0", stepTone[step.status])}>{stepGlyph[step.status]}</span>
|
|
62
|
-
<span className="truncate">{step.label}</span>
|
|
63
|
-
{step.detail ? <span className="truncate text-foreground/50">{step.detail}</span> : null}
|
|
64
|
-
</li>
|
|
65
|
-
))}
|
|
66
|
-
</ul>
|
|
67
|
-
</details>
|
|
68
|
-
);
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
const Row = ({ name, args, result, progress }: RowProps) => {
|
|
72
|
-
const { l } = usePage();
|
|
73
|
-
const payload = result ? payloadOf(result) : null;
|
|
74
|
-
const head = (
|
|
75
|
-
<>
|
|
76
|
-
{result ? (
|
|
77
|
-
<span
|
|
78
|
-
aria-label={l(result.error ? "base.agentToolFailed" : "base.agentToolDone")}
|
|
79
|
-
className={cn("shrink-0 text-[10px]", result.error ? "text-destructive" : "text-success")}
|
|
80
|
-
role="img"
|
|
81
|
-
>
|
|
82
|
-
{result.error ? "✕" : "✓"}
|
|
83
|
-
</span>
|
|
84
|
-
) : (
|
|
85
|
-
<span
|
|
86
|
-
aria-label={l("base.agentToolRunning")}
|
|
87
|
-
className="size-1.5 shrink-0 animate-pulse rounded-full bg-warning"
|
|
88
|
-
role="img"
|
|
89
|
-
/>
|
|
90
|
-
)}
|
|
91
|
-
<span className="shrink-0 font-mono text-xs">{name}</span>
|
|
92
|
-
{progress ? (
|
|
93
|
-
<span className="truncate text-[10px] text-foreground/60">
|
|
94
|
-
{progress.message}
|
|
95
|
-
{progress.total ? ` ${progress.done ?? 0}/${progress.total}` : ""}
|
|
96
|
-
</span>
|
|
97
|
-
) : null}
|
|
98
|
-
{!progress && args && Object.keys(args).length ? (
|
|
99
|
-
<span className="truncate font-mono text-[10px] text-foreground/50">{JSON.stringify(args)}</span>
|
|
100
|
-
) : null}
|
|
101
|
-
{result?.error ? <span className="truncate text-[10px] text-destructive">{result.error}</span> : null}
|
|
102
|
-
<span className="ml-auto flex shrink-0 items-baseline gap-2 text-[10px] text-foreground/40">
|
|
103
|
-
{result?.changes?.length ? <span>Δ {result.changes.length}</span> : null}
|
|
104
|
-
{result ? <span>{l("base.agentTokens", { count: tokenCount(ToolOutput.tokensOf(result)) })}</span> : null}
|
|
105
|
-
</span>
|
|
106
|
-
</>
|
|
107
|
-
);
|
|
108
|
-
if (progress?.steps?.length)
|
|
109
|
-
return (
|
|
110
|
-
<div className="rounded-field bg-muted">
|
|
111
|
-
<div className="flex items-baseline gap-2 px-2 py-1">{head}</div>
|
|
112
|
-
<StepList steps={progress.steps} />
|
|
113
|
-
</div>
|
|
114
|
-
);
|
|
115
|
-
if (!payload || !Object.keys(payload).length)
|
|
116
|
-
return <div className="flex items-baseline gap-2 rounded-field bg-muted px-2 py-1">{head}</div>;
|
|
117
|
-
return (
|
|
118
|
-
<details className="group rounded-field bg-muted">
|
|
119
|
-
<summary
|
|
120
|
-
aria-label={l("base.agentToolResult")}
|
|
121
|
-
className="flex cursor-pointer items-baseline gap-2 px-2 py-1"
|
|
122
|
-
title={l("base.agentToolResult")}
|
|
123
|
-
>
|
|
124
|
-
<span className="shrink-0 text-[8px] text-foreground/40 transition-transform group-open:rotate-90">▶</span>
|
|
125
|
-
{head}
|
|
126
|
-
</summary>
|
|
127
|
-
<pre className="scrollbar-thin max-h-64 overflow-auto whitespace-pre-wrap break-all border-foreground/5 border-t px-2 py-1.5 font-mono text-[10px] text-foreground/70">
|
|
128
|
-
{JSON.stringify(payload, null, 2)}
|
|
129
|
-
</pre>
|
|
130
|
-
</details>
|
|
131
|
-
);
|
|
132
|
-
};
|
|
133
|
-
|
|
134
20
|
interface AskProps {
|
|
135
21
|
args?: Record<string, unknown>;
|
|
136
22
|
result: ToolCallResult;
|
|
@@ -168,7 +54,7 @@ const Content = ({ className, message, progress, results }: BubbleProps) => {
|
|
|
168
54
|
return (
|
|
169
55
|
<div className={cn("flex flex-col gap-1", className)}>
|
|
170
56
|
{(message.toolResults ?? []).map((result) => (
|
|
171
|
-
<
|
|
57
|
+
<ToolRow key={result.id} name={result.name} result={result} />
|
|
172
58
|
))}
|
|
173
59
|
</div>
|
|
174
60
|
);
|
|
@@ -190,7 +76,7 @@ const Content = ({ className, message, progress, results }: BubbleProps) => {
|
|
|
190
76
|
const result = results?.get(call.id);
|
|
191
77
|
if (call.name !== AgentSession.askUserTool.name)
|
|
192
78
|
return [
|
|
193
|
-
<
|
|
79
|
+
<ToolRow
|
|
194
80
|
key={call.id}
|
|
195
81
|
args={call.args}
|
|
196
82
|
name={call.name}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { cn, usePage } from "akanjs/client";
|
|
3
|
+
import { type AgentProgressReport, type AgentProgressStep, type ToolCallResult, ToolOutput } from "../../vendor/use-agentic";
|
|
4
|
+
import { createOverridable } from "../UiOverride";
|
|
5
|
+
import { tokenCount } from "./tokenCount";
|
|
6
|
+
|
|
7
|
+
export interface ToolRowProps {
|
|
8
|
+
className?: string;
|
|
9
|
+
name: string;
|
|
10
|
+
args?: Record<string, unknown>;
|
|
11
|
+
/** Absent while the call runs. */
|
|
12
|
+
result?: ToolCallResult;
|
|
13
|
+
/** What the running call last reported about itself; never set once it has a result. */
|
|
14
|
+
progress?: AgentProgressReport | null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const payloadOf = ({ result, changes, error }: ToolCallResult) => ({
|
|
18
|
+
...(result !== undefined ? { result } : {}),
|
|
19
|
+
...(changes?.length ? { changes } : {}),
|
|
20
|
+
...(error ? { error } : {}),
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const stepGlyph = { pending: "○", running: "●", done: "✓", error: "✕" } as const;
|
|
24
|
+
const stepTone = {
|
|
25
|
+
pending: "text-foreground/40",
|
|
26
|
+
running: "animate-pulse text-warning",
|
|
27
|
+
done: "text-success",
|
|
28
|
+
error: "text-destructive",
|
|
29
|
+
} as const;
|
|
30
|
+
|
|
31
|
+
interface StepListProps {
|
|
32
|
+
steps: AgentProgressStep[];
|
|
33
|
+
}
|
|
34
|
+
const StepList = ({ steps }: StepListProps) => {
|
|
35
|
+
const settled = steps.filter((step) => step.status === "done" || step.status === "error").length;
|
|
36
|
+
return (
|
|
37
|
+
<details className="px-2 pb-1">
|
|
38
|
+
<summary className="cursor-pointer font-mono text-[10px] text-foreground/50">
|
|
39
|
+
{settled}/{steps.length}
|
|
40
|
+
</summary>
|
|
41
|
+
<ul className="mt-1 flex flex-col gap-0.5">
|
|
42
|
+
{steps.map((step) => (
|
|
43
|
+
<li className="flex items-baseline gap-2 text-[10px]" key={step.id}>
|
|
44
|
+
<span className={cn("shrink-0", stepTone[step.status])}>{stepGlyph[step.status]}</span>
|
|
45
|
+
<span className="truncate">{step.label}</span>
|
|
46
|
+
{step.detail ? <span className="truncate text-foreground/50">{step.detail}</span> : null}
|
|
47
|
+
</li>
|
|
48
|
+
))}
|
|
49
|
+
</ul>
|
|
50
|
+
</details>
|
|
51
|
+
);
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
export const DefaultToolRow = ({ className, name, args, result, progress }: ToolRowProps) => {
|
|
55
|
+
const { l } = usePage();
|
|
56
|
+
const payload = result ? payloadOf(result) : null;
|
|
57
|
+
const head = (
|
|
58
|
+
<>
|
|
59
|
+
{result ? (
|
|
60
|
+
<span
|
|
61
|
+
aria-label={l(result.error ? "base.agentToolFailed" : "base.agentToolDone")}
|
|
62
|
+
className={cn("shrink-0 text-[10px]", result.error ? "text-destructive" : "text-success")}
|
|
63
|
+
role="img"
|
|
64
|
+
>
|
|
65
|
+
{result.error ? "✕" : "✓"}
|
|
66
|
+
</span>
|
|
67
|
+
) : (
|
|
68
|
+
<span
|
|
69
|
+
aria-label={l("base.agentToolRunning")}
|
|
70
|
+
className="size-1.5 shrink-0 animate-pulse rounded-full bg-warning"
|
|
71
|
+
role="img"
|
|
72
|
+
/>
|
|
73
|
+
)}
|
|
74
|
+
<span className="shrink-0 font-mono text-xs">{name}</span>
|
|
75
|
+
{progress ? (
|
|
76
|
+
<span className="truncate text-[10px] text-foreground/60">
|
|
77
|
+
{progress.message}
|
|
78
|
+
{progress.total ? ` ${progress.done ?? 0}/${progress.total}` : ""}
|
|
79
|
+
</span>
|
|
80
|
+
) : null}
|
|
81
|
+
{!progress && args && Object.keys(args).length ? (
|
|
82
|
+
<span className="truncate font-mono text-[10px] text-foreground/50">{JSON.stringify(args)}</span>
|
|
83
|
+
) : null}
|
|
84
|
+
{result?.error ? <span className="truncate text-[10px] text-destructive">{result.error}</span> : null}
|
|
85
|
+
<span className="ml-auto flex shrink-0 items-baseline gap-2 text-[10px] text-foreground/40">
|
|
86
|
+
{result?.changes?.length ? <span>Δ {result.changes.length}</span> : null}
|
|
87
|
+
{result ? <span>{l("base.agentTokens", { count: tokenCount(ToolOutput.tokensOf(result)) })}</span> : null}
|
|
88
|
+
</span>
|
|
89
|
+
</>
|
|
90
|
+
);
|
|
91
|
+
if (progress?.steps?.length)
|
|
92
|
+
return (
|
|
93
|
+
<div className={cn("rounded-field bg-muted", className)}>
|
|
94
|
+
<div className="flex items-baseline gap-2 px-2 py-1">{head}</div>
|
|
95
|
+
<StepList steps={progress.steps} />
|
|
96
|
+
</div>
|
|
97
|
+
);
|
|
98
|
+
if (!payload || !Object.keys(payload).length)
|
|
99
|
+
return <div className={cn("flex items-baseline gap-2 rounded-field bg-muted px-2 py-1", className)}>{head}</div>;
|
|
100
|
+
return (
|
|
101
|
+
<details className={cn("group rounded-field bg-muted", className)}>
|
|
102
|
+
<summary
|
|
103
|
+
aria-label={l("base.agentToolResult")}
|
|
104
|
+
className="flex cursor-pointer items-baseline gap-2 px-2 py-1"
|
|
105
|
+
title={l("base.agentToolResult")}
|
|
106
|
+
>
|
|
107
|
+
<span className="shrink-0 text-[8px] text-foreground/40 transition-transform group-open:rotate-90">▶</span>
|
|
108
|
+
{head}
|
|
109
|
+
</summary>
|
|
110
|
+
<pre className="scrollbar-thin max-h-64 overflow-auto whitespace-pre-wrap break-all border-foreground/5 border-t px-2 py-1.5 font-mono text-[10px] text-foreground/70">
|
|
111
|
+
{JSON.stringify(payload, null, 2)}
|
|
112
|
+
</pre>
|
|
113
|
+
</details>
|
|
114
|
+
);
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
export default createOverridable("AgentToolRow", DefaultToolRow);
|
|
@@ -13,6 +13,7 @@ import type { QuestionProps as AgentQuestionProps } from "../Agent/Question";
|
|
|
13
13
|
import type { QueuedProps as AgentQueuedProps } from "../Agent/Queued";
|
|
14
14
|
import type { StepsProps as AgentStepsProps } from "../Agent/Steps";
|
|
15
15
|
import type { ToolCardProps as AgentToolCardProps } from "../Agent/ToolCard";
|
|
16
|
+
import type { ToolRowProps as AgentToolRowProps } from "../Agent/ToolRow";
|
|
16
17
|
import type { BadgeProps } from "../Badge";
|
|
17
18
|
import type { ButtonProps } from "../Button";
|
|
18
19
|
import type { DatePickerProps, RangePickerProps, TimePickerProps } from "../DatePicker";
|
|
@@ -61,6 +62,7 @@ export interface AkanUiOverrides {
|
|
|
61
62
|
AgentMenu: ComponentType<AgentMenuProps>;
|
|
62
63
|
AgentMarkdown: ComponentType<AgentMarkdownProps>;
|
|
63
64
|
AgentToolCard: ComponentType<AgentToolCardProps>;
|
|
65
|
+
AgentToolRow: ComponentType<AgentToolRowProps>;
|
|
64
66
|
AgentCode: ComponentType<AgentCodeProps>;
|
|
65
67
|
|
|
66
68
|
Button: ComponentType<ButtonProps<unknown>>;
|
package/ui/index.ts
CHANGED
|
@@ -59,6 +59,7 @@ export {
|
|
|
59
59
|
} from "./Agent/Refer";
|
|
60
60
|
export { DefaultSteps, type StepsProps } from "./Agent/Steps";
|
|
61
61
|
export { DefaultToolCard, type ToolCardProps } from "./Agent/ToolCard";
|
|
62
|
+
export { DefaultToolRow, type ToolRowProps } from "./Agent/ToolRow";
|
|
62
63
|
export { tokenCount } from "./Agent/tokenCount";
|
|
63
64
|
export type { QueuedMessage } from "./Agent/useChatQueue";
|
|
64
65
|
export type { ReferenceCandidate, ReferenceSource } from "./Agent/useReferenceMenu";
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { AgentProgressReport } from "./AgentProgress";
|
|
2
2
|
import { Compaction, type CompactOptions } from "./Compaction";
|
|
3
3
|
import { Reference } from "./Reference";
|
|
4
|
+
import { SessionQuestion } from "./SessionQuestion";
|
|
4
5
|
import { ToolOutput } from "./ToolOutput";
|
|
5
6
|
import { type ToolApprovalRequest, type ToolCardAnswer, type ToolCardRequest, ToolRunner } from "./ToolRunner";
|
|
6
7
|
import { Transcript } from "./Transcript";
|
|
@@ -169,7 +170,7 @@ export class AgentSession {
|
|
|
169
170
|
#messages: ChatMessage[] = [];
|
|
170
171
|
#running = false;
|
|
171
172
|
#pending: PendingApproval | null = null;
|
|
172
|
-
#
|
|
173
|
+
readonly #questions = new SessionQuestion(() => this.#notify());
|
|
173
174
|
#card: PendingCard | null = null;
|
|
174
175
|
#staged: MessageReference[] = [];
|
|
175
176
|
#inserts: MessageReference[] = [];
|
|
@@ -216,13 +217,13 @@ export class AgentSession {
|
|
|
216
217
|
},
|
|
217
218
|
fallback: async (call, signal) =>
|
|
218
219
|
call.name === AgentSession.askUserTool.name
|
|
219
|
-
? await this.#ask(call, signal)
|
|
220
|
+
? await this.#questions.ask(call, signal)
|
|
220
221
|
: { id: call.id, name: call.name, error: this.#unknown(call.name) },
|
|
221
222
|
});
|
|
222
223
|
this.#history = options.history;
|
|
223
224
|
this.#onCompact = options.onCompact;
|
|
224
225
|
const restored = AgentSession.#restored(options.history);
|
|
225
|
-
if (Array.isArray(restored)) this.#
|
|
226
|
+
if (Array.isArray(restored)) this.#reopen(restored);
|
|
226
227
|
else {
|
|
227
228
|
this.#restoring = true;
|
|
228
229
|
void this.#hydrate(restored);
|
|
@@ -263,7 +264,7 @@ export class AgentSession {
|
|
|
263
264
|
}
|
|
264
265
|
|
|
265
266
|
get pendingQuestion(): PendingQuestion | null {
|
|
266
|
-
return this.#
|
|
267
|
+
return this.#questions.pending;
|
|
267
268
|
}
|
|
268
269
|
|
|
269
270
|
get pendingCard(): PendingCard | null {
|
|
@@ -401,6 +402,7 @@ export class AgentSession {
|
|
|
401
402
|
/** A user's text, or prewritten messages — how a host injects a prompt's result as the user's turn. */
|
|
402
403
|
send = async (input: string | ChatMessage[]) => {
|
|
403
404
|
if (this.#running) throw new Error("A turn is already running.");
|
|
405
|
+
this.#questions.clear();
|
|
404
406
|
this.#running = true;
|
|
405
407
|
const run = this.#turn(input);
|
|
406
408
|
this.#active = run;
|
|
@@ -470,7 +472,7 @@ export class AgentSession {
|
|
|
470
472
|
this.#controller = null;
|
|
471
473
|
this.#active = null;
|
|
472
474
|
this.#pending = null;
|
|
473
|
-
this.#
|
|
475
|
+
this.#questions.clear();
|
|
474
476
|
this.#card = null;
|
|
475
477
|
this.#progress = null;
|
|
476
478
|
|
|
@@ -497,6 +499,7 @@ export class AgentSession {
|
|
|
497
499
|
await this.#active;
|
|
498
500
|
}
|
|
499
501
|
this.#messages = [];
|
|
502
|
+
this.#questions.clear();
|
|
500
503
|
this.#staged = [];
|
|
501
504
|
this.#inserts = [];
|
|
502
505
|
this.#tools.forgetUntrusted();
|
|
@@ -576,6 +579,7 @@ export class AgentSession {
|
|
|
576
579
|
if (this.#running) return false;
|
|
577
580
|
const controller = new AbortController();
|
|
578
581
|
this.#controller = controller;
|
|
582
|
+
this.#questions.clear();
|
|
579
583
|
this.#running = true;
|
|
580
584
|
|
|
581
585
|
this.#notify();
|
|
@@ -782,7 +786,8 @@ export class AgentSession {
|
|
|
782
786
|
async #askToContinue(turns: number, signal: AbortSignal): Promise<string | null> {
|
|
783
787
|
const ask = this.#options.continueAsk?.();
|
|
784
788
|
if (!ask) return null;
|
|
785
|
-
const
|
|
789
|
+
const asked = { question: ask.question, choices: [ask.keep], multiple: false };
|
|
790
|
+
const settled = await this.#questions.wait(`continue-${turns}`, asked, signal);
|
|
786
791
|
if ("error" in settled) return null;
|
|
787
792
|
return Array.isArray(settled.result) ? settled.result.join(", ") : settled.result;
|
|
788
793
|
}
|
|
@@ -801,52 +806,6 @@ export class AgentSession {
|
|
|
801
806
|
: `Unknown tool: ${name}. Call only a tool listed to you, by its exact name — never a guessed one. Listed now: ${now.join(", ")}.`;
|
|
802
807
|
}
|
|
803
808
|
|
|
804
|
-
/** No surface call and so no diff to report: the only thing this changes is what the model knows. */
|
|
805
|
-
async #ask(call: ToolCallRequest, signal: AbortSignal): Promise<ToolCallResult> {
|
|
806
|
-
const base = { id: call.id, name: call.name };
|
|
807
|
-
const question = typeof call.args.question === "string" ? call.args.question.trim() : "";
|
|
808
|
-
if (!question) return { ...base, error: "askUser needs a question to ask." };
|
|
809
|
-
|
|
810
|
-
const choices = [
|
|
811
|
-
...new Set(
|
|
812
|
-
(Array.isArray(call.args.choices) ? call.args.choices : [])
|
|
813
|
-
.filter((choice): choice is string => typeof choice === "string")
|
|
814
|
-
.map((choice) => choice.trim())
|
|
815
|
-
.filter(Boolean),
|
|
816
|
-
),
|
|
817
|
-
];
|
|
818
|
-
const multiple = call.args.multiple === true && choices.length > 1;
|
|
819
|
-
return { ...base, ...(await this.#awaitAnswer(call.id, question, choices, multiple, signal)) };
|
|
820
|
-
}
|
|
821
|
-
|
|
822
|
-
#awaitAnswer(
|
|
823
|
-
callId: string,
|
|
824
|
-
question: string,
|
|
825
|
-
choices: string[],
|
|
826
|
-
multiple: boolean,
|
|
827
|
-
signal: AbortSignal,
|
|
828
|
-
): Promise<{ result: string | string[] } | { error: string }> {
|
|
829
|
-
return new Promise((resolve) => {
|
|
830
|
-
const settle = (value: { result: string | string[] } | { error: string }) => {
|
|
831
|
-
this.#question = null;
|
|
832
|
-
signal.removeEventListener("abort", onAbort);
|
|
833
|
-
this.#notify();
|
|
834
|
-
resolve(value);
|
|
835
|
-
};
|
|
836
|
-
const onAbort = () => settle({ error: "The user aborted the turn." });
|
|
837
|
-
signal.addEventListener("abort", onAbort);
|
|
838
|
-
this.#question = {
|
|
839
|
-
callId,
|
|
840
|
-
question,
|
|
841
|
-
choices,
|
|
842
|
-
multiple,
|
|
843
|
-
answer: (value) => settle({ result: value }),
|
|
844
|
-
dismiss: (reason) => settle({ error: reason ?? "The user dismissed the question without answering it." }),
|
|
845
|
-
};
|
|
846
|
-
this.#notify();
|
|
847
|
-
});
|
|
848
|
-
}
|
|
849
|
-
|
|
850
809
|
#awaitCard(request: ToolCardRequest, signal: AbortSignal): Promise<ToolCardAnswer> {
|
|
851
810
|
return new Promise((resolve) => {
|
|
852
811
|
const settle = (answer: ToolCardAnswer) => {
|
|
@@ -965,7 +924,7 @@ export class AgentSession {
|
|
|
965
924
|
|
|
966
925
|
static #settled(messages: ChatMessage[] | null): ChatMessage[] {
|
|
967
926
|
|
|
968
|
-
return Array.isArray(messages) ? Transcript.sanitize(messages) : [];
|
|
927
|
+
return Array.isArray(messages) ? Transcript.sanitize(messages, SessionQuestion.openCall(messages)?.id) : [];
|
|
969
928
|
}
|
|
970
929
|
|
|
971
930
|
/**
|
|
@@ -989,8 +948,13 @@ export class AgentSession {
|
|
|
989
948
|
* which would save the transcript it has just loaded.
|
|
990
949
|
*/
|
|
991
950
|
#restore(restored: ChatMessage[]) {
|
|
992
|
-
if (this.#version === 0 && restored.length) this.#
|
|
951
|
+
if (this.#version === 0 && restored.length) this.#reopen(restored);
|
|
993
952
|
this.#version += 1;
|
|
994
953
|
for (const listener of this.#listeners) listener();
|
|
995
954
|
}
|
|
955
|
+
|
|
956
|
+
#reopen(restored: ChatMessage[]) {
|
|
957
|
+
this.#messages = restored;
|
|
958
|
+
this.#questions.reopen(restored, (result) => void this.send([{ role: "tool", toolResults: [result] }]));
|
|
959
|
+
}
|
|
996
960
|
}
|
|
@@ -17,6 +17,16 @@
|
|
|
17
17
|
|
|
18
18
|
Both are new and optional, so no upgrade step is needed.
|
|
19
19
|
|
|
20
|
+
- f5d1e63: A restored chat transcript that ends on an unanswered `askUser` call now opens on that question instead of closing it. This covers a server run that parked on a question while no chat was open, and a page reloaded mid-question.
|
|
21
|
+
|
|
22
|
+
- The session's `pendingQuestion` holds the question, so `Agent.Chat` draws its card and the composer answers it as usual.
|
|
23
|
+
- Answering or dismissing it appends the `askUser` result (or the dismissal's error) and runs a turn through the runner, which carries the answer back to wherever the question came from.
|
|
24
|
+
- A turn started first, `reset()` and `compact()` take the question down. The call is then closed as unanswered on the wire, as before.
|
|
25
|
+
- Only the first unanswered call of the last batch reopens, and only when it asks something. Calls after it are closed as unanswered when the transcript is restored.
|
|
26
|
+
- `Transcript.sanitize(messages, openCallId?)` takes the id of one call to leave unanswered.
|
|
27
|
+
|
|
28
|
+
Before this, a reload in the middle of a question closed the call as stopped. It now asks again, so no upgrade step is needed.
|
|
29
|
+
|
|
20
30
|
### Patch Changes
|
|
21
31
|
|
|
22
32
|
- 8c70603: A failed agent turn now names a code a host can branch on, beside the message it already sent, which is unchanged. No upgrade step is needed: the fields are new.
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { PendingQuestion } from "./AgentSession";
|
|
2
|
+
import { Transcript } from "./Transcript";
|
|
3
|
+
import type { ChatMessage, ToolCallRequest, ToolCallResult } from "./types";
|
|
4
|
+
|
|
5
|
+
type Settled = { result: string | string[] } | { error: string };
|
|
6
|
+
type Asked = Pick<PendingQuestion, "question" | "choices" | "multiple">;
|
|
7
|
+
|
|
8
|
+
export class SessionQuestion {
|
|
9
|
+
static readonly toolName = "askUser";
|
|
10
|
+
static readonly dismissed = "The user dismissed the question without answering it.";
|
|
11
|
+
|
|
12
|
+
readonly #changed: () => void;
|
|
13
|
+
#pending: PendingQuestion | null = null;
|
|
14
|
+
|
|
15
|
+
constructor(changed: () => void) {
|
|
16
|
+
this.#changed = changed;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
get pending(): PendingQuestion | null {
|
|
20
|
+
return this.#pending;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
clear() {
|
|
24
|
+
this.#pending = null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** No surface call and so no diff to report: the only thing this changes is what the model knows. */
|
|
28
|
+
async ask(call: ToolCallRequest, signal: AbortSignal): Promise<ToolCallResult> {
|
|
29
|
+
const base = { id: call.id, name: call.name };
|
|
30
|
+
const asked = SessionQuestion.#asked(call);
|
|
31
|
+
if (!asked) return { ...base, error: "askUser needs a question to ask." };
|
|
32
|
+
return { ...base, ...(await this.wait(call.id, asked, signal)) };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
wait(callId: string, asked: Asked, signal: AbortSignal): Promise<Settled> {
|
|
36
|
+
return new Promise((resolve) => {
|
|
37
|
+
const settle = (value: Settled) => {
|
|
38
|
+
this.#pending = null;
|
|
39
|
+
signal.removeEventListener("abort", onAbort);
|
|
40
|
+
this.#changed();
|
|
41
|
+
resolve(value);
|
|
42
|
+
};
|
|
43
|
+
const onAbort = () => settle({ error: "The user aborted the turn." });
|
|
44
|
+
signal.addEventListener("abort", onAbort);
|
|
45
|
+
this.#pending = {
|
|
46
|
+
callId,
|
|
47
|
+
...asked,
|
|
48
|
+
answer: (value) => settle({ result: value }),
|
|
49
|
+
dismiss: (reason) => settle({ error: reason ?? SessionQuestion.dismissed }),
|
|
50
|
+
};
|
|
51
|
+
this.#changed();
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Puts back a question a restored transcript ends on, which a run asked while no chat was open; settling it hands
|
|
57
|
+
* the result to `resume` once, and a turn that starts first takes it down, leaving the call to the wire's closing.
|
|
58
|
+
*/
|
|
59
|
+
reopen(messages: readonly ChatMessage[], resume: (result: ToolCallResult) => void) {
|
|
60
|
+
const call = SessionQuestion.openCall(messages);
|
|
61
|
+
const asked = call ? SessionQuestion.#asked(call) : null;
|
|
62
|
+
if (!call || !asked) return;
|
|
63
|
+
const settle = (value: Settled) => {
|
|
64
|
+
if (this.#pending !== question) return;
|
|
65
|
+
this.#pending = null;
|
|
66
|
+
resume({ id: call.id, name: call.name, ...value });
|
|
67
|
+
};
|
|
68
|
+
const question: PendingQuestion = {
|
|
69
|
+
callId: call.id,
|
|
70
|
+
...asked,
|
|
71
|
+
answer: (value) => settle({ result: value }),
|
|
72
|
+
dismiss: (reason) => settle({ error: reason ?? SessionQuestion.dismissed }),
|
|
73
|
+
};
|
|
74
|
+
this.#pending = question;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
static openCall(messages: readonly ChatMessage[]): ToolCallRequest | null {
|
|
78
|
+
const last = messages.findLast((message) => message.role !== "tool" && Transcript.carries(message));
|
|
79
|
+
if (last?.role !== "assistant") return null;
|
|
80
|
+
const answered = new Set(messages.flatMap((message) => (message.toolResults ?? []).map((result) => result.id)));
|
|
81
|
+
const call = last.toolCalls?.find((one) => !answered.has(one.id));
|
|
82
|
+
return call?.name === SessionQuestion.toolName && SessionQuestion.#asked(call) ? call : null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
static #asked({ args }: ToolCallRequest): Asked | null {
|
|
86
|
+
const question = typeof args.question === "string" ? args.question.trim() : "";
|
|
87
|
+
if (!question) return null;
|
|
88
|
+
|
|
89
|
+
const choices = [
|
|
90
|
+
...new Set(
|
|
91
|
+
(Array.isArray(args.choices) ? args.choices : [])
|
|
92
|
+
.filter((choice): choice is string => typeof choice === "string")
|
|
93
|
+
.map((choice) => choice.trim())
|
|
94
|
+
.filter(Boolean),
|
|
95
|
+
),
|
|
96
|
+
];
|
|
97
|
+
return { question, choices, multiple: args.multiple === true && choices.length > 1 };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -62,7 +62,7 @@ export class Transcript {
|
|
|
62
62
|
return message.usage ? { ...message, usage: undefined } : message;
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
-
static sanitize(messages: readonly ChatMessage[]): ChatMessage[] {
|
|
65
|
+
static sanitize(messages: readonly ChatMessage[], openCallId?: string): ChatMessage[] {
|
|
66
66
|
const answered = new Set(messages.flatMap((message) => (message.toolResults ?? []).map((result) => result.id)));
|
|
67
67
|
const called = new Set<string>();
|
|
68
68
|
const kept: ChatMessage[] = [];
|
|
@@ -76,7 +76,7 @@ export class Transcript {
|
|
|
76
76
|
kept.push(message);
|
|
77
77
|
const calls = message.toolCalls ?? [];
|
|
78
78
|
for (const call of calls) called.add(call.id);
|
|
79
|
-
const unanswered = calls.filter((call) => !answered.has(call.id));
|
|
79
|
+
const unanswered = calls.filter((call) => !answered.has(call.id) && call.id !== openCallId);
|
|
80
80
|
|
|
81
81
|
if (unanswered.length)
|
|
82
82
|
kept.push({
|