@shunagent/shun 0.1.162 → 0.1.201

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 (2) hide show
  1. package/dist/cli.js +383 -49
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawn, execFile } from "node:child_process";
2
- import { access, mkdir, mkdtemp, writeFile, rename, rm, readFile, lstat, copyFile, readdir, stat, realpath, open, appendFile, cp, chmod, unlink } from "node:fs/promises";
2
+ import { access, mkdir, mkdtemp, writeFile, rename, rm, readFile, appendFile, lstat, copyFile, readdir, stat, realpath, open, cp, chmod, unlink } from "node:fs/promises";
3
3
  import { createHash, randomUUID, randomBytes, timingSafeEqual } from "node:crypto";
4
4
  import { homedir, tmpdir, platform } from "node:os";
5
5
  import { resolve, join, dirname, delimiter, basename, sep, relative, extname, win32, isAbsolute } from "node:path";
@@ -11,7 +11,9 @@ import { promisify } from "node:util";
11
11
  import "defuddle/node";
12
12
  import { DOMParser } from "linkedom";
13
13
  import "https-proxy-agent";
14
- import { constants, existsSync, mkdirSync, openSync, closeSync, rmSync, readFileSync, statSync, readSync, writeFileSync, renameSync, accessSync, createReadStream } from "node:fs";
14
+ import { createWriteStream, createReadStream, constants, existsSync, mkdirSync, openSync, closeSync, rmSync, readFileSync, statSync, readSync, writeFileSync, renameSync, accessSync } from "node:fs";
15
+ import { createInterface } from "node:readline";
16
+ import { once } from "node:events";
15
17
  import { createProvider } from "@earendil-works/pi-ai";
16
18
  import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
17
19
  import { unzipSync, gunzipSync } from "fflate";
@@ -191,8 +193,10 @@ function readProductToolPresentation(tool) {
191
193
  return sitesPresentation(failed ? "Site deletion failed" : "Took site down", input.slug);
192
194
  case "sites_setup":
193
195
  return sitesPresentation(failed ? "Publishing setup failed" : "Set up publishing", input.base_domain || input.zone_id);
194
- case "background_start":
196
+ case "background_start": {
197
+ if (input.wait_until_exit === true) return finiteProcessPresentation(tool, input);
195
198
  return backgroundPresentation(failed ? "Background process start failed" : "Started background process", input.label || backgroundCommandTarget(input.command));
199
+ }
196
200
  case "background_list":
197
201
  return backgroundPresentation(failed ? "Background process listing failed" : "Listed background processes", "task-owned processes");
198
202
  case "background_output":
@@ -292,6 +296,8 @@ function readProductToolPresentation(tool) {
292
296
  return { title: failed ? "Memory search failed" : "Read memory", detail: String(input.query || input.scope || ""), kind: "skill" };
293
297
  case "memory_update":
294
298
  return { title: failed ? "Memory update failed" : input.remove ? "Forgot memory" : "Updated memory", detail: "", kind: "skill" };
299
+ case "assistant_task_update":
300
+ return { title: failed ? "Task could not be updated" : "Updated task", detail: "", kind: "background" };
295
301
  case "assistant_task_continue":
296
302
  return { title: failed ? "Task could not continue" : "Continued task", detail: "", kind: "background" };
297
303
  case "assistant_task_start":
@@ -536,6 +542,20 @@ function compactUrl(value) {
536
542
  return raw.slice(0, 100);
537
543
  }
538
544
  }
545
+ function finiteProcessPresentation(tool, input) {
546
+ let report = {};
547
+ try {
548
+ const parsed = JSON.parse(tool.output || "{}");
549
+ if (parsed && typeof parsed === "object") report = parsed;
550
+ } catch {
551
+ }
552
+ const failed = tool.state === "error" || report.task?.state === "failed";
553
+ const active = tool.state === "running" && !["exited", "failed", "stopped"].includes(report.task?.state || "");
554
+ const elapsed = typeof report.task?.elapsed_ms === "number" ? `${Math.max(0, Math.floor(report.task.elapsed_ms / 1e3))}s` : "";
555
+ const chunks = Array.isArray(report.output) ? report.output : [];
556
+ const latest = chunks.map((chunk) => typeof chunk.text === "string" ? chunk.text : "").join("").trim().split("\n").at(-1)?.trim().slice(0, 160);
557
+ return backgroundPresentation(failed ? "Process failed" : active ? "Process running" : "Process finished", [input.label || backgroundCommandTarget(input.command), elapsed, latest || (active ? "No output yet" : "Output ready for review")].filter(Boolean).join(" · "));
558
+ }
539
559
  const HOST_PROTOCOL = 2;
540
560
  function applyHostEvent(turns, envelope) {
541
561
  const payload = envelope.payload;
@@ -587,6 +607,13 @@ function hostToolLabel(tool) {
587
607
  const target = ["path", "pattern", "query", "url"].map((key) => args2[key]).filter((value) => typeof value === "string").join(" · ");
588
608
  return `${labels[tool.name] || tool.name}${target ? ` · ${target}` : ""}`;
589
609
  }
610
+ const adapters = /* @__PURE__ */ new Map();
611
+ function configuredProviderAdapter(provider, settings) {
612
+ if (!provider?.authMode) return void 0;
613
+ const adapter = adapters.get(provider.authMode);
614
+ if (!adapter) throw Error("This model connection is unavailable here. Open it in Shun Desktop.");
615
+ return adapter(provider, settings);
616
+ }
590
617
  function normalizeProviderConnection(provider) {
591
618
  const api = provider.api || "openai-completions";
592
619
  const rawEndpoint = provider.endpoint.trim().replace(/\/+$/, "");
@@ -632,14 +659,12 @@ function applyDefaultPluginInstallations(settings) {
632
659
  }
633
660
  return { ...settings, plugins, pluginDefaultsVersion };
634
661
  }
635
- function contextTokens(value) {
636
- return value.usedTokens || Math.ceil(value.usedCharacters / 2.5);
637
- }
638
662
  function contextAfterCompaction(previous, compaction) {
639
663
  if (!previous || !Number.isFinite(compaction.tokensBefore) || !Number.isFinite(compaction.tokensAfter)) return void 0;
640
664
  if (compaction.tokensBefore <= 0 || compaction.tokensAfter < 0) return void 0;
641
- const usedTokens = Math.max(0, Math.round(contextTokens(previous) - compaction.tokensBefore + compaction.tokensAfter));
642
665
  const breakdown = previous.breakdown;
666
+ const fixedTokens = breakdown ? breakdown.systemTokens + breakdown.toolTokens + breakdown.mcpTokens : 0;
667
+ const usedTokens = Math.max(0, Math.round(fixedTokens + compaction.tokensAfter));
643
668
  return {
644
669
  ...previous,
645
670
  state: "compacted",
@@ -746,7 +771,7 @@ function capabilityPrompt(activeTools, context = {}) {
746
771
  lines.push("Files uploaded to this task are task-owned attachments, not workspace files, and their original source paths are deliberately unavailable. Discover their stable IDs with attachment_list and read them by ID with attachment_read. An image arrives whole and already at the resolution this session is shown, so when something inside it is too small to read — print on a label, a price tag, a dense table — read that part of it with region=[x, y, width, height], four fractions of the image from the top-left corner, instead of going after the file. That region read is the enlarged view, and it is the only one this session has. Never locate an upload with workspace read, bash, find, or filename search.");
747
772
  }
748
773
  if (activeTools.includes("background_start")) {
749
- lines.push("For long-running servers, watchers, and workers, use background_start. When starting a local web UI, pass its localhost URL as preview_url so the product can present Browser Preview when ready. Observe and stop background work by stable ID with background_list, background_output, and background_stop; do not rely on shell job control for managed background work. To wait for new output — a verification URL, a ready line, or an error — call background_output with wait_ms (and optionally until) instead of sleeping and re-polling with foreground commands.");
774
+ lines.push("Use background_start for long-running work; finite jobs set wait_until_exit=true to stream progress and return the exit result to this turn. Emit unbuffered progress; do not pipe live jobs into tail. Verify artifacts and explain the result after exit. For local web UIs, pass preview_url for Browser Preview. Use stable IDs with background_list, background_output, and background_stop, not shell job control. Observe services with background_output with wait_ms (and optionally until) instead of sleeping and re-polling with foreground commands.");
750
775
  }
751
776
  if (activeTools.includes("mcp_list") && activeTools.includes("mcp_call")) {
752
777
  lines.push("Installed plugin capabilities are available through mcp_list and mcp_call. Discover only the relevant server when needed; do not enumerate unrelated plugin schemas.");
@@ -1407,6 +1432,169 @@ function webUserAgent() {
1407
1432
  }
1408
1433
  webUserAgent();
1409
1434
  new FreeSearchCoordinator();
1435
+ function imageBlocks(content) {
1436
+ if (!Array.isArray(content)) return [];
1437
+ return content.filter((block) => Boolean(block) && typeof block === "object" && block.type === "image");
1438
+ }
1439
+ function hasInlineImage(content) {
1440
+ return imageBlocks(content).some((block) => typeof block.data === "string" && block.data.length > 0);
1441
+ }
1442
+ function imageExtension(mimeType) {
1443
+ if (mimeType === "image/jpeg") return "jpg";
1444
+ if (mimeType === "image/webp") return "webp";
1445
+ if (mimeType === "image/gif") return "gif";
1446
+ if (mimeType === "image/bmp") return "bmp";
1447
+ if (mimeType === "image/tiff") return "tiff";
1448
+ return "png";
1449
+ }
1450
+ async function externalizeContent(content, taskId, store) {
1451
+ if (!Array.isArray(content)) return content;
1452
+ const inline = imageBlocks(content).filter((block) => block.data);
1453
+ if (!inline.length) return content;
1454
+ const imported = await store.importBuffers(taskId, inline.map((block, index) => ({
1455
+ name: `transcript-image-${index + 1}.${imageExtension(block.mimeType)}`,
1456
+ bytes: Buffer.from(block.data, "base64")
1457
+ })), Number.POSITIVE_INFINITY);
1458
+ let cursor = 0;
1459
+ return content.map((block) => {
1460
+ if (!block || typeof block !== "object" || block.type !== "image") return block;
1461
+ const image = block;
1462
+ if (!image.data) return block;
1463
+ const attachment = imported[cursor++];
1464
+ if (!attachment) return block;
1465
+ return { type: "image", mimeType: image.mimeType, data: "", attachmentId: attachment.id };
1466
+ });
1467
+ }
1468
+ async function externalizeSessionFile(path, taskId, store) {
1469
+ const temporary = `${path}.${process.pid}.externalizing`;
1470
+ const output = createWriteStream(temporary);
1471
+ const write = async (line) => {
1472
+ if (!output.write(line)) await once(output, "drain");
1473
+ };
1474
+ let changed = false;
1475
+ const reader = createInterface({ input: createReadStream(path, { encoding: "utf8" }), crlfDelay: Infinity });
1476
+ try {
1477
+ for await (const line of reader) {
1478
+ if (!line.trim()) continue;
1479
+ let entry;
1480
+ try {
1481
+ entry = JSON.parse(line);
1482
+ } catch {
1483
+ await write(`${line}
1484
+ `);
1485
+ continue;
1486
+ }
1487
+ const content = entry?.type === "message" ? entry.message?.content : entry?.type === "custom_message" ? entry.content : void 0;
1488
+ if (!hasInlineImage(content)) {
1489
+ await write(`${line}
1490
+ `);
1491
+ continue;
1492
+ }
1493
+ const externalized = await externalizeContent(content, taskId, store);
1494
+ if (entry.type === "message") entry.message.content = externalized;
1495
+ else entry.content = externalized;
1496
+ changed = true;
1497
+ await write(`${JSON.stringify(entry)}
1498
+ `);
1499
+ }
1500
+ } finally {
1501
+ reader.close();
1502
+ }
1503
+ output.end();
1504
+ await once(output, "finish");
1505
+ if (!changed) {
1506
+ await rm(temporary, { force: true });
1507
+ return false;
1508
+ }
1509
+ try {
1510
+ await rename(temporary, path);
1511
+ } catch (error) {
1512
+ await rm(temporary, { force: true });
1513
+ throw error;
1514
+ }
1515
+ return true;
1516
+ }
1517
+ const RETAINED_BYTES = 8 * 1024 * 1024;
1518
+ const archivePath = (path) => `${path}.archive.jsonl`;
1519
+ async function readEntries(path) {
1520
+ const entries = [];
1521
+ const reader = createInterface({ input: createReadStream(path, { encoding: "utf8" }), crlfDelay: Infinity });
1522
+ try {
1523
+ for await (const line of reader) {
1524
+ if (!line.trim()) continue;
1525
+ try {
1526
+ entries.push(JSON.parse(line));
1527
+ } catch {
1528
+ }
1529
+ }
1530
+ } finally {
1531
+ reader.close();
1532
+ }
1533
+ return entries;
1534
+ }
1535
+ function branchOf(entries) {
1536
+ const byId = new Map(entries.map((entry) => [entry.id, entry]));
1537
+ const branch = [];
1538
+ let current = entries[entries.length - 1];
1539
+ while (current) {
1540
+ branch.push(current);
1541
+ current = current.parentId ? byId.get(current.parentId) : void 0;
1542
+ }
1543
+ return branch;
1544
+ }
1545
+ async function pruneSessionFile(path, retainedBytes = RETAINED_BYTES) {
1546
+ const entries = await readEntries(path);
1547
+ if (entries.length < 2) return false;
1548
+ const compaction = [...entries].reverse().find((entry) => entry.type === "compaction");
1549
+ if (!compaction) return false;
1550
+ if (!branchOf(entries).some((entry) => entry.id === compaction.id)) return false;
1551
+ const firstKept = entries.findIndex((entry) => entry.id === compaction.firstKeptEntryId);
1552
+ if (firstKept < 1) return false;
1553
+ let start = firstKept, retained = 0;
1554
+ while (start > 1 && retained < retainedBytes) {
1555
+ retained += JSON.stringify(entries[start - 1]).length;
1556
+ start--;
1557
+ }
1558
+ if (start <= 1) return false;
1559
+ const dropped = entries.slice(1, start), kept = [entries[0], ...entries.slice(start)];
1560
+ const temporary = `${path}.${process.pid}.pruning`;
1561
+ try {
1562
+ await appendFile(archivePath(path), `${dropped.map((entry) => JSON.stringify(entry)).join("\n")}
1563
+ `);
1564
+ await writeFile(temporary, `${kept.map((entry) => JSON.stringify(entry)).join("\n")}
1565
+ `);
1566
+ await rename(temporary, path);
1567
+ } catch (error) {
1568
+ await rm(temporary, { force: true });
1569
+ throw error;
1570
+ }
1571
+ return true;
1572
+ }
1573
+ async function restoreArchivedEntries(path) {
1574
+ let content;
1575
+ try {
1576
+ content = await readFile(archivePath(path), "utf8");
1577
+ } catch {
1578
+ return false;
1579
+ }
1580
+ const archived = [];
1581
+ for (const line of content.split("\n")) {
1582
+ if (!line.trim()) continue;
1583
+ try {
1584
+ archived.push(JSON.parse(line));
1585
+ } catch {
1586
+ }
1587
+ }
1588
+ if (!archived.length) return false;
1589
+ const current = await readEntries(path);
1590
+ if (!current.length) return false;
1591
+ const present = new Set(current.map((entry) => entry.id));
1592
+ const merged = [current[0], ...archived.filter((entry) => !present.has(entry.id)), ...current.slice(1)];
1593
+ await writeFile(path, `${merged.map((entry) => JSON.stringify(entry)).join("\n")}
1594
+ `);
1595
+ await rm(archivePath(path), { force: true });
1596
+ return true;
1597
+ }
1410
1598
  const MAX_SKILL_FILES = 400;
1411
1599
  const MAX_SKILL_BYTES = 25 * 1024 * 1024;
1412
1600
  const MAX_SKILL_MARKDOWN = 512 * 1024;
@@ -2092,6 +2280,7 @@ async function inferredPythonDependencies(files, python) {
2092
2280
  return [...new Set([...imports].filter((name) => !standard.has(name) && !local.has(name)).map(pythonDistributionName))].sort();
2093
2281
  }
2094
2282
  const entryType = "shun:provider-context:v1";
2283
+ const encodingFields = ["system", "tools", "declarations", "revisions"];
2095
2284
  const copy = (value) => structuredClone(value);
2096
2285
  function canonical(value) {
2097
2286
  return JSON.stringify(value, (_, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])) : item);
@@ -2127,7 +2316,7 @@ function encodeStableContext(payload, previous) {
2127
2316
  const nodes = incoming.filter((message) => !declaration(message));
2128
2317
  const first = instruction(nodes[0]) ? nodes[0] : void 0;
2129
2318
  const root = hash(canonical(nodes.find((message) => !instruction(message)) || null));
2130
- const encoding = validEncoding(previous) && previous.root === root && Boolean(previous.system) === Boolean(first) ? copy(previous) : {
2319
+ const encoding = validEncoding(previous) && previous.root === root && Boolean(previous.system) === Boolean(first) && Array.isArray(previous.tools) === Array.isArray(payload.tools) ? copy(previous) : {
2131
2320
  version: 1,
2132
2321
  root,
2133
2322
  system: copy(first),
@@ -2173,13 +2362,38 @@ const stableContextExtension = (api) => {
2173
2362
  api.on("before_provider_request", (event, context) => {
2174
2363
  const entries = context.sessionManager.getBranch();
2175
2364
  const identity = `${context.model?.provider}/${context.model?.id}/${context.model?.baseUrl}`;
2176
- const saved = [...entries].reverse().find((entry) => entry.type === "custom" && entry.customType === entryType && entry.data?.identity === identity);
2177
- const previous = saved?.type === "custom" ? saved.data?.encoding : void 0;
2365
+ const previous = readEncoding(entries, identity);
2178
2366
  const result = encodeStableContext(event.payload, previous);
2179
- if (canonical(previous) !== canonical(result.encoding)) api.appendEntry(entryType, { identity, encoding: result.encoding });
2367
+ if (canonical(previous) !== canonical(result.encoding)) api.appendEntry(entryType, { identity, encoding: storedEncoding(result.encoding, previous) });
2180
2368
  return result.payload;
2181
2369
  });
2182
2370
  };
2371
+ function storedEncoding(encoding, previous) {
2372
+ const stored = { version: 1, root: encoding.root };
2373
+ for (const field of encodingFields) {
2374
+ if (previous && canonical(previous[field]) === canonical(encoding[field])) continue;
2375
+ stored[field] = encoding[field] ?? null;
2376
+ }
2377
+ return stored;
2378
+ }
2379
+ function readEncoding(entries, identity) {
2380
+ let current;
2381
+ for (const entry of entries) {
2382
+ if (entry.type !== "custom" || entry.customType !== entryType) continue;
2383
+ const data = entry.data;
2384
+ if (data?.identity !== identity || !data.encoding) continue;
2385
+ const stored = data.encoding;
2386
+ current = {
2387
+ version: 1,
2388
+ root: stored.root,
2389
+ system: "system" in stored ? stored.system ?? void 0 : current?.system,
2390
+ tools: "tools" in stored ? stored.tools ?? void 0 : current?.tools,
2391
+ declarations: "declarations" in stored ? stored.declarations : current?.declarations ?? {},
2392
+ revisions: "revisions" in stored ? stored.revisions : current?.revisions ?? []
2393
+ };
2394
+ }
2395
+ return current;
2396
+ }
2183
2397
  function deploymentReasoningApi(api) {
2184
2398
  function optionsFor(model2, options) {
2185
2399
  if (model2.api !== "openai-completions" || !model2.compat || !("thinkingFormat" in model2.compat) || model2.compat.thinkingFormat !== "deepseek" || model2.reasoning) return options;
@@ -2231,7 +2445,7 @@ async function runAgentSession(req, signal, emitRaw, options) {
2231
2445
  const modelRuntime = await createModelRuntime(req);
2232
2446
  const model2 = modelRuntime.getModel(providerId(req), req.settings.model);
2233
2447
  if (!model2) throw Error(`Model ${req.settings.model} is unavailable.`);
2234
- const sessionManager = await openSessionManager(req.taskId || req.id, cwd, options.sessionDir);
2448
+ const sessionManager = await openSessionManager(req.taskId || req.id, cwd, options.sessionDir, options.sessionImages, options.branchFrom);
2235
2449
  if (options.branchFrom) {
2236
2450
  if (options.branchFrom.entryId) sessionManager.branch(options.branchFrom.entryId);
2237
2451
  else sessionManager.resetLeaf();
@@ -2334,6 +2548,7 @@ async function runAgentSession(req, signal, emitRaw, options) {
2334
2548
  const restoredDeferredToolNames = [...previouslyDisclosedToolNames].filter((name) => currentlySearchableToolNames.has(name));
2335
2549
  session.setActiveToolsByName([.../* @__PURE__ */ new Set([...sessionActiveTools, ...restoredDeferredToolNames])]);
2336
2550
  session.setAutoCompactionEnabled(true);
2551
+ if (options.compactionSettings) settingsManager.applyOverrides({ compaction: { enabled: true, ...options.compactionSettings } });
2337
2552
  const extensionNames = new Set(session.getAllTools().map((tool) => tool.name).filter((name) => !builtInToolNames.has(name) && !customTools.some((tool) => tool.name === name)));
2338
2553
  const allowedExtensionNames = options.extensionToolNames ? new Set(options.extensionToolNames) : void 0;
2339
2554
  const beforeToolCall = async (context, toolSignal) => {
@@ -2365,13 +2580,21 @@ async function runAgentSession(req, signal, emitRaw, options) {
2365
2580
  emit({ id: req.id, type: "phase", text: req.settings.language === "zh-CN" ? "思考中" : "Thinking" });
2366
2581
  try {
2367
2582
  signal.throwIfAborted();
2368
- await session.prompt(req.text, options.initialImages?.length ? { images: options.initialImages } : void 0);
2583
+ await session.prompt(req.text, {
2584
+ ...options.initialImages?.length ? { images: options.initialImages } : {},
2585
+ // Prompt preparation can await compaction/auth/extensions before the model
2586
+ // run exists. An earlier abort has no run to stop; retain cancellation at
2587
+ // the public preflight boundary before that later run can be created.
2588
+ preflightResult: () => signal.throwIfAborted()
2589
+ });
2369
2590
  await session.waitForIdle();
2370
2591
  await Promise.all([...pendingForwards]);
2371
2592
  if (signal.aborted) throw signal.reason;
2372
2593
  const last = [...session.messages].reverse().find((message) => message.role === "assistant");
2373
2594
  if (!last) throw Error("Provider returned no assistant message.");
2374
2595
  if (last.stopReason === "error" || last.stopReason === "aborted") throw Error(last.errorMessage || `Model stopped: ${last.stopReason}`);
2596
+ if (last.stopReason === "length" && !last.content.some((block) => block.type === "text" && block.text.trim())) throw Error("The model reached its output limit without a reply. Retry this message.");
2597
+ if (!last.content.some((block) => block.type === "text" && block.text.trim())) throw Error(req.settings.language === "zh-CN" ? "模型没有返回回复正文。请重试,或切换模型后继续。" : "The model returned no reply text. Retry or choose another model to continue.");
2375
2598
  emitContext(req.id, session, emit, contextState);
2376
2599
  emit({ id: req.id, type: "done" });
2377
2600
  } finally {
@@ -2522,6 +2745,11 @@ async function createModelRuntime(req) {
2522
2745
  const selected = req.settings.providers.find((provider) => provider.id === req.settings.providerId);
2523
2746
  const selectedModel = selected?.models?.find((model2) => model2.id === req.settings.model);
2524
2747
  const id = providerId(req);
2748
+ const adapter = configuredProviderAdapter(selected, req.settings);
2749
+ if (adapter) {
2750
+ runtime.registerNativeProvider(adapter);
2751
+ return runtime;
2752
+ }
2525
2753
  const deepSeek = /deepseek/i.test([id, selected?.name, req.settings.model, req.settings.endpoint].filter(Boolean).join(" "));
2526
2754
  const reasoning = selectedModel?.reasoning === true;
2527
2755
  const { api, endpoint } = resolveAgentProviderConnection(req);
@@ -2568,11 +2796,23 @@ function resolveAgentProviderConnection(req) {
2568
2796
  function providerId(req) {
2569
2797
  return req.settings.providerId || "shun-provider";
2570
2798
  }
2571
- async function openSessionManager(id, cwd, sessionDir) {
2799
+ async function openSessionManager(id, cwd, sessionDir, images, branchFrom) {
2572
2800
  const names = (await readdir(sessionDir)).filter((name) => name.endsWith(`_${id}.jsonl`));
2573
2801
  const matches = await Promise.all(names.map(async (name) => ({ path: join(sessionDir, name), modified: (await stat(join(sessionDir, name))).mtimeMs })));
2574
2802
  const existing = matches.sort((a, b) => b.modified - a.modified)[0];
2575
- return existing ? SessionManager.open(existing.path, sessionDir, cwd) : SessionManager.create(cwd, sessionDir, { id });
2803
+ if (!existing) return SessionManager.create(cwd, sessionDir, { id });
2804
+ if (images) await externalizeSessionFile(existing.path, images.taskId, images.store).catch((error) => console.warn("[session-images]", error));
2805
+ await pruneSessionFile(existing.path).catch((error) => console.warn("[session-prune]", error));
2806
+ let manager = SessionManager.open(existing.path, sessionDir, cwd);
2807
+ if (branchFrom?.entryId && !manager.getEntries().some((entry) => entry.id === branchFrom.entryId)) {
2808
+ if (await restoreArchivedEntries(existing.path).catch((error) => {
2809
+ console.warn("[session-prune]", error);
2810
+ return false;
2811
+ })) {
2812
+ manager = SessionManager.open(existing.path, sessionDir, cwd);
2813
+ }
2814
+ }
2815
+ return manager;
2576
2816
  }
2577
2817
  async function removeAgentSessions(id, sessionDir) {
2578
2818
  let names;
@@ -2581,7 +2821,7 @@ async function removeAgentSessions(id, sessionDir) {
2581
2821
  } catch {
2582
2822
  return 0;
2583
2823
  }
2584
- const suffix = `_${id}.jsonl`, matches = names.filter((name) => name.endsWith(suffix));
2824
+ const suffix = `_${id}.jsonl`, matches = names.filter((name) => name.endsWith(suffix) || name.endsWith(`${suffix}.archive.jsonl`));
2585
2825
  await Promise.all(matches.map((name) => rm(join(sessionDir, name), { force: true })));
2586
2826
  return matches.length;
2587
2827
  }
@@ -3081,11 +3321,18 @@ class AttachmentStore {
3081
3321
  return imported;
3082
3322
  });
3083
3323
  }
3084
- async importBuffers(taskId, files) {
3324
+ /**
3325
+ * Store many buffers in one pass.
3326
+ *
3327
+ * The default limit is what a person can hand over at once. A caller moving a
3328
+ * transcript's images out of memory has no such bound and passes its own, so
3329
+ * the whole batch shares one directory listing instead of one per file.
3330
+ */
3331
+ async importBuffers(taskId, files, limit = 20) {
3085
3332
  safeId(taskId, "task ID");
3086
3333
  return this.mutateTask(taskId, async () => {
3087
3334
  const existing = await this.list(taskId), imported = [];
3088
- for (const file of files.slice(0, 20)) imported.push(await this.persist(taskId, file.name, file.bytes, existing, imported));
3335
+ for (const file of files.slice(0, limit)) imported.push(await this.persist(taskId, file.name, file.bytes, existing, imported));
3089
3336
  return imported;
3090
3337
  });
3091
3338
  }
@@ -3581,7 +3828,9 @@ async function previewAttachment(store, taskId, attachmentId, page = 1, purpose
3581
3828
  const { metadata, bytes } = await store.read(taskId, attachmentId);
3582
3829
  return previewAttachmentBytes(metadata, bytes, page, purpose);
3583
3830
  }
3831
+ const READ_BYTES = 64 * 1024;
3584
3832
  class TaskEventStore {
3833
+ #cursors = /* @__PURE__ */ new Map();
3585
3834
  #root;
3586
3835
  #allocations = /* @__PURE__ */ new Map();
3587
3836
  #writes = /* @__PURE__ */ new Map();
@@ -3630,22 +3879,65 @@ class TaskEventStore {
3630
3879
  });
3631
3880
  await (this.#writes.get(taskId) || Promise.resolve()).catch(() => {
3632
3881
  });
3633
- let raw = "";
3882
+ const file = await open(this.path(taskId), "r").catch(() => void 0);
3883
+ if (!file) return [];
3634
3884
  try {
3635
- raw = await readFile(this.path(taskId), "utf8");
3636
- } catch {
3637
- return [];
3638
- }
3639
- const rows = [];
3640
- for (const line of raw.split("\n")) {
3641
- if (!line) continue;
3642
- try {
3643
- const event = JSON.parse(line);
3644
- if (event.taskId === taskId && Number.isInteger(event.seq) && event.seq > afterSeq) rows.push(event);
3645
- } catch {
3885
+ const stat2 = await file.stat();
3886
+ const cursor = this.#cursor(taskId, stat2);
3887
+ let offset = 0;
3888
+ let nearest = -1;
3889
+ for (const [seq, position] of cursor.offsets) {
3890
+ if (seq <= afterSeq && seq > nearest) {
3891
+ nearest = seq;
3892
+ offset = position;
3893
+ }
3894
+ }
3895
+ const rows = [];
3896
+ const count = Math.min(2e3, Math.max(1, Math.floor(limit) || 500));
3897
+ let pending2 = Buffer.alloc(0);
3898
+ let lineStart = offset;
3899
+ while (offset < stat2.size) {
3900
+ const chunk = Buffer.allocUnsafe(Math.min(READ_BYTES, stat2.size - offset));
3901
+ const { bytesRead } = await file.read(chunk, 0, chunk.length, offset);
3902
+ if (!bytesRead) break;
3903
+ offset += bytesRead;
3904
+ pending2 = Buffer.concat([pending2, chunk.subarray(0, bytesRead)]);
3905
+ let start = 0;
3906
+ for (let end = pending2.indexOf(10); end >= 0; end = pending2.indexOf(10, start)) {
3907
+ const event = parseEvent(pending2.subarray(start, end), taskId);
3908
+ lineStart += end + 1 - start;
3909
+ if (event) {
3910
+ this.#remember(cursor, event.seq, lineStart);
3911
+ if (event.seq > afterSeq) rows.push(event);
3912
+ }
3913
+ start = end + 1;
3914
+ if (rows.length >= count) return rows;
3915
+ }
3916
+ pending2 = pending2.subarray(start);
3646
3917
  }
3918
+ const final = parseEvent(pending2, taskId);
3919
+ if (final && final.seq > afterSeq) rows.push(final);
3920
+ return rows;
3921
+ } finally {
3922
+ await file.close();
3647
3923
  }
3648
- return rows.slice(0, Math.min(2e3, Math.max(1, Math.floor(limit) || 500)));
3924
+ }
3925
+ #cursor(taskId, stat2) {
3926
+ let cursor = this.#cursors.get(taskId);
3927
+ if (!cursor || cursor.ino !== stat2.ino || stat2.size < cursor.size || stat2.size === cursor.size && stat2.mtimeMs !== cursor.mtimeMs) {
3928
+ cursor = { ...stat2, offsets: /* @__PURE__ */ new Map() };
3929
+ }
3930
+ cursor.size = stat2.size;
3931
+ cursor.mtimeMs = stat2.mtimeMs;
3932
+ this.#cursors.delete(taskId);
3933
+ this.#cursors.set(taskId, cursor);
3934
+ while (this.#cursors.size > 64) this.#cursors.delete(this.#cursors.keys().next().value);
3935
+ return cursor;
3936
+ }
3937
+ #remember(cursor, seq, offset) {
3938
+ cursor.offsets.delete(seq);
3939
+ cursor.offsets.set(seq, offset);
3940
+ while (cursor.offsets.size > 128) cursor.offsets.delete(cursor.offsets.keys().next().value);
3649
3941
  }
3650
3942
  /**
3651
3943
  * The newest sequence this task holds.
@@ -3681,6 +3973,7 @@ class TaskEventStore {
3681
3973
  this.#allocations.delete(taskId);
3682
3974
  this.#writes.delete(taskId);
3683
3975
  this.#sequences.delete(taskId);
3976
+ this.#cursors.delete(taskId);
3684
3977
  await rm(this.path(taskId), { force: true });
3685
3978
  }
3686
3979
  path(taskIdValue) {
@@ -3693,24 +3986,52 @@ class TaskEventStore {
3693
3986
  async #lastWritten(taskId) {
3694
3987
  const known = this.#sequences.get(taskId);
3695
3988
  if (known !== void 0) return known;
3696
- let last;
3989
+ const file = await open(this.path(taskId), "r").catch(() => void 0);
3990
+ if (!file) return void 0;
3697
3991
  try {
3698
- const raw = await readFile(this.path(taskId), "utf8");
3699
- for (const line of raw.trim().split("\n").reverse()) {
3700
- try {
3701
- const event = JSON.parse(line);
3702
- if (event.taskId === taskId && Number.isInteger(event.seq)) {
3703
- last = event.seq;
3704
- break;
3992
+ const stat2 = await file.stat();
3993
+ const cursor = this.#cursor(taskId, stat2);
3994
+ let position = stat2.size;
3995
+ let pending2 = Buffer.alloc(0);
3996
+ while (position > 0) {
3997
+ const start = Math.max(0, position - READ_BYTES);
3998
+ const chunk = Buffer.allocUnsafe(position - start);
3999
+ const { bytesRead } = await file.read(chunk, 0, chunk.length, start);
4000
+ if (bytesRead !== chunk.length) return void 0;
4001
+ pending2 = Buffer.concat([chunk, pending2]);
4002
+ position = start;
4003
+ let end = pending2.length;
4004
+ for (let newline = pending2.lastIndexOf(10, end - 1); newline >= 0; ) {
4005
+ const event = parseEvent(pending2.subarray(newline + 1, end), taskId);
4006
+ if (event) {
4007
+ if (pending2[end] === 10) this.#remember(cursor, event.seq, position + end + 1);
4008
+ return event.seq;
3705
4009
  }
3706
- } catch {
4010
+ end = newline;
4011
+ newline = end > 0 ? pending2.lastIndexOf(10, end - 1) : -1;
4012
+ }
4013
+ if (position === 0) {
4014
+ const event = parseEvent(pending2.subarray(0, end), taskId);
4015
+ if (event && pending2[end] === 10) this.#remember(cursor, event.seq, end + 1);
4016
+ return event?.seq;
3707
4017
  }
4018
+ pending2 = pending2.subarray(0, end);
3708
4019
  }
3709
- } catch {
4020
+ return void 0;
4021
+ } finally {
4022
+ await file.close();
3710
4023
  }
3711
- return last;
3712
4024
  }
3713
4025
  }
4026
+ function parseEvent(line, taskId) {
4027
+ if (!line.length) return void 0;
4028
+ try {
4029
+ const event = JSON.parse(line.toString("utf8"));
4030
+ if (event && event.taskId === taskId && Number.isInteger(event.seq)) return event;
4031
+ } catch {
4032
+ }
4033
+ return void 0;
4034
+ }
3714
4035
  function validTaskId(value) {
3715
4036
  const taskId = String(value || "");
3716
4037
  if (!/^[A-Za-z0-9_-]{1,100}$/.test(taskId)) throw Error("Invalid task ID.");
@@ -4321,7 +4642,7 @@ class BackgroundTaskManager {
4321
4642
  async observe(sessionId, taskId, options = {}) {
4322
4643
  const snapshot = await this.waitForOutput(sessionId, taskId, options);
4323
4644
  const task = this.#owned(sessionId, taskId);
4324
- const { id, state, exitCode, startedAt, finishedAt, endpoints, previewUrl } = task.public;
4645
+ const { id, state, exitCode, startedAt, finishedAt, lastOutputAt, endpoints, previewUrl } = task.public;
4325
4646
  let remaining = Math.max(1024, Math.min(64e3, Math.floor(options.maxChars || 12e3)));
4326
4647
  const output = [];
4327
4648
  let omitted = 0;
@@ -4332,13 +4653,25 @@ class BackgroundTaskManager {
4332
4653
  remaining -= text2.length;
4333
4654
  }
4334
4655
  return {
4335
- task: { id, state, exitCode: exitCode ?? null, startedAt, finishedAt: finishedAt ?? null, endpoints, previewUrl },
4656
+ task: { id, state, exitCode: exitCode ?? null, startedAt, finishedAt: finishedAt ?? null, lastOutputAt: lastOutputAt ?? null, elapsed_ms: Math.max(0, (finishedAt ?? Date.now()) - (startedAt ?? task.public.createdAt)), endpoints, previewUrl },
4336
4657
  output,
4337
4658
  next_seq: snapshot.at(-1)?.seq ?? options.afterSeq ?? 0,
4338
4659
  ...options.until ? { matched: snapshot.some((chunk) => chunk.text.includes(options.until)) } : {},
4339
4660
  ...omitted ? { truncated: true, omitted_characters: omitted, log_files: { stdout: task.stdoutPath, stderr: task.stderrPath } } : {}
4340
4661
  };
4341
4662
  }
4663
+ async waitForExit(sessionId, taskId, signal, update) {
4664
+ for (; ; ) {
4665
+ if (signal?.aborted) {
4666
+ await this.stopAndWait(sessionId, taskId);
4667
+ throw signal.reason ?? Error("Process wait cancelled.");
4668
+ }
4669
+ const value = await this.observe(sessionId, taskId);
4670
+ update?.(value);
4671
+ if (!activeStates.has(value.task.state)) return this.observe(sessionId, taskId);
4672
+ await this.#waitForChange(this.#owned(sessionId, taskId), 1e3);
4673
+ }
4674
+ }
4342
4675
  async stop(sessionId, taskId) {
4343
4676
  const task = this.#owned(sessionId, taskId);
4344
4677
  if (!activeStates.has(task.public.state)) return this.#copy(task.public);
@@ -4405,7 +4738,7 @@ class BackgroundTaskManager {
4405
4738
  candidates.add(endpoint);
4406
4739
  if (candidates.size > 8) candidates.delete(candidates.values().next().value);
4407
4740
  }
4408
- task.public = { ...task.public, outputSeq: chunk.seq, outputBytes: bytes };
4741
+ task.public = { ...task.public, outputSeq: chunk.seq, outputBytes: bytes, lastOutputAt: chunk.at };
4409
4742
  void this.#refreshEndpoints(task);
4410
4743
  this.#emit({ type: "output", task: this.#copy(task.public), chunk: { ...chunk } });
4411
4744
  this.#schedulePersist(task);
@@ -6616,6 +6949,7 @@ function createShellTool(cwd) {
6616
6949
  (windows && windows.kind !== "bash" ? tool.description.replace("Execute a bash command", "Execute a shell command") : tool.description).replace(/Output is truncated to last .*?temp file\./, "Long output returns a preview of the last 16KB; complete output is saved to a file."),
6617
6950
  ...interpreter ? [interpreter] : [],
6618
6951
  `Foreground commands default to a ${DEFAULT_FOREGROUND_TIMEOUT_SECONDS}-second timeout; use the task-owned background process tools for servers, watchers, and other intentionally long-running work.`,
6952
+ "For finite long-running jobs use background_start with wait_until_exit=true. Preserve live progress instead of piping it into tail; bounded output is provided by the process tools.",
6619
6953
  "Runs with the desktop user’s inherited non-interactive environment and may reuse existing authentication when relevant.",
6620
6954
  "When present, a task-root .venv or venv and node_modules/.bin are placed before the inherited executable path for every command.",
6621
6955
  "Plain commands such as python, pip, pytest, node, and package scripts resolve through that project environment automatically; do not inspect or activate it again.",
@@ -7223,7 +7557,7 @@ class ShunHostService {
7223
7557
  async call(method, input = {}) {
7224
7558
  const desktop = this.desktop;
7225
7559
  const sharedDesktop = Boolean(desktop);
7226
- if (["assistant.open", "assistant.overview", "assistant.memory.update"].includes(method)) {
7560
+ if (["assistant.open", "assistant.overview", "assistant.memory.update", "assistant.task.reply"].includes(method)) {
7227
7561
  if (!desktop) throw Error("Open Shun Desktop to use your personal assistant. Your ordinary terminal tasks remain available.");
7228
7562
  return desktop(`conversation.${method}`, input);
7229
7563
  }
@@ -7795,7 +8129,7 @@ const clean$1 = (text2) => stripTerminalSequences(text2).replace(/[\x00-\x1f\x7f
7795
8129
  const accent = (text2) => `\x1B[38;5;205m${text2}\x1B[0m`;
7796
8130
  const muted = (text2) => `\x1B[2m${text2}\x1B[0m`;
7797
8131
  const bold = (text2) => `\x1B[1m${text2}\x1B[0m`;
7798
- const version$1 = "0.1.162";
8132
+ const version$1 = "0.1.201";
7799
8133
  class WelcomeHeader {
7800
8134
  state = { title: "", model: "", workspace: "", running: false, compact: false, ready: false };
7801
8135
  update(state) {
@@ -8813,7 +9147,7 @@ ${activeRun ? "Task continues running in Shun.\n" : ""}Resume this conversation:
8813
9147
  process.off("SIGTERM", onSignal);
8814
9148
  process.off("SIGINT", onSignal);
8815
9149
  }
8816
- const version = "0.1.162";
9150
+ const version = "0.1.201";
8817
9151
  const args = process.argv.slice(2);
8818
9152
  async function main() {
8819
9153
  if (args.includes("--version") || args.includes("-v")) {
package/package.json CHANGED
@@ -60,5 +60,5 @@
60
60
  "mcp",
61
61
  "developer-tools"
62
62
  ],
63
- "version": "0.1.162"
63
+ "version": "0.1.201"
64
64
  }