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