@slopus/happy-providers 0.0.47 → 0.0.49
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/dist/core/ProviderModelCompatibility.d.ts +2 -2
- package/dist/core/ProviderModelCompatibility.d.ts.map +1 -1
- package/dist/core/ProviderModelCompatibility.js +8 -2
- package/dist/core/ProviderModelCompatibility.js.map +1 -1
- package/dist/core/SessionProviderError.d.ts +12 -0
- package/dist/core/SessionProviderError.d.ts.map +1 -1
- package/dist/core/SessionProviderError.js +2 -0
- package/dist/core/SessionProviderError.js.map +1 -1
- package/dist/core/SessionRunRequest.d.ts +6 -0
- package/dist/core/SessionRunRequest.d.ts.map +1 -1
- package/dist/core/isNetworkFailure.d.ts +8 -0
- package/dist/core/isNetworkFailure.d.ts.map +1 -0
- package/dist/core/isNetworkFailure.js +45 -0
- package/dist/core/isNetworkFailure.js.map +1 -0
- package/dist/core/providerModelFamily.d.ts.map +1 -1
- package/dist/core/providerModelFamily.js +4 -0
- package/dist/core/providerModelFamily.js.map +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/protocol/acp/AcpConnection.d.ts +41 -0
- package/dist/protocol/acp/AcpConnection.d.ts.map +1 -0
- package/dist/protocol/acp/AcpConnection.js +2 -0
- package/dist/protocol/acp/AcpConnection.js.map +1 -0
- package/dist/protocol/acp/AcpProvider.d.ts +86 -0
- package/dist/protocol/acp/AcpProvider.d.ts.map +1 -0
- package/dist/protocol/acp/AcpProvider.js +27 -0
- package/dist/protocol/acp/AcpProvider.js.map +1 -0
- package/dist/protocol/acp/AcpSession.d.ts +26 -0
- package/dist/protocol/acp/AcpSession.d.ts.map +1 -0
- package/dist/protocol/acp/AcpSession.js +737 -0
- package/dist/protocol/acp/AcpSession.js.map +1 -0
- package/dist/protocol/acp/acpDiscoverModels.d.ts +10 -0
- package/dist/protocol/acp/acpDiscoverModels.d.ts.map +1 -0
- package/dist/protocol/acp/acpDiscoverModels.js +34 -0
- package/dist/protocol/acp/acpDiscoverModels.js.map +1 -0
- package/dist/protocol/acp/impl/AcpToolBridgeServer.d.ts +37 -0
- package/dist/protocol/acp/impl/AcpToolBridgeServer.d.ts.map +1 -0
- package/dist/protocol/acp/impl/AcpToolBridgeServer.js +136 -0
- package/dist/protocol/acp/impl/AcpToolBridgeServer.js.map +1 -0
- package/dist/protocol/acp/impl/AcpTurnQueue.d.ts +10 -0
- package/dist/protocol/acp/impl/AcpTurnQueue.d.ts.map +1 -0
- package/dist/protocol/acp/impl/AcpTurnQueue.js +26 -0
- package/dist/protocol/acp/impl/AcpTurnQueue.js.map +1 -0
- package/dist/protocol/acp/impl/acpCompactWithAgent.d.ts +10 -0
- package/dist/protocol/acp/impl/acpCompactWithAgent.d.ts.map +1 -0
- package/dist/protocol/acp/impl/acpCompactWithAgent.js +69 -0
- package/dist/protocol/acp/impl/acpCompactWithAgent.js.map +1 -0
- package/dist/protocol/acp/impl/acpConfigOptions.d.ts +22 -0
- package/dist/protocol/acp/impl/acpConfigOptions.d.ts.map +1 -0
- package/dist/protocol/acp/impl/acpConfigOptions.js +37 -0
- package/dist/protocol/acp/impl/acpConfigOptions.js.map +1 -0
- package/dist/protocol/acp/impl/acpConnectionSpawn.d.ts +9 -0
- package/dist/protocol/acp/impl/acpConnectionSpawn.d.ts.map +1 -0
- package/dist/protocol/acp/impl/acpConnectionSpawn.js +64 -0
- package/dist/protocol/acp/impl/acpConnectionSpawn.js.map +1 -0
- package/dist/protocol/acp/impl/acpPromptFromMessages.d.ts +22 -0
- package/dist/protocol/acp/impl/acpPromptFromMessages.d.ts.map +1 -0
- package/dist/protocol/acp/impl/acpPromptFromMessages.js +139 -0
- package/dist/protocol/acp/impl/acpPromptFromMessages.js.map +1 -0
- package/dist/protocol/acp/impl/acpResponseEvents.d.ts +20 -0
- package/dist/protocol/acp/impl/acpResponseEvents.d.ts.map +1 -0
- package/dist/protocol/acp/impl/acpResponseEvents.js +183 -0
- package/dist/protocol/acp/impl/acpResponseEvents.js.map +1 -0
- package/dist/protocol/acp/impl/acpSessionStore.d.ts +25 -0
- package/dist/protocol/acp/impl/acpSessionStore.d.ts.map +1 -0
- package/dist/protocol/acp/impl/acpSessionStore.js +50 -0
- package/dist/protocol/acp/impl/acpSessionStore.js.map +1 -0
- package/dist/protocol/acp/impl/processTree.d.ts +11 -0
- package/dist/protocol/acp/impl/processTree.d.ts.map +1 -0
- package/dist/protocol/acp/impl/processTree.js +80 -0
- package/dist/protocol/acp/impl/processTree.js.map +1 -0
- package/dist/vendors/bedrock/errors/anthropicBedrockErrors.d.ts.map +1 -1
- package/dist/vendors/bedrock/errors/anthropicBedrockErrors.js +6 -3
- package/dist/vendors/bedrock/errors/anthropicBedrockErrors.js.map +1 -1
- package/dist/vendors/claude/impl/auth.d.ts +3 -1
- package/dist/vendors/claude/impl/auth.d.ts.map +1 -1
- package/dist/vendors/claude/impl/auth.js +9 -6
- package/dist/vendors/claude/impl/auth.js.map +1 -1
- package/dist/vendors/claudeAgent/claudeAgentConnect.d.ts +10 -0
- package/dist/vendors/claudeAgent/claudeAgentConnect.d.ts.map +1 -0
- package/dist/vendors/claudeAgent/claudeAgentConnect.js +347 -0
- package/dist/vendors/claudeAgent/claudeAgentConnect.js.map +1 -0
- package/dist/vendors/claudeAgent/impl/AsyncInputQueue.d.ts +8 -0
- package/dist/vendors/claudeAgent/impl/AsyncInputQueue.d.ts.map +1 -0
- package/dist/vendors/claudeAgent/impl/AsyncInputQueue.js +37 -0
- package/dist/vendors/claudeAgent/impl/AsyncInputQueue.js.map +1 -0
- package/dist/vendors/claudeAgent/impl/claudeAgentUpdates.d.ts +12 -0
- package/dist/vendors/claudeAgent/impl/claudeAgentUpdates.d.ts.map +1 -0
- package/dist/vendors/claudeAgent/impl/claudeAgentUpdates.js +126 -0
- package/dist/vendors/claudeAgent/impl/claudeAgentUpdates.js.map +1 -0
- package/dist/vendors/codex/errors/codexErrors.d.ts.map +1 -1
- package/dist/vendors/codex/errors/codexErrors.js +8 -4
- package/dist/vendors/codex/errors/codexErrors.js.map +1 -1
- package/dist/vendors/codexAppServer/codexAppServerConnect.d.ts +11 -0
- package/dist/vendors/codexAppServer/codexAppServerConnect.d.ts.map +1 -0
- package/dist/vendors/codexAppServer/codexAppServerConnect.js +409 -0
- package/dist/vendors/codexAppServer/codexAppServerConnect.js.map +1 -0
- package/dist/vendors/codexAppServer/impl/codexItemUpdates.d.ts +10 -0
- package/dist/vendors/codexAppServer/impl/codexItemUpdates.d.ts.map +1 -0
- package/dist/vendors/codexAppServer/impl/codexItemUpdates.js +113 -0
- package/dist/vendors/codexAppServer/impl/codexItemUpdates.js.map +1 -0
- package/dist/vendors/codexAppServer/resolveCodexExecutable.d.ts +10 -0
- package/dist/vendors/codexAppServer/resolveCodexExecutable.d.ts.map +1 -0
- package/dist/vendors/codexAppServer/resolveCodexExecutable.js +61 -0
- package/dist/vendors/codexAppServer/resolveCodexExecutable.js.map +1 -0
- package/dist/vendors/foreignAgents/ForeignAgent.d.ts +74 -0
- package/dist/vendors/foreignAgents/ForeignAgent.d.ts.map +1 -0
- package/dist/vendors/foreignAgents/ForeignAgent.js +54 -0
- package/dist/vendors/foreignAgents/ForeignAgent.js.map +1 -0
- package/dist/vendors/foreignAgents/acpGenericAgent.d.ts +11 -0
- package/dist/vendors/foreignAgents/acpGenericAgent.d.ts.map +1 -0
- package/dist/vendors/foreignAgents/acpGenericAgent.js +33 -0
- package/dist/vendors/foreignAgents/acpGenericAgent.js.map +1 -0
- package/dist/vendors/foreignAgents/antigravityAgent.d.ts +11 -0
- package/dist/vendors/foreignAgents/antigravityAgent.d.ts.map +1 -0
- package/dist/vendors/foreignAgents/antigravityAgent.js +104 -0
- package/dist/vendors/foreignAgents/antigravityAgent.js.map +1 -0
- package/dist/vendors/foreignAgents/claudeCodeAgent.d.ts +8 -0
- package/dist/vendors/foreignAgents/claudeCodeAgent.d.ts.map +1 -0
- package/dist/vendors/foreignAgents/claudeCodeAgent.js +71 -0
- package/dist/vendors/foreignAgents/claudeCodeAgent.js.map +1 -0
- package/dist/vendors/foreignAgents/codexCliAgent.d.ts +10 -0
- package/dist/vendors/foreignAgents/codexCliAgent.d.ts.map +1 -0
- package/dist/vendors/foreignAgents/codexCliAgent.js +68 -0
- package/dist/vendors/foreignAgents/codexCliAgent.js.map +1 -0
- package/dist/vendors/foreignAgents/foreignAgents.d.ts +6 -0
- package/dist/vendors/foreignAgents/foreignAgents.d.ts.map +1 -0
- package/dist/vendors/foreignAgents/foreignAgents.js +17 -0
- package/dist/vendors/foreignAgents/foreignAgents.js.map +1 -0
- package/dist/vendors/foreignAgents/opencodeAgent.d.ts +8 -0
- package/dist/vendors/foreignAgents/opencodeAgent.d.ts.map +1 -0
- package/dist/vendors/foreignAgents/opencodeAgent.js +28 -0
- package/dist/vendors/foreignAgents/opencodeAgent.js.map +1 -0
- package/dist/vendors/grok/errors/grokErrors.d.ts.map +1 -1
- package/dist/vendors/grok/errors/grokErrors.js +6 -3
- package/dist/vendors/grok/errors/grokErrors.js.map +1 -1
- package/package.json +3 -1
|
@@ -0,0 +1,737 @@
|
|
|
1
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { BaseSession } from "../../core/BaseSession.js";
|
|
4
|
+
import { acpCompactWithAgent } from "../../protocol/acp/impl/acpCompactWithAgent.js";
|
|
5
|
+
import { acpConnectionSpawn } from "../../protocol/acp/impl/acpConnectionSpawn.js";
|
|
6
|
+
import { acpCatchUpPrompt, acpPromptFromMessages, acpReplayPrompt, } from "../../protocol/acp/impl/acpPromptFromMessages.js";
|
|
7
|
+
import { ACP_BRIDGE_NAME, AcpResponseEvents } from "../../protocol/acp/impl/acpResponseEvents.js";
|
|
8
|
+
import { acpSessionRecordRead, acpSessionRecordWrite, acpTranscriptFingerprint, } from "../../protocol/acp/impl/acpSessionStore.js";
|
|
9
|
+
import { acpBridgeResult, AcpToolBridgeServer, } from "../../protocol/acp/impl/AcpToolBridgeServer.js";
|
|
10
|
+
import { AcpTurnQueue } from "../../protocol/acp/impl/AcpTurnQueue.js";
|
|
11
|
+
import { acpAcceptsConfigValue, acpConfigOptionId } from "../../protocol/acp/impl/acpConfigOptions.js";
|
|
12
|
+
const PREVIOUS_PROMPT_GRACE_MS = 10_000;
|
|
13
|
+
/** How long a cancelled agent gets to end its prompt and save its session before it is stopped. */
|
|
14
|
+
const CANCEL_GRACE_MS = 2_000;
|
|
15
|
+
/** The longest a new session waits for the one before it to bind its native conversation. */
|
|
16
|
+
const NEW_SESSION_GATE_MS = 60_000;
|
|
17
|
+
/**
|
|
18
|
+
* Waits before sending a prompt the agent's service refused as too many requests again. Agents
|
|
19
|
+
* retry only briefly themselves, and a burst — a restarted agent's first request, or several
|
|
20
|
+
* sessions on one account at once — clears within seconds.
|
|
21
|
+
*/
|
|
22
|
+
const RATE_LIMIT_RETRY_MS = [3_000, 10_000, 30_000];
|
|
23
|
+
const ABORTED = Symbol("acp_aborted");
|
|
24
|
+
const STEERED = Symbol("acp_steered");
|
|
25
|
+
/** Updates an agent can only send from inside a turn, once it has a conversation to report. */
|
|
26
|
+
const TURN_CONTENT_UPDATES = new Set([
|
|
27
|
+
"agent_message_chunk",
|
|
28
|
+
"agent_thought_chunk",
|
|
29
|
+
"tool_call",
|
|
30
|
+
"tool_call_update",
|
|
31
|
+
"plan",
|
|
32
|
+
]);
|
|
33
|
+
/** The first prompt of the last new session started per agent profile, for agents that need it. */
|
|
34
|
+
const newSessionPrompts = new WeakMap();
|
|
35
|
+
/**
|
|
36
|
+
* A Happy conversation continued inside a foreign agent's own ACP session.
|
|
37
|
+
*
|
|
38
|
+
* Each run sends only the input the foreign session has not seen yet. When the foreign session
|
|
39
|
+
* cannot be continued — it was lost, or Happy's transcript no longer matches what it saw — a new
|
|
40
|
+
* one is opened and given Happy's instructions and transcript to continue from.
|
|
41
|
+
*/
|
|
42
|
+
export class AcpSession extends BaseSession {
|
|
43
|
+
#options;
|
|
44
|
+
#bridgedTools;
|
|
45
|
+
#connection;
|
|
46
|
+
#connecting;
|
|
47
|
+
#acpSessionId;
|
|
48
|
+
#cwd;
|
|
49
|
+
#record;
|
|
50
|
+
#recordLoaded = false;
|
|
51
|
+
#turn;
|
|
52
|
+
#previousPrompt = Promise.resolve();
|
|
53
|
+
/** Settles once a stopped agent process has exited, so its successor never overlaps it. */
|
|
54
|
+
#stopping = Promise.resolve();
|
|
55
|
+
#replaying = false;
|
|
56
|
+
/** Whether the foreign session was opened by this run and has not been prompted yet. */
|
|
57
|
+
#unprompted = false;
|
|
58
|
+
/** Lets the next new session start once this one's agent has bound its conversation. */
|
|
59
|
+
#releaseNewSession;
|
|
60
|
+
#permissionMode;
|
|
61
|
+
#bridge;
|
|
62
|
+
#applied = new Map();
|
|
63
|
+
/** The configuration options the foreign session last advertised. */
|
|
64
|
+
#advertised;
|
|
65
|
+
#closedCalls = new Set();
|
|
66
|
+
#contextUsed = 0;
|
|
67
|
+
#destroyed = false;
|
|
68
|
+
constructor(id, options) {
|
|
69
|
+
super(id);
|
|
70
|
+
this.#options = options;
|
|
71
|
+
// Provider-owned server tools stay with the provider that owns them.
|
|
72
|
+
this.#bridgedTools = options.tools.filter((tool) => tool.server === undefined);
|
|
73
|
+
}
|
|
74
|
+
run(ctx, request) {
|
|
75
|
+
// A consumer stops a response by returning its iterator. An async generator only honors
|
|
76
|
+
// that at its next `yield`, and a foreign agent can stay silent for minutes inside its own
|
|
77
|
+
// command, so returning also signals the turn directly.
|
|
78
|
+
const stopped = new AbortController();
|
|
79
|
+
const lifetime = ctx.lifetime === undefined
|
|
80
|
+
? stopped.signal
|
|
81
|
+
: AbortSignal.any([ctx.lifetime, stopped.signal]);
|
|
82
|
+
const inner = this.#stream(ctx, lifetime, request);
|
|
83
|
+
return {
|
|
84
|
+
[Symbol.asyncIterator]: () => ({
|
|
85
|
+
next: () => inner.next(),
|
|
86
|
+
return: async (value) => {
|
|
87
|
+
stopped.abort();
|
|
88
|
+
return await inner.return(value);
|
|
89
|
+
},
|
|
90
|
+
}),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
async compact(ctx, options) {
|
|
94
|
+
const result = await acpCompactWithAgent(ctx, options, (runCtx, request) => this.#stream(runCtx, runCtx.lifetime, request));
|
|
95
|
+
if (result.status === "completed") {
|
|
96
|
+
// The foreign session still holds the long context; the next run opens a new one
|
|
97
|
+
// from the summary instead.
|
|
98
|
+
this.#acpSessionId = undefined;
|
|
99
|
+
this.#record = undefined;
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
this.#abandonTurn();
|
|
103
|
+
}
|
|
104
|
+
return result;
|
|
105
|
+
}
|
|
106
|
+
destroy() {
|
|
107
|
+
this.#destroyed = true;
|
|
108
|
+
this.#abandonTurn();
|
|
109
|
+
this.#bridge?.close();
|
|
110
|
+
this.#bridge = undefined;
|
|
111
|
+
const connection = this.#connection;
|
|
112
|
+
this.#connection = undefined;
|
|
113
|
+
this.#connecting = undefined;
|
|
114
|
+
connection?.terminate();
|
|
115
|
+
}
|
|
116
|
+
async *#stream(ctx, signal, request) {
|
|
117
|
+
if (signal?.aborted) {
|
|
118
|
+
yield { type: "done", state: "cancelled" };
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
const environment = this.#options.environment(ctx);
|
|
122
|
+
this.#permissionMode = environment.permissionMode;
|
|
123
|
+
yield { type: "block_start" };
|
|
124
|
+
let connection;
|
|
125
|
+
let turn;
|
|
126
|
+
try {
|
|
127
|
+
connection = await this.#connect(environment);
|
|
128
|
+
await this.#loadRecord();
|
|
129
|
+
const live = this.#turn;
|
|
130
|
+
if (live !== undefined &&
|
|
131
|
+
(live.awaiting.size > 0 || live.steering) &&
|
|
132
|
+
this.#acpSessionId !== undefined) {
|
|
133
|
+
turn = live;
|
|
134
|
+
await this.#continueTurn(connection, turn, request.context.messages);
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
this.#abandonTurn();
|
|
138
|
+
await settleWithin(this.#previousPrompt, PREVIOUS_PROMPT_GRACE_MS);
|
|
139
|
+
const prompt = await this.#prepareSession(connection, environment, request);
|
|
140
|
+
await this.#applyOptions(connection, request, environment);
|
|
141
|
+
turn = this.#startTurn(connection, prompt);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
yield { type: "block_stop" };
|
|
146
|
+
yield errorDone(error, connection?.stderr() ?? "");
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
const events = new AcpResponseEvents(this.#closedCalls);
|
|
150
|
+
const aborted = abortPromise(signal);
|
|
151
|
+
// Steering ends this response so Agent Base can deliver the new input on the next run.
|
|
152
|
+
const steered = abortPromise(request.steered).then(() => STEERED);
|
|
153
|
+
let finished = false;
|
|
154
|
+
let retries = 0;
|
|
155
|
+
// Anything the agent reported — text, reasoning, its own tool calls — means it acted on
|
|
156
|
+
// the prompt, and sending it again could repeat that work.
|
|
157
|
+
let reported = false;
|
|
158
|
+
try {
|
|
159
|
+
for (;;) {
|
|
160
|
+
turn.reading ??= turn.items.next();
|
|
161
|
+
const item = await Promise.race([turn.reading, aborted, steered]);
|
|
162
|
+
if (item !== ABORTED && item !== STEERED)
|
|
163
|
+
turn.reading = undefined;
|
|
164
|
+
if (item === STEERED) {
|
|
165
|
+
yield* events.close();
|
|
166
|
+
yield* events.settleAll();
|
|
167
|
+
await this.#commit(request.context.messages);
|
|
168
|
+
// An agent whose loop takes input mid-turn keeps going; the steering joins it
|
|
169
|
+
// on the next run. Any other agent is interrupted.
|
|
170
|
+
if (connection.conn.steer !== undefined)
|
|
171
|
+
turn.steering = true;
|
|
172
|
+
else
|
|
173
|
+
this.#stopTurn(connection);
|
|
174
|
+
finished = true;
|
|
175
|
+
const usage = this.#usage(undefined, events.outputCharacters);
|
|
176
|
+
yield { type: "token_usage", usage };
|
|
177
|
+
yield { type: "block_stop" };
|
|
178
|
+
yield {
|
|
179
|
+
type: "done",
|
|
180
|
+
state: "normal",
|
|
181
|
+
tokens: { input: usage.input, output: usage.output },
|
|
182
|
+
};
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
// A consumer stops reading at `done`, so everything that must happen for a turn
|
|
186
|
+
// happens before that event is yielded.
|
|
187
|
+
if (item === ABORTED) {
|
|
188
|
+
yield* events.close();
|
|
189
|
+
yield* events.settleAll();
|
|
190
|
+
// The agent already saw this turn's input, so the next run sends only what is
|
|
191
|
+
// new rather than repeating a request the user stopped.
|
|
192
|
+
await this.#commit(request.context.messages);
|
|
193
|
+
this.#stopTurn(connection);
|
|
194
|
+
finished = true;
|
|
195
|
+
yield { type: "block_stop" };
|
|
196
|
+
yield { type: "done", state: "cancelled" };
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (item.kind === "update") {
|
|
200
|
+
reported = true;
|
|
201
|
+
yield* events.update(item.update);
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
if (item.kind === "prompt_end" && turn.deferred.length > 0) {
|
|
205
|
+
const next = turn.deferred.splice(0);
|
|
206
|
+
this.#sendPrompt(connection, turn, acpPromptFromMessages(next, images(connection)));
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
yield* events.close();
|
|
210
|
+
yield* events.settleAll();
|
|
211
|
+
if (item.kind === "prompt_error") {
|
|
212
|
+
const wait = RATE_LIMIT_RETRY_MS[retries];
|
|
213
|
+
if (wait !== undefined &&
|
|
214
|
+
turn.sent !== undefined &&
|
|
215
|
+
isRateLimited(item.error) &&
|
|
216
|
+
!reported &&
|
|
217
|
+
turn.awaiting.size === 0 &&
|
|
218
|
+
this.#connection === connection &&
|
|
219
|
+
this.#turn === turn) {
|
|
220
|
+
// Refused before saying anything: the same prompt, a little later.
|
|
221
|
+
retries++;
|
|
222
|
+
yield { type: "retrying", attempt: retries, reason: errorText(item.error) };
|
|
223
|
+
let timer;
|
|
224
|
+
const waited = await Promise.race([
|
|
225
|
+
new Promise((resolve) => (timer = setTimeout(resolve, wait))),
|
|
226
|
+
aborted,
|
|
227
|
+
steered,
|
|
228
|
+
]).finally(() => clearTimeout(timer));
|
|
229
|
+
if (waited !== ABORTED && waited !== STEERED) {
|
|
230
|
+
this.#sendPrompt(connection, turn, turn.sent);
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
this.#turn = undefined;
|
|
234
|
+
finished = true;
|
|
235
|
+
yield { type: "block_stop" };
|
|
236
|
+
if (waited === ABORTED) {
|
|
237
|
+
yield { type: "done", state: "cancelled" };
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
// The agent never took the refused prompt, so nothing is recorded as
|
|
241
|
+
// seen: the next run sends it together with the steering, once.
|
|
242
|
+
yield { type: "done", state: "normal", tokens: { input: 0, output: 0 } };
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
this.#turn = undefined;
|
|
246
|
+
finished = true;
|
|
247
|
+
yield { type: "block_stop" };
|
|
248
|
+
yield errorDone(item.error, connection.stderr());
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
if (item.kind === "bridge_call") {
|
|
252
|
+
const { call } = item;
|
|
253
|
+
turn.awaiting.set(call.callId, call);
|
|
254
|
+
yield {
|
|
255
|
+
type: "toolcall_start",
|
|
256
|
+
callId: call.callId,
|
|
257
|
+
name: call.tool.name,
|
|
258
|
+
...(call.tool.namespace === undefined
|
|
259
|
+
? {}
|
|
260
|
+
: { namespace: call.tool.namespace }),
|
|
261
|
+
};
|
|
262
|
+
yield { type: "toolcall_end", callId: call.callId, arguments: call.arguments };
|
|
263
|
+
}
|
|
264
|
+
const response = item.kind === "prompt_end" ? item.response : undefined;
|
|
265
|
+
if (response !== undefined)
|
|
266
|
+
this.#turn = undefined;
|
|
267
|
+
const usage = this.#usage(response, events.outputCharacters);
|
|
268
|
+
const tokens = { input: usage.input, output: usage.output };
|
|
269
|
+
await this.#commit(request.context.messages);
|
|
270
|
+
finished = true;
|
|
271
|
+
yield { type: "token_usage", usage };
|
|
272
|
+
yield { type: "block_stop" };
|
|
273
|
+
if (response === undefined) {
|
|
274
|
+
yield { type: "done", state: "tool_call", tokens };
|
|
275
|
+
}
|
|
276
|
+
else if (response.stopReason === "cancelled") {
|
|
277
|
+
yield { type: "done", state: "cancelled" };
|
|
278
|
+
}
|
|
279
|
+
else if (response.stopReason === "max_tokens" ||
|
|
280
|
+
response.stopReason === "max_turn_requests") {
|
|
281
|
+
yield { type: "done", state: "length", tokens };
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
yield { type: "done", state: "normal", tokens, endTurn: true };
|
|
285
|
+
}
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
finally {
|
|
290
|
+
// A consumer that stopped reading mid-turn stopped it: this is how Agent Base aborts.
|
|
291
|
+
if (!finished) {
|
|
292
|
+
void this.#commit(request.context.messages).catch(() => undefined);
|
|
293
|
+
this.#stopTurn(connection);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Continue a prompt that outlived the last Happy response: answer its open MCP requests with
|
|
299
|
+
* the results Agent Base produced, and hand any new input to the agent's loop when it takes
|
|
300
|
+
* input mid-turn, or keep it for the next prompt when it does not.
|
|
301
|
+
*/
|
|
302
|
+
async #continueTurn(connection, turn, messages) {
|
|
303
|
+
turn.steering = false;
|
|
304
|
+
const input = [];
|
|
305
|
+
for (const message of inputMessages(messages).slice(this.#record?.consumed ?? 0)) {
|
|
306
|
+
const call = message.role === "tool" ? turn.awaiting.get(message.callId) : undefined;
|
|
307
|
+
if (call !== undefined && message.role === "tool") {
|
|
308
|
+
turn.awaiting.delete(message.callId);
|
|
309
|
+
call.resolve(acpBridgeResult(message));
|
|
310
|
+
}
|
|
311
|
+
else {
|
|
312
|
+
input.push(message);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
const steer = connection.conn.steer;
|
|
316
|
+
const taken = input.length > 0 &&
|
|
317
|
+
steer !== undefined &&
|
|
318
|
+
(await steer
|
|
319
|
+
.call(connection.conn, {
|
|
320
|
+
sessionId: this.#acpSessionId,
|
|
321
|
+
prompt: acpPromptFromMessages(input, images(connection)),
|
|
322
|
+
})
|
|
323
|
+
.catch(() => false));
|
|
324
|
+
if (!taken)
|
|
325
|
+
turn.deferred.push(...input);
|
|
326
|
+
for (const call of turn.awaiting.values()) {
|
|
327
|
+
call.resolve({
|
|
328
|
+
content: [{ type: "text", text: "No result was recorded for this call." }],
|
|
329
|
+
isError: true,
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
turn.awaiting.clear();
|
|
333
|
+
}
|
|
334
|
+
async #connect(environment) {
|
|
335
|
+
if (this.#destroyed)
|
|
336
|
+
throw new Error("The agent session was closed.");
|
|
337
|
+
if (this.#connection !== undefined)
|
|
338
|
+
return this.#connection;
|
|
339
|
+
await this.#stopping;
|
|
340
|
+
if (this.#connection !== undefined)
|
|
341
|
+
return this.#connection;
|
|
342
|
+
const { connect, launch } = this.#options;
|
|
343
|
+
this.#connecting ??= (connect === undefined
|
|
344
|
+
? acpConnectionSpawn(launch, environment.cwd, this.#client())
|
|
345
|
+
: connect(environment.cwd, this.#client())).then((connection) => {
|
|
346
|
+
this.#connecting = undefined;
|
|
347
|
+
// Closed while the agent was starting: nothing will ever end it but this.
|
|
348
|
+
if (this.#destroyed) {
|
|
349
|
+
connection.terminate();
|
|
350
|
+
throw new Error("The agent session was closed.");
|
|
351
|
+
}
|
|
352
|
+
this.#connection = connection;
|
|
353
|
+
void connection.exited.then((error) => {
|
|
354
|
+
// A stopped agent was already detached; its exit belongs to no current turn.
|
|
355
|
+
if (this.#connection !== connection)
|
|
356
|
+
return;
|
|
357
|
+
this.#openNewSessionGate();
|
|
358
|
+
this.#turn?.items.push({ kind: "prompt_error", error });
|
|
359
|
+
this.#connection = undefined;
|
|
360
|
+
this.#acpSessionId = undefined;
|
|
361
|
+
this.#applied.clear();
|
|
362
|
+
});
|
|
363
|
+
return connection;
|
|
364
|
+
}, (error) => {
|
|
365
|
+
this.#connecting = undefined;
|
|
366
|
+
throw error;
|
|
367
|
+
});
|
|
368
|
+
return await this.#connecting;
|
|
369
|
+
}
|
|
370
|
+
#client() {
|
|
371
|
+
return {
|
|
372
|
+
requestPermission: async (params) => this.#answerPermission(params),
|
|
373
|
+
sessionUpdate: async (params) => {
|
|
374
|
+
if (this.#replaying || params.sessionId !== this.#acpSessionId)
|
|
375
|
+
return;
|
|
376
|
+
// Session-level notices arrive before the agent has a conversation; only turn
|
|
377
|
+
// content proves it bound one.
|
|
378
|
+
if (TURN_CONTENT_UPDATES.has(params.update.sessionUpdate)) {
|
|
379
|
+
this.#openNewSessionGate();
|
|
380
|
+
}
|
|
381
|
+
if (params.update.sessionUpdate === "config_option_update") {
|
|
382
|
+
this.#advertised = params.update.configOptions;
|
|
383
|
+
}
|
|
384
|
+
if (params.update.sessionUpdate === "usage_update") {
|
|
385
|
+
this.#contextUsed = params.update.used;
|
|
386
|
+
}
|
|
387
|
+
this.#turn?.items.push({ kind: "update", update: params.update });
|
|
388
|
+
},
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
async #loadRecord() {
|
|
392
|
+
if (this.#recordLoaded)
|
|
393
|
+
return;
|
|
394
|
+
this.#record = await acpSessionRecordRead(this.#options.stateDirectory, this.id);
|
|
395
|
+
this.#recordLoaded = true;
|
|
396
|
+
}
|
|
397
|
+
/** Open, restore, or keep the foreign session, and return the prompt this run sends. */
|
|
398
|
+
async #prepareSession(connection, environment, request) {
|
|
399
|
+
const messages = request.context.messages;
|
|
400
|
+
const inputs = inputMessages(messages);
|
|
401
|
+
const record = this.#record;
|
|
402
|
+
const continues = record !== undefined &&
|
|
403
|
+
record.cwd === environment.cwd &&
|
|
404
|
+
record.consumed <= inputs.length &&
|
|
405
|
+
acpTranscriptFingerprint(inputs.slice(0, record.consumed)) === record.fingerprint;
|
|
406
|
+
if (continues) {
|
|
407
|
+
const delta = acpDeltaPrompt(messages, record.consumed, images(connection));
|
|
408
|
+
if (this.#acpSessionId === record.acpSessionId && this.#cwd === environment.cwd) {
|
|
409
|
+
return delta;
|
|
410
|
+
}
|
|
411
|
+
if (await this.#restoreSession(connection, record, environment))
|
|
412
|
+
return delta;
|
|
413
|
+
}
|
|
414
|
+
const response = await connection.conn.newSession({
|
|
415
|
+
cwd: environment.cwd,
|
|
416
|
+
mcpServers: await this.#mcpServers(connection),
|
|
417
|
+
...(await this.#additionalDirectories()),
|
|
418
|
+
});
|
|
419
|
+
this.#acpSessionId = response.sessionId;
|
|
420
|
+
this.#advertised = response.configOptions ?? undefined;
|
|
421
|
+
this.#cwd = environment.cwd;
|
|
422
|
+
this.#applied.clear();
|
|
423
|
+
this.#record = undefined;
|
|
424
|
+
this.#unprompted = true;
|
|
425
|
+
let lastResponse = -1;
|
|
426
|
+
messages.forEach((message, index) => {
|
|
427
|
+
if (message.role === "assistant")
|
|
428
|
+
lastResponse = index;
|
|
429
|
+
});
|
|
430
|
+
return acpReplayPrompt(request.context.instructions, messages.slice(0, lastResponse + 1), messages.slice(lastResponse + 1), images(connection));
|
|
431
|
+
}
|
|
432
|
+
async #restoreSession(connection, record, environment) {
|
|
433
|
+
const capabilities = connection.init.agentCapabilities;
|
|
434
|
+
const params = {
|
|
435
|
+
sessionId: record.acpSessionId,
|
|
436
|
+
cwd: environment.cwd,
|
|
437
|
+
mcpServers: await this.#mcpServers(connection),
|
|
438
|
+
...(await this.#additionalDirectories()),
|
|
439
|
+
};
|
|
440
|
+
try {
|
|
441
|
+
if (capabilities?.sessionCapabilities?.resume != null) {
|
|
442
|
+
const resumed = await connection.conn.resumeSession(params);
|
|
443
|
+
this.#advertised = resumed.configOptions ?? undefined;
|
|
444
|
+
}
|
|
445
|
+
else if (capabilities?.loadSession === true) {
|
|
446
|
+
// Loading replays the whole history as notifications; Happy already has it.
|
|
447
|
+
this.#replaying = true;
|
|
448
|
+
try {
|
|
449
|
+
const loaded = await connection.conn.loadSession(params);
|
|
450
|
+
this.#advertised = loaded.configOptions ?? undefined;
|
|
451
|
+
}
|
|
452
|
+
finally {
|
|
453
|
+
this.#replaying = false;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
else {
|
|
457
|
+
return false;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
catch {
|
|
461
|
+
return false;
|
|
462
|
+
}
|
|
463
|
+
this.#acpSessionId = record.acpSessionId;
|
|
464
|
+
this.#cwd = environment.cwd;
|
|
465
|
+
this.#applied.clear();
|
|
466
|
+
return true;
|
|
467
|
+
}
|
|
468
|
+
async #applyOptions(connection, request, environment) {
|
|
469
|
+
const profile = this.#options.profile;
|
|
470
|
+
const wanted = [
|
|
471
|
+
...(profile?.modelOptions?.(request.model, request.effort) ?? []),
|
|
472
|
+
...(environment.permissionMode === undefined
|
|
473
|
+
? []
|
|
474
|
+
: (profile?.permissionOptions?.(environment.permissionMode) ?? [])),
|
|
475
|
+
];
|
|
476
|
+
for (const option of wanted) {
|
|
477
|
+
const configId = acpConfigOptionId(this.#advertised, option);
|
|
478
|
+
if (configId === undefined)
|
|
479
|
+
continue;
|
|
480
|
+
if (this.#applied.get(configId) === option.value)
|
|
481
|
+
continue;
|
|
482
|
+
// A value the agent does not offer, such as a model it no longer serves, would fail
|
|
483
|
+
// the whole turn; the agent keeps its current choice instead.
|
|
484
|
+
if (!acpAcceptsConfigValue(this.#advertised, configId, option.value))
|
|
485
|
+
continue;
|
|
486
|
+
const changed = await connection.conn.setSessionConfigOption({
|
|
487
|
+
sessionId: this.#acpSessionId,
|
|
488
|
+
configId,
|
|
489
|
+
...(typeof option.value === "boolean"
|
|
490
|
+
? { type: "boolean", value: option.value }
|
|
491
|
+
: { value: option.value }),
|
|
492
|
+
});
|
|
493
|
+
this.#advertised = changed.configOptions;
|
|
494
|
+
this.#applied.set(configId, option.value);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
async #mcpServers(connection) {
|
|
498
|
+
const bridge = await this.#ensureBridge();
|
|
499
|
+
if (bridge === undefined)
|
|
500
|
+
return [];
|
|
501
|
+
if (connection.init.agentCapabilities?.mcpCapabilities?.http !== true)
|
|
502
|
+
return [];
|
|
503
|
+
return [
|
|
504
|
+
{
|
|
505
|
+
type: "http",
|
|
506
|
+
name: ACP_BRIDGE_NAME,
|
|
507
|
+
url: bridge.url,
|
|
508
|
+
headers: Object.entries(bridge.headers).map(([name, value]) => ({ name, value })),
|
|
509
|
+
},
|
|
510
|
+
];
|
|
511
|
+
}
|
|
512
|
+
/** Agents that ignore ACP `mcpServers` discover the bridge from a private extra directory. */
|
|
513
|
+
async #additionalDirectories() {
|
|
514
|
+
const files = this.#options.profile?.bridgeDirectoryFiles;
|
|
515
|
+
const bridge = await this.#ensureBridge();
|
|
516
|
+
if (files === undefined || bridge === undefined)
|
|
517
|
+
return {};
|
|
518
|
+
const directory = join(this.#options.stateDirectory, "bridge", encodeURIComponent(this.id));
|
|
519
|
+
for (const file of files({
|
|
520
|
+
name: ACP_BRIDGE_NAME,
|
|
521
|
+
url: bridge.url,
|
|
522
|
+
headers: bridge.headers,
|
|
523
|
+
})) {
|
|
524
|
+
const path = join(directory, file.path);
|
|
525
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
526
|
+
await writeFile(path, file.content, { mode: 0o600 });
|
|
527
|
+
}
|
|
528
|
+
return { additionalDirectories: [directory] };
|
|
529
|
+
}
|
|
530
|
+
async #ensureBridge() {
|
|
531
|
+
if (this.#bridgedTools.length === 0)
|
|
532
|
+
return undefined;
|
|
533
|
+
this.#bridge ??= await AcpToolBridgeServer.start(this.#bridgedTools, (call) => {
|
|
534
|
+
const turn = this.#turn;
|
|
535
|
+
if (turn === undefined) {
|
|
536
|
+
call.resolve({
|
|
537
|
+
content: [{ type: "text", text: "No Happy turn is active." }],
|
|
538
|
+
isError: true,
|
|
539
|
+
});
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
turn.items.push({ kind: "bridge_call", call });
|
|
543
|
+
});
|
|
544
|
+
return this.#bridge;
|
|
545
|
+
}
|
|
546
|
+
#startTurn(connection, prompt) {
|
|
547
|
+
const turn = {
|
|
548
|
+
items: new AcpTurnQueue(),
|
|
549
|
+
awaiting: new Map(),
|
|
550
|
+
deferred: [],
|
|
551
|
+
steering: false,
|
|
552
|
+
reading: undefined,
|
|
553
|
+
sent: undefined,
|
|
554
|
+
};
|
|
555
|
+
this.#turn = turn;
|
|
556
|
+
this.#sendPrompt(connection, turn, prompt);
|
|
557
|
+
return turn;
|
|
558
|
+
}
|
|
559
|
+
#sendPrompt(connection, turn, prompt) {
|
|
560
|
+
const sessionId = this.#acpSessionId;
|
|
561
|
+
const profile = this.#options.profile;
|
|
562
|
+
turn.sent = prompt;
|
|
563
|
+
let send = () => connection.conn.prompt({ sessionId, prompt });
|
|
564
|
+
if (this.#unprompted && profile?.serializeNewSessions === true) {
|
|
565
|
+
// The agent has bound its native conversation once it reports anything, so the next
|
|
566
|
+
// new session waits only for that, never for a whole turn that may itself wait on it.
|
|
567
|
+
const before = newSessionPrompts.get(profile) ?? Promise.resolve();
|
|
568
|
+
let release;
|
|
569
|
+
const bound = new Promise((resolve) => (release = resolve));
|
|
570
|
+
this.#releaseNewSession = release;
|
|
571
|
+
newSessionPrompts.set(profile, bound);
|
|
572
|
+
send = async () => {
|
|
573
|
+
// Bounded, so a session that went quiet without ever binding cannot hold every
|
|
574
|
+
// later one forever.
|
|
575
|
+
await settleWithin(before, NEW_SESSION_GATE_MS);
|
|
576
|
+
const response = connection.conn.prompt({ sessionId, prompt });
|
|
577
|
+
void response.finally(release).catch(() => undefined);
|
|
578
|
+
return await response;
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
this.#unprompted = false;
|
|
582
|
+
this.#previousPrompt = send().then((response) => turn.items.push({ kind: "prompt_end", response }), (error) => turn.items.push({ kind: "prompt_error", error }));
|
|
583
|
+
}
|
|
584
|
+
#cancelTurn(connection) {
|
|
585
|
+
if (this.#turn === undefined)
|
|
586
|
+
return;
|
|
587
|
+
if (this.#acpSessionId !== undefined) {
|
|
588
|
+
void connection.conn.cancel({ sessionId: this.#acpSessionId }).catch(() => undefined);
|
|
589
|
+
}
|
|
590
|
+
this.#abandonTurn();
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* Stop means stopped: cancel the prompt, give the agent a moment to end it and save its
|
|
594
|
+
* session, then end the agent and whatever it was still running. The next run starts a new
|
|
595
|
+
* agent process and restores the same foreign session from the record.
|
|
596
|
+
*/
|
|
597
|
+
#stopTurn(connection) {
|
|
598
|
+
const prompt = this.#previousPrompt;
|
|
599
|
+
// Taken before cancelling: an agent may orphan the command it was running as it cancels.
|
|
600
|
+
const groups = connection.processGroups();
|
|
601
|
+
this.#cancelTurn(connection);
|
|
602
|
+
if (this.#connection === connection) {
|
|
603
|
+
this.#connection = undefined;
|
|
604
|
+
this.#acpSessionId = undefined;
|
|
605
|
+
this.#applied.clear();
|
|
606
|
+
}
|
|
607
|
+
this.#stopping = settleWithin(prompt, CANCEL_GRACE_MS).then(async () => {
|
|
608
|
+
connection.terminate(groups);
|
|
609
|
+
await settleWithin(connection.exited, CANCEL_GRACE_MS);
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
#abandonTurn() {
|
|
613
|
+
// A new session that will never report anything must not hold back the next one.
|
|
614
|
+
this.#openNewSessionGate();
|
|
615
|
+
const turn = this.#turn;
|
|
616
|
+
this.#turn = undefined;
|
|
617
|
+
if (turn === undefined)
|
|
618
|
+
return;
|
|
619
|
+
for (const call of turn.awaiting.values()) {
|
|
620
|
+
call.resolve({
|
|
621
|
+
content: [{ type: "text", text: "The Happy turn was cancelled." }],
|
|
622
|
+
isError: true,
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
turn.awaiting.clear();
|
|
626
|
+
}
|
|
627
|
+
#openNewSessionGate() {
|
|
628
|
+
this.#releaseNewSession?.();
|
|
629
|
+
this.#releaseNewSession = undefined;
|
|
630
|
+
}
|
|
631
|
+
async #commit(messages) {
|
|
632
|
+
if (this.#acpSessionId === undefined || this.#cwd === undefined)
|
|
633
|
+
return;
|
|
634
|
+
const inputs = inputMessages(messages);
|
|
635
|
+
this.#record = {
|
|
636
|
+
acpSessionId: this.#acpSessionId,
|
|
637
|
+
cwd: this.#cwd,
|
|
638
|
+
consumed: inputs.length,
|
|
639
|
+
fingerprint: acpTranscriptFingerprint(inputs),
|
|
640
|
+
};
|
|
641
|
+
await acpSessionRecordWrite(this.#options.stateDirectory, this.id, this.#record);
|
|
642
|
+
}
|
|
643
|
+
#answerPermission(params) {
|
|
644
|
+
// The agent asks before acting on its own. Read only refuses; every other mode lets
|
|
645
|
+
// this one action through.
|
|
646
|
+
const allow = this.#permissionMode !== "read_only";
|
|
647
|
+
const option = params.options.find((candidate) => candidate.kind === (allow ? "allow_once" : "reject_once")) ??
|
|
648
|
+
params.options.find((candidate) => candidate.kind.startsWith(allow ? "allow" : "reject"));
|
|
649
|
+
if (option === undefined)
|
|
650
|
+
return { outcome: { outcome: "cancelled" } };
|
|
651
|
+
return { outcome: { outcome: "selected", optionId: option.optionId } };
|
|
652
|
+
}
|
|
653
|
+
#usage(response, outputCharacters) {
|
|
654
|
+
const reported = response?.usage ?? undefined;
|
|
655
|
+
const output = reported?.outputTokens ?? Math.ceil(outputCharacters / 4);
|
|
656
|
+
const input = this.#contextUsed > 0 ? this.#contextUsed : (reported?.inputTokens ?? 0);
|
|
657
|
+
return {
|
|
658
|
+
input,
|
|
659
|
+
output,
|
|
660
|
+
cacheRead: reported?.cachedReadTokens ?? 0,
|
|
661
|
+
cacheWrite: reported?.cachedWriteTokens ?? 0,
|
|
662
|
+
totalTokens: input + output,
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
/** Everything the foreign session consumes. Its own responses are never sent back to it. */
|
|
667
|
+
function inputMessages(messages) {
|
|
668
|
+
return messages.filter((message) => message.role !== "assistant");
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* What a continuing foreign session is sent: the input after the `consumed` it has seen. Its own
|
|
672
|
+
* replies follow that input directly; a reply after any newer input came from somewhere else —
|
|
673
|
+
* another account, harness or model the conversation was switched to — so everything up to the
|
|
674
|
+
* last such reply is passed on as a transcript rather than lost.
|
|
675
|
+
*/
|
|
676
|
+
function acpDeltaPrompt(messages, consumed, images) {
|
|
677
|
+
let start = 0;
|
|
678
|
+
for (let seen = 0; start < messages.length && seen < consumed; start++) {
|
|
679
|
+
if (messages[start].role !== "assistant")
|
|
680
|
+
seen++;
|
|
681
|
+
}
|
|
682
|
+
while (start < messages.length && messages[start].role === "assistant")
|
|
683
|
+
start++;
|
|
684
|
+
const rest = messages.slice(start);
|
|
685
|
+
const answered = rest.findLastIndex((message) => message.role === "assistant");
|
|
686
|
+
if (answered === -1)
|
|
687
|
+
return acpPromptFromMessages(rest, images);
|
|
688
|
+
return acpCatchUpPrompt(rest.slice(0, answered + 1), rest.slice(answered + 1), images);
|
|
689
|
+
}
|
|
690
|
+
function images(connection) {
|
|
691
|
+
return connection.init.agentCapabilities?.promptCapabilities?.image === true;
|
|
692
|
+
}
|
|
693
|
+
function errorText(error) {
|
|
694
|
+
if (typeof error !== "object" || error === null || !("message" in error))
|
|
695
|
+
return String(error);
|
|
696
|
+
const message = String(error.message);
|
|
697
|
+
// An ACP agent's own failure arrives as a JSON-RPC internal error carrying its text.
|
|
698
|
+
const details = error.data?.details;
|
|
699
|
+
return typeof details === "string" && details.length > 0 ? `${message}: ${details}` : message;
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* The agent's service refused the request as too many, which passes in seconds. A quota or
|
|
703
|
+
* usage limit is often sent with the same status but resets in hours, so it is never retried.
|
|
704
|
+
*/
|
|
705
|
+
function isRateLimited(error) {
|
|
706
|
+
const text = errorText(error);
|
|
707
|
+
return (/\b429\b|too many requests|rate[ _-]?limit(?:ed)?\b/iu.test(text) &&
|
|
708
|
+
!/quota|usage[ _-]?limit|weekly|monthly|daily|session limit|billing|credits?\b|plan limit|resets? (?:at|in|on)\b|try again (?:at|in \d+ ?(?:h|hours?|d|days?)\b)/iu.test(text));
|
|
709
|
+
}
|
|
710
|
+
function errorDone(error, stderr) {
|
|
711
|
+
const message = errorText(error);
|
|
712
|
+
const tail = stderr.trim().split("\n").slice(-5).join("\n");
|
|
713
|
+
return {
|
|
714
|
+
type: "done",
|
|
715
|
+
state: "error",
|
|
716
|
+
kind: "internal_error",
|
|
717
|
+
message: tail.length === 0 ? message : `${message}\n${tail}`,
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
function abortPromise(signal) {
|
|
721
|
+
return new Promise((resolve) => {
|
|
722
|
+
if (signal === undefined)
|
|
723
|
+
return;
|
|
724
|
+
if (signal.aborted) {
|
|
725
|
+
resolve(ABORTED);
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
signal.addEventListener("abort", () => resolve(ABORTED), { once: true });
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
async function settleWithin(promise, ms) {
|
|
732
|
+
await Promise.race([
|
|
733
|
+
promise.catch(() => undefined),
|
|
734
|
+
new Promise((resolve) => setTimeout(resolve, ms).unref()),
|
|
735
|
+
]);
|
|
736
|
+
}
|
|
737
|
+
//# sourceMappingURL=AcpSession.js.map
|