@oh-my-pi/pi-agent-core 19.2.0 → 19.3.0
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 +33 -0
- package/dist/types/agent-loop.d.ts +3 -0
- package/dist/types/agent.d.ts +25 -3
- package/dist/types/append-only-context.d.ts +3 -0
- package/dist/types/compaction/compaction.d.ts +19 -2
- package/dist/types/compaction/messages.d.ts +2 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/inherited-tool-descriptions.d.ts +23 -0
- package/dist/types/types.d.ts +16 -2
- package/package.json +12 -12
- package/src/agent-loop.ts +72 -7
- package/src/agent.ts +83 -42
- package/src/append-only-context.ts +9 -1
- package/src/compaction/compaction.ts +125 -99
- package/src/compaction/messages.ts +2 -0
- package/src/compaction/shake.ts +3 -1
- package/src/index.ts +2 -0
- package/src/inherited-tool-descriptions.ts +43 -0
- package/src/telemetry.ts +6 -5
- package/src/tokenizer.ts +69 -19
- package/src/types.ts +20 -2
package/src/agent.ts
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
streamSimple,
|
|
20
20
|
type TextContent,
|
|
21
21
|
type ThinkingBudgets,
|
|
22
|
+
type Tool,
|
|
22
23
|
type ToolChoice,
|
|
23
24
|
type ToolResultMessage,
|
|
24
25
|
} from "@oh-my-pi/pi-ai";
|
|
@@ -27,7 +28,7 @@ import * as AIError from "@oh-my-pi/pi-ai/error";
|
|
|
27
28
|
import { openAIResponsesReplaysNativeHistory } from "@oh-my-pi/pi-ai/providers/openai-responses-state";
|
|
28
29
|
import type { HarmonyAuditEvent } from "@oh-my-pi/pi-ai/utils/harmony-leak";
|
|
29
30
|
import { getBundledModel } from "@oh-my-pi/pi-catalog/models";
|
|
30
|
-
import { logger } from "@oh-my-pi/pi-utils";
|
|
31
|
+
import { Laps, logger } from "@oh-my-pi/pi-utils";
|
|
31
32
|
import {
|
|
32
33
|
AgentLoopError,
|
|
33
34
|
abortReasonText,
|
|
@@ -45,6 +46,7 @@ import {
|
|
|
45
46
|
import type { AppendOnlyContextManager } from "./append-only-context";
|
|
46
47
|
import { agentPauseGate } from "./pause";
|
|
47
48
|
import { filterProviderReplayMessages } from "./replay-policy";
|
|
49
|
+
import { InheritedToolDescriptions } from "./inherited-tool-descriptions";
|
|
48
50
|
import { SentToolDefinitions } from "./sent-tool-definitions";
|
|
49
51
|
import { Tokenizer } from "./tokenizer";
|
|
50
52
|
import {
|
|
@@ -510,6 +512,7 @@ export class Agent {
|
|
|
510
512
|
#intentTracing: boolean;
|
|
511
513
|
#intentDescription?: string;
|
|
512
514
|
#pruneToolDescriptions: boolean;
|
|
515
|
+
#inheritedToolDescriptions?: InheritedToolDescriptions;
|
|
513
516
|
#dialect?: Dialect;
|
|
514
517
|
#dialectResolver?: (model: Model) => Dialect | undefined;
|
|
515
518
|
#abortOnFabricatedToolResult?: boolean;
|
|
@@ -684,6 +687,36 @@ export class Agent {
|
|
|
684
687
|
return this.#sentToolDefinitions.copy(keep);
|
|
685
688
|
}
|
|
686
689
|
|
|
690
|
+
/**
|
|
691
|
+
* Provider-bound specs of the tools the next request to the active model declares, before the
|
|
692
|
+
* provider-context transform; empty without a model or under an owned dialect. A fork passes
|
|
693
|
+
* its owner's to {@link inheritToolDescriptions}.
|
|
694
|
+
*/
|
|
695
|
+
normalizedTools(): Tool[] {
|
|
696
|
+
const model = this.#state.model;
|
|
697
|
+
if (!model || this.#ownedDialect(model)) return [];
|
|
698
|
+
return normalizeTools(this.#toolsForModel(model), this.#toolOptions()) ?? [];
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/**
|
|
702
|
+
* Send `owner`'s wording for every current tool that differs from it only in description, so
|
|
703
|
+
* this fork's requests open with the owner's cached prefix. Call once the fork's tool set is
|
|
704
|
+
* final; see {@link InheritedToolDescriptions}.
|
|
705
|
+
*/
|
|
706
|
+
inheritToolDescriptions(owner: readonly Tool[]): void {
|
|
707
|
+
this.#inheritedToolDescriptions = undefined;
|
|
708
|
+
this.#inheritedToolDescriptions = new InheritedToolDescriptions(this.normalizedTools(), owner);
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
#toolOptions(): NormalizeToolsOptions {
|
|
712
|
+
return {
|
|
713
|
+
injectIntent: this.#intentTracing,
|
|
714
|
+
intentDescription: this.#intentDescription,
|
|
715
|
+
pruneDescriptions: this.#pruneToolDescriptions,
|
|
716
|
+
inheritedDescriptions: this.#inheritedToolDescriptions,
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
|
|
687
720
|
/**
|
|
688
721
|
* Fields added to every log record written while this agent runs (the
|
|
689
722
|
* owning session's `sessionId`), so in-process agents' records stay apart.
|
|
@@ -1000,11 +1033,7 @@ export class Agent {
|
|
|
1000
1033
|
if (!model) throw new Error("No active model on agent");
|
|
1001
1034
|
const ownedDialect = this.#ownedDialect(model);
|
|
1002
1035
|
const messages = normalizeMessagesForProvider(llmMessages, model);
|
|
1003
|
-
const toolOptions
|
|
1004
|
-
injectIntent: this.#intentTracing,
|
|
1005
|
-
intentDescription: this.#intentDescription,
|
|
1006
|
-
pruneDescriptions: this.#pruneToolDescriptions,
|
|
1007
|
-
};
|
|
1036
|
+
const toolOptions = this.#toolOptions();
|
|
1008
1037
|
const tools = ownedDialect ? [] : (normalizeTools(this.#toolsForModel(model), toolOptions) ?? []);
|
|
1009
1038
|
const standby = ownedDialect ? undefined : normalizeTools(this.#standbyTools, toolOptions);
|
|
1010
1039
|
let context: Context = { systemPrompt, messages, tools };
|
|
@@ -1063,16 +1092,22 @@ export class Agent {
|
|
|
1063
1092
|
for (const hook of this.#beforeQueuedMessageDequeueHooks) await hook(signal);
|
|
1064
1093
|
}
|
|
1065
1094
|
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1095
|
+
/**
|
|
1096
|
+
* Run the before-dequeue hooks, then take and prepare `queue`'s next batch. Logs at debug how
|
|
1097
|
+
* long each took: queued input shows nowhere new until its turn's request opens.
|
|
1098
|
+
*/
|
|
1099
|
+
async #dequeueAfterHooks(queue: QueuedMessageQueue, signal: AbortSignal): Promise<AgentMessage[]> {
|
|
1100
|
+
const pending = queue === "steering" ? this.#steeringQueue : this.#followUpQueue;
|
|
1101
|
+
if (signal.aborted || pending.length === 0) return [];
|
|
1102
|
+
const laps = new Laps();
|
|
1074
1103
|
await this.#runBeforeQueuedMessageDequeueHooks(signal);
|
|
1075
|
-
|
|
1104
|
+
laps.lap("hooksMs");
|
|
1105
|
+
if (signal.aborted) return [];
|
|
1106
|
+
const messages = await this.#prepareQueuedMessageBatch(queue, signal);
|
|
1107
|
+
laps.lap("prepareMs");
|
|
1108
|
+
if (messages.length > 0)
|
|
1109
|
+
logger.debug("Queued messages dequeued", { queue, count: messages.length, ...laps.record() });
|
|
1110
|
+
return messages;
|
|
1076
1111
|
}
|
|
1077
1112
|
|
|
1078
1113
|
async #prepareQueuedMessageBatch(queue: QueuedMessageQueue, signal: AbortSignal): Promise<AgentMessage[]> {
|
|
@@ -1215,9 +1250,9 @@ export class Agent {
|
|
|
1215
1250
|
suppress(message, controller);
|
|
1216
1251
|
for (const context of additional ?? []) suppress(context, controller);
|
|
1217
1252
|
}
|
|
1218
|
-
// Every snapshot counts live-steered messages as pending, so clearing
|
|
1253
|
+
// Every snapshot counts live-steered and delivering messages as pending, so clearing
|
|
1219
1254
|
// them is a queue change even when the caller re-queues them right after.
|
|
1220
|
-
const
|
|
1255
|
+
const hadUndelivered = this.#liveSteered.length > 0 || this.#queuedMessageDeliveries.size > 0;
|
|
1221
1256
|
this.#liveSteered = [];
|
|
1222
1257
|
for (const delivery of this.#queuedMessageDeliveries) {
|
|
1223
1258
|
const pending = delivery.messages.slice(delivery.next);
|
|
@@ -1228,7 +1263,7 @@ export class Agent {
|
|
|
1228
1263
|
if (withdrawn.steering.length > 0 || withdrawn.followUp.length > 0) {
|
|
1229
1264
|
this.queuedMessageGate?.release([...withdrawn.steering, ...withdrawn.followUp]);
|
|
1230
1265
|
}
|
|
1231
|
-
if (
|
|
1266
|
+
if (hadUndelivered) this.#emitQueueChanged();
|
|
1232
1267
|
return withdrawn;
|
|
1233
1268
|
}
|
|
1234
1269
|
|
|
@@ -1477,6 +1512,8 @@ export class Agent {
|
|
|
1477
1512
|
for (const delivery of this.#queuedMessageDeliveries) {
|
|
1478
1513
|
if (delivery.messages[delivery.next] !== m) continue;
|
|
1479
1514
|
if (++delivery.next === delivery.messages.length) this.#queuedMessageDeliveries.delete(delivery);
|
|
1515
|
+
// It stops showing as on its way ({@link peekDeliveringMessages}) now that it is recorded.
|
|
1516
|
+
this.#emitQueueChanged();
|
|
1480
1517
|
break;
|
|
1481
1518
|
}
|
|
1482
1519
|
}
|
|
@@ -1592,8 +1629,16 @@ export class Agent {
|
|
|
1592
1629
|
* requeues them, so the session's empty-submit interrupt counts them as
|
|
1593
1630
|
* pending input even though {@link peekSteeringQueue} no longer does. */
|
|
1594
1631
|
peekUndeliveredQueuedMessages(): AgentMessage[] {
|
|
1595
|
-
|
|
1632
|
+
return [...this.peekLiveSteeredMessages(), ...this.peekDeliveringMessages()];
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
/** Messages dequeued from `queue` (both queues when omitted) for the next model request that the
|
|
1636
|
+
* transcript has not recorded yet, oldest first. Their events only emit once the request opens,
|
|
1637
|
+
* so queue displays keep listing them until then. */
|
|
1638
|
+
peekDeliveringMessages(queue?: QueuedMessageQueue): AgentMessage[] {
|
|
1639
|
+
const messages: AgentMessage[] = [];
|
|
1596
1640
|
for (const delivery of this.#queuedMessageDeliveries) {
|
|
1641
|
+
if (queue !== undefined && delivery.queue !== queue) continue;
|
|
1597
1642
|
for (let i = delivery.next; i < delivery.messages.length; i++) messages.push(delivery.messages[i]);
|
|
1598
1643
|
}
|
|
1599
1644
|
return messages;
|
|
@@ -1809,9 +1854,6 @@ export class Agent {
|
|
|
1809
1854
|
await this.#inLogContext(() => this.#runLoop(msgs, promptOptions));
|
|
1810
1855
|
}
|
|
1811
1856
|
|
|
1812
|
-
/**
|
|
1813
|
-
* Continue from current context (used for retries and resuming queued messages).
|
|
1814
|
-
*/
|
|
1815
1857
|
#continuationDequeueSignal(signal?: AbortSignal): AbortSignal | undefined {
|
|
1816
1858
|
const signals: AbortSignal[] = [];
|
|
1817
1859
|
if (this.#abortController) signals.push(this.#abortController.signal);
|
|
@@ -1830,15 +1872,20 @@ export class Agent {
|
|
|
1830
1872
|
return signals.length === 1 ? signals[0] : AbortSignal.any(signals);
|
|
1831
1873
|
}
|
|
1832
1874
|
|
|
1833
|
-
|
|
1875
|
+
/**
|
|
1876
|
+
* Retry the current context or start a turn with queued input. Set `queuedOnly`
|
|
1877
|
+
* to drain the queue without making a model call on its own when nothing is delivered.
|
|
1878
|
+
*/
|
|
1879
|
+
continue(signal?: AbortSignal, options?: { queuedOnly?: boolean }): Promise<void> {
|
|
1834
1880
|
// Queued-message hooks run before the loop and are this agent's work too.
|
|
1835
|
-
return this.#inLogContext(() => this.#continue(signal));
|
|
1881
|
+
return this.#inLogContext(() => this.#continue(signal, options));
|
|
1836
1882
|
}
|
|
1837
1883
|
|
|
1838
|
-
async #continue(signal?: AbortSignal) {
|
|
1884
|
+
async #continue(signal?: AbortSignal, options?: { queuedOnly?: boolean }) {
|
|
1839
1885
|
if (this.#state.isStreaming) {
|
|
1840
1886
|
throw new AgentBusyError();
|
|
1841
1887
|
}
|
|
1888
|
+
if (options?.queuedOnly && !this.hasQueuedMessages()) return;
|
|
1842
1889
|
|
|
1843
1890
|
const { promise, resolve } = Promise.withResolvers<void>();
|
|
1844
1891
|
this.#runningPrompt = promise;
|
|
@@ -1857,36 +1904,29 @@ export class Agent {
|
|
|
1857
1904
|
// model sees. A queued steer/follow-up is delivered as if they were absent; with nothing queued,
|
|
1858
1905
|
// continue from them as before and leave the tail to the caller's recovery.
|
|
1859
1906
|
const tail = lastContextMessage(messages);
|
|
1860
|
-
if (!tail || tail.role === "assistant") {
|
|
1861
|
-
//
|
|
1862
|
-
|
|
1863
|
-
// queued-message delivery: injecting a message between the tool_use
|
|
1864
|
-
// blocks and their results would break the provider's pairing
|
|
1865
|
-
// invariant. Queued messages drain inside the resumed loop instead.
|
|
1866
|
-
if (tail && unpairedToolCallTail([tail])) {
|
|
1907
|
+
if (options?.queuedOnly || !tail || tail.role === "assistant") {
|
|
1908
|
+
// Unanswered tool calls must run before queued messages to preserve tool/result pairing.
|
|
1909
|
+
if (tail?.role === "assistant" && unpairedToolCallTail([tail])) {
|
|
1867
1910
|
await this.#runLoop(undefined, undefined, signal, true);
|
|
1868
1911
|
return;
|
|
1869
1912
|
}
|
|
1870
|
-
//
|
|
1871
|
-
|
|
1872
|
-
// message undeliverable, and idle-drain callers
|
|
1873
|
-
// (AgentSession#scheduleQueuedMessageDrain) re-arm continue() on every
|
|
1874
|
-
// microtask because hasQueuedMessages() never clears, spinning an unbounded
|
|
1875
|
-
// allocation loop until OOM (issue #6344).
|
|
1876
|
-
const queuedSteering = await this.#dequeueSteeringMessagesAfterHooks(dequeueSignal);
|
|
1913
|
+
// Start with queued input, not an extra model call on the existing context.
|
|
1914
|
+
const queuedSteering = await this.#dequeueAfterHooks("steering", dequeueSignal);
|
|
1877
1915
|
if (this.#abortController !== continuationAbortController) return;
|
|
1878
1916
|
if (queuedSteering.length > 0) {
|
|
1879
1917
|
await this.#runLoop(queuedSteering, { skipInitialSteeringPoll: true }, signal, true);
|
|
1880
1918
|
return;
|
|
1881
1919
|
}
|
|
1882
1920
|
|
|
1883
|
-
const queuedFollowUp = await this.#
|
|
1921
|
+
const queuedFollowUp = await this.#dequeueAfterHooks("followUp", dequeueSignal);
|
|
1884
1922
|
if (this.#abortController !== continuationAbortController) return;
|
|
1885
1923
|
if (queuedFollowUp.length > 0) {
|
|
1886
1924
|
await this.#runLoop(queuedFollowUp, undefined, signal, true);
|
|
1887
1925
|
return;
|
|
1888
1926
|
}
|
|
1889
1927
|
|
|
1928
|
+
// A dequeue hook may withdraw the queued input while the drain starts.
|
|
1929
|
+
if (options?.queuedOnly) return;
|
|
1890
1930
|
if (!literalTail) throw new Error("No messages to continue from");
|
|
1891
1931
|
if (literalTail === tail) throw new Error("Cannot continue from message role: assistant");
|
|
1892
1932
|
}
|
|
@@ -2115,6 +2155,7 @@ export class Agent {
|
|
|
2115
2155
|
intentTracing: this.#intentTracing,
|
|
2116
2156
|
intentDescription: this.#intentDescription,
|
|
2117
2157
|
pruneToolDescriptions: this.#pruneToolDescriptions,
|
|
2158
|
+
inheritedToolDescriptions: this.#inheritedToolDescriptions,
|
|
2118
2159
|
dialect: this.#dialect,
|
|
2119
2160
|
getDialect: this.#dialectResolver,
|
|
2120
2161
|
abortOnFabricatedToolResult: this.#abortOnFabricatedToolResult,
|
|
@@ -2153,7 +2194,7 @@ export class Agent {
|
|
|
2153
2194
|
skipInitialSteeringPoll = false;
|
|
2154
2195
|
return [];
|
|
2155
2196
|
}
|
|
2156
|
-
return this.#
|
|
2197
|
+
return this.#dequeueAfterHooks("steering", signal ?? loopSignal);
|
|
2157
2198
|
},
|
|
2158
2199
|
isUndeliveredQueuedMessage: message => this.#isUndeliveredQueuedMessage(message),
|
|
2159
2200
|
hasSteeringMessages: () =>
|
|
@@ -2168,7 +2209,7 @@ export class Agent {
|
|
|
2168
2209
|
hasIrcInterrupts: this.hasIrcInterrupts,
|
|
2169
2210
|
hasBackgroundCompletions: this.hasBackgroundCompletions,
|
|
2170
2211
|
hasQueuedAsides: this.hasQueuedAsides,
|
|
2171
|
-
getFollowUpMessages: signal => this.#
|
|
2212
|
+
getFollowUpMessages: signal => this.#dequeueAfterHooks("followUp", signal ?? loopSignal),
|
|
2172
2213
|
getAsideMessages: async boundary => (await this.#asideMessageProvider?.(boundary)) ?? [],
|
|
2173
2214
|
onBeforeYield: () => this.#onBeforeYield?.(),
|
|
2174
2215
|
onDetachedToolUpdate: event => this.emitExternalEvent(event),
|
|
@@ -18,6 +18,7 @@ import type { AgentTool } from "./types";
|
|
|
18
18
|
import type { Context, Message, Tool } from "@oh-my-pi/pi-ai";
|
|
19
19
|
import { toolWireSchema } from "@oh-my-pi/pi-ai";
|
|
20
20
|
import { normalizeTools } from "./agent-loop";
|
|
21
|
+
import type { InheritedToolDescriptions } from "./inherited-tool-descriptions";
|
|
21
22
|
import { messageEstimateVersion } from "./compaction/message-cache";
|
|
22
23
|
import type { AgentContext, AgentMessage } from "./types";
|
|
23
24
|
|
|
@@ -86,6 +87,8 @@ export interface BuildOptions {
|
|
|
86
87
|
intentDescription?: string;
|
|
87
88
|
/** Strip tool descriptions from the provider-bound specs (must match normalizeTools). */
|
|
88
89
|
pruneToolDescriptions?: boolean;
|
|
90
|
+
/** A fork's owner-worded descriptions (must match normalizeTools). */
|
|
91
|
+
inheritedToolDescriptions?: InheritedToolDescriptions;
|
|
89
92
|
}
|
|
90
93
|
|
|
91
94
|
/**
|
|
@@ -140,6 +143,7 @@ export class StablePrefix {
|
|
|
140
143
|
#lastIntentTracing: boolean | undefined;
|
|
141
144
|
#lastIntentDescription: string | undefined;
|
|
142
145
|
#lastPruneToolDescriptions: boolean | undefined;
|
|
146
|
+
#lastInheritedToolDescriptions: InheritedToolDescriptions | undefined;
|
|
143
147
|
|
|
144
148
|
build(context: AgentContext, options: BuildOptions): boolean {
|
|
145
149
|
const prev = this.#snapshot;
|
|
@@ -170,7 +174,8 @@ export class StablePrefix {
|
|
|
170
174
|
if (
|
|
171
175
|
this.#lastIntentTracing !== options.intentTracing ||
|
|
172
176
|
this.#lastIntentDescription !== options.intentDescription ||
|
|
173
|
-
this.#lastPruneToolDescriptions !== options.pruneToolDescriptions
|
|
177
|
+
this.#lastPruneToolDescriptions !== options.pruneToolDescriptions ||
|
|
178
|
+
this.#lastInheritedToolDescriptions !== options.inheritedToolDescriptions
|
|
174
179
|
) {
|
|
175
180
|
return false;
|
|
176
181
|
}
|
|
@@ -202,6 +207,7 @@ export class StablePrefix {
|
|
|
202
207
|
this.#lastIntentTracing = options.intentTracing;
|
|
203
208
|
this.#lastIntentDescription = options.intentDescription;
|
|
204
209
|
this.#lastPruneToolDescriptions = options.pruneToolDescriptions;
|
|
210
|
+
this.#lastInheritedToolDescriptions = options.inheritedToolDescriptions;
|
|
205
211
|
this.#lastToolKey = renderedToolKeys;
|
|
206
212
|
}
|
|
207
213
|
|
|
@@ -212,6 +218,7 @@ export class StablePrefix {
|
|
|
212
218
|
this.#lastToolKey = undefined;
|
|
213
219
|
this.#lastIntentTracing = undefined;
|
|
214
220
|
this.#lastPruneToolDescriptions = undefined;
|
|
221
|
+
this.#lastInheritedToolDescriptions = undefined;
|
|
215
222
|
}
|
|
216
223
|
|
|
217
224
|
/**
|
|
@@ -489,6 +496,7 @@ function normalizeWireTools(tools: AgentContext["tools"], options: BuildOptions)
|
|
|
489
496
|
injectIntent: options.intentTracing,
|
|
490
497
|
intentDescription: options.intentDescription,
|
|
491
498
|
pruneDescriptions: options.pruneToolDescriptions,
|
|
499
|
+
inheritedDescriptions: options.inheritedToolDescriptions,
|
|
492
500
|
}) ?? []
|
|
493
501
|
);
|
|
494
502
|
}
|