ytdb-slate 0.20.0 → 0.21.0

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/CHANGELOG.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  Approved update notes for Slate releases appear here.
4
4
 
5
+ ## [0.21.0]
6
+
7
+ The `threads` tool now lists the worker threads of the current session by default. The new `parentSession` parameter lists the threads of the newest earlier session. After a Slate handoff, `pi --continue` now opens the new session instead of the earlier session. Use pi 1.6.0 or later.
8
+
9
+ https://github.com/JetBrains/ytdb-slate/releases/tag/v0.21.0
10
+
5
11
  ## [0.20.0]
6
12
 
7
13
  Slate now uses a default `contextBudget` of 400,000 tokens for every provider. Sessions with a provider other than Anthropic can run longer before a handoff to a new session. The `threads` tool now returns short pages and uses less context. Native notifications on Windows now find Windows PowerShell under a different Start menu name. Use pi 1.6.0 or later.
@@ -30,8 +30,10 @@
30
30
  * the orchestrator's base model, unlike a failover fallback.
31
31
  */
32
32
 
33
- import { existsSync, readFileSync } from "node:fs";
34
- import { join } from "node:path";
33
+ import { randomUUID } from "node:crypto";
34
+ import { closeSync, existsSync, fstatSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
35
+ import { dirname, join } from "node:path";
36
+ import { setTimeout as delay } from "node:timers/promises";
35
37
  import {
36
38
  CONFIG_DIR_NAME,
37
39
  getAgentDir,
@@ -294,6 +296,44 @@ function buildKickoff(cwd: string, trusted: boolean, brief: string, focus?: stri
294
296
  return parts.join("\n");
295
297
  }
296
298
 
299
+ const SESSION_CLOCK_LIMIT_MS = 3_000;
300
+ const SESSION_CLOCK_POLL_MS = 10;
301
+
302
+ async function waitForSessionClock(ctx: ExtensionContext, parentFile: string | undefined): Promise<void> {
303
+ if (!parentFile) return;
304
+ try {
305
+ const parent = statSync(parentFile, { throwIfNoEntry: false });
306
+ if (!parent) return;
307
+
308
+ // Pi sorts sessions by modification time. A tie can select the parent.
309
+ // Measure a write in the session directory before the successor writes.
310
+ const probe = join(dirname(parentFile), `.slate-handoff-clock-${randomUUID()}.tmp`);
311
+ const fd = openSync(probe, "wx", 0o600);
312
+ try {
313
+ const deadline = performance.now() + SESSION_CLOCK_LIMIT_MS;
314
+ while (performance.now() < deadline) {
315
+ writeFileSync(fd, ".");
316
+ if (fstatSync(fd).mtimeMs > parent.mtimeMs) return;
317
+ await delay(SESSION_CLOCK_POLL_MS);
318
+ }
319
+ } finally {
320
+ try {
321
+ closeSync(fd);
322
+ } catch (error) {
323
+ reportFailure(ctx, `slate: could not close the handoff clock probe: ${sanitizeForNotify(String(error))}`);
324
+ }
325
+ try {
326
+ unlinkSync(probe);
327
+ } catch (error) {
328
+ reportFailure(ctx, `slate: could not delete the handoff clock probe: ${sanitizeForNotify(String(error))}`);
329
+ }
330
+ }
331
+ reportFailure(ctx, `slate: the handoff session file clock did not advance within the ${SESSION_CLOCK_LIMIT_MS / 1_000}-second polling limit.`);
332
+ } catch (error) {
333
+ reportFailure(ctx, `slate: could not check the handoff session file clock: ${sanitizeForNotify(String(error))}`);
334
+ }
335
+ }
336
+
297
337
  type KickoffSender = (message: { customType: string; content: string; display: boolean; details?: { sessionId: string } }, options?: { triggerTurn?: boolean }) => void | Promise<void>;
298
338
 
299
339
  /** Claim delivery before starting a turn. A claimed kickoff is never replayed on reload. */
@@ -694,7 +734,13 @@ export function registerSlateHandoff(
694
734
  }
695
735
  });
696
736
 
697
- const performHandoff = async (ctx: ExtensionCommandContext, focus?: string, summaryVisible?: boolean, purpose?: HandoffPurpose): Promise<boolean> => {
737
+ const performHandoff = async (
738
+ ctx: ExtensionCommandContext,
739
+ focus: string | undefined,
740
+ summaryVisible: boolean | undefined,
741
+ purpose: HandoffPurpose,
742
+ onTransfer: (fresh: ExtensionContext) => void,
743
+ ): Promise<void> => {
698
744
  const brief = lastAssistantText(ctx);
699
745
  const parentSession = ctx.sessionManager.getSessionFile();
700
746
  // ctx.model can be undefined (no-model session): capture neither field
@@ -729,6 +775,9 @@ export function registerSlateHandoff(
729
775
  successor.appendCustomEntry("slate-handoff", entry as unknown as Record<string, unknown>);
730
776
  },
731
777
  withSession: async (fresh) => {
778
+ // Finish the parent write after setup and before kickoff.
779
+ onTransfer(fresh);
780
+ await waitForSessionClock(fresh, parentSession);
732
781
  await deliverKickoff(fresh, (message, options) => fresh.sendMessage(message, options));
733
782
  },
734
783
  });
@@ -738,7 +787,6 @@ export function registerSlateHandoff(
738
787
  store.save();
739
788
  if (ctx.hasUI) ctx.ui.notify("slate: handoff cancelled — pause cleared.", "warning");
740
789
  }
741
- return !cancelled;
742
790
  } catch (error) {
743
791
  // Best-effort: if the replacement partially happened, the old pi/ctx
744
792
  // are stale and these calls themselves throw.
@@ -770,10 +818,14 @@ export function registerSlateHandoff(
770
818
  const selected = purpose ?? retained ?? "user-request";
771
819
  pi.appendEntry("slate-handoff-purpose", { sessionId, purpose: selected });
772
820
  await ctx.waitForIdle();
773
- const transferred = await performHandoff(ctx, focus, summaryVisible, selected);
774
- if (transferred && parentManager instanceof SessionManager) {
775
- parentManager.appendCustomEntry("slate-handoff-purpose", { sessionId, purpose: selected, consumed: true });
776
- }
821
+ await performHandoff(ctx, focus, summaryVisible, selected, (fresh) => {
822
+ if (!(parentManager instanceof SessionManager)) return;
823
+ try {
824
+ parentManager.appendCustomEntry("slate-handoff-purpose", { sessionId, purpose: selected, consumed: true });
825
+ } catch (error) {
826
+ reportFailure(fresh, `slate: could not record the handoff purpose as consumed: ${sanitizeForNotify(String(error))}`);
827
+ }
828
+ });
777
829
  });
778
830
  };
779
831
 
@@ -114,6 +114,7 @@ export function threadTypeMarker(type: ThreadType): string {
114
114
 
115
115
  export interface ThreadRecord {
116
116
  id: string; // "t1", "t2", ...
117
+ sessionId?: string;
117
118
  name: string;
118
119
  status: "queued" | "running" | "successful" | "failed" | "cancelled";
119
120
  /** Immutable thread type. */
@@ -499,6 +500,7 @@ export const ADOPTED_SNAPSHOT_FIELDS = {
499
500
 
500
501
  export const ADOPTED_THREAD_FIELDS = {
501
502
  id: true,
503
+ sessionId: true,
502
504
  name: true,
503
505
  status: true,
504
506
  type: true,
@@ -548,7 +550,7 @@ export const ADOPTED_EPISODE_FIELDS = {
548
550
  * So the checklist is also enforced against what the sanitizer actually BUILT: a field
549
551
  * the snapshot carries, that adoption claims to know, that the built record lacks, and
550
552
  * that was not deliberately refused (those are already reported by name) is a slate bug,
551
- * and it says so. Cheap — one pass over ten keys per record — and it fires on the first
553
+ * and it says so. It checks the known fields once per record and fires on the first
552
554
  * restore after the omission rather than whenever the missing data is next needed.
553
555
  *
554
556
  * Exported for the same reason as the checklists: a checker can drive it with a record
@@ -626,6 +628,7 @@ export function sanitizeThreadRecord(raw: unknown, repairs: string[]): ThreadRec
626
628
  const now = Date.now();
627
629
  const built: ThreadRecord = {
628
630
  id,
631
+ sessionId: keep("sessionId", t.sessionId, str(t.sessionId) || undefined),
629
632
  name,
630
633
  status: adoptedStatus,
631
634
  type,
@@ -374,13 +374,22 @@ export class ThreadManager {
374
374
  if (this.store.currentChange !== capturedChange || this.store.changeOwnerSessionId !== capturedOwner) {
375
375
  throw new Error("The current change or its session owner changed during action validation. No action was admitted.");
376
376
  }
377
+ let sessionId: string | undefined;
378
+ try {
379
+ sessionId = ctx.sessionManager?.getSessionId?.();
380
+ } catch (cause) {
381
+ throw new Error("Cannot create a thread without a nonempty session ID.", { cause });
382
+ }
383
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
384
+ throw new Error("Cannot create a thread without a nonempty session ID.");
385
+ }
377
386
  const temporary = capturedChange === undefined ? undefined : allocateActionTemporary(ctx.cwd, capturedChange);
378
387
  if (temporary) this.store.actionTemporaryOwners.add(temporary);
379
388
  let thread: ThreadRecord;
380
389
  let actionMessage: ReturnType<typeof actionTemporaryMessage> | undefined;
381
390
  try {
382
391
  if (temporary) actionMessage = actionTemporaryMessage(`slate-changes/${capturedChange}/tmp/${basename(temporary.path)}`);
383
- thread = this.createThread(accepted);
392
+ thread = this.createThread(accepted, sessionId);
384
393
  } catch (error) {
385
394
  if (temporary) {
386
395
  const message = retainedActionTemporary(temporary.path, error);
@@ -392,7 +401,7 @@ export class ThreadManager {
392
401
  return await this.runDispatch(thread, accepted, prompt, ctx, signal, onProgress, admission, initialRoute, reviewGuidance, temporary, folderGuidance, actionMessage);
393
402
  }
394
403
 
395
- private createThread(opts: DispatchOptions): ThreadRecord {
404
+ private createThread(opts: DispatchOptions, sessionId: string): ThreadRecord {
396
405
  const id = this.store.claimNextThreadId();
397
406
  const type = parseThreadType(opts.type, true)!
398
407
  const configuredTools = opts.tools ?? this.config.workerTools;
@@ -400,6 +409,7 @@ export class ThreadManager {
400
409
  const now = Date.now();
401
410
  const record: ThreadRecord = {
402
411
  id,
412
+ sessionId,
403
413
  name: opts.name?.trim() || id,
404
414
  status: "queued",
405
415
  type,
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  import { readFileSync } from "node:fs";
6
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+ import type { ExtensionAPI, ExtensionToolContext } from "@earendil-works/pi-coding-agent";
7
7
  import { Type, type Static } from "typebox";
8
8
  import { renderCompactCall, renderCompactResult, renderThreadCall, renderThreadResult, type DisplayDetails } from "./render.ts";
9
9
  import {
@@ -59,8 +59,7 @@ function dispatchCostLine(episode: EpisodeRecord): string {
59
59
  return `Cost: ${partialCost ? "≥" : ""}$${reportedCost.toFixed(4)}${costScope} | tokens: ${quantities.join(", ")} | ended ${model} ${effort}${warm}`;
60
60
  }
61
61
 
62
- const THREAD_PAGE_ROWS = 8;
63
- const THREAD_PAGE_BYTES = 4096;
62
+ const THREAD_PAGE_ROWS = 20;
64
63
  const MAX_THREAD_CURSOR = "t9007199254740992";
65
64
 
66
65
  function compareThreadIds(a: string, b: string): number {
@@ -71,7 +70,7 @@ function compareThreadIds(a: string, b: string): number {
71
70
  function validateThreadCursor(value: unknown): asserts value is string {
72
71
  if (typeof value !== "string" || value.length > MAX_THREAD_CURSOR.length
73
72
  || !/^t[1-9][0-9]*$/u.test(value) || compareThreadIds(value, MAX_THREAD_CURSOR) > 0) {
74
- throw new Error('Invalid before value. Use a thread ID such as "t9". Omit before to start with the newest thread.');
73
+ throw new Error('Invalid before value. Use a thread ID such as "t9". Omit both before and parentSession to list the current session.');
75
74
  }
76
75
  }
77
76
 
@@ -80,8 +79,9 @@ function inspectThreadArguments(args: unknown) {
80
79
  if (typeof args === "object" && args !== null && !Array.isArray(args)) {
81
80
  const before = Object.getOwnPropertyDescriptor(args, "before");
82
81
  const detail = Object.getOwnPropertyDescriptor(args, "detail");
83
- if ((!before || Object.hasOwn(before, "value")) && (!detail || Object.hasOwn(detail, "value"))) {
84
- return { before, detail };
82
+ const parentSession = Object.getOwnPropertyDescriptor(args, "parentSession");
83
+ if ([before, detail, parentSession].every((entry) => !entry || Object.hasOwn(entry, "value"))) {
84
+ return { before, detail, parentSession };
85
85
  }
86
86
  }
87
87
  } catch {
@@ -131,7 +131,6 @@ function threadPageRow(thread: ThreadRecord, store: SlateStore, getManager: () =
131
131
  const episode = ` — episode: ${thread.episodeId ?? "(none)"}`;
132
132
  if (!detail) return row + episode;
133
133
 
134
- // A sanitized reason uses at most 602 bytes after quoting. One full row fits with its summary and next call.
135
134
  const last = thread.episodeId === undefined ? undefined : store.episodes.get(thread.episodeId);
136
135
  const marks: string[] = [];
137
136
  if (last?.logicalModel) marks.push(`logical=${routingLabel(last.logicalModel, 80)}`);
@@ -156,42 +155,56 @@ function threadPageRow(thread: ThreadRecord, store: SlateStore, getManager: () =
156
155
  return `${row}${models}${episode} — updated ${updated}`;
157
156
  }
158
157
 
159
- function listThreads(store: SlateStore, getManager: () => ThreadManager, before?: string, detail?: boolean) {
158
+ function validateThreadMode(hasBefore: boolean, parentSession: boolean | undefined): void {
159
+ if (hasBefore && parentSession === true) {
160
+ throw new Error("Use either before or parentSession: true, not both.");
161
+ }
162
+ }
163
+
164
+ function listThreads(
165
+ store: SlateStore,
166
+ getManager: () => ThreadManager,
167
+ ctx: ExtensionToolContext,
168
+ { before, detail, parentSession }: { before?: string; detail?: boolean; parentSession?: boolean },
169
+ ) {
160
170
  const count = store.threads.size;
161
171
  if (count === 0) {
162
172
  return { text: "No threads yet. Use the thread tool to create one.", details: { count, failedCount: 0 } };
163
173
  }
174
+ const sessionId = ctx.sessionManager.getSessionId();
164
175
  const totals = { queued: 0, running: 0, successful: 0, failed: 0, cancelled: 0 };
165
- const page: ThreadRecord[] = [];
166
- let eligible = 0;
167
- for (const thread of store.threads.values()) {
168
- totals[thread.status]++;
169
- if (before !== undefined && compareThreadIds(thread.id, before) >= 0) continue;
170
- eligible++;
171
- const aheadOf = page.findIndex((row) => compareThreadIds(thread.id, row.id) > 0);
172
- if (aheadOf >= 0) {
173
- if (page.length === THREAD_PAGE_ROWS) page.pop();
174
- page.splice(aheadOf, 0, thread);
175
- } else if (page.length < THREAD_PAGE_ROWS) {
176
- page.push(thread);
177
- }
178
- }
176
+ const all = [...store.threads.values()].sort((a, b) => compareThreadIds(b.id, a.id));
177
+ const current = all.filter((thread) => thread.sessionId === sessionId);
178
+ for (const thread of all) totals[thread.status]++;
179
179
 
180
- let text = `Threads: ${count}. Queued: ${totals.queued}. Running: ${totals.running}. Successful: ${totals.successful}. Failed: ${totals.failed}. Cancelled: ${totals.cancelled}.`;
181
- const details = { count, failedCount: totals.failed };
182
- if (eligible === 0) return { text: text + "\nNo older threads.", details };
180
+ let rows = current;
181
+ let mode = "current session";
182
+ let limit = rows.length;
183
+ if (before !== undefined) {
184
+ rows = all.filter((thread) => compareThreadIds(thread.id, before) < 0);
185
+ limit = THREAD_PAGE_ROWS;
186
+ } else if (parentSession === true) {
187
+ const parent = all.find((thread) => thread.sessionId !== sessionId);
188
+ rows = parent ? all.filter((thread) => thread.sessionId === parent.sessionId) : [];
189
+ mode = "parent session";
190
+ limit = parent?.sessionId === undefined ? THREAD_PAGE_ROWS : rows.length;
191
+ }
183
192
 
184
- let footer = "";
185
- for (const [index, thread] of page.entries()) {
186
- const nextArgs = JSON.stringify({ before: thread.id, detail });
187
- const remaining = eligible - index - 1;
188
- const next = remaining > 0 ? `\nRemaining threads: ${remaining}. Next call: threads(${nextArgs})` : "";
189
- const withRow = `${text}\n${threadPageRow(thread, store, getManager, detail === true)}`;
190
- if (Buffer.byteLength(withRow + next, "utf8") > THREAD_PAGE_BYTES) break;
191
- text = withRow;
192
- footer = next;
193
+ const summary = `Threads: ${count}. Queued: ${totals.queued}. Running: ${totals.running}. Successful: ${totals.successful}. Failed: ${totals.failed}. Cancelled: ${totals.cancelled}. Current session: ${current.length}.`;
194
+ const page = rows.slice(0, limit);
195
+ const listing = before === undefined
196
+ ? `${mode}, ${page.length} ${page.length === 1 ? "thread" : "threads"}`
197
+ : `all sessions, threads older than ${before}${page.length === 0 ? ", 0 threads" : ""}`;
198
+ const lines = [summary, `Listing: ${listing}.`];
199
+ for (const thread of page) lines.push(threadPageRow(thread, store, getManager, detail === true));
200
+ if (before !== undefined && page.length === 0) lines.push("No older threads.");
201
+ if (page.length < rows.length) {
202
+ const last = page.at(-1)!;
203
+ const remaining = all.length - all.indexOf(last) - 1;
204
+ const nextArgs = JSON.stringify({ before: last.id, detail });
205
+ lines.push(`Remaining threads: ${remaining}. Next call: threads(${nextArgs})`);
193
206
  }
194
- return { text: text + footer, details };
207
+ return { text: lines.join("\n"), details: { count, failedCount: totals.failed } };
195
208
  }
196
209
 
197
210
  export function registerSlateTools(pi: ExtensionAPI, store: SlateStore, getManager: () => ThreadManager): void {
@@ -375,43 +388,58 @@ export function registerSlateTools(pi: ExtensionAPI, store: SlateStore, getManag
375
388
  });
376
389
 
377
390
  const threadsParameters = Type.Object({
378
- before: Type.Optional(Type.String({ description: "List threads created before this thread ID. Omit it to start with the newest thread." })),
391
+ before: Type.Optional(Type.String({ description: "List up to 20 threads from all sessions that are older than this thread ID." })),
392
+ parentSession: Type.Optional(Type.Union([Type.Literal(true), Type.Literal(false)], {
393
+ description: "List threads from the newest earlier session with threads. Do not combine true with before.",
394
+ })),
379
395
  detail: Type.Optional(Type.Union([Type.Literal(true), Type.Literal(false)], {
380
396
  description: "Show model choices, effort, the reason for the choice, and update times.",
381
397
  })),
382
398
  });
399
+ const prepareThreadsArguments = (args: unknown): Static<typeof threadsParameters> => {
400
+ const { before, detail, parentSession } = inspectThreadArguments(args);
401
+ const prepared: Static<typeof threadsParameters> = {};
402
+ if (parentSession) {
403
+ const value: unknown = parentSession.value;
404
+ if (typeof value !== "boolean") {
405
+ throw new Error("Invalid parentSession value. Use true or false.");
406
+ }
407
+ prepared.parentSession = value;
408
+ }
409
+ validateThreadMode(before !== undefined, prepared.parentSession);
410
+ if (before) {
411
+ const value: unknown = before.value;
412
+ validateThreadCursor(value);
413
+ prepared.before = value;
414
+ }
415
+ if (detail) {
416
+ const value: unknown = detail.value;
417
+ if (typeof value !== "boolean") {
418
+ throw new Error("Invalid detail value. Use true or false.");
419
+ }
420
+ prepared.detail = value;
421
+ }
422
+ return prepared;
423
+ };
383
424
  pi.registerTool({
384
425
  name: "threads",
385
426
  label: "Threads",
386
427
  renderCall: (args, theme, context) => renderCompactCall("threads", args, theme, context),
387
428
  renderResult: (result, options, theme, context) => renderCompactResult("threads", result, options, theme, context),
388
429
  description:
389
- "List up to eight worker threads and their episode IDs, newest thread first. " +
390
- "The totals cover all threads. " +
391
- "Follow the next call or set before to a thread ID to list older threads. " +
430
+ "List worker threads and their episode IDs, newest thread first. " +
431
+ "By default, list the current session. " +
432
+ "Set parentSession to true to list the newest earlier session with threads. Slate skips sessions without threads. " +
433
+ "Slate groups threads without a saved session ID together and lists up to 20 when that group is the parent. " +
434
+ "Set before to a thread ID to list up to 20 older threads from all sessions. " +
435
+ "Use only one of before or parentSession: true. Follow the next call to list older threads. " +
436
+ "Lists and totals use only the thread records available in this session. The totals include the current session count. " +
392
437
  "Set detail to true to see model choices, effort, the reason for the choice, and update times.",
393
438
  promptSnippet: "List worker threads and their episodes",
394
439
  parameters: threadsParameters,
395
- prepareArguments(args) {
396
- const { before, detail } = inspectThreadArguments(args);
397
- const prepared: Static<typeof threadsParameters> = {};
398
- if (before) {
399
- const value: unknown = before.value;
400
- validateThreadCursor(value);
401
- prepared.before = value;
402
- }
403
- if (detail) {
404
- const value: unknown = detail.value;
405
- if (typeof value !== "boolean") {
406
- throw new Error("Invalid detail value. Use true or false.");
407
- }
408
- prepared.detail = value;
409
- }
410
- return prepared;
411
- },
412
- async execute(_toolCallId, { before, detail }) {
413
- if (before !== undefined) validateThreadCursor(before);
414
- const { text, details } = listThreads(store, getManager, before, detail);
440
+ prepareArguments: prepareThreadsArguments,
441
+ async execute(_toolCallId, args, _signal, _onUpdate, ctx) {
442
+ const { text, details } = listThreads(store, getManager, ctx, prepareThreadsArguments(args));
415
443
  return { content: [{ type: "text", text }], details };
416
444
  },
417
445
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ytdb-slate",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
4
4
  "description": "Design-first feature development for the pi coding agent. Slate researches, designs, implements and reviews each change. You judge the design and keep control of the code without reading every line.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {