@oyasmi/pipiclaw 0.8.2 → 0.8.4

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.
@@ -4,7 +4,7 @@ import type { ChannelStore } from "../runtime/store.js";
4
4
  import type { UsageTotals } from "../shared/types.js";
5
5
  import { type RunnerBuiltInCommand } from "./commands.js";
6
6
  import type { RunnerFactoryPaths } from "./runner-factory.js";
7
- import { type AgentRunner, type RunnerStatusSnapshot } from "./types.js";
7
+ import { type AgentRunner, type RunnerStatusSnapshot, type TurnStatus } from "./types.js";
8
8
  export declare class ChannelRunner implements AgentRunner {
9
9
  private readonly executor;
10
10
  private readonly channelId;
@@ -30,12 +30,19 @@ export declare class ChannelRunner implements AgentRunner {
30
30
  private currentSkills;
31
31
  private currentTools;
32
32
  private firstTurnMemoryBootstrapPending;
33
- private acceptingBusyMessages;
34
- private agentLoopStarted;
33
+ /** Mirror of `tools.tasks.enabled` from the last tools-config load (see buildRuntimeTools). */
34
+ private tasksEnabled;
35
+ /** Single owner of turn state; see TurnPhase in types.ts. */
36
+ private turn;
35
37
  /** When the primary model last failed and we switched to the backup. null = on primary. */
36
38
  private primaryFailedAt;
37
39
  private runState;
38
40
  constructor(channelId: string, channelDir: string, paths: RunnerFactoryPaths);
41
+ beginTurn(taskText: string): void;
42
+ endTurn(): void;
43
+ isBusy(): boolean;
44
+ requestStop(): void;
45
+ getTurnStatus(): TurnStatus;
39
46
  run(ctx: ChannelContext, store: ChannelStore): Promise<{
40
47
  stopReason: string;
41
48
  errorMessage?: string;
@@ -61,6 +68,13 @@ export declare class ChannelRunner implements AgentRunner {
61
68
  private requireQueuedMessage;
62
69
  private shouldPreserveRawInput;
63
70
  private formatUserMessage;
71
+ /**
72
+ * Single source of truth for the busy-message window: steer is accepted while
73
+ * the prompt is being assembled ("preparing") or while the agent loop is
74
+ * actually streaming. Re-asserted after every await because the turn can end
75
+ * while this call was suspended.
76
+ */
77
+ private assertBusyWindowOpen;
64
78
  private queueBusyMessage;
65
79
  private resetRunState;
66
80
  private refreshSessionResources;
@@ -1,5 +1,5 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
- import { AgentSession, AgentSessionRuntime, AuthStorage, convertToLlm, createExtensionRuntime, DefaultResourceLoader, ModelRegistry, SessionManager, } from "@earendil-works/pi-coding-agent";
2
+ import { AgentSession, AgentSessionRuntime, AuthStorage, convertToLlm, createExtensionRuntime, DefaultResourceLoader, SessionManager, } from "@earendil-works/pi-coding-agent";
3
3
  import { mkdir, readFile, writeFile } from "fs/promises";
4
4
  import { dirname, join, resolve } from "path";
5
5
  import { createExecutor } from "../executor.js";
@@ -12,7 +12,7 @@ import { applyMemoryActivityToState, updateMemoryMaintenanceState, } from "../me
12
12
  import { recallRelevantMemory } from "../memory/recall.js";
13
13
  import { buildTaskDigest } from "../memory/task-digest.js";
14
14
  import { getApiKeyForModel } from "../models/api-keys.js";
15
- import { findExactModelReferenceMatch, formatModelReference, resolveInitialModel } from "../models/utils.js";
15
+ import { createModelRegistry, findExactModelReferenceMatch, formatModelReference, resolveInitialModel, } from "../models/utils.js";
16
16
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
17
17
  import { PipiclawSettingsManager } from "../settings.js";
18
18
  import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
@@ -44,12 +44,6 @@ function isFinalOutcome(outcome) {
44
44
  function getFinalOutcomeText(outcome) {
45
45
  return isFinalOutcome(outcome) ? outcome.text : null;
46
46
  }
47
- function createModelRegistry(authStorage, modelsJsonPath) {
48
- const registryClass = ModelRegistry;
49
- return typeof registryClass.create === "function"
50
- ? registryClass.create(authStorage, modelsJsonPath)
51
- : new registryClass(authStorage, modelsJsonPath);
52
- }
53
47
  function asSdkSettingsManager(manager) {
54
48
  return manager;
55
49
  }
@@ -58,8 +52,13 @@ export class ChannelRunner {
58
52
  this.ledger = getUsageLedger();
59
53
  this.currentTools = [];
60
54
  this.firstTurnMemoryBootstrapPending = true;
61
- this.acceptingBusyMessages = false;
62
- this.agentLoopStarted = false;
55
+ /** Mirror of `tools.tasks.enabled` from the last tools-config load (see buildRuntimeTools). */
56
+ this.tasksEnabled = true;
57
+ /** Single owner of turn state; see TurnPhase in types.ts. */
58
+ this.turn = {
59
+ phase: "idle",
60
+ stopRequested: false,
61
+ };
63
62
  /** When the primary model last failed and we switched to the backup. null = on primary. */
64
63
  this.primaryFailedAt = null;
65
64
  // --- Per run ---
@@ -147,11 +146,36 @@ export class ChannelRunner {
147
146
  this.sessionReady = this.initializeSession();
148
147
  }
149
148
  // === Public API ===
149
+ beginTurn(taskText) {
150
+ if (this.turn.phase !== "idle") {
151
+ log.logWarning(`[${this.channelId}] beginTurn while phase=${this.turn.phase}; turns must be serialized`);
152
+ }
153
+ this.turn = { phase: "dispatching", stopRequested: false, taskText };
154
+ }
155
+ endTurn() {
156
+ this.turn = { phase: "idle", stopRequested: false };
157
+ }
158
+ isBusy() {
159
+ return this.turn.phase !== "idle";
160
+ }
161
+ requestStop() {
162
+ if (this.turn.phase !== "idle") {
163
+ this.turn.stopRequested = true;
164
+ }
165
+ }
166
+ getTurnStatus() {
167
+ return { ...this.turn };
168
+ }
150
169
  async run(ctx, store) {
151
170
  const startedAt = Date.now();
152
171
  this.resetRunState(ctx, store);
153
- this.acceptingBusyMessages = true;
154
- this.agentLoopStarted = false;
172
+ // Direct callers (tests) may skip the transport's beginTurn/endTurn wrapper;
173
+ // then run() owns the whole turn itself.
174
+ const implicitTurn = this.turn.phase === "idle";
175
+ if (implicitTurn) {
176
+ this.beginTurn(ctx.message.text);
177
+ }
178
+ this.turn.phase = "preparing";
155
179
  const runQueue = createRunQueue();
156
180
  this.runState.queue = runQueue.queue;
157
181
  let promptSubmitted = false;
@@ -198,8 +222,9 @@ export class ChannelRunner {
198
222
  promptText = `${recall.renderedText}\n\n<user_message>\n${promptText}\n</user_message>`;
199
223
  }
200
224
  }
201
- const taskDigestSettings = this.settingsManager.getTaskDigestSettings();
202
- if (taskDigestSettings.enabled) {
225
+ // Gated by the same master autonomy switch as task_manage and the TaskDriver.
226
+ if (this.tasksEnabled) {
227
+ const taskDigestSettings = this.settingsManager.getTaskDigestSettings();
203
228
  taskDigestText = await buildTaskDigest({
204
229
  channelDir: this.channelDir,
205
230
  maxTasks: taskDigestSettings.maxTasks,
@@ -292,8 +317,7 @@ export class ChannelRunner {
292
317
  log.logWarning(`[${this.channelId}] Runner failed`, this.runState.errorMessage);
293
318
  }
294
319
  finally {
295
- this.acceptingBusyMessages = false;
296
- this.agentLoopStarted = false;
320
+ this.turn.phase = "finishing";
297
321
  if (!promptSubmitted) {
298
322
  const discarded = this.session.clearQueue();
299
323
  const discardedCount = discarded.steering.length + discarded.followUp.length;
@@ -404,6 +428,9 @@ export class ChannelRunner {
404
428
  this.runState.ctx = null;
405
429
  this.runState.logCtx = null;
406
430
  this.runState.queue = null;
431
+ if (implicitTurn) {
432
+ this.endTurn();
433
+ }
407
434
  }
408
435
  return {
409
436
  stopReason: this.runState.stopReason,
@@ -556,13 +583,23 @@ export class ChannelRunner {
556
583
  const timestamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}${offsetSign}${offsetHours}:${offsetMins}`;
557
584
  return `[${timestamp}] [${userName || "unknown"}]: ${text}`;
558
585
  }
559
- async queueBusyMessage(text, userName) {
560
- if (!this.acceptingBusyMessages) {
561
- throw new Error("No task is currently running.");
586
+ /**
587
+ * Single source of truth for the busy-message window: steer is accepted while
588
+ * the prompt is being assembled ("preparing") or while the agent loop is
589
+ * actually streaming. Re-asserted after every await because the turn can end
590
+ * while this call was suspended.
591
+ */
592
+ assertBusyWindowOpen() {
593
+ if (this.turn.phase === "preparing") {
594
+ return;
562
595
  }
563
- if (this.agentLoopStarted && !this.session.isStreaming) {
564
- throw new Error("No task is currently running.");
596
+ if (this.turn.phase === "streaming" && this.session.isStreaming) {
597
+ return;
565
598
  }
599
+ throw new Error("No task is currently running.");
600
+ }
601
+ async queueBusyMessage(text, userName) {
602
+ this.assertBusyWindowOpen();
566
603
  await this.ensureSessionReady();
567
604
  const clippedText = clipUserInput(text, MAX_USER_MESSAGE_CHARS);
568
605
  if (clippedText !== text.trim()) {
@@ -570,16 +607,9 @@ export class ChannelRunner {
570
607
  }
571
608
  const queuedMessage = this.formatUserMessage(clippedText, userName);
572
609
  await this.maybeRunPreventiveCompactionForIncomingText(queuedMessage);
573
- if (!this.acceptingBusyMessages) {
574
- throw new Error("No task is currently running.");
575
- }
576
- if (this.agentLoopStarted && !this.session.isStreaming) {
577
- throw new Error("No task is currently running.");
578
- }
610
+ this.assertBusyWindowOpen();
579
611
  const queueMessage = async () => {
580
- if (this.agentLoopStarted && !this.session.isStreaming) {
581
- throw new Error("No task is currently running.");
582
- }
612
+ this.assertBusyWindowOpen();
583
613
  await this.session.steer(queuedMessage);
584
614
  };
585
615
  await this.sessionResourceGate.runPrompt(queueMessage);
@@ -827,6 +857,7 @@ export class ChannelRunner {
827
857
  const securityLoad = loadSecurityConfigWithDiagnostics(this.appHomeDir);
828
858
  const toolsLoad = loadToolsConfigWithDiagnostics(this.appHomeDir);
829
859
  this.reportConfigDiagnostics([...securityLoad.diagnostics, ...toolsLoad.diagnostics]);
860
+ this.tasksEnabled = toolsLoad.config.tools.tasks.enabled;
830
861
  const tools = createPipiclawTools({
831
862
  executor: this.executor,
832
863
  getCurrentModel: () => this.activeModel,
@@ -869,8 +900,8 @@ export class ChannelRunner {
869
900
  subscribeToSessionEvents() {
870
901
  this.sessionUnsubscribe?.();
871
902
  this.sessionUnsubscribe = this.session.subscribe(async (event) => {
872
- if (isRecord(event) && event.type === "message_start") {
873
- this.agentLoopStarted = true;
903
+ if (isRecord(event) && event.type === "message_start" && this.turn.phase === "preparing") {
904
+ this.turn.phase = "streaming";
874
905
  }
875
906
  if (isRecord(event) && "reason" in event && event.reason === "new") {
876
907
  this.firstTurnMemoryBootstrapPending = true;
@@ -0,0 +1,23 @@
1
+ import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
2
+ import type { PipiclawSettingsManager } from "../settings.js";
3
+ export interface DetachedMaintenanceContextOptions {
4
+ channelId: string;
5
+ channelDir: string;
6
+ workspaceDir: string;
7
+ authConfigPath: string;
8
+ modelsConfigPath: string;
9
+ settingsManager: PipiclawSettingsManager;
10
+ }
11
+ /** Test hook: drop cached transcripts so a fresh read is forced. */
12
+ export declare function clearDetachedMaintenanceCache(): void;
13
+ /**
14
+ * Build a MemoryMaintenanceRuntimeContext for a channel with no live runner,
15
+ * straight from disk. This is deliberately much lighter than a ChannelRunner:
16
+ * no Agent, no AgentSession, no tool set, no sub-agent discovery — just the
17
+ * persisted transcript, the resolved model, and current settings. Channels
18
+ * that spoke this boot keep using their runner's in-memory context instead.
19
+ *
20
+ * Returns null when the channel has no persisted transcript (nothing for the
21
+ * memory pipeline to work with) or the transcript cannot be read.
22
+ */
23
+ export declare function loadDetachedMaintenanceContext(options: DetachedMaintenanceContextOptions): Promise<MemoryMaintenanceRuntimeContext | null>;
@@ -0,0 +1,72 @@
1
+ import { statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { AuthStorage, SessionManager } from "@earendil-works/pi-coding-agent";
4
+ import { getApiKeyForModel } from "../models/api-keys.js";
5
+ import { createModelRegistry, resolveInitialModel } from "../models/utils.js";
6
+ import { loadPipiclawSkills } from "./workspace-resources.js";
7
+ // The maintenance scheduler visits idle channels every tick; re-parsing an
8
+ // unchanged context.jsonl each time would be pure I/O waste for long-dead
9
+ // channels. Keyed by channelDir, replaced whenever the file changes.
10
+ const transcriptCache = new Map();
11
+ /** Test hook: drop cached transcripts so a fresh read is forced. */
12
+ export function clearDetachedMaintenanceCache() {
13
+ transcriptCache.clear();
14
+ }
15
+ /**
16
+ * Build a MemoryMaintenanceRuntimeContext for a channel with no live runner,
17
+ * straight from disk. This is deliberately much lighter than a ChannelRunner:
18
+ * no Agent, no AgentSession, no tool set, no sub-agent discovery — just the
19
+ * persisted transcript, the resolved model, and current settings. Channels
20
+ * that spoke this boot keep using their runner's in-memory context instead.
21
+ *
22
+ * Returns null when the channel has no persisted transcript (nothing for the
23
+ * memory pipeline to work with) or the transcript cannot be read.
24
+ */
25
+ export async function loadDetachedMaintenanceContext(options) {
26
+ const contextFile = join(options.channelDir, "context.jsonl");
27
+ let stats;
28
+ try {
29
+ stats = statSync(contextFile);
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ let cached = transcriptCache.get(options.channelDir);
35
+ if (!cached || cached.mtimeMs !== stats.mtimeMs || cached.size !== stats.size) {
36
+ try {
37
+ const sessionManager = SessionManager.open(contextFile, options.channelDir);
38
+ cached = {
39
+ mtimeMs: stats.mtimeMs,
40
+ size: stats.size,
41
+ messages: sessionManager.buildSessionContext().messages,
42
+ sessionEntries: sessionManager.getBranch(),
43
+ };
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ transcriptCache.set(options.channelDir, cached);
49
+ }
50
+ const authStorage = AuthStorage.create(options.authConfigPath);
51
+ const modelRegistry = createModelRegistry(authStorage, options.modelsConfigPath);
52
+ const model = resolveInitialModel(modelRegistry, options.settingsManager);
53
+ options.settingsManager.reload();
54
+ return {
55
+ channelId: options.channelId,
56
+ channelDir: options.channelDir,
57
+ workspaceDir: options.workspaceDir,
58
+ messages: [...cached.messages],
59
+ sessionEntries: [...cached.sessionEntries],
60
+ model,
61
+ resolveApiKey: async (candidate) => getApiKeyForModel(modelRegistry, candidate),
62
+ settings: {
63
+ sessionMemory: options.settingsManager.getSessionMemorySettings(),
64
+ memoryGrowth: options.settingsManager.getMemoryGrowthSettings(),
65
+ memoryMaintenance: options.settingsManager.getMemoryMaintenanceSettings(),
66
+ },
67
+ loadedSkills: loadPipiclawSkills(options.channelDir).map((skill) => ({
68
+ name: skill.name,
69
+ description: skill.description,
70
+ })),
71
+ };
72
+ }
@@ -1,12 +1,8 @@
1
1
  import type { AgentRunner } from "./types.js";
2
- /** Minimal per-channel run state the status renderer needs. */
3
- export interface StatusRenderState {
4
- running: boolean;
5
- currentTaskText?: string;
6
- runner: Pick<AgentRunner, "getStatusSnapshot">;
7
- }
2
+ /** Run state and snapshot both come from the runner's own turn state machine. */
3
+ export type StatusRenderRunner = Pick<AgentRunner, "getStatusSnapshot" | "isBusy" | "getTurnStatus">;
8
4
  export interface RenderStatusOptions {
9
- state: StatusRenderState | undefined;
5
+ runner: StatusRenderRunner | undefined;
10
6
  version: string;
11
7
  uptimeMs: number;
12
8
  }
@@ -25,19 +25,19 @@ export function formatUptime(ms) {
25
25
  return parts.join(" ");
26
26
  }
27
27
  export function renderStatus(options) {
28
- const { state, version, uptimeMs } = options;
28
+ const { runner, version, uptimeMs } = options;
29
29
  const lines = ["# Status"];
30
- if (state?.running) {
31
- const task = state.currentTaskText?.trim();
30
+ if (runner?.isBusy()) {
31
+ const task = runner.getTurnStatus().taskText?.trim();
32
32
  const preview = task ? `: ${task.length > 80 ? `${task.slice(0, 79)}…` : task}` : "";
33
33
  lines.push(`- Run state: running${preview}`);
34
34
  }
35
35
  else {
36
36
  lines.push("- Run state: idle");
37
37
  }
38
- if (state) {
38
+ if (runner) {
39
39
  try {
40
- const snapshot = state.runner.getStatusSnapshot();
40
+ const snapshot = runner.getStatusSnapshot();
41
41
  lines.push(`- Model: ${snapshot.model}`);
42
42
  if (snapshot.fallback) {
43
43
  const until = new Date(snapshot.fallback.cooldownUntilMs);
@@ -14,6 +14,24 @@ export interface RunnerStatusSnapshot {
14
14
  cooldownUntilMs: number;
15
15
  };
16
16
  }
17
+ /**
18
+ * Phases of a single turn. The runner is the single owner of this state; every
19
+ * other "is this channel busy?" question (transport busy-routing, scheduler
20
+ * idle checks, /status) derives from it instead of keeping a parallel flag.
21
+ *
22
+ * idle → dispatching (beginTurn: transport accepted a message; archive/command
23
+ * routing may still be ahead) → preparing (run() is assembling the prompt;
24
+ * steer is queued into the session) → streaming (agent loop started; steer
25
+ * allowed while the session streams) → finishing (run() epilogue: delivery
26
+ * flush, ledger) → idle (endTurn).
27
+ */
28
+ export type TurnPhase = "idle" | "dispatching" | "preparing" | "streaming" | "finishing";
29
+ export interface TurnStatus {
30
+ phase: TurnPhase;
31
+ stopRequested: boolean;
32
+ /** The message text this turn is processing (set by beginTurn). */
33
+ taskText?: string;
34
+ }
17
35
  export interface AgentRunner {
18
36
  run(ctx: ChannelContext, store: ChannelStore): Promise<{
19
37
  stopReason: string;
@@ -29,6 +47,19 @@ export interface AgentRunner {
29
47
  getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
30
48
  getStatusSnapshot(): RunnerStatusSnapshot;
31
49
  abort(): Promise<void>;
50
+ /**
51
+ * Synchronously reserve the turn for a message. Transports MUST call this in
52
+ * the same tick they dequeue the message, before any await, so a concurrent
53
+ * arrival never observes a stale idle state.
54
+ */
55
+ beginTurn(taskText: string): void;
56
+ /** Release the turn (idempotent). Transports call this after all per-message work. */
57
+ endTurn(): void;
58
+ /** True from beginTurn until endTurn. */
59
+ isBusy(): boolean;
60
+ /** Mark the current turn as user-stopped (no-op when idle). */
61
+ requestStop(): void;
62
+ getTurnStatus(): TurnStatus;
32
63
  }
33
64
  export type FinalOutcome = {
34
65
  kind: "none";
@@ -1,6 +1,8 @@
1
1
  import type { Api, Model } from "@earendil-works/pi-ai";
2
- import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
2
+ import { type AuthStorage, ModelRegistry } from "@earendil-works/pi-coding-agent";
3
3
  import type { PipiclawSettingsManager } from "../settings.js";
4
+ /** SDK-version-tolerant construction: newer SDKs expose a static create(), older ones a constructor. */
5
+ export declare function createModelRegistry(authStorage: AuthStorage, modelsJsonPath: string): ModelRegistry;
4
6
  export declare function formatModelReference(model: Model<Api>): string;
5
7
  export declare function findExactModelReferenceMatch(modelReference: string, availableModels: Model<Api>[]): {
6
8
  match?: Model<Api>;
@@ -1,6 +1,14 @@
1
1
  import { getBuiltinModel as getModel } from "@earendil-works/pi-ai/providers/all";
2
+ import { ModelRegistry } from "@earendil-works/pi-coding-agent";
2
3
  // Default model - will be overridden by ModelRegistry if custom models are configured
3
4
  const defaultModel = getModel("anthropic", "claude-sonnet-4-5");
5
+ /** SDK-version-tolerant construction: newer SDKs expose a static create(), older ones a constructor. */
6
+ export function createModelRegistry(authStorage, modelsJsonPath) {
7
+ const registryClass = ModelRegistry;
8
+ return typeof registryClass.create === "function"
9
+ ? registryClass.create(authStorage, modelsJsonPath)
10
+ : new registryClass(authStorage, modelsJsonPath);
11
+ }
4
12
  export function formatModelReference(model) {
5
13
  return `${model.provider}/${model.id}`;
6
14
  }
@@ -0,0 +1,9 @@
1
+ export interface RuntimePlaybookMetadata {
2
+ name: string;
3
+ description: string;
4
+ filename: string;
5
+ path: string;
6
+ }
7
+ /** Load the small always-on catalog; playbook bodies remain on disk until the agent reads one. */
8
+ export declare function loadRuntimePlaybookCatalog(directory?: string): RuntimePlaybookMetadata[];
9
+ export declare function renderRuntimePlaybookIndex(directory?: string): string;
@@ -0,0 +1,44 @@
1
+ import { readdirSync, readFileSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ import { PLAYBOOKS_DIR } from "../paths.js";
4
+ function parseFrontmatter(content, filename) {
5
+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(content);
6
+ if (!match)
7
+ throw new Error(`Runtime playbook ${filename} has no YAML frontmatter.`);
8
+ const fields = new Map();
9
+ for (const line of match[1]?.split(/\r?\n/) ?? []) {
10
+ const separator = line.indexOf(":");
11
+ if (separator < 0)
12
+ continue;
13
+ const key = line.slice(0, separator).trim();
14
+ let value = line.slice(separator + 1).trim();
15
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
16
+ value = value.slice(1, -1);
17
+ }
18
+ fields.set(key, value);
19
+ }
20
+ const name = fields.get("name")?.trim();
21
+ const description = fields.get("description")?.trim();
22
+ if (!name || !description) {
23
+ throw new Error(`Runtime playbook ${filename} requires non-empty name and description metadata.`);
24
+ }
25
+ if (`${name}.md` !== filename) {
26
+ throw new Error(`Runtime playbook ${filename} metadata name must be "${basename(filename, ".md")}".`);
27
+ }
28
+ return { name, description };
29
+ }
30
+ /** Load the small always-on catalog; playbook bodies remain on disk until the agent reads one. */
31
+ export function loadRuntimePlaybookCatalog(directory = PLAYBOOKS_DIR) {
32
+ return readdirSync(directory)
33
+ .filter((filename) => filename.endsWith(".md"))
34
+ .sort()
35
+ .map((filename) => {
36
+ const path = join(directory, filename);
37
+ return { ...parseFrontmatter(readFileSync(path, "utf-8"), filename), filename, path };
38
+ });
39
+ }
40
+ export function renderRuntimePlaybookIndex(directory = PLAYBOOKS_DIR) {
41
+ return loadRuntimePlaybookCatalog(directory)
42
+ .map((playbook) => `- ${playbook.filename} — ${playbook.description}`)
43
+ .join("\n");
44
+ }