@ycodium-ai/agent-pi 0.2.5448 → 0.2.5503

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.
Files changed (3) hide show
  1. package/README.md +6 -0
  2. package/dist/index.js +418 -38
  3. package/package.json +4 -3
package/README.md CHANGED
@@ -72,6 +72,12 @@ to the instance under `~/.pi/ycodium/`, unless a session directory is configured
72
72
  under advanced settings. Keep that directory stable to resume existing sessions;
73
73
  use a separate directory for each instance.
74
74
 
75
+ Session import scans Pi's terminal session store under
76
+ `~/.pi/agent/sessions`. The terminal store can be overridden through
77
+ an absolute `PI_CODING_AGENT_DIR` or `PI_CODING_AGENT_SESSION_DIR`. Import reads the active
78
+ branch of the original transcript. Continuing the imported thread appends to
79
+ that same file.
80
+
75
81
  Pi creates its history file lazily. A thread stopped before its first prompt may have no saved
76
82
  history and require a new thread. Missing saved history is reported as an error; the integration
77
83
  does not silently replace it with an empty conversation.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  // src/index.ts
2
- import * as NodeOS2 from "node:os";
3
- import * as NodePath3 from "node:path";
2
+ import * as NodeOS3 from "node:os";
3
+ import * as NodePath4 from "node:path";
4
4
  import { definePlugin } from "@ycodium-ai/plugin-api";
5
5
 
6
6
  // ../../packages/plugin-api/src/version.ts
7
- var PLUGIN_API_VERSION = 171;
7
+ var PLUGIN_API_VERSION = 173;
8
8
 
9
9
  // src/index.ts
10
10
  import {
@@ -230,14 +230,389 @@ import {
230
230
  import { runProcessOperation } from "@ycodium-ai/plugin-api/process-operation";
231
231
 
232
232
  // src/connection.ts
233
- import * as NodeFSP from "node:fs/promises";
234
- import * as NodePath2 from "node:path";
233
+ import * as NodeFSP2 from "node:fs/promises";
234
+ import * as NodePath3 from "node:path";
235
235
  import * as NodeCrypto2 from "node:crypto";
236
236
  import {
237
237
  isOperationCleanupError,
238
238
  withProcessOperation
239
239
  } from "@ycodium-ai/plugin-api/process-operation";
240
240
 
241
+ // src/nativeSessions.ts
242
+ import * as NodeFS from "node:fs";
243
+ import * as NodeFSP from "node:fs/promises";
244
+ import * as NodeOS2 from "node:os";
245
+ import * as NodePath2 from "node:path";
246
+ import * as NodeReadline from "node:readline";
247
+
248
+ // ../../packages/ycodium-jsonl-stream/src/sessionTranscript.ts
249
+ var SESSION_IMPORT_ACTIVITY_TEXT_LIMIT = 32e3;
250
+ var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
251
+ function isoTranscriptTimestamp(value) {
252
+ return typeof value === "number" && Math.abs(value) <= 864e13 ? new Date(value).toISOString() : void 0;
253
+ }
254
+ function toolInput(value) {
255
+ if (typeof value === "string") return value;
256
+ const input = record2(value);
257
+ if (input && Object.keys(input).length === 1 && typeof input.command === "string")
258
+ return input.command;
259
+ if (input && Object.keys(input).length === 1 && typeof input.cmd === "string") return input.cmd;
260
+ if (value === void 0 || value === null) return void 0;
261
+ try {
262
+ return JSON.stringify(value, null, 2);
263
+ } catch {
264
+ return void 0;
265
+ }
266
+ }
267
+ function bounded(value, tail = false) {
268
+ if (value.length <= SESSION_IMPORT_ACTIVITY_TEXT_LIMIT) return { text: value, truncated: false };
269
+ const offset = tail ? value.length - SESSION_IMPORT_ACTIVITY_TEXT_LIMIT : SESSION_IMPORT_ACTIVITY_TEXT_LIMIT;
270
+ const character = value.charCodeAt(offset);
271
+ const previous = value.charCodeAt(offset - 1);
272
+ const splitPair = character >= 56320 && character <= 57343 && previous >= 55296 && previous <= 56319;
273
+ return {
274
+ text: tail ? value.slice(offset + (splitPair ? 1 : 0)) : value.slice(0, offset - (splitPair ? 1 : 0)),
275
+ truncated: true
276
+ };
277
+ }
278
+ function inputPayload(input) {
279
+ if (input === void 0) return {};
280
+ const result = bounded(input);
281
+ return { input: result.text, ...result.truncated ? { inputTruncated: true } : {} };
282
+ }
283
+ function outputPayload(output) {
284
+ if (output === void 0) return {};
285
+ const result = bounded(output, true);
286
+ return { output: result.text, ...result.truncated ? { outputTruncated: true } : {} };
287
+ }
288
+ function reasoning(identity, text, streamKind) {
289
+ const result = bounded(text);
290
+ return {
291
+ ...identity,
292
+ kind: "reasoning",
293
+ tone: "info",
294
+ summary: "Reasoning",
295
+ payload: {
296
+ text: result.text,
297
+ streamKind,
298
+ chars: result.text.length,
299
+ streaming: false,
300
+ ...result.truncated ? { truncated: true } : {}
301
+ }
302
+ };
303
+ }
304
+
305
+ // src/nativeSessions.ts
306
+ var PiTranscriptChangedError = class extends Error {
307
+ };
308
+ var PI_SESSION_ID = /^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/;
309
+ function piTerminalSessionRoot(config) {
310
+ const sessionDir = config.environment.PI_CODING_AGENT_SESSION_DIR ?? process.env.PI_CODING_AGENT_SESSION_DIR;
311
+ const agentDir = config.environment.PI_CODING_AGENT_DIR ?? process.env.PI_CODING_AGENT_DIR;
312
+ return NodePath2.normalize(
313
+ sessionDir || NodePath2.join(agentDir || NodePath2.join(NodeOS2.homedir(), ".pi", "agent"), "sessions")
314
+ );
315
+ }
316
+ async function* files(directory, depth, signal) {
317
+ signal?.throwIfAborted();
318
+ const entries = await NodeFSP.readdir(directory, { withFileTypes: true }).catch(
319
+ (error) => {
320
+ if (error.code === "ENOENT") return [];
321
+ throw error;
322
+ }
323
+ );
324
+ for (const entry of entries) {
325
+ signal?.throwIfAborted();
326
+ const file = NodePath2.join(directory, entry.name);
327
+ if (entry.isFile() && entry.name.endsWith(".jsonl")) yield file;
328
+ else if (depth > 0 && entry.isDirectory()) yield* files(file, depth - 1, signal);
329
+ }
330
+ }
331
+ function inDirectory(cwd, directory) {
332
+ const relative3 = NodePath2.relative(directory, cwd);
333
+ return relative3 !== ".." && !relative3.startsWith(`..${NodePath2.sep}`) && !NodePath2.isAbsolute(relative3);
334
+ }
335
+ function contentText(content) {
336
+ if (typeof content === "string") return content;
337
+ return Array.isArray(content) ? content.map(record).filter((block) => block.type === "text").map((block) => string(block.text)).join("\n") : "";
338
+ }
339
+ async function readPiFile(config, sessionDirectory, sessionFile, select, scanOnly, signal) {
340
+ const before = await NodeFSP.lstat(sessionFile, { bigint: true }).catch(
341
+ (error) => {
342
+ if (error.code === "ENOENT") return void 0;
343
+ throw error;
344
+ }
345
+ );
346
+ if (!before?.isFile()) return;
347
+ const stream = NodeFS.createReadStream(sessionFile, { encoding: "utf8", signal });
348
+ const closed = new Promise((resolve4) => stream.once("close", resolve4));
349
+ const lines = NodeReadline.createInterface({ input: stream, crlfDelay: Infinity });
350
+ let header;
351
+ const byId = /* @__PURE__ */ new Map();
352
+ let nextSourceOrder = 0;
353
+ let leaf = "";
354
+ try {
355
+ for await (const line of lines) {
356
+ signal?.throwIfAborted();
357
+ if (!line.trim()) continue;
358
+ let row;
359
+ try {
360
+ row = record(JSON.parse(line));
361
+ } catch {
362
+ continue;
363
+ }
364
+ if (!header) {
365
+ const id2 = string(row.id);
366
+ const cwd = string(row.cwd);
367
+ if (row.type !== "session" || !PI_SESSION_ID.test(id2) || !NodePath2.isAbsolute(cwd) || !select(id2, cwd))
368
+ return;
369
+ header = { id: id2, cwd };
370
+ continue;
371
+ }
372
+ const id = string(row.id);
373
+ if (id) {
374
+ if (byId.has(id)) return;
375
+ const message = record(row.message);
376
+ const content = message.content;
377
+ byId.set(id, {
378
+ sourceOrder: nextSourceOrder,
379
+ row: scanOnly ? {
380
+ id,
381
+ parentId: row.parentId,
382
+ type: row.type,
383
+ timestamp: row.timestamp,
384
+ name: row.name,
385
+ provider: row.provider,
386
+ modelId: row.modelId,
387
+ message: {
388
+ role: message.role,
389
+ provider: message.provider,
390
+ model: message.model,
391
+ content: message.role === "user" ? contentText(content).trim().slice(0, 300) : void 0
392
+ }
393
+ } : row
394
+ });
395
+ nextSourceOrder += 1 + (Array.isArray(content) ? content.length : 0);
396
+ leaf = id;
397
+ }
398
+ }
399
+ } finally {
400
+ lines.close();
401
+ stream.destroy();
402
+ await closed;
403
+ signal?.throwIfAborted();
404
+ if (header) {
405
+ const after = await NodeFSP.lstat(sessionFile, { bigint: true });
406
+ signal?.throwIfAborted();
407
+ if (before.ino !== after.ino || before.dev !== after.dev || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs) {
408
+ throw new PiTranscriptChangedError(
409
+ "The native Pi transcript changed while it was being read."
410
+ );
411
+ }
412
+ }
413
+ }
414
+ if (!header) return;
415
+ const chain = [];
416
+ while (leaf) {
417
+ const entry = byId.get(leaf);
418
+ if (!entry) return;
419
+ byId.delete(leaf);
420
+ chain.push(entry);
421
+ leaf = string(entry.row.parentId);
422
+ }
423
+ const messages = [];
424
+ const activities = [];
425
+ let title = null;
426
+ let model = null;
427
+ let nativeTurnId;
428
+ let firstUser = "";
429
+ let turnCount = 0;
430
+ for (const { row, sourceOrder } of chain.reverse()) {
431
+ const message = record(row.message);
432
+ if (row.type === "session_info") title = string(row.name).trim() || null;
433
+ if (row.type === "model_change") {
434
+ model = modelSlug(config, { provider: row.provider, id: row.modelId }) || model;
435
+ }
436
+ if (row.type !== "message") continue;
437
+ const createdAt = isoTranscriptTimestamp(Date.parse(string(row.timestamp)));
438
+ if (!createdAt) continue;
439
+ const sourceId = string(row.id);
440
+ const role = message.role;
441
+ if (role === "user") nativeTurnId = sourceId;
442
+ if (role === "assistant")
443
+ model = modelSlug(config, { provider: message.provider, id: message.model }) || model;
444
+ const identity = {
445
+ createdAt,
446
+ ...nativeTurnId ? { nativeTurnId } : {},
447
+ ...model ? { model } : {}
448
+ };
449
+ const text = contentText(message.content);
450
+ if (role === "user" && text.trim()) {
451
+ firstUser ||= text.trim().slice(0, 300);
452
+ turnCount++;
453
+ }
454
+ if (scanOnly) continue;
455
+ if ((role === "user" || role === "assistant" || role === "system") && text.trim()) {
456
+ messages.push({
457
+ ...identity,
458
+ sourceId,
459
+ sourceOrder,
460
+ role,
461
+ text
462
+ });
463
+ }
464
+ if (role === "assistant" && Array.isArray(message.content)) {
465
+ for (const [index, value] of message.content.entries()) {
466
+ const block = record(value);
467
+ if (block.type !== "toolCall" && block.type !== "thinking") continue;
468
+ const activityIdentity = {
469
+ ...identity,
470
+ sourceId: `${sourceId}:${index}`,
471
+ sourceOrder: sourceOrder + index + 1
472
+ };
473
+ if (block.type === "thinking") {
474
+ const thinking = string(block.thinking);
475
+ const activity = reasoning(activityIdentity, thinking, "reasoning_text");
476
+ activities.push({
477
+ ...activity,
478
+ payload: { ...activity.payload, chars: thinking.length }
479
+ });
480
+ } else {
481
+ activities.push({
482
+ ...activityIdentity,
483
+ kind: "tool.started",
484
+ tone: "tool",
485
+ summary: string(block.name) || "Tool call",
486
+ payload: {
487
+ toolCallId: string(block.id),
488
+ itemType: "dynamic_tool_call",
489
+ toolName: string(block.name),
490
+ startedAt: identity.createdAt,
491
+ ...inputPayload(toolInput(block.arguments))
492
+ }
493
+ });
494
+ }
495
+ }
496
+ }
497
+ if (role === "toolResult") {
498
+ activities.push({
499
+ ...identity,
500
+ sourceId,
501
+ sourceOrder,
502
+ kind: "tool.completed",
503
+ tone: message.isError === true ? "error" : "tool",
504
+ summary: string(message.toolName) || "Tool result",
505
+ payload: {
506
+ toolCallId: string(message.toolCallId),
507
+ toolName: string(message.toolName),
508
+ itemType: "dynamic_tool_call",
509
+ status: message.isError === true ? "failed" : "completed",
510
+ ...outputPayload(text)
511
+ }
512
+ });
513
+ }
514
+ }
515
+ return {
516
+ candidate: {
517
+ nativeSessionId: header.id,
518
+ cwd: header.cwd,
519
+ title: title ?? (firstUser.slice(0, 100) || null),
520
+ preview: firstUser.slice(0, 300) || null,
521
+ model,
522
+ turnCount,
523
+ updatedAt: Number(before.mtimeNs / 1000000n),
524
+ availability: "importable",
525
+ openElsewhere: false
526
+ },
527
+ transcript: {
528
+ resumeCursor: { sessionId: header.id, sessionDirectory, sessionFile },
529
+ title: title ?? (firstUser.slice(0, 100) || null),
530
+ model,
531
+ messages,
532
+ activities,
533
+ availableMessages: messages.length,
534
+ availableActivities: activities.length
535
+ }
536
+ };
537
+ }
538
+ function piNativeSessions(config) {
539
+ const configuredRoot = piTerminalSessionRoot(config);
540
+ const root = NodePath2.isAbsolute(configuredRoot) ? NodePath2.resolve(configuredRoot) : configuredRoot;
541
+ const configError = "Set an absolute PI_CODING_AGENT_SESSION_DIR or PI_CODING_AGENT_DIR to import Pi terminal sessions.";
542
+ const readImport = async ({ nativeSessionId, cwd, signal }) => {
543
+ signal?.throwIfAborted();
544
+ if (!NodePath2.isAbsolute(root)) throw new Error(configError);
545
+ if (!PI_SESSION_ID.test(nativeSessionId) || !cwd || !NodePath2.isAbsolute(cwd)) {
546
+ throw new Error("Invalid Pi session identity or working directory.");
547
+ }
548
+ let found;
549
+ for await (const file of files(root, 1, signal)) {
550
+ const result = await readPiFile(
551
+ config,
552
+ root,
553
+ file,
554
+ (id, recorded) => id === nativeSessionId && NodePath2.relative(cwd, recorded) === "",
555
+ false,
556
+ signal
557
+ );
558
+ if (!result) continue;
559
+ if (found) throw new Error(`Multiple transcripts for Pi session ${nativeSessionId}.`);
560
+ found = result.transcript;
561
+ }
562
+ if (!found)
563
+ throw new Error(
564
+ `No transcript for Pi session ${nativeSessionId} in the requested directory.`
565
+ );
566
+ return found;
567
+ };
568
+ return {
569
+ ...NodePath2.isAbsolute(root) ? { storageKey: `pi:sessions:${NodePath2.sep === "\\" ? root.toLowerCase() : root}` } : {},
570
+ scan: async ({ directory, signal }) => {
571
+ signal?.throwIfAborted();
572
+ if (!NodePath2.isAbsolute(root)) throw new Error(configError);
573
+ if (!directory || !NodePath2.isAbsolute(directory)) return { candidates: [] };
574
+ const candidates = /* @__PURE__ */ new Map();
575
+ for await (const file of files(root, 1, signal)) {
576
+ const result = await readPiFile(
577
+ config,
578
+ root,
579
+ file,
580
+ (_, cwd) => inDirectory(cwd, directory),
581
+ true,
582
+ signal
583
+ ).catch((error) => {
584
+ signal?.throwIfAborted();
585
+ if (error instanceof PiTranscriptChangedError || record(error).code === "ENOENT") return;
586
+ throw error;
587
+ });
588
+ if (!result) continue;
589
+ const { candidate } = result;
590
+ candidates.set(
591
+ candidate.nativeSessionId,
592
+ candidates.has(candidate.nativeSessionId) ? void 0 : candidate
593
+ );
594
+ }
595
+ return {
596
+ candidates: [...candidates.values()].filter((candidate) => candidate !== void 0).sort((a, b) => b.updatedAt - a.updatedAt)
597
+ };
598
+ },
599
+ readImport,
600
+ read: async (input) => {
601
+ const { messages, model, resumeCursor: resumeCursor2 } = await readImport(input);
602
+ return {
603
+ nativeSessionId: input.nativeSessionId,
604
+ messages: messages.map(({ role, text, createdAt }) => ({
605
+ role,
606
+ text,
607
+ createdAt: Date.parse(createdAt)
608
+ })),
609
+ model,
610
+ resumeCursor: resumeCursor2
611
+ };
612
+ }
613
+ };
614
+ }
615
+
241
616
  // src/rpc.ts
242
617
  var PiProcessExitedError = class extends Error {
243
618
  name = "PiProcessExitedError";
@@ -252,8 +627,8 @@ var PiRpc = class {
252
627
  failed = this.failureResult.promise;
253
628
  drained;
254
629
  process;
255
- constructor(process, onEvent) {
256
- this.process = process;
630
+ constructor(process2, onEvent) {
631
+ this.process = process2;
257
632
  const read = async () => {
258
633
  const decoder = new TextDecoder("utf-8", { fatal: true });
259
634
  let fragments = [];
@@ -288,7 +663,7 @@ var PiRpc = class {
288
663
  if (length > 16 * 1024 * 1024) throw new Error("Pi protocol record is too large.");
289
664
  }
290
665
  };
291
- for await (const chunk of process.stdout)
666
+ for await (const chunk of process2.stdout)
292
667
  await consume(decoder.decode(chunk, { stream: true }));
293
668
  await consume(decoder.decode());
294
669
  if (fragments.join("").trim())
@@ -296,7 +671,7 @@ var PiRpc = class {
296
671
  this.fail(new PiProcessExitedError("Pi protocol stream ended."));
297
672
  };
298
673
  const stderr = async () => {
299
- for await (const _ of process.stderr) {
674
+ for await (const _ of process2.stderr) {
300
675
  }
301
676
  };
302
677
  const stdout = read();
@@ -312,15 +687,15 @@ var PiRpc = class {
312
687
  });
313
688
  void this.drained.catch(() => {
314
689
  });
315
- void process.exited.then(
690
+ void process2.exited.then(
316
691
  async (code) => {
317
692
  let timer;
318
693
  try {
319
694
  await Promise.race([
320
695
  stdout.catch(() => {
321
696
  }),
322
- new Promise((resolve3) => {
323
- timer = setTimeout(resolve3, 1e3);
697
+ new Promise((resolve4) => {
698
+ timer = setTimeout(resolve4, 1e3);
324
699
  })
325
700
  ]);
326
701
  this.fail(new PiProcessExitedError(`Pi process exited (${String(code)}).`));
@@ -401,38 +776,40 @@ function resumeCursor(config, input) {
401
776
  const sessionId = string(stored.sessionId);
402
777
  const sessionDirectory = string(stored.sessionDirectory);
403
778
  if (sessionId && sessionDirectory) {
404
- if (!/^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/.test(sessionId) || !NodePath2.isAbsolute(sessionDirectory) || NodePath2.resolve(sessionDirectory) !== NodePath2.resolve(config.homePath, "sessions"))
779
+ if (!PI_SESSION_ID.test(sessionId) || !NodePath3.isAbsolute(sessionDirectory) || ![NodePath3.join(config.homePath, "sessions"), piTerminalSessionRoot(config)].some(
780
+ (root) => NodePath3.isAbsolute(root) && NodePath3.relative(root, sessionDirectory) === ""
781
+ ))
405
782
  throw new Error("Invalid Pi session resume cursor.");
406
783
  const sessionFile = string(stored.sessionFile);
407
- const fileRelative = NodePath2.relative(sessionDirectory, sessionFile);
408
- if (sessionFile && (!NodePath2.isAbsolute(sessionFile) || !fileRelative || fileRelative.startsWith("..") || NodePath2.isAbsolute(fileRelative)))
784
+ const fileRelative = NodePath3.relative(sessionDirectory, sessionFile);
785
+ if (sessionFile && (!NodePath3.isAbsolute(sessionFile) || !fileRelative || fileRelative.startsWith("..") || NodePath3.isAbsolute(fileRelative)))
409
786
  throw new Error("Invalid Pi session resume cursor.");
410
787
  return { sessionId, sessionDirectory, ...sessionFile ? { sessionFile } : {} };
411
788
  }
412
789
  if (Object.keys(stored).length) throw new Error("Invalid Pi session resume cursor.");
413
790
  return {
414
791
  sessionId: `ycodium-${identifier(input.threadId)}${input.discardResumeCursor ? `-${identifier(NodeCrypto2.randomUUID())}` : ""}`,
415
- sessionDirectory: NodePath2.join(config.homePath, "sessions")
792
+ sessionDirectory: NodePath3.join(config.homePath, "sessions")
416
793
  };
417
794
  }
418
795
  function initializeResumeCursor(cursor, state) {
419
796
  const sessionFile = string(state.sessionFile);
420
- if (!sessionFile || !NodePath2.isAbsolute(sessionFile)) return;
421
- const relative2 = NodePath2.relative(cursor.sessionDirectory, sessionFile);
422
- if (!relative2 || relative2.startsWith("..") || NodePath2.isAbsolute(relative2))
797
+ if (!sessionFile || !NodePath3.isAbsolute(sessionFile)) return;
798
+ const relative3 = NodePath3.relative(cursor.sessionDirectory, sessionFile);
799
+ if (!relative3 || relative3.startsWith("..") || NodePath3.isAbsolute(relative3))
423
800
  throw new Error("Invalid Pi session file location.");
424
- if (cursor.sessionFile && NodePath2.resolve(cursor.sessionFile) !== NodePath2.resolve(sessionFile))
801
+ if (cursor.sessionFile && NodePath3.resolve(cursor.sessionFile) !== NodePath3.resolve(sessionFile))
425
802
  throw new Error("Pi resumed a different session file.");
426
803
  cursor.sessionFile = sessionFile;
427
804
  }
428
805
  async function createLaunch(config, input, cursor) {
429
806
  const custom = config.connection === "custom";
430
- await NodeFSP.mkdir(config.homePath, { recursive: true });
431
- const directory = await NodeFSP.mkdtemp(NodePath2.join(config.homePath, "launch-"));
807
+ await NodeFSP2.mkdir(config.homePath, { recursive: true });
808
+ const directory = await NodeFSP2.mkdtemp(NodePath3.join(config.homePath, "launch-"));
432
809
  try {
433
810
  if (custom)
434
- await NodeFSP.writeFile(
435
- NodePath2.join(directory, "models.json"),
811
+ await NodeFSP2.writeFile(
812
+ NodePath3.join(directory, "models.json"),
436
813
  JSON.stringify({
437
814
  providers: {
438
815
  [CUSTOM_PROVIDER]: {
@@ -463,8 +840,8 @@ async function createLaunch(config, input, cursor) {
463
840
  ];
464
841
  })
465
842
  );
466
- const mcpServersPath = NodePath2.join(directory, "mcp.json");
467
- await NodeFSP.writeFile(mcpServersPath, JSON.stringify({ mcpServers: servers }), {
843
+ const mcpServersPath = NodePath3.join(directory, "mcp.json");
844
+ await NodeFSP2.writeFile(mcpServersPath, JSON.stringify({ mcpServers: servers }), {
468
845
  mode: 384
469
846
  });
470
847
  const model = requestedModel(config, input?.modelSelection) ?? config.model;
@@ -477,21 +854,23 @@ async function createLaunch(config, input, cursor) {
477
854
  "--no-skills"
478
855
  ];
479
856
  if (cursor) {
480
- await NodeFSP.mkdir(cursor.sessionDirectory, { recursive: true });
481
- args.push("--session-dir", cursor.sessionDirectory, "--session-id", cursor.sessionId);
857
+ await NodeFSP2.mkdir(cursor.sessionDirectory, { recursive: true });
858
+ args.push("--session-dir", cursor.sessionDirectory);
859
+ if (cursor.sessionFile) args.push("--session", cursor.sessionFile);
860
+ else args.push("--session-id", cursor.sessionId);
482
861
  } else args.push("--no-session", "--no-prompt-templates", "--no-context-files");
483
862
  const mcpExtension = !custom && Boolean(input?.mcpServers?.length);
484
863
  if (mcpExtension)
485
- await NodeFSP.writeFile(NodePath2.join(directory, "ycodium-mcp.js"), MCP_EXTENSION_SOURCE, {
864
+ await NodeFSP2.writeFile(NodePath3.join(directory, "ycodium-mcp.js"), MCP_EXTENSION_SOURCE, {
486
865
  mode: 384
487
866
  });
488
867
  if (input?.mcpServers?.length) args.push("-e", "builtin:mcp", "-e", "builtin:tool-search");
489
- if (mcpExtension) args.push("-e", NodePath2.join(directory, "ycodium-mcp.js"));
868
+ if (mcpExtension) args.push("-e", NodePath3.join(directory, "ycodium-mcp.js"));
490
869
  if (input?.skills)
491
870
  for (const name of input.skills.names) {
492
- const skill = NodePath2.resolve(input.skills.skillsDir, name);
493
- const relative2 = NodePath2.relative(NodePath2.resolve(input.skills.skillsDir), skill);
494
- if (!relative2 || relative2.startsWith("..") || NodePath2.isAbsolute(relative2))
871
+ const skill = NodePath3.resolve(input.skills.skillsDir, name);
872
+ const relative3 = NodePath3.relative(NodePath3.resolve(input.skills.skillsDir), skill);
873
+ if (!relative3 || relative3.startsWith("..") || NodePath3.isAbsolute(relative3))
495
874
  throw new Error("Invalid Pi skill path.");
496
875
  args.push("--skill", skill);
497
876
  }
@@ -504,7 +883,7 @@ async function createLaunch(config, input, cursor) {
504
883
  else if (mcpExtension) env[PI_MCP_SERVERS_ENV] = mcpServersPath;
505
884
  return { directory, args, env };
506
885
  } catch (cause) {
507
- await NodeFSP.rm(directory, { recursive: true, force: true });
886
+ await NodeFSP2.rm(directory, { recursive: true, force: true });
508
887
  throw cause;
509
888
  }
510
889
  }
@@ -516,7 +895,7 @@ async function openConnection(input) {
516
895
  });
517
896
  if (input.cursor?.sessionFile) {
518
897
  try {
519
- if (!(await NodeFSP.stat(input.cursor.sessionFile)).isFile())
898
+ if (!(await NodeFSP2.stat(input.cursor.sessionFile)).isFile())
520
899
  throw Object.assign(new Error("Invalid Pi session file."), { code: "ENOENT" });
521
900
  } catch (cause) {
522
901
  if (record(cause).code !== "ENOENT") throw cause;
@@ -597,11 +976,11 @@ async function openConnection(input) {
597
976
  });
598
977
  const cleaned = completed.then(
599
978
  async () => {
600
- await NodeFSP.rm(launch.directory, { recursive: true, force: true });
979
+ await NodeFSP2.rm(launch.directory, { recursive: true, force: true });
601
980
  },
602
981
  async (cause) => {
603
982
  if (!isOperationCleanupError(cause))
604
- await NodeFSP.rm(launch.directory, { recursive: true, force: true });
983
+ await NodeFSP2.rm(launch.directory, { recursive: true, force: true });
605
984
  throw cause;
606
985
  }
607
986
  );
@@ -1486,6 +1865,7 @@ function createPiInstance(value, host) {
1486
1865
  };
1487
1866
  return {
1488
1867
  ...instance,
1868
+ sessions: piNativeSessions(config),
1489
1869
  startSession: safely(instance.startSession),
1490
1870
  sendTurn: safely(instance.sendTurn),
1491
1871
  interruptTurn: safely(instance.interruptTurn),
@@ -1519,7 +1899,7 @@ var index_default = definePlugin({
1519
1899
  const { instanceId } = readExecutorEffectiveRequest(payload);
1520
1900
  return {
1521
1901
  homePath: instanceId === void 0 ? { detailKey: "form.homePath.newInstance" } : {
1522
- value: NodePath3.join(NodeOS2.homedir(), ".pi", "ycodium", identifier(instanceId))
1902
+ value: NodePath4.join(NodeOS3.homedir(), ".pi", "ycodium", identifier(instanceId))
1523
1903
  }
1524
1904
  };
1525
1905
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ycodium-ai/agent-pi",
3
- "version": "0.2.5448",
3
+ "version": "0.2.5503",
4
4
  "description": "Pi executor over the native RPC protocol.",
5
5
  "keywords": [
6
6
  "ycodium",
@@ -30,10 +30,11 @@
30
30
  "tailwindcss": "^4.0.0",
31
31
  "typescript": "~6.0.3",
32
32
  "vite-plus": "0.2.2",
33
- "@ycodium-ai/plugin-api": "0.2.0",
33
+ "@ycodium-ai/plugin-api": "0.2.5503",
34
34
  "@ycodium/contracts": "0.0.33",
35
+ "ycodium-react-test-harness": "0.0.0",
35
36
  "ycodium-executor-testing": "0.0.0",
36
- "ycodium-react-test-harness": "0.0.0"
37
+ "ycodium-jsonl-stream": "0.0.0"
37
38
  },
38
39
  "ycodium": {
39
40
  "plugin": "./dist/index.js",