akanjs 3.2.0-rc.22 → 3.2.0-rc.24
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 +40 -0
- package/package.json +1 -1
- package/service/agentLoop/agentLoop.ts +51 -15
- package/service/agentLoop/agentLoopTypes.ts +14 -3
- package/service/agentLoop/loopAsk.ts +44 -0
- package/service/agentLoop/loopCompaction.ts +5 -1
- package/service/agentLoop/loopRequest.ts +4 -1
- package/signal/agentTurnStream.ts +7 -2
- package/types/server/logging/rotatingLogWriter.d.ts +1 -1
- package/types/service/agentLoop/agentLoopTypes.d.ts +14 -2
- package/types/service/agentLoop/loopAsk.d.ts +12 -0
- package/types/service/agentLoop/loopCompaction.d.ts +2 -1
- package/types/service/agentLoop/loopRequest.d.ts +1 -1
- package/types/signal/agentTurnStream.d.ts +1 -0
- 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/Compaction.d.ts +3 -1
- package/types/vendor/use-agentic/SessionQuestion.d.ts +26 -0
- package/types/vendor/use-agentic/Transcript.d.ts +1 -1
- package/types/vendor/use-agentic/types.d.ts +6 -3
- 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 +24 -62
- package/vendor/use-agentic/CHANGELOG.md +21 -0
- package/vendor/use-agentic/Compaction.ts +10 -1
- package/vendor/use-agentic/SessionQuestion.ts +99 -0
- package/vendor/use-agentic/Transcript.ts +2 -2
- package/vendor/use-agentic/WIRE.md +4 -2
- package/vendor/use-agentic/httpRunner.ts +7 -4
- package/vendor/use-agentic/types.ts +7 -1
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.
|
|
@@ -34,6 +45,17 @@
|
|
|
34
45
|
|
|
35
46
|
Both are new and optional, so no upgrade step is needed.
|
|
36
47
|
|
|
48
|
+
- 3ebf990: `agentService.loop` now recovers from a model call refused for length, the way the in-page chat does, instead of ending the run. Both now read a refusal's `limit` in the refusal's own unit when it also gives `requested`.
|
|
49
|
+
|
|
50
|
+
- With `compact` set, a round whose call fails as `agent.error.contextOverflow` compacts at once, whatever `at` says, emits `compacted` as usual, and asks again.
|
|
51
|
+
- The retry is part of the same round. A second refusal, a transcript with nothing to cut, or a summary that fails ends the run with the original error, as before.
|
|
52
|
+
- The refused attempt is metered as a `failed` turn with what the provider counted, which is nothing for a refusal an adaptor makes before any network call.
|
|
53
|
+
- When the refusal's data carries `limit` and `requested`, the run lowers `at` for its remaining rounds to where that request would have fit, so the next one compacts ahead instead of being refused.
|
|
54
|
+
- The relay now forwards `requested` beside `limit` on the wire's `overflow` (`TurnOverflow`). Given both, the chat scales its own estimate of the refused prompt by `limit / requested` to get the window it adopts. Given `limit` alone, the chat still takes it as the window in tokens.
|
|
55
|
+
- The two numbers may be in any unit, as long as it is the same one. An adaptor that caps the request body in bytes can throw `new Err("agent.error.contextOverflow", { limit, requested })` with its own byte counts, and neither the loop nor the chat mistakes them for tokens.
|
|
56
|
+
|
|
57
|
+
A run without `compact` ends on the refusal as before. With `compact` set, a refused round now costs up to two more model calls (the summary and the retry) before the run ends. `AgentTurnStream.failure(...).overflow` and `RunnerEvent`'s error `overflow` gain an optional `requested`; code reading only `limit` needs no change.
|
|
58
|
+
|
|
37
59
|
- 2da2adc: `agentService.loop` takes `toolkits`, so a run over a large catalogue no longer sends every tool definition every round.
|
|
38
60
|
|
|
39
61
|
- **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.
|
|
@@ -82,6 +104,14 @@
|
|
|
82
104
|
|
|
83
105
|
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
106
|
|
|
107
|
+
- 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`.
|
|
108
|
+
|
|
109
|
+
- 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.
|
|
110
|
+
- 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.
|
|
111
|
+
- `DefaultToolRow` and `ToolRowProps` are exported from `akanjs/ui`, so a replacement can wrap the default.
|
|
112
|
+
|
|
113
|
+
The default row is unchanged, so no upgrade step is needed.
|
|
114
|
+
|
|
85
115
|
- eb88032: A service can now run the `/mcp` tool catalogue in-process, as a given account, with `plug(AgentToolsRole)`.
|
|
86
116
|
|
|
87
117
|
- **`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.
|
|
@@ -251,6 +281,16 @@
|
|
|
251
281
|
- **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
282
|
- **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
283
|
|
|
284
|
+
- 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.
|
|
285
|
+
|
|
286
|
+
- The session's `pendingQuestion` holds the question, so `Agent.Chat` draws its card and the composer answers it as usual.
|
|
287
|
+
- 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.
|
|
288
|
+
- A turn started first, `reset()` and `compact()` take the question down. The call is then closed as unanswered on the wire, as before.
|
|
289
|
+
- 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.
|
|
290
|
+
- `Transcript.sanitize(messages, openCallId?)` takes the id of one call to leave unanswered.
|
|
291
|
+
|
|
292
|
+
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.
|
|
293
|
+
|
|
254
294
|
- 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
295
|
|
|
256
296
|
`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`).
|
package/package.json
CHANGED
|
@@ -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;
|
|
@@ -68,6 +70,7 @@ export class AgentLoop {
|
|
|
68
70
|
#toolCalls = 0;
|
|
69
71
|
#tainted: boolean = false;
|
|
70
72
|
#compactFloor = 0;
|
|
73
|
+
#overflowAt = Number.POSITIVE_INFINITY;
|
|
71
74
|
|
|
72
75
|
constructor(port: AgentLoopPort, request: AgentLoopRequest) {
|
|
73
76
|
this.#port = port;
|
|
@@ -75,6 +78,7 @@ export class AgentLoop {
|
|
|
75
78
|
this.#messages = Array.isArray(request.messages) ? [...request.messages] : [];
|
|
76
79
|
this.#signal = request.signal ? AbortSignal.any([request.signal, this.#halt.signal]) : this.#halt.signal;
|
|
77
80
|
this.#toolkits = new LoopToolkits(request.toolkits);
|
|
81
|
+
this.#askUser = new LoopAsk(request.ask);
|
|
78
82
|
}
|
|
79
83
|
|
|
80
84
|
async *run(): Events<void> {
|
|
@@ -104,7 +108,9 @@ export class AgentLoop {
|
|
|
104
108
|
async *#drive(): Events<AgentLoopStop> {
|
|
105
109
|
this.#toolkits.restore(this.#messages);
|
|
106
110
|
this.#tainted = LoopTranscript.markedTainted(this.#messages, !!this.#request.untrusted);
|
|
107
|
-
|
|
111
|
+
|
|
112
|
+
for (const result of LoopTranscript.results(this.#messages))
|
|
113
|
+
if (!this.#askUser.isMeta(result.name)) this.#taintBy(result);
|
|
108
114
|
const pending = LoopTranscript.pending(this.#messages);
|
|
109
115
|
if (pending.length) {
|
|
110
116
|
if (!(await this.#authorize())) return "unauthorized";
|
|
@@ -154,12 +160,12 @@ export class AgentLoop {
|
|
|
154
160
|
const taken = new Set(visible.map((tool) => tool.name));
|
|
155
161
|
|
|
156
162
|
const client = (this.#request.clientTools ?? []).filter((tool) => {
|
|
157
|
-
if (taken.has(tool.name) || this.#toolkits.isMeta(tool.name)) return false;
|
|
163
|
+
if (taken.has(tool.name) || this.#toolkits.isMeta(tool.name) || this.#askUser.isMeta(tool.name)) return false;
|
|
158
164
|
taken.add(tool.name);
|
|
159
165
|
return true;
|
|
160
166
|
});
|
|
161
167
|
this.#clientNames = new Set(client.map((tool) => tool.name));
|
|
162
|
-
return [...listed, ...client.map(AgentLoop.#clientTool)];
|
|
168
|
+
return [...listed, ...client.map(AgentLoop.#clientTool), ...this.#askUser.listed()];
|
|
163
169
|
}
|
|
164
170
|
|
|
165
171
|
static #clientTool({ name, description, parameters, readOnly, needsConfirm }: AgentTool): AgentTool {
|
|
@@ -173,16 +179,37 @@ export class AgentLoop {
|
|
|
173
179
|
}
|
|
174
180
|
|
|
175
181
|
async *#ask(tools: AgentTool[]): Events<AgentLoopAnswer> {
|
|
182
|
+
const preamble = this.#request.preamble ?? false;
|
|
183
|
+
const request = this.#turnOf(tools);
|
|
184
|
+
try {
|
|
185
|
+
return yield* this.#metered(request, preamble, true);
|
|
186
|
+
} catch (error) {
|
|
187
|
+
if (!this.#request.compact || !Err.is(error, "agent.error.contextOverflow")) throw error;
|
|
188
|
+
this.#learnOverflow(error.data, request);
|
|
189
|
+
|
|
190
|
+
if (!(yield* this.#compact(true))) throw error;
|
|
191
|
+
}
|
|
192
|
+
return yield* this.#metered(this.#turnOf(tools), preamble, true);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
#turnOf(tools: AgentTool[]): LlmTurnRequest {
|
|
176
196
|
const { context = [], model, preamble } = this.#request;
|
|
177
197
|
const instructions = this.#request.instructions || (preamble ? "" : AgentLoop.noInstructions);
|
|
178
|
-
|
|
198
|
+
return {
|
|
179
199
|
messages: LoopTranscript.wire(this.#messages),
|
|
180
200
|
tools: tools.map(({ readOnly: _readOnly, ...tool }) => tool),
|
|
181
201
|
context,
|
|
182
202
|
...(instructions ? { instructions } : {}),
|
|
183
203
|
...(model ? { model } : {}),
|
|
184
204
|
};
|
|
185
|
-
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
#learnOverflow(data: Record<string, unknown> | undefined, request: LlmTurnRequest) {
|
|
208
|
+
const { limit, requested } = data ?? {};
|
|
209
|
+
if (typeof limit !== "number" || typeof requested !== "number" || !(limit > 0 && requested > limit)) return;
|
|
210
|
+
const frame = LoopCompaction.frameTokensOf(request);
|
|
211
|
+
const fits = Math.floor(((LoopCompaction.tokensOf(this.#messages) + frame) * limit) / requested) - frame;
|
|
212
|
+
if (fits > 0) this.#overflowAt = Math.min(this.#overflowAt, fits);
|
|
186
213
|
}
|
|
187
214
|
|
|
188
215
|
async *#metered(request: LlmTurnRequest, preamble: string | false, streamed: boolean): Events<AgentLoopAnswer> {
|
|
@@ -216,12 +243,13 @@ export class AgentLoop {
|
|
|
216
243
|
return answer;
|
|
217
244
|
}
|
|
218
245
|
|
|
219
|
-
async *#compact(): Events<
|
|
246
|
+
async *#compact(forced = false): Events<boolean> {
|
|
220
247
|
const { compact, model, untrusted } = this.#request;
|
|
221
|
-
if (!compact) return;
|
|
222
|
-
|
|
248
|
+
if (!compact) return false;
|
|
249
|
+
const threshold = Math.min(compact.at, this.#overflowAt);
|
|
250
|
+
if (!forced && LoopCompaction.tokensOf(this.#messages) < Math.max(threshold, this.#compactFloor)) return false;
|
|
223
251
|
const at = LoopCompaction.cutAt(this.#messages, compact.keep ?? LoopCompaction.keep);
|
|
224
|
-
if (at <= 0) return;
|
|
252
|
+
if (at <= 0) return false;
|
|
225
253
|
const digest = LoopCompaction.digest(this.#messages.slice(0, at));
|
|
226
254
|
let text = "";
|
|
227
255
|
try {
|
|
@@ -237,9 +265,9 @@ export class AgentLoop {
|
|
|
237
265
|
if (this.#haltedBy(error)) throw error;
|
|
238
266
|
|
|
239
267
|
AgentLoop.#logger.warn(`agent loop compaction failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
240
|
-
return;
|
|
268
|
+
return false;
|
|
241
269
|
}
|
|
242
|
-
if (!text) return;
|
|
270
|
+
if (!text) return false;
|
|
243
271
|
const summary = LoopCompaction.message(
|
|
244
272
|
text,
|
|
245
273
|
this.#tainted || untrusted ? this.#tainted : undefined,
|
|
@@ -248,8 +276,9 @@ export class AgentLoop {
|
|
|
248
276
|
this.#messages.splice(0, at, summary);
|
|
249
277
|
const after = LoopCompaction.tokensOf(this.#messages);
|
|
250
278
|
|
|
251
|
-
this.#compactFloor = after >=
|
|
279
|
+
this.#compactFloor = after >= threshold ? after + threshold : 0;
|
|
252
280
|
yield { type: "compacted", replaced: at, summary };
|
|
281
|
+
return true;
|
|
253
282
|
}
|
|
254
283
|
|
|
255
284
|
async *#runCalls(calls: AgentWireToolCall[], tools: AgentTool[]): Events<AgentLoopStop | null> {
|
|
@@ -269,17 +298,24 @@ export class AgentLoop {
|
|
|
269
298
|
try {
|
|
270
299
|
for (const [at, call] of calls.entries()) {
|
|
271
300
|
const verdict = verdicts[at] ?? { deny: AgentLoop.unjudged };
|
|
272
|
-
const
|
|
301
|
+
const asked = this.#askUser.isMeta(call.name);
|
|
302
|
+
const meta = asked || this.#toolkits.isMeta(call.name);
|
|
273
303
|
stop = this.#haltStop() ?? (verdict === "allow" && !meta ? this.#callBudgetStop() : null);
|
|
274
304
|
if (stop) break;
|
|
305
|
+
const unasked = asked ? LoopAsk.refusalOf(call) : null;
|
|
275
306
|
|
|
307
|
+
if (asked && !unasked) {
|
|
308
|
+
yield { type: "awaiting", call, question: true };
|
|
309
|
+
stop = "awaiting";
|
|
310
|
+
break;
|
|
311
|
+
}
|
|
276
312
|
if (verdict === "allow" && this.#clientNames.has(call.name)) {
|
|
277
313
|
this.#toolCalls += 1;
|
|
278
314
|
yield { type: "awaiting", call, client: true };
|
|
279
315
|
stop = "awaiting";
|
|
280
316
|
break;
|
|
281
317
|
}
|
|
282
|
-
const whole = meta ? this.#toolkits.open(call) : await this.#execute(call, verdict);
|
|
318
|
+
const whole = unasked ?? (meta ? this.#toolkits.open(call) : await this.#execute(call, verdict));
|
|
283
319
|
const result = LoopToolOutput.clipped(whole);
|
|
284
320
|
results.push(result);
|
|
285
321
|
|
|
@@ -295,7 +331,7 @@ export class AgentLoop {
|
|
|
295
331
|
}
|
|
296
332
|
|
|
297
333
|
async #verdictOf(call: AgentWireToolCall, tool: AgentTool | undefined): Promise<Verdict> {
|
|
298
|
-
if (this.#toolkits.isMeta(call.name)) return "allow";
|
|
334
|
+
if (this.#toolkits.isMeta(call.name) || this.#askUser.isMeta(call.name)) return "allow";
|
|
299
335
|
|
|
300
336
|
if (!tool) {
|
|
301
337
|
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,7 +74,18 @@ export interface AgentLoopOptions {
|
|
|
74
74
|
* an endpoint tool or `openToolkit` holds is dropped.
|
|
75
75
|
*/
|
|
76
76
|
clientTools?: AgentTool[];
|
|
77
|
-
/**
|
|
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;
|
|
84
|
+
/**
|
|
85
|
+
* Summarizes all but the last `keep` messages (6) once the transcript is estimated at `at` tokens, and also when a
|
|
86
|
+
* round's call fails as `agent.error.contextOverflow`, which is then asked again once. A refusal whose data carries
|
|
87
|
+
* `limit` and `requested`, in any one unit, lowers `at` for the rest of the run to where the request would fit.
|
|
88
|
+
*/
|
|
78
89
|
compact?: { at: number; keep?: number };
|
|
79
90
|
/** Asked before every call; without it a `needsConfirm` tool is refused, and so is any write once tainted. */
|
|
80
91
|
approve?: AgentLoopApprove;
|
|
@@ -107,6 +118,6 @@ export type AgentLoopEvent =
|
|
|
107
118
|
* whole: its `tainted` carries the run's taint across a resume.
|
|
108
119
|
*/
|
|
109
120
|
| { type: "compacted"; replaced: number; summary: AgentWireMessage }
|
|
110
|
-
| { type: "awaiting"; call: AgentWireToolCall; client?: true }
|
|
121
|
+
| { type: "awaiting"; call: AgentWireToolCall; client?: true; question?: true }
|
|
111
122
|
| { type: "done"; stop: AgentLoopStop; rounds: number }
|
|
112
123
|
| { 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,4 +1,4 @@
|
|
|
1
|
-
import type { AgentWireAttachment, AgentWireMessage } from "../predefinedAdaptor/llm.adaptor";
|
|
1
|
+
import type { AgentWireAttachment, AgentWireMessage, LlmTurnRequest } from "../predefinedAdaptor/llm.adaptor";
|
|
2
2
|
import { LoopTranscript } from "./loopTranscript";
|
|
3
3
|
|
|
4
4
|
export class LoopCompaction {
|
|
@@ -20,6 +20,10 @@ export class LoopCompaction {
|
|
|
20
20
|
return Math.ceil(chars / 4);
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
static frameTokensOf({ messages: _messages, ...frame }: LlmTurnRequest): number {
|
|
24
|
+
return Math.ceil(JSON.stringify(frame).length / 4);
|
|
25
|
+
}
|
|
26
|
+
|
|
23
27
|
static #charsOf(message: AgentWireMessage): number {
|
|
24
28
|
const own = LoopCompaction.#blanked(message.attachments);
|
|
25
29
|
let images = own.images;
|
|
@@ -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);
|
|
@@ -25,7 +25,7 @@ export class AgentTurnStream {
|
|
|
25
25
|
message: string;
|
|
26
26
|
code: string;
|
|
27
27
|
data?: Record<string, string | number>;
|
|
28
|
-
overflow?: { limit?: number };
|
|
28
|
+
overflow?: { limit?: number; requested?: number };
|
|
29
29
|
} {
|
|
30
30
|
const status = isExceptionLike(error) ? error.statusCode : SignalFailure.generalized(error).statusCode;
|
|
31
31
|
const code = SignalFailure.codeOf(error, status);
|
|
@@ -40,7 +40,12 @@ export class AgentTurnStream {
|
|
|
40
40
|
raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record<string, string | number>) : null;
|
|
41
41
|
|
|
42
42
|
const overflow =
|
|
43
|
-
message === "agent.error.contextOverflow"
|
|
43
|
+
message === "agent.error.contextOverflow"
|
|
44
|
+
? {
|
|
45
|
+
...(typeof data?.limit === "number" ? { limit: data.limit } : {}),
|
|
46
|
+
...(typeof data?.requested === "number" ? { requested: data.requested } : {}),
|
|
47
|
+
}
|
|
48
|
+
: null;
|
|
44
49
|
return { message, code, ...(data ? { data } : {}), ...(overflow ? { overflow } : {}) };
|
|
45
50
|
}
|
|
46
51
|
|
|
@@ -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
|
}
|
|
@@ -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,7 +56,18 @@ export interface AgentLoopOptions {
|
|
|
56
56
|
* an endpoint tool or `openToolkit` holds is dropped.
|
|
57
57
|
*/
|
|
58
58
|
clientTools?: AgentTool[];
|
|
59
|
-
/**
|
|
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;
|
|
66
|
+
/**
|
|
67
|
+
* Summarizes all but the last `keep` messages (6) once the transcript is estimated at `at` tokens, and also when a
|
|
68
|
+
* round's call fails as `agent.error.contextOverflow`, which is then asked again once. A refusal whose data carries
|
|
69
|
+
* `limit` and `requested`, in any one unit, lowers `at` for the rest of the run to where the request would fit.
|
|
70
|
+
*/
|
|
60
71
|
compact?: {
|
|
61
72
|
at: number;
|
|
62
73
|
keep?: number;
|
|
@@ -115,6 +126,7 @@ export type AgentLoopEvent = {
|
|
|
115
126
|
type: "awaiting";
|
|
116
127
|
call: AgentWireToolCall;
|
|
117
128
|
client?: true;
|
|
129
|
+
question?: true;
|
|
118
130
|
} | {
|
|
119
131
|
type: "done";
|
|
120
132
|
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
|
+
}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import type { AgentWireMessage } from "../predefinedAdaptor/llm.adaptor";
|
|
1
|
+
import type { AgentWireMessage, LlmTurnRequest } from "../predefinedAdaptor/llm.adaptor";
|
|
2
2
|
export declare class LoopCompaction {
|
|
3
3
|
#private;
|
|
4
4
|
static readonly keep = 6;
|
|
5
5
|
static readonly imageTokens = 1600;
|
|
6
6
|
static readonly instruction: string;
|
|
7
7
|
static tokensOf(messages: readonly AgentWireMessage[]): number;
|
|
8
|
+
static frameTokensOf({ messages: _messages, ...frame }: LlmTurnRequest): number;
|
|
8
9
|
static cutAt(messages: readonly AgentWireMessage[], keep: number): number;
|
|
9
10
|
static digest(messages: readonly AgentWireMessage[], budget?: number): string;
|
|
10
11
|
static message(summary: string, tainted?: boolean, toolkits?: string[]): AgentWireMessage;
|
|
@@ -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";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ChatMessage, ToolCallResult, TurnLimits } from "./types.d.ts";
|
|
1
|
+
import type { ChatMessage, RunnerRequest, ToolCallResult, TurnLimits, TurnOverflow } from "./types.d.ts";
|
|
2
2
|
export interface CompactOptions {
|
|
3
3
|
/**
|
|
4
4
|
* Estimated transcript tokens above which a turn summarizes its own history first — a ceiling on what each turn
|
|
@@ -52,6 +52,7 @@ export declare class Compaction {
|
|
|
52
52
|
static tokensOf(messages: readonly ChatMessage[]): number;
|
|
53
53
|
/** One tool result as it rides the wire, by the same rule. */
|
|
54
54
|
static resultTokensOf(result: ToolCallResult): number;
|
|
55
|
+
static frameTokensOf(frame: Omit<RunnerRequest, "messages" | "signal">): number;
|
|
55
56
|
/**
|
|
56
57
|
* What the next request is estimated to cost, prompt and all: the provider's own count for the last turn that
|
|
57
58
|
* reported one, plus four characters a token for what the transcript gained since. The provider's number is the
|
|
@@ -60,6 +61,7 @@ export declare class Compaction {
|
|
|
60
61
|
* transcript: the tools, the screen context and the instructions.
|
|
61
62
|
*/
|
|
62
63
|
static promptTokensOf(messages: readonly ChatMessage[], overhead: () => number): number;
|
|
64
|
+
static windowOf({ limit, requested }: TurnOverflow, messages: readonly ChatMessage[], overhead: number): number | undefined;
|
|
63
65
|
/**
|
|
64
66
|
* The prompt size past which a turn compacts first, or `Infinity` while the window is unknown. The answer shares
|
|
65
67
|
* the window with the prompt, so its ceiling is held back along with `buffer`.
|
|
@@ -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
|
}
|
|
@@ -300,10 +300,13 @@ export type RunnerEvent = {
|
|
|
300
300
|
message: string;
|
|
301
301
|
code?: string;
|
|
302
302
|
data?: Record<string, string | number>;
|
|
303
|
-
overflow?:
|
|
304
|
-
limit?: number;
|
|
305
|
-
};
|
|
303
|
+
overflow?: TurnOverflow;
|
|
306
304
|
};
|
|
305
|
+
/** `limit` alone is a window in tokens; with `requested` beside it, both are in the refusal's own unit, bytes included. */
|
|
306
|
+
export interface TurnOverflow {
|
|
307
|
+
limit?: number;
|
|
308
|
+
requested?: number;
|
|
309
|
+
}
|
|
307
310
|
export interface RunnerRequest {
|
|
308
311
|
messages: ChatMessage[];
|
|
309
312
|
tools: PublishedTool[];
|