@agentknight/sdk 0.9.64 → 0.9.69
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/chunks/{acp-adapter-MBYKOCA2.js → acp-adapter-VJ2OUSBS.js} +41 -4
- package/dist/chunks/{chunk-3AMFPDE5.js → chunk-2D34UDII.js} +4 -13
- package/dist/chunks/chunk-35OF2ZNS.js +275 -0
- package/dist/chunks/{chunk-A4YCCQ3I.js → chunk-5QYL6NKJ.js} +1 -1
- package/dist/chunks/chunk-ES2N66EH.js +109 -0
- package/dist/chunks/{chunk-P2PH5KMV.js → chunk-F5YCEWE4.js} +9 -0
- package/dist/chunks/{chunk-7CNBPLNE.js → chunk-IRYEOV62.js} +5 -2
- package/dist/chunks/{chunk-7OGTK7KB.js → chunk-J63A5OLO.js} +1 -1
- package/dist/chunks/chunk-LA6A4TUM.js +302 -0
- package/dist/chunks/{chunk-ZNQ2I5EF.js → chunk-LU73CEHE.js} +11 -132
- package/dist/chunks/chunk-MB34W52S.js +78 -0
- package/dist/chunks/{chunk-CHKNC6PD.js → chunk-MH7FDSTY.js} +1 -1
- package/dist/chunks/{chunk-ALUQLM54.js → chunk-Q5NNNSU2.js} +2 -2
- package/dist/chunks/chunk-UTF7KLMJ.js +11 -0
- package/dist/chunks/chunk-WAPJZKUK.js +115 -0
- package/dist/chunks/{chunk-SIFCCGXF.js → chunk-ZAU2MYQI.js} +2 -2
- package/dist/chunks/{claude-adapter-D3JWXMNX.js → claude-adapter-FZNLF5XN.js} +240 -27
- package/dist/chunks/{codex-adapter-655KHW7H.js → codex-adapter-5ZVOAT6O.js} +249 -66
- package/dist/chunks/{copilot-adapter-EZUXHBE3.js → copilot-adapter-V6RAQ4WK.js} +58 -149
- package/dist/chunks/{managed-agent-adapter-RIXRCURU.js → managed-agent-adapter-THUSTKRW.js} +35 -24
- package/dist/chunks/{pi-adapter-LAD5GOCP.js → pi-adapter-EHCSR5I2.js} +329 -54
- package/dist/configuration.js +4 -4
- package/dist/index.d.ts +15 -8
- package/dist/index.js +37 -35
- package/dist/runtime.js +2 -2
- package/dist/session-analytics-worker.js +6 -5
- package/package.json +3 -3
- package/dist/chunks/chunk-CM5LVXVL.js +0 -572
- package/dist/chunks/chunk-H4SHMWQ6.js +0 -48
|
@@ -1,22 +1,33 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
stagePromptAttachments,
|
|
3
|
+
validatePromptAttachments
|
|
4
|
+
} from "./chunk-ES2N66EH.js";
|
|
5
|
+
import "./chunk-35OF2ZNS.js";
|
|
6
|
+
import {
|
|
7
|
+
decodeTimelineImage,
|
|
8
|
+
latestPreviewItems,
|
|
9
|
+
normalizeImageMimeType,
|
|
10
|
+
splitTimelineImages
|
|
11
|
+
} from "./chunk-WAPJZKUK.js";
|
|
4
12
|
import {
|
|
5
13
|
AgentSessionRenameError,
|
|
14
|
+
SessionDeletionRejectedError,
|
|
6
15
|
UnsupportedAgentOperationError,
|
|
7
16
|
validateSessionName
|
|
8
|
-
} from "./chunk-
|
|
9
|
-
import "./chunk-
|
|
17
|
+
} from "./chunk-IRYEOV62.js";
|
|
18
|
+
import "./chunk-J63A5OLO.js";
|
|
10
19
|
import {
|
|
20
|
+
ConversationAttachmentSchema,
|
|
11
21
|
InteractionRequestSchema,
|
|
12
22
|
REASONING_EFFORTS,
|
|
13
23
|
SESSION_TIMELINE_PAGE_SIZE
|
|
14
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-F5YCEWE4.js";
|
|
15
25
|
|
|
16
26
|
// src/pi-adapter.ts
|
|
17
27
|
import { createHash as createHash2, randomUUID } from "node:crypto";
|
|
28
|
+
import { closeSync, lstatSync, openSync, readSync, realpathSync, unlinkSync } from "node:fs";
|
|
18
29
|
import { open, readdir, realpath, stat } from "node:fs/promises";
|
|
19
|
-
import { dirname, join, resolve } from "node:path";
|
|
30
|
+
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
20
31
|
import { getSupportedThinkingLevels } from "@earendil-works/pi-ai";
|
|
21
32
|
import {
|
|
22
33
|
DefaultResourceLoader,
|
|
@@ -26,14 +37,23 @@ import {
|
|
|
26
37
|
SettingsManager,
|
|
27
38
|
VERSION,
|
|
28
39
|
createAgentSession,
|
|
40
|
+
formatDimensionNote,
|
|
29
41
|
getAgentDir,
|
|
30
|
-
hasTrustRequiringProjectResources
|
|
42
|
+
hasTrustRequiringProjectResources,
|
|
43
|
+
resizeImage
|
|
31
44
|
} from "@earendil-works/pi-coding-agent";
|
|
32
45
|
|
|
33
46
|
// src/pi-timeline.ts
|
|
34
47
|
import { createHash } from "node:crypto";
|
|
48
|
+
import { z } from "zod";
|
|
35
49
|
var FINAL_REVISION = 1e9;
|
|
36
50
|
var PI_PROMPT_SOURCE_ENTRY = "agentknight.prompt-source.v1";
|
|
51
|
+
var PromptSourceSchema = z.object({
|
|
52
|
+
projectionId: z.string().min(1),
|
|
53
|
+
messageId: z.string().min(1).max(256),
|
|
54
|
+
content: z.string().max(1e5).optional(),
|
|
55
|
+
attachments: z.array(ConversationAttachmentSchema).max(8).optional()
|
|
56
|
+
});
|
|
37
57
|
function key(value) {
|
|
38
58
|
return createHash("sha256").update(value).digest("hex").slice(0, 32);
|
|
39
59
|
}
|
|
@@ -43,9 +63,8 @@ var PiTimeline = class {
|
|
|
43
63
|
this.#turnId = `pi:${sessionId}`;
|
|
44
64
|
for (const entry of entries) {
|
|
45
65
|
if (entry.type !== "custom" || entry.customType !== PI_PROMPT_SOURCE_ENTRY) continue;
|
|
46
|
-
const
|
|
47
|
-
if (
|
|
48
|
-
this.#promptSources.set(data.projectionId, data.messageId);
|
|
66
|
+
const source = PromptSourceSchema.safeParse(entry.data);
|
|
67
|
+
if (source.success) this.#promptSources.set(source.data.projectionId, source.data);
|
|
49
68
|
}
|
|
50
69
|
for (const entry of entries) {
|
|
51
70
|
if (entry.type === "message") {
|
|
@@ -66,7 +85,7 @@ var PiTimeline = class {
|
|
|
66
85
|
#activeMessages = /* @__PURE__ */ new Map();
|
|
67
86
|
#promptSources = /* @__PURE__ */ new Map();
|
|
68
87
|
#turnId;
|
|
69
|
-
event(event,
|
|
88
|
+
event(event, source) {
|
|
70
89
|
const previous = new Map(this.items);
|
|
71
90
|
if (event.type === "message_start" || event.type === "message_update" || event.type === "message_end") {
|
|
72
91
|
const signature = this.#signature(event.message);
|
|
@@ -75,7 +94,13 @@ var PiTimeline = class {
|
|
|
75
94
|
id = this.#nextMessageId(event.message);
|
|
76
95
|
this.#activeMessages.set(signature, id);
|
|
77
96
|
}
|
|
78
|
-
if (event.message.role === "user" &&
|
|
97
|
+
if (event.message.role === "user" && source) {
|
|
98
|
+
this.#promptSources.set(id, {
|
|
99
|
+
projectionId: id,
|
|
100
|
+
messageId: source.id,
|
|
101
|
+
...source.attachments.length ? { content: source.text, attachments: source.attachments } : {}
|
|
102
|
+
});
|
|
103
|
+
}
|
|
79
104
|
this.#message(event.message, id, event.type === "message_end");
|
|
80
105
|
if (event.type === "message_end") this.#activeMessages.delete(signature);
|
|
81
106
|
} else if (event.type === "tool_execution_start" || event.type === "tool_execution_update" || event.type === "tool_execution_end") {
|
|
@@ -84,9 +109,6 @@ var PiTimeline = class {
|
|
|
84
109
|
event.toolName,
|
|
85
110
|
event.type === "tool_execution_end" ? event.isError ? "failed" : "completed" : "running"
|
|
86
111
|
);
|
|
87
|
-
if (event.type === "tool_execution_end") {
|
|
88
|
-
this.#text(event.result.content, this.#toolId(event.toolCallId), this.items.get(this.#toolId(event.toolCallId)).timestamp);
|
|
89
|
-
}
|
|
90
112
|
}
|
|
91
113
|
return [...this.items.values()].filter((item) => previous.get(item.id) !== item);
|
|
92
114
|
}
|
|
@@ -118,7 +140,8 @@ var PiTimeline = class {
|
|
|
118
140
|
const timestamp = new Date(message.timestamp).toISOString();
|
|
119
141
|
if (message.role === "user") this.#turnId = id;
|
|
120
142
|
if (message.role === "user" || message.role === "assistant") {
|
|
121
|
-
const
|
|
143
|
+
const source = this.#promptSources.get(id);
|
|
144
|
+
const content = source?.content ?? this.#text(message.content, id, timestamp, message.role === "user");
|
|
122
145
|
const limit = message.role === "user" ? 1e5 : 5e5;
|
|
123
146
|
if (content.length > limit) {
|
|
124
147
|
this.notice(`${id}:truncated`, timestamp, "warning", "Content truncated", "The PI message exceeds the timeline content limit.");
|
|
@@ -129,11 +152,16 @@ var PiTimeline = class {
|
|
|
129
152
|
turnId: this.#turnId,
|
|
130
153
|
timestamp,
|
|
131
154
|
sourceEventIds: [id],
|
|
132
|
-
sourceMessageIds: [id, ...
|
|
155
|
+
sourceMessageIds: [id, ...source ? [source.messageId] : []],
|
|
133
156
|
content: content.slice(0, limit)
|
|
134
157
|
};
|
|
135
158
|
if (message.role === "user") {
|
|
136
|
-
this.#put({
|
|
159
|
+
this.#put({
|
|
160
|
+
...base,
|
|
161
|
+
kind: "human-message",
|
|
162
|
+
actor: "human",
|
|
163
|
+
attachments: this.#userAttachments(message.content, source?.attachments ?? [], id, timestamp)
|
|
164
|
+
});
|
|
137
165
|
} else {
|
|
138
166
|
this.#put({
|
|
139
167
|
...base,
|
|
@@ -152,8 +180,7 @@ var PiTimeline = class {
|
|
|
152
180
|
}
|
|
153
181
|
}
|
|
154
182
|
} else if (message.role === "toolResult") {
|
|
155
|
-
this.#
|
|
156
|
-
this.#text(message.content, this.#toolId(message.toolCallId), timestamp);
|
|
183
|
+
if (final) this.#toolResult(message, timestamp);
|
|
157
184
|
} else if (message.role === "bashExecution") {
|
|
158
185
|
this.notice(id, timestamp, message.exitCode === 0 ? "info" : "error", message.command, message.output);
|
|
159
186
|
} else if (message.role === "custom") {
|
|
@@ -164,9 +191,89 @@ var PiTimeline = class {
|
|
|
164
191
|
this.notice(`${id}:unsupported`, timestamp, "warning", "Unsupported PI message", "This native message type cannot be displayed.");
|
|
165
192
|
}
|
|
166
193
|
}
|
|
167
|
-
#
|
|
194
|
+
#toolResult(message, timestamp) {
|
|
195
|
+
const { toolCallId, toolName, content, isError } = message;
|
|
196
|
+
this.#tool(toolCallId, toolName, isError ? "failed" : "completed", timestamp);
|
|
197
|
+
const toolId = this.#toolId(toolCallId);
|
|
198
|
+
const turnId = this.items.get(toolId)?.turnId ?? this.#turnId;
|
|
199
|
+
this.#text(content, toolId, timestamp, true);
|
|
200
|
+
const images = /* @__PURE__ */ new Map();
|
|
201
|
+
let failed = false;
|
|
202
|
+
for (const part of content) {
|
|
203
|
+
if (part.type !== "image") continue;
|
|
204
|
+
const mimeType = normalizeImageMimeType(part.mimeType);
|
|
205
|
+
const image = decodeTimelineImage(part.data, mimeType, "content");
|
|
206
|
+
if ("failure" in image) {
|
|
207
|
+
failed = true;
|
|
208
|
+
} else {
|
|
209
|
+
const key2 = `${mimeType}:${image.sha256}`;
|
|
210
|
+
if (!images.has(key2)) images.set(key2, {
|
|
211
|
+
kind: "image",
|
|
212
|
+
name: `${toolName.trim().slice(0, 256) || "PI"} image ${images.size + 1}`,
|
|
213
|
+
mimeType,
|
|
214
|
+
...image
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (failed) this.notice(
|
|
219
|
+
`${toolId}:image-unavailable`,
|
|
220
|
+
timestamp,
|
|
221
|
+
"warning",
|
|
222
|
+
"Image unavailable",
|
|
223
|
+
"PI returned an invalid image, an unsupported format, or an image that exceeds the size limit."
|
|
224
|
+
);
|
|
225
|
+
for (const [index, attachments] of splitTimelineImages([...images.values()], (image) => image.byteLength ?? 0).entries()) {
|
|
226
|
+
const id = `${toolId}:image:${index}`;
|
|
227
|
+
this.#put({
|
|
228
|
+
id,
|
|
229
|
+
revision: FINAL_REVISION,
|
|
230
|
+
turnId,
|
|
231
|
+
timestamp,
|
|
232
|
+
sourceEventIds: [toolId],
|
|
233
|
+
kind: "assistant-message",
|
|
234
|
+
actor: "assistant",
|
|
235
|
+
content: "",
|
|
236
|
+
final: true,
|
|
237
|
+
attachments
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
#userAttachments(content, metadata, id, timestamp) {
|
|
242
|
+
const images = metadata.filter((attachment) => attachment.kind === "image");
|
|
243
|
+
const attachments = [];
|
|
244
|
+
if (typeof content !== "string") {
|
|
245
|
+
for (const part of content) {
|
|
246
|
+
if (part.type !== "image") continue;
|
|
247
|
+
const bytes = Buffer.from(part.data, "base64");
|
|
248
|
+
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
|
249
|
+
const index = images.findIndex((image2) => image2.sha256 === sha256);
|
|
250
|
+
const metadata2 = index === -1 ? void 0 : images.splice(index, 1)[0];
|
|
251
|
+
const image = ConversationAttachmentSchema.safeParse({
|
|
252
|
+
kind: "image",
|
|
253
|
+
name: metadata2?.name ?? "Image",
|
|
254
|
+
mimeType: part.mimeType,
|
|
255
|
+
data: part.data,
|
|
256
|
+
byteLength: bytes.length,
|
|
257
|
+
sha256
|
|
258
|
+
});
|
|
259
|
+
if (image.success) attachments.push(image.data);
|
|
260
|
+
else this.notice(`${id}:unsupported`, timestamp, "warning", "Unsupported PI content", "This image cannot be displayed.");
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
if (images.length) {
|
|
264
|
+
this.notice(
|
|
265
|
+
`${id}:missing-image`,
|
|
266
|
+
timestamp,
|
|
267
|
+
"error",
|
|
268
|
+
"Image unavailable",
|
|
269
|
+
"PI omitted an uploaded image from the model input. Check the image format and retry."
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
return [...attachments, ...metadata.filter((attachment) => attachment.kind !== "image")];
|
|
273
|
+
}
|
|
274
|
+
#text(content, id, timestamp, images = false) {
|
|
168
275
|
if (typeof content === "string") return content;
|
|
169
|
-
if (content.some((part) => part.type !== "text" && part.type !== "thinking" && part.type !== "toolCall")) {
|
|
276
|
+
if (content.some((part) => part.type !== "text" && part.type !== "thinking" && part.type !== "toolCall" && !(images && part.type === "image"))) {
|
|
170
277
|
this.notice(`${id}:unsupported`, timestamp, "warning", "Unsupported PI content", "This message contains media that cannot be displayed by this adapter.");
|
|
171
278
|
}
|
|
172
279
|
return content.filter((part) => part.type === "text").map((part) => part.text ?? "").join("");
|
|
@@ -210,6 +317,15 @@ var PiOpeningCancelledError = class extends Error {
|
|
|
210
317
|
};
|
|
211
318
|
var isMissing = (error) => error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
212
319
|
var modelId = (model) => `${model.provider}/${model.id}`;
|
|
320
|
+
function assertSessionHeader(info, buffer) {
|
|
321
|
+
const header = JSON.parse(buffer.toString("utf8").split("\n", 1)[0] ?? "");
|
|
322
|
+
if (typeof header !== "object" || header === null || !("type" in header) || header.type !== "session" || !("id" in header) || header.id !== info.id || !("cwd" in header) || header.cwd !== info.cwd) {
|
|
323
|
+
throw new Error(`PI session header does not match the known session: ${info.id}`);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
function isIdleRuntime(runtime) {
|
|
327
|
+
return !runtime.busy && !runtime.aborting && !runtime.configuring && runtime.queue.length === 0 && runtime.primarySource === void 0 && runtime.steeringSources.length === 0 && runtime.followUpSources.length === 0 && runtime.session.isIdle === true && runtime.session.isStreaming === false && runtime.session.isCompacting === false && runtime.session.isRetrying === false && runtime.session.isBashRunning === false && runtime.session.hasPendingBashMessages === false && runtime.session.pendingMessageCount === 0;
|
|
328
|
+
}
|
|
213
329
|
var PiCodingAgentAdapter = class {
|
|
214
330
|
agentId = "pi";
|
|
215
331
|
sdkVersion = VERSION;
|
|
@@ -217,8 +333,8 @@ var PiCodingAgentAdapter = class {
|
|
|
217
333
|
supportsReasoningEffort = true;
|
|
218
334
|
supportsSessionListUpdates = true;
|
|
219
335
|
supportsAssistantPreview = true;
|
|
220
|
-
supportsSessionDelete =
|
|
221
|
-
supportsFileAttachments =
|
|
336
|
+
supportsSessionDelete = true;
|
|
337
|
+
supportsFileAttachments = true;
|
|
222
338
|
#agentDirectory;
|
|
223
339
|
#timeout;
|
|
224
340
|
#dependencies;
|
|
@@ -230,6 +346,7 @@ var PiCodingAgentAdapter = class {
|
|
|
230
346
|
#opening = /* @__PURE__ */ new Map();
|
|
231
347
|
#cancelledOpenings = /* @__PURE__ */ new Set();
|
|
232
348
|
#pending = /* @__PURE__ */ new Map();
|
|
349
|
+
#sessionDeletionRevision = 0;
|
|
233
350
|
#modelRuntime;
|
|
234
351
|
#modelRefresh;
|
|
235
352
|
#callbacks;
|
|
@@ -294,7 +411,7 @@ var PiCodingAgentAdapter = class {
|
|
|
294
411
|
if (errors.length) throw new AggregateError(errors, "PI shutdown failed.");
|
|
295
412
|
}
|
|
296
413
|
async canUpgrade() {
|
|
297
|
-
return this.#started && !this.#stopping && this.#opening.size === 0 && this.#startingPrompts.size === 0 && this.#pending.size === 0 && this.#modelRefresh === void 0 && [...this.#runtimes.values()].every(
|
|
414
|
+
return this.#started && !this.#stopping && this.#opening.size === 0 && this.#startingPrompts.size === 0 && this.#pending.size === 0 && this.#modelRefresh === void 0 && [...this.#runtimes.values()].every(isIdleRuntime);
|
|
298
415
|
}
|
|
299
416
|
async listModels() {
|
|
300
417
|
this.#assertStarted();
|
|
@@ -401,6 +518,34 @@ var PiCodingAgentAdapter = class {
|
|
|
401
518
|
configOptions: this.#configOptions(manager.getCwd())
|
|
402
519
|
};
|
|
403
520
|
}
|
|
521
|
+
async deleteSession(sessionId) {
|
|
522
|
+
this.#assertStarted();
|
|
523
|
+
if (!this.#sessions.has(sessionId)) await this.#refreshSessions();
|
|
524
|
+
this.#assertStarted();
|
|
525
|
+
const info = this.#requireSession(sessionId);
|
|
526
|
+
const runtime = this.#runtimes.get(sessionId);
|
|
527
|
+
if (this.#opening.has(sessionId) || this.#startingPrompts.has(sessionId) || this.#cancelledOpenings.has(sessionId) || runtime && !isIdleRuntime(runtime) || [...this.#pending.values()].some((pending) => pending.sessionId === sessionId)) {
|
|
528
|
+
throw new SessionDeletionRejectedError("Cannot delete a PI session while it is active. Stop it and try again.");
|
|
529
|
+
}
|
|
530
|
+
if (runtime && (runtime.session.sessionId !== sessionId || !runtime.session.sessionFile || relative(info.path, runtime.session.sessionFile) !== "")) {
|
|
531
|
+
throw new SessionDeletionRejectedError("PI runtime no longer matches the known session file.");
|
|
532
|
+
}
|
|
533
|
+
try {
|
|
534
|
+
this.#unlinkSession(info);
|
|
535
|
+
} catch (error) {
|
|
536
|
+
throw new SessionDeletionRejectedError("Could not remove the native PI session file.", { cause: error });
|
|
537
|
+
}
|
|
538
|
+
this.#sessionDeletionRevision++;
|
|
539
|
+
this.#sessions.delete(sessionId);
|
|
540
|
+
this.#prepared.delete(sessionId);
|
|
541
|
+
this.#openingNotices.delete(sessionId);
|
|
542
|
+
this.#runtimes.delete(sessionId);
|
|
543
|
+
if (runtime) {
|
|
544
|
+
runtime.unsubscribe();
|
|
545
|
+
runtime.session.dispose();
|
|
546
|
+
}
|
|
547
|
+
this.#callbacks?.onSessionInventoryChanged(sessionId);
|
|
548
|
+
}
|
|
404
549
|
async renameSession(sessionId, name, assertAccess) {
|
|
405
550
|
const requested = validateSessionName(name);
|
|
406
551
|
this.#assertStarted();
|
|
@@ -413,6 +558,7 @@ var PiCodingAgentAdapter = class {
|
|
|
413
558
|
runtime = pending ? await pending : this.#runtimes.get(sessionId);
|
|
414
559
|
this.#assertStarted();
|
|
415
560
|
assertAccess?.();
|
|
561
|
+
const info = this.#requireSession(sessionId);
|
|
416
562
|
let confirmed;
|
|
417
563
|
if (runtime) {
|
|
418
564
|
runtime.session.setSessionName(requested);
|
|
@@ -426,8 +572,7 @@ var PiCodingAgentAdapter = class {
|
|
|
426
572
|
if (confirmed !== requested) {
|
|
427
573
|
throw new AgentSessionRenameError("SESSION_RENAME_FAILED", "PI did not confirm the requested session name.");
|
|
428
574
|
}
|
|
429
|
-
|
|
430
|
-
if (info) info.name = confirmed;
|
|
575
|
+
info.name = confirmed;
|
|
431
576
|
this.#callbacks?.onSessionInventoryChanged(sessionId);
|
|
432
577
|
return confirmed;
|
|
433
578
|
}
|
|
@@ -459,6 +604,7 @@ var PiCodingAgentAdapter = class {
|
|
|
459
604
|
return { ...current, configOptions: this.#configOptions(process.cwd()) };
|
|
460
605
|
}
|
|
461
606
|
const runtime = await this.#runtime(sessionId);
|
|
607
|
+
if (this.#runtimes.get(sessionId) !== runtime) throw new Error(`PI session is no longer open: ${sessionId}`);
|
|
462
608
|
const model = options.modelId === void 0 ? runtime.session.model : this.#model(options.modelId);
|
|
463
609
|
if (!model) throw new Error("No PI model is selected.");
|
|
464
610
|
const thinking = options.reasoningEffort === void 0 ? void 0 : this.#thinking(model, options.reasoningEffort, runtime.session.settingsManager);
|
|
@@ -466,8 +612,14 @@ var PiCodingAgentAdapter = class {
|
|
|
466
612
|
const thinkingChanged = thinking !== void 0 && thinking !== runtime.session.thinkingLevel;
|
|
467
613
|
if (!modelChanged && !thinkingChanged) return this.#configuration(runtime);
|
|
468
614
|
if (runtime.busy || runtime.session.isStreaming) throw new Error("PI session configuration cannot change while a prompt is running.");
|
|
469
|
-
if (
|
|
470
|
-
|
|
615
|
+
if (runtime.configuring) throw new Error("PI session configuration is already changing.");
|
|
616
|
+
runtime.configuring = true;
|
|
617
|
+
try {
|
|
618
|
+
if (modelChanged) await runtime.session.setModel(model);
|
|
619
|
+
if (thinking !== void 0 && (modelChanged || thinkingChanged)) runtime.session.setThinkingLevel(thinking);
|
|
620
|
+
} finally {
|
|
621
|
+
runtime.configuring = false;
|
|
622
|
+
}
|
|
471
623
|
this.#callbacks?.onSessionInventoryChanged(sessionId);
|
|
472
624
|
return this.#configuration(runtime);
|
|
473
625
|
}
|
|
@@ -535,22 +687,38 @@ var PiCodingAgentAdapter = class {
|
|
|
535
687
|
setSessionCallbacks(callbacks) {
|
|
536
688
|
this.#callbacks = callbacks;
|
|
537
689
|
}
|
|
538
|
-
async sendPrompt(sessionId, prompt, mode, attachments, _persistInteractions, fileAttachments) {
|
|
539
|
-
|
|
540
|
-
if (fileAttachments
|
|
541
|
-
if (!prompt.trim()) throw new Error("PI prompt must not be empty.");
|
|
690
|
+
async sendPrompt(sessionId, prompt, mode, attachments = [], _persistInteractions, fileAttachments = []) {
|
|
691
|
+
const validated = validatePromptAttachments(attachments, fileAttachments);
|
|
692
|
+
if (!prompt.trim() && !attachments.length && !fileAttachments.length) throw new Error("PI prompt must not be empty.");
|
|
542
693
|
if (mode !== "enqueue" && mode !== "immediate") throw new UnsupportedAgentOperationError("pi", `prompt delivery mode ${mode}`);
|
|
543
694
|
this.#assertStarted();
|
|
544
695
|
let runtime = this.#runtimes.get(sessionId);
|
|
545
696
|
if (!runtime) {
|
|
546
697
|
const configuration = await this.getSessionConfiguration(sessionId);
|
|
547
698
|
this.#assertStarted();
|
|
699
|
+
this.#requireSession(sessionId);
|
|
548
700
|
if (!configuration.modelId) throw new Error("No PI model is selected.");
|
|
549
|
-
this.#model(configuration.modelId);
|
|
701
|
+
this.#validateImages(this.#model(configuration.modelId), attachments);
|
|
550
702
|
runtime = this.#runtimes.get(sessionId);
|
|
551
703
|
}
|
|
552
704
|
if (this.#cancelledOpenings.has(sessionId)) throw new Error("PI session is being aborted.");
|
|
553
|
-
const message = {
|
|
705
|
+
const message = {
|
|
706
|
+
id: randomUUID(),
|
|
707
|
+
text: prompt,
|
|
708
|
+
nativeText: prompt,
|
|
709
|
+
mode,
|
|
710
|
+
files: validated.files,
|
|
711
|
+
images: [],
|
|
712
|
+
pendingImages: attachments.map((image) => ({ ...image })),
|
|
713
|
+
attachments: attachments.map(({ name, mimeType, sha256, byteLength }) => ({
|
|
714
|
+
kind: "image",
|
|
715
|
+
name,
|
|
716
|
+
mimeType,
|
|
717
|
+
sha256,
|
|
718
|
+
byteLength,
|
|
719
|
+
imageRef: "sha256"
|
|
720
|
+
}))
|
|
721
|
+
};
|
|
554
722
|
const startup = this.#startingPrompts.get(sessionId);
|
|
555
723
|
if (startup) {
|
|
556
724
|
if (startup.cancelled) throw new Error("PI session is being aborted.");
|
|
@@ -563,7 +731,7 @@ var PiCodingAgentAdapter = class {
|
|
|
563
731
|
}
|
|
564
732
|
if (runtime.aborting) throw new Error("PI session is being aborted.");
|
|
565
733
|
if (!runtime.session.model) throw new Error("No PI model is selected.");
|
|
566
|
-
this.#model(modelId(runtime.session.model));
|
|
734
|
+
this.#validateImages(this.#model(modelId(runtime.session.model)), attachments);
|
|
567
735
|
const queued = runtime.busy || runtime.session.isStreaming;
|
|
568
736
|
runtime.queue.push(message);
|
|
569
737
|
if (queued) this.#dispatchQueued(runtime);
|
|
@@ -617,6 +785,11 @@ var PiCodingAgentAdapter = class {
|
|
|
617
785
|
#assertStarted() {
|
|
618
786
|
if (!this.#started || this.#stopping) throw new Error("PI adapter is not running.");
|
|
619
787
|
}
|
|
788
|
+
#requireSession(sessionId) {
|
|
789
|
+
const info = this.#sessions.get(sessionId);
|
|
790
|
+
if (!info) throw new Error(`Unknown PI session: ${sessionId}`);
|
|
791
|
+
return info;
|
|
792
|
+
}
|
|
620
793
|
#checkRegistry() {
|
|
621
794
|
const registry = this.#modelRuntime;
|
|
622
795
|
if (!registry) throw new Error("PI adapter has not initialized its model registry.");
|
|
@@ -633,6 +806,11 @@ var PiCodingAgentAdapter = class {
|
|
|
633
806
|
if (!registry.getAvailableSnapshot().some((candidate) => modelId(candidate) === id)) throw new Error(`Authentication is missing or the PI model is unavailable: ${id}`);
|
|
634
807
|
return model;
|
|
635
808
|
}
|
|
809
|
+
#validateImages(model, images) {
|
|
810
|
+
if (images.length && !model.input.includes("image")) {
|
|
811
|
+
throw new Error(`PI model ${modelId(model)} does not support image input. Select a model with image support.`);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
636
814
|
#settings(cwd) {
|
|
637
815
|
const disk = SettingsManager.create(cwd, this.#agentDirectory, { projectTrusted: false });
|
|
638
816
|
this.#checkSettings(disk);
|
|
@@ -684,6 +862,7 @@ var PiCodingAgentAdapter = class {
|
|
|
684
862
|
};
|
|
685
863
|
}
|
|
686
864
|
async #refreshSessions() {
|
|
865
|
+
const revision = this.#sessionDeletionRevision;
|
|
687
866
|
const root = join(this.#agentDirectory, "sessions");
|
|
688
867
|
let directories;
|
|
689
868
|
try {
|
|
@@ -693,6 +872,7 @@ var PiCodingAgentAdapter = class {
|
|
|
693
872
|
directories = [];
|
|
694
873
|
}
|
|
695
874
|
const lists = await Promise.all(directories.filter((entry) => entry.isDirectory()).map((entry) => SessionManager.listAll(join(root, entry.name))));
|
|
875
|
+
if (revision !== this.#sessionDeletionRevision) return this.#refreshSessions();
|
|
696
876
|
const next = /* @__PURE__ */ new Map();
|
|
697
877
|
for (const info of lists.flat()) {
|
|
698
878
|
if (next.has(info.id) && next.get(info.id).path !== info.path) throw new Error(`Duplicate PI native session ID: ${info.id}`);
|
|
@@ -710,6 +890,34 @@ var PiCodingAgentAdapter = class {
|
|
|
710
890
|
this.#sessions.clear();
|
|
711
891
|
for (const [id, info] of next) this.#sessions.set(id, info);
|
|
712
892
|
}
|
|
893
|
+
#unlinkSession(info) {
|
|
894
|
+
const root = join(this.#agentDirectory, "sessions");
|
|
895
|
+
const parent = dirname(info.path);
|
|
896
|
+
if (relative(root, dirname(parent)) !== "" || !info.path.endsWith(".jsonl")) {
|
|
897
|
+
throw new Error("PI session file is outside the native session directory.");
|
|
898
|
+
}
|
|
899
|
+
let path;
|
|
900
|
+
try {
|
|
901
|
+
const directory = join(realpathSync(this.#agentDirectory), "sessions");
|
|
902
|
+
const workspace = join(directory, basename(parent));
|
|
903
|
+
if (!lstatSync(directory).isDirectory() || !lstatSync(workspace).isDirectory()) {
|
|
904
|
+
throw new Error("PI session storage must use real directories.");
|
|
905
|
+
}
|
|
906
|
+
path = join(workspace, basename(info.path));
|
|
907
|
+
if (!lstatSync(path).isFile()) throw new Error("PI session storage must be a regular file.");
|
|
908
|
+
} catch (error) {
|
|
909
|
+
if (isMissing(error)) return;
|
|
910
|
+
throw error;
|
|
911
|
+
}
|
|
912
|
+
const fd = openSync(path, "r");
|
|
913
|
+
try {
|
|
914
|
+
const buffer = Buffer.alloc(64 * 1024);
|
|
915
|
+
assertSessionHeader(info, buffer.subarray(0, readSync(fd, buffer, 0, buffer.length, 0)));
|
|
916
|
+
} finally {
|
|
917
|
+
closeSync(fd);
|
|
918
|
+
}
|
|
919
|
+
unlinkSync(path);
|
|
920
|
+
}
|
|
713
921
|
async #openKnownSession(sessionId) {
|
|
714
922
|
const prepared = this.#prepared.get(sessionId);
|
|
715
923
|
if (prepared) return prepared.manager;
|
|
@@ -723,14 +931,11 @@ var PiCodingAgentAdapter = class {
|
|
|
723
931
|
try {
|
|
724
932
|
const buffer = Buffer.alloc(64 * 1024);
|
|
725
933
|
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
726
|
-
|
|
727
|
-
const header = JSON.parse(firstLine);
|
|
728
|
-
if (typeof header !== "object" || header === null || !("type" in header) || header.type !== "session" || !("id" in header) || header.id !== sessionId || !("cwd" in header) || typeof header.cwd !== "string" || header.cwd !== info.cwd) {
|
|
729
|
-
throw new Error(`PI session header does not match the known session: ${sessionId}`);
|
|
730
|
-
}
|
|
934
|
+
assertSessionHeader(info, buffer.subarray(0, bytesRead));
|
|
731
935
|
} finally {
|
|
732
936
|
await handle.close();
|
|
733
937
|
}
|
|
938
|
+
if (this.#requireSession(sessionId).path !== info.path) throw new Error(`PI session file changed while opening: ${sessionId}`);
|
|
734
939
|
const manager = SessionManager.open(info.path, dirname(info.path));
|
|
735
940
|
if (manager.getSessionId() !== sessionId) throw new Error(`PI session changed while opening: ${sessionId}`);
|
|
736
941
|
return manager;
|
|
@@ -814,6 +1019,7 @@ var PiCodingAgentAdapter = class {
|
|
|
814
1019
|
},
|
|
815
1020
|
busy: false,
|
|
816
1021
|
aborting: false,
|
|
1022
|
+
configuring: false,
|
|
817
1023
|
queue: [],
|
|
818
1024
|
work: void 0,
|
|
819
1025
|
dispatch: Promise.resolve(),
|
|
@@ -854,11 +1060,12 @@ var PiCodingAgentAdapter = class {
|
|
|
854
1060
|
const id = runtime.session.sessionId;
|
|
855
1061
|
try {
|
|
856
1062
|
const source = event.type === "message_start" && event.message.role === "user" ? this.#claimPromptSource(runtime, event.message.content) : void 0;
|
|
857
|
-
for (const item of runtime.timeline.event(event, source
|
|
1063
|
+
for (const item of runtime.timeline.event(event, source)) {
|
|
858
1064
|
if (item.kind === "human-message" && source) {
|
|
859
1065
|
runtime.session.sessionManager.appendCustomEntry(PI_PROMPT_SOURCE_ENTRY, {
|
|
860
1066
|
projectionId: item.id,
|
|
861
|
-
messageId: source.id
|
|
1067
|
+
messageId: source.id,
|
|
1068
|
+
...source.attachments.length ? { content: source.text, attachments: source.attachments } : {}
|
|
862
1069
|
});
|
|
863
1070
|
}
|
|
864
1071
|
this.#callbacks?.onConversationItem(id, item);
|
|
@@ -916,18 +1123,21 @@ var PiCodingAgentAdapter = class {
|
|
|
916
1123
|
this.#callbacks?.onSessionInventoryChanged(sessionId);
|
|
917
1124
|
});
|
|
918
1125
|
}
|
|
919
|
-
#runNext(runtime) {
|
|
1126
|
+
#runNext(runtime, continuing = false) {
|
|
920
1127
|
if (runtime.busy || runtime.aborting || this.#stopping) return;
|
|
921
|
-
const
|
|
1128
|
+
const immediate = continuing ? runtime.queue.findIndex((prompt2) => prompt2.mode === "immediate") : -1;
|
|
1129
|
+
const prompt = runtime.queue.splice(Math.max(0, immediate), 1)[0];
|
|
922
1130
|
if (!prompt) return;
|
|
923
1131
|
runtime.busy = true;
|
|
924
1132
|
this.#callbacks?.onSessionActivity?.(runtime.session.sessionId, "working", (/* @__PURE__ */ new Date()).toISOString());
|
|
925
|
-
runtime.work = Promise.resolve().then(() => {
|
|
1133
|
+
runtime.work = Promise.resolve().then(async () => {
|
|
1134
|
+
await this.#preparePrompt(runtime, prompt);
|
|
926
1135
|
if (runtime.aborting || this.#stopping) return;
|
|
927
1136
|
runtime.primarySource = prompt;
|
|
928
|
-
return runtime.session.prompt(prompt.
|
|
1137
|
+
return runtime.session.prompt(prompt.nativeText, {
|
|
929
1138
|
expandPromptTemplates: false,
|
|
930
|
-
source: "rpc"
|
|
1139
|
+
source: "rpc",
|
|
1140
|
+
...prompt.images.length ? { images: prompt.images } : {}
|
|
931
1141
|
});
|
|
932
1142
|
}).catch((error) => {
|
|
933
1143
|
this.#error(runtime, error);
|
|
@@ -937,7 +1147,7 @@ var PiCodingAgentAdapter = class {
|
|
|
937
1147
|
runtime.busy = false;
|
|
938
1148
|
this.#callbacks?.onSessionActivity?.(runtime.session.sessionId, "idle", (/* @__PURE__ */ new Date()).toISOString());
|
|
939
1149
|
this.#callbacks?.onSessionInventoryChanged(runtime.session.sessionId);
|
|
940
|
-
this.#runNext(runtime);
|
|
1150
|
+
this.#runNext(runtime, true);
|
|
941
1151
|
});
|
|
942
1152
|
}
|
|
943
1153
|
#dispatchQueued(runtime) {
|
|
@@ -946,10 +1156,16 @@ var PiCodingAgentAdapter = class {
|
|
|
946
1156
|
while (runtime.queue.length && runtime.session.isStreaming && !runtime.aborting && !this.#stopping) {
|
|
947
1157
|
const prompt = runtime.queue.shift();
|
|
948
1158
|
const sources = prompt.mode === "immediate" ? runtime.steeringSources : runtime.followUpSources;
|
|
949
|
-
sources.push(prompt);
|
|
950
1159
|
try {
|
|
951
|
-
|
|
952
|
-
|
|
1160
|
+
await this.#preparePrompt(runtime, prompt);
|
|
1161
|
+
if (runtime.aborting || this.#stopping) return;
|
|
1162
|
+
if (!runtime.session.isStreaming) {
|
|
1163
|
+
runtime.queue.unshift(prompt);
|
|
1164
|
+
return;
|
|
1165
|
+
}
|
|
1166
|
+
sources.push(prompt);
|
|
1167
|
+
if (prompt.mode === "immediate") await runtime.session.steer(prompt.nativeText, prompt.images);
|
|
1168
|
+
else await runtime.session.followUp(prompt.nativeText, prompt.images);
|
|
953
1169
|
} catch (error) {
|
|
954
1170
|
const index = sources.findIndex((source) => source.id === prompt.id);
|
|
955
1171
|
if (index !== -1) sources.splice(index, 1);
|
|
@@ -958,6 +1174,64 @@ var PiCodingAgentAdapter = class {
|
|
|
958
1174
|
}
|
|
959
1175
|
});
|
|
960
1176
|
}
|
|
1177
|
+
async #preparePrompt(runtime, prompt) {
|
|
1178
|
+
if (runtime.aborting || this.#stopping) return;
|
|
1179
|
+
const hints = [];
|
|
1180
|
+
for (const [index, image] of prompt.pendingImages.entries()) {
|
|
1181
|
+
if (runtime.aborting || this.#stopping) return;
|
|
1182
|
+
let data = image.data;
|
|
1183
|
+
let mimeType = image.mimeType;
|
|
1184
|
+
if (runtime.session.settingsManager.getImageAutoResize()) {
|
|
1185
|
+
const model = runtime.session.routedModel?.model ?? runtime.session.model;
|
|
1186
|
+
const resized = await resizeImage(Buffer.from(data, "base64"), mimeType, model?.inputLimits?.images?.resize);
|
|
1187
|
+
if (!resized) {
|
|
1188
|
+
hints.push("[Image omitted: could not be resized below the inline image size limit.]");
|
|
1189
|
+
continue;
|
|
1190
|
+
}
|
|
1191
|
+
data = resized.data;
|
|
1192
|
+
mimeType = resized.mimeType;
|
|
1193
|
+
const hint = formatDimensionNote(resized);
|
|
1194
|
+
if (hint) hints.push(hint);
|
|
1195
|
+
}
|
|
1196
|
+
const bytes = Buffer.from(data, "base64");
|
|
1197
|
+
prompt.images.push({ type: "image", data, mimeType });
|
|
1198
|
+
prompt.attachments[index] = {
|
|
1199
|
+
kind: "image",
|
|
1200
|
+
name: image.name,
|
|
1201
|
+
mimeType,
|
|
1202
|
+
imageRef: "sha256",
|
|
1203
|
+
byteLength: bytes.length,
|
|
1204
|
+
sha256: createHash2("sha256").update(bytes).digest("hex")
|
|
1205
|
+
};
|
|
1206
|
+
}
|
|
1207
|
+
prompt.pendingImages = [];
|
|
1208
|
+
if (hints.length) prompt.nativeText += `
|
|
1209
|
+
|
|
1210
|
+
${hints.join("\n")}`;
|
|
1211
|
+
if (!prompt.files.length || runtime.aborting || this.#stopping) return;
|
|
1212
|
+
const staged = await stagePromptAttachments(
|
|
1213
|
+
runtime.session.sessionId,
|
|
1214
|
+
{ images: [], files: prompt.files },
|
|
1215
|
+
join(this.#agentDirectory, "uploads", runtime.session.sessionId)
|
|
1216
|
+
);
|
|
1217
|
+
const paths = [];
|
|
1218
|
+
for (const [index, attachment] of staged.entries()) {
|
|
1219
|
+
const file = prompt.files[index]?.attachment;
|
|
1220
|
+
if (attachment.type !== "file" || !file) throw new Error("PI file staging returned an invalid attachment.");
|
|
1221
|
+
paths.push(JSON.stringify({ name: file.name, path: attachment.path }));
|
|
1222
|
+
prompt.attachments.push({
|
|
1223
|
+
kind: "file",
|
|
1224
|
+
name: file.name,
|
|
1225
|
+
uri: attachment.path,
|
|
1226
|
+
mimeType: file.mimeType
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
prompt.nativeText += `
|
|
1230
|
+
|
|
1231
|
+
Attached files (local paths; use file tools to read):
|
|
1232
|
+
${paths.join("\n")}`;
|
|
1233
|
+
prompt.files = [];
|
|
1234
|
+
}
|
|
961
1235
|
async #abort(runtime) {
|
|
962
1236
|
runtime.aborting = true;
|
|
963
1237
|
runtime.queue = [];
|
|
@@ -985,13 +1259,14 @@ var PiCodingAgentAdapter = class {
|
|
|
985
1259
|
}
|
|
986
1260
|
#claimPromptSource(runtime, content) {
|
|
987
1261
|
const text = typeof content === "string" ? content : content.filter((part) => part.type === "text").map((part) => part.text ?? "").join("");
|
|
988
|
-
|
|
1262
|
+
const matches = (source) => source.nativeText === text;
|
|
1263
|
+
if (runtime.primarySource && matches(runtime.primarySource)) {
|
|
989
1264
|
const source = runtime.primarySource;
|
|
990
1265
|
runtime.primarySource = void 0;
|
|
991
1266
|
return source;
|
|
992
1267
|
}
|
|
993
1268
|
for (const sources of [runtime.steeringSources, runtime.followUpSources]) {
|
|
994
|
-
const index = sources.findIndex(
|
|
1269
|
+
const index = sources.findIndex(matches);
|
|
995
1270
|
if (index !== -1) return sources.splice(index, 1)[0];
|
|
996
1271
|
}
|
|
997
1272
|
return void 0;
|