@oyasmi/pipiclaw 0.8.9 → 0.8.10-beta.2

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 (75) hide show
  1. package/README.md +3 -3
  2. package/dist/agent/channel-runner.d.ts +1 -0
  3. package/dist/agent/channel-runner.js +6 -10
  4. package/dist/agent/maintenance-context.d.ts +0 -1
  5. package/dist/agent/maintenance-context.js +0 -7
  6. package/dist/agent/session-events.d.ts +1 -0
  7. package/dist/agent/session-events.js +10 -0
  8. package/dist/agent/types.d.ts +7 -0
  9. package/dist/agent/types.js +2 -0
  10. package/dist/index.d.ts +16 -34
  11. package/dist/index.js +14 -32
  12. package/dist/memory/consolidation.js +0 -1
  13. package/dist/memory/extraction.d.ts +1 -7
  14. package/dist/memory/extraction.js +2 -46
  15. package/dist/memory/lifecycle.js +3 -3
  16. package/dist/memory/maintenance-gates.d.ts +4 -16
  17. package/dist/memory/maintenance-gates.js +11 -51
  18. package/dist/memory/maintenance-jobs.d.ts +3 -14
  19. package/dist/memory/maintenance-jobs.js +12 -103
  20. package/dist/memory/maintenance-state.d.ts +2 -6
  21. package/dist/memory/maintenance-state.js +14 -10
  22. package/dist/memory/maintenance-tuning.d.ts +37 -0
  23. package/dist/memory/maintenance-tuning.js +46 -0
  24. package/dist/memory/promotion.d.ts +0 -22
  25. package/dist/memory/promotion.js +1 -8
  26. package/dist/memory/review-log.d.ts +1 -1
  27. package/dist/memory/scheduler.d.ts +1 -9
  28. package/dist/memory/scheduler.js +3 -15
  29. package/dist/memory/source-window.d.ts +2 -2
  30. package/dist/memory/task-digest.js +2 -5
  31. package/dist/models/utils.d.ts +5 -0
  32. package/dist/models/utils.js +10 -0
  33. package/dist/paths.d.ts +0 -1
  34. package/dist/paths.js +0 -1
  35. package/dist/playbooks/task-closeout.md +2 -0
  36. package/dist/playbooks/task-delegation.md +8 -14
  37. package/dist/playbooks/task-driving.md +3 -4
  38. package/dist/playbooks/task-planning.md +8 -9
  39. package/dist/runtime/bootstrap.d.ts +14 -0
  40. package/dist/runtime/bootstrap.js +9 -4
  41. package/dist/runtime/task-commands.js +46 -73
  42. package/dist/runtime/task-driver.js +6 -23
  43. package/dist/settings.d.ts +39 -40
  44. package/dist/settings.js +87 -107
  45. package/dist/shared/task-ledger.d.ts +19 -2
  46. package/dist/shared/task-ledger.js +194 -5
  47. package/dist/subagents/discovery.d.ts +41 -7
  48. package/dist/subagents/discovery.js +74 -24
  49. package/dist/subagents/tool.d.ts +3 -12
  50. package/dist/subagents/tool.js +11 -115
  51. package/dist/tasks/control.d.ts +57 -27
  52. package/dist/tasks/control.js +94 -93
  53. package/dist/tasks/store.d.ts +1 -4
  54. package/dist/tasks/store.js +1 -39
  55. package/dist/tasks/transitions.d.ts +1 -1
  56. package/dist/tasks/transitions.js +1 -0
  57. package/dist/tasks/verification.d.ts +10 -6
  58. package/dist/tasks/verification.js +0 -6
  59. package/dist/tools/memory-manage.js +46 -24
  60. package/dist/tools/task-manage/create.js +1 -2
  61. package/dist/tools/task-manage/lifecycle.d.ts +7 -0
  62. package/dist/tools/task-manage/lifecycle.js +52 -32
  63. package/dist/tools/task-manage/schema.d.ts +2 -9
  64. package/dist/tools/task-manage/schema.js +9 -19
  65. package/dist/tools/task-manage/shared.d.ts +0 -2
  66. package/dist/tools/task-manage/shared.js +8 -69
  67. package/dist/tools/task-manage/types.d.ts +1 -1
  68. package/dist/tools/task-manage/verification.js +5 -6
  69. package/dist/tools/task-manage.js +4 -2
  70. package/examples/sub-agents/README.md +1 -1
  71. package/package.json +3 -1
  72. package/dist/memory/post-turn-review.d.ts +0 -43
  73. package/dist/memory/post-turn-review.js +0 -136
  74. package/dist/memory/promotion-signals.d.ts +0 -5
  75. package/dist/memory/promotion-signals.js +0 -33
package/README.md CHANGED
@@ -16,7 +16,7 @@ npm package: [`@oyasmi/pipiclaw`](https://www.npmjs.com/package/@oyasmi/pipiclaw
16
16
 
17
17
  **自己推进长程工作。** 定时事件支持立即、单次、周期三类,`preAction` 可用脚本做零 token 的触发前门控。语义更高一层的是任务台账(task ledger):任务以 Markdown 文件持久存在,内建 task driver 到点自动恢复、有进展有界续跑、停滞自动退避;配套受预算约束的恢复、独立验收、外部副作用授权,以及 `/tasks` 系列零 LLM 成本的控制面命令。
18
18
 
19
- **会用工具、能委派。** 内建 `bash`(支持 `async` 后台作业)、`read`(含目录树与 PDF)、`write` / `edit`、结构化 `grep`、`web_search` / `web_fetch`(结果缓存与分页续读),以及 `send_media`——生成好的报表、截图、导出文件可以作为原生附件直接发回钉钉,而不是丢给你一个打不开的主机路径。工作区配置的子代理可以把 reviewer、researcher 这类角色沉淀成可复用能力,支持 worktree 隔离与独立验收(verify);workspace skills 沉淀你自己的流程知识。完整清单见 [docs/tools.md](./docs/tools.md)。
19
+ **会用工具、能委派。** 内建 `bash`(支持 `async` 后台作业)、`read`(含目录树与 PDF)、`write` / `edit`、结构化 `grep`、`web_search` / `web_fetch`(结果缓存与分页续读),以及 `send_media`——生成好的报表、截图、导出文件可以作为原生附件直接发回钉钉,而不是丢给你一个打不开的主机路径。工作区配置的子代理可以把 reviewer、researcher 这类角色沉淀成可复用能力,支持独立验收(verify);workspace skills 沉淀你自己的流程知识。完整清单见 [docs/tools.md](./docs/tools.md)。
20
20
 
21
21
  **有安全护栏。** 所有文件、命令、网络工具都经过安全守卫:`bash` 命令拦截、统一路径检查、常见凭据与敏感位置默认拒绝、阻断写入审计日志;可通过 `security.json` 做实例级策略调整。详见 [docs/security.md](./docs/security.md)。
22
22
 
@@ -55,7 +55,7 @@ pipiclaw
55
55
  ├── channel.json # 钉钉应用配置
56
56
  ├── auth.json # 模型凭据
57
57
  ├── models.json # 自定义模型提供方
58
- ├── settings.json # 默认模型与运行时设置
58
+ ├── settings.json # 默认模型与模块开关
59
59
  ├── tools.json # 内建工具配置
60
60
  ├── security.json # 工具层安全策略
61
61
  └── workspace/ # 长期工作区:SOUL.md、AGENTS.md、MEMORY.md、
@@ -244,7 +244,7 @@ pipiclaw
244
244
  | [docs/memory.md](./docs/memory.md) | 记忆分层:它记得什么、怎么让它记住或忘掉 |
245
245
  | [docs/configuration.md](./docs/configuration.md) | 全部配置项:钉钉、模型、settings、tools、TUI、记忆与工作区文件 |
246
246
  | [docs/events-and-tasks.md](./docs/events-and-tasks.md) | 定时事件(含 `preAction` 门控、`event_manage`)、任务台账、内建 task driver、`/tasks` 控制面与 `task_manage` 工具 |
247
- | [docs/sub-agents.md](./docs/sub-agents.md) | 工作区配置子代理:委派、隔离 worktree 与独立验收 |
247
+ | [docs/sub-agents.md](./docs/sub-agents.md) | 工作区配置子代理:委派与独立验收 |
248
248
  | [docs/security.md](./docs/security.md) | 默认安全策略、`security.json` 配置与已知边界 |
249
249
  | [docs/deployment-and-operations.md](./docs/deployment-and-operations.md) | 长期运行、日志、可观测性、升级、备份与排障 |
250
250
  | [docs/scaling-and-concurrency.md](./docs/scaling-and-concurrency.md) | 并发模型与容量边界 |
@@ -57,6 +57,7 @@ export declare class ChannelRunner implements AgentRunner {
57
57
  stopReason: string;
58
58
  errorMessage?: string;
59
59
  usage: UsageTotals;
60
+ costKnown: boolean;
60
61
  durationMs: number;
61
62
  silent: boolean;
62
63
  }>;
@@ -14,7 +14,7 @@ import { applyMemoryActivityToState, updateMemoryMaintenanceState, } from "../me
14
14
  import { MEMORY_RECALL_MAX_UNITS, recallRelevantMemory } from "../memory/recall.js";
15
15
  import { buildTaskDigest, TASK_AGENDA_MAX_UNITS } from "../memory/task-digest.js";
16
16
  import { getApiKeyForModel } from "../models/api-keys.js";
17
- import { createModelRuntime, defaultModel, findExactModelReferenceMatch, formatModelReference, resolveInitialModel, wrapModelRegistry, } from "../models/utils.js";
17
+ import { createModelRuntime, defaultModel, findExactModelReferenceMatch, formatModelReference, hasKnownModelPricing, resolveInitialModel, wrapModelRegistry, } from "../models/utils.js";
18
18
  import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks/catalog.js";
19
19
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
20
20
  import { PipiclawSettingsManager } from "../settings.js";
@@ -451,6 +451,7 @@ export class ChannelRunner {
451
451
  stopReason: this.runState.stopReason,
452
452
  errorMessage: this.runState.errorMessage,
453
453
  usage: { ...this.runState.totalUsage, cost: { ...this.runState.totalUsage.cost } },
454
+ costKnown: this.runState.usageSources > 0 && this.runState.costKnown,
454
455
  durationMs: Date.now() - startedAt,
455
456
  silent: this.runState.finalOutcome.kind === "silent",
456
457
  };
@@ -519,23 +520,14 @@ export class ChannelRunner {
519
520
  return {
520
521
  channelId: this.channelId,
521
522
  channelDir: this.channelDir,
522
- workspaceDir: this.workspaceDir,
523
523
  messages: [...this.session.messages],
524
524
  sessionEntries: [...this.sessionManager.getBranch()],
525
525
  model: this.session.model ?? this.activeModel,
526
526
  resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
527
527
  settings: {
528
528
  sessionMemory: this.settingsManager.getSessionMemorySettings(),
529
- memoryGrowth: this.settingsManager.getMemoryGrowthSettings(),
530
529
  memoryMaintenance: this.settingsManager.getMemoryMaintenanceSettings(),
531
530
  },
532
- loadedSkills: this.currentSkills.skills.map((skill) => ({
533
- name: skill.name,
534
- description: skill.description,
535
- })),
536
- refreshWorkspaceResources: async () => {
537
- await this.refreshSessionResources();
538
- },
539
531
  };
540
532
  }
541
533
  getStatusSnapshot() {
@@ -1082,6 +1074,10 @@ export class ChannelRunner {
1082
1074
  runState: this.runState,
1083
1075
  memoryLifecycle: this.memoryLifecycle,
1084
1076
  ledger: this.ledger,
1077
+ isModelCostKnown: (reference) => {
1078
+ const model = findExactModelReferenceMatch(reference, this.modelRegistry.getAvailable()).match;
1079
+ return model ? hasKnownModelPricing(model) : false;
1080
+ },
1085
1081
  refreshSessionResources: async () => {
1086
1082
  await this.refreshSessionResources();
1087
1083
  },
@@ -3,7 +3,6 @@ import type { PipiclawSettingsManager } from "../settings.js";
3
3
  export interface DetachedMaintenanceContextOptions {
4
4
  channelId: string;
5
5
  channelDir: string;
6
- workspaceDir: string;
7
6
  authConfigPath: string;
8
7
  modelsConfigPath: string;
9
8
  settingsManager: PipiclawSettingsManager;
@@ -3,7 +3,6 @@ import { join } from "node:path";
3
3
  import { SessionManager } from "@earendil-works/pi-coding-agent";
4
4
  import { getApiKeyForModel } from "../models/api-keys.js";
5
5
  import { createModelRuntime, resolveInitialModel, wrapModelRegistry } from "../models/utils.js";
6
- import { loadPipiclawSkills } from "./workspace-resources.js";
7
6
  // The maintenance scheduler visits idle channels every tick; re-parsing an
8
7
  // unchanged context.jsonl each time would be pure I/O waste for long-dead
9
8
  // channels. Keyed by channelDir, replaced whenever the file changes.
@@ -57,19 +56,13 @@ export async function loadDetachedMaintenanceContext(options) {
57
56
  return {
58
57
  channelId: options.channelId,
59
58
  channelDir: options.channelDir,
60
- workspaceDir: options.workspaceDir,
61
59
  messages: [...cached.messages],
62
60
  sessionEntries: [...cached.sessionEntries],
63
61
  model,
64
62
  resolveApiKey: async (candidate) => getApiKeyForModel(modelRegistry, candidate),
65
63
  settings: {
66
64
  sessionMemory: options.settingsManager.getSessionMemorySettings(),
67
- memoryGrowth: options.settingsManager.getMemoryGrowthSettings(),
68
65
  memoryMaintenance: options.settingsManager.getMemoryMaintenanceSettings(),
69
66
  },
70
- loadedSkills: loadPipiclawSkills(options.channelDir).skills.map((skill) => ({
71
- name: skill.name,
72
- description: skill.description,
73
- })),
74
67
  };
75
68
  }
@@ -12,6 +12,7 @@ export interface SessionEventHandlerContext {
12
12
  runState: RunState;
13
13
  memoryLifecycle: MemoryLifecycle;
14
14
  ledger: UsageLedger;
15
+ isModelCostKnown?: (modelReference: string) => boolean;
15
16
  refreshSessionResources?: () => Promise<void>;
16
17
  }
17
18
  export declare function handleSessionEvent(event: unknown, context: SessionEventHandlerContext): Promise<void>;
@@ -82,6 +82,9 @@ export async function handleSessionEvent(event, context) {
82
82
  : null;
83
83
  if (subAgentDetails) {
84
84
  mergeSubAgentUsage(runState.totalUsage, subAgentDetails);
85
+ runState.usageSources++;
86
+ runState.costKnown &&=
87
+ subAgentDetails.usage.cost.total > 0 || (context.isModelCostKnown?.(subAgentDetails.model) ?? false);
85
88
  const label = pending?.args &&
86
89
  typeof pending.args === "object" &&
87
90
  "label" in pending.args &&
@@ -193,6 +196,13 @@ export async function handleSessionEvent(event, context) {
193
196
  }
194
197
  if (assistantMsg.usage) {
195
198
  mergeAssistantUsage(runState, assistantMsg.usage);
199
+ runState.usageSources++;
200
+ const modelReference = assistantMsg.provider && assistantMsg.model
201
+ ? `${assistantMsg.provider}/${assistantMsg.model}`
202
+ : assistantMsg.model;
203
+ runState.costKnown &&=
204
+ assistantMsg.usage.cost.total > 0 ||
205
+ (modelReference ? (context.isModelCostKnown?.(modelReference) ?? false) : false);
196
206
  }
197
207
  const thinkingParts = [];
198
208
  const textParts = [];
@@ -37,6 +37,8 @@ export interface AgentRunner {
37
37
  stopReason: string;
38
38
  errorMessage?: string;
39
39
  usage?: UsageTotals;
40
+ /** False when any model used by the turn omitted pricing metadata. */
41
+ costKnown?: boolean;
40
42
  durationMs?: number;
41
43
  silent?: boolean;
42
44
  }>;
@@ -94,6 +96,9 @@ export interface RunState {
94
96
  totalUsage: UsageTotals;
95
97
  /** Main-loop assistant usage only (excludes sub-agents). Feeds the turn ledger entry. */
96
98
  assistantUsage: UsageTotals;
99
+ /** True only while every observed assistant/sub-agent usage source has known model pricing. */
100
+ costKnown: boolean;
101
+ usageSources: number;
97
102
  stopReason: string;
98
103
  errorMessage: string | undefined;
99
104
  lastCompactionError: string | undefined;
@@ -131,6 +136,8 @@ export type AssistantContentPart = {
131
136
  export interface AssistantEventMessage {
132
137
  role: "assistant";
133
138
  content: AssistantContentPart[];
139
+ provider?: string;
140
+ model?: string;
134
141
  stopReason?: string;
135
142
  errorMessage?: string;
136
143
  usage?: AssistantUsage;
@@ -21,6 +21,8 @@ export function createEmptyRunState() {
21
21
  total: 0,
22
22
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
23
23
  },
24
+ costKnown: true,
25
+ usageSources: 0,
24
26
  stopReason: "stop",
25
27
  errorMessage: undefined,
26
28
  lastCompactionError: undefined,
package/dist/index.d.ts CHANGED
@@ -1,34 +1,16 @@
1
- export { COMMAND_RESULT_CUSTOM_TYPE, createCommandExtension, type PipiclawCommandExtensionOptions, } from "./agent/command-extension.js";
2
- export { type BuiltInCommand, type BuiltInCommandName, parseBuiltInCommand, renderBuiltInHelp, } from "./agent/commands.js";
3
- export { type AgentRunner, getOrCreateRunner } from "./agent/index.js";
4
- export { buildPipiclawSystemPrompt, RUNTIME_PROMPT_HARD_UNITS, RUNTIME_PROMPT_TARGET_UNITS, RUNTIME_PROMPT_VERSION, } from "./agent/prompt/builder.js";
5
- export { createPromptBoundaryExtension } from "./agent/prompt/extension.js";
6
- export { buildPromptManifest, type PromptManifest, renderContextReport } from "./agent/prompt/manifest.js";
7
- export { loadWorkspacePromptResources, type WorkspacePromptResources } from "./agent/prompt/resources.js";
8
- export { MAIN_PROMPT_SECTIONS } from "./agent/prompt/sections.js";
9
- export type { PromptAuthority, PromptBuildContext, PromptBuildResult, PromptCacheClass, PromptMode, PromptSectionDefinition, ResolvedPromptSection, ToolDescriptor, } from "./agent/prompt/types.js";
10
- export { loadPipiclawSkills, type PipiclawSkillsResult, resolvePipiclawSkills, } from "./agent/workspace-resources.js";
11
- export { createExecutor, type ExecOptions, type ExecResult, type Executor } from "./executor.js";
12
- export { type BuildMemoryCandidatesOptions, buildMemoryCandidates, createMemoryCandidateStore, type MemoryCandidate, type MemoryCandidateStore, } from "./memory/candidates.js";
13
- export { type ConsolidationRunOptions, type InlineConsolidationResult, runInlineConsolidation, } from "./memory/consolidation.js";
14
- export { ensureChannelMemoryFiles, ensureChannelMemoryFilesSync, getChannelSessionPath, readChannelSession, rewriteChannelSession, } from "./memory/files.js";
15
- export { type ConsolidationReason, MemoryLifecycle, type MemoryLifecycleOptions } from "./memory/lifecycle.js";
16
- export { type RecalledMemory, type RecallRequest, type RecallResult, recallRelevantMemory, } from "./memory/recall.js";
17
- export { renderSessionMemory, type SessionMemoryState, type SessionMemoryUpdateOptions, updateChannelSessionMemory, } from "./memory/session.js";
18
- export { runSidecarTask, type SidecarResult, type SidecarTask, } from "./memory/sidecar-worker.js";
19
- export { getApiKeyForModel } from "./models/api-keys.js";
20
- export { findExactModelReferenceMatch, findModelReferenceMatch, formatModelList, formatModelReference, resolveInitialModel, } from "./models/utils.js";
21
- export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, SUB_AGENTS_DIR, SUB_AGENTS_DIR_NAME, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
22
- export type { ChannelContext, ChannelContext as DingTalkContext, FinalDelivery, ProgressStyle, } from "./runtime/channel-context.js";
23
- export { ensureChannelDir, getChannelDir, getChannelDirName, } from "./runtime/channel-paths.js";
24
- export { createDingTalkContext } from "./runtime/delivery.js";
25
- export { type BusyMessageDefaultConfig, type BusyMessageMode, DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler, finalDeliveryOf, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, progressStyleOf, type ResponseMode, } from "./runtime/dingtalk.js";
26
- export { createEventsWatcher, type EventAction, EventsWatcher, type OneShotEvent, type PeriodicEvent, type ScheduledEvent, } from "./runtime/events.js";
27
- export { ChannelStore, type LoggedMessage, type LoggedSubAgentRun } from "./runtime/store.js";
28
- export { type PipiclawMemoryGrowthSettings, type PipiclawMemoryMaintenanceSettings, type PipiclawMemoryRecallSettings, type PipiclawSessionMemorySettings, type PipiclawSettings, PipiclawSettingsManager, } from "./settings.js";
29
- export { discoverSubAgents, formatSubAgentList, getSubAgentsDir, type ResolvedSubAgentConfig, resolveSubAgentConfig, type SubAgentConfig, type SubAgentContextMode, type SubAgentDiscoveryResult, type SubAgentInvocationOverrides, type SubAgentMemoryMode, type SubAgentToolName, } from "./subagents/discovery.js";
30
- export { createSubAgentTool, type SubAgentToolDetails, type SubAgentToolOptions, } from "./subagents/tool.js";
31
- export { DEFAULT_TOOLS_CONFIG, getToolsConfigPath, loadToolsConfig, type PipiclawToolsConfig, type PipiclawWebFetchConfig, type PipiclawWebSearchConfig, type PipiclawWebToolsConfig, } from "./tools/config.js";
32
- export { type CreatePipiclawToolsOptions, createPipiclawTools, } from "./tools/index.js";
33
- export { createUsageLedger, getUsageLedger, type UsageKind, type UsageLedger, type UsageLedgerEntry, type UsageSummary, } from "./usage/ledger.js";
34
- export { parseUsageMode, renderUsageReport, type UsageQueryMode, usageWindows } from "./usage/render.js";
1
+ /**
2
+ * Public API surface (spec 035 D4).
3
+ *
4
+ * Pipiclaw's product is the CLI/runtime, not an SDK. This barrel therefore
5
+ * supports exactly one use case — embedding the daemon in another process — and
6
+ * nothing else is a compatibility promise. Everything else is internal: import
7
+ * it from its module and expect it to move.
8
+ *
9
+ * Keep this list small. Every name added here also becomes a knip blind spot,
10
+ * because `src/index.ts` is a knip entry point.
11
+ */
12
+ export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
13
+ export { type AppContext, type BootstrapOptions, type BootstrapPaths, type BootstrapResult, bootstrap, isBootstrapExitError, } from "./runtime/bootstrap.js";
14
+ export type { ChannelContext, FinalDelivery, ProgressStyle } from "./runtime/channel-context.js";
15
+ export { DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler, type ResponseMode, } from "./runtime/dingtalk.js";
16
+ export type { PipiclawSettings } from "./settings.js";
package/dist/index.js CHANGED
@@ -1,32 +1,14 @@
1
- export { COMMAND_RESULT_CUSTOM_TYPE, createCommandExtension, } from "./agent/command-extension.js";
2
- export { parseBuiltInCommand, renderBuiltInHelp, } from "./agent/commands.js";
3
- export { getOrCreateRunner } from "./agent/index.js";
4
- export { buildPipiclawSystemPrompt, RUNTIME_PROMPT_HARD_UNITS, RUNTIME_PROMPT_TARGET_UNITS, RUNTIME_PROMPT_VERSION, } from "./agent/prompt/builder.js";
5
- export { createPromptBoundaryExtension } from "./agent/prompt/extension.js";
6
- export { buildPromptManifest, renderContextReport } from "./agent/prompt/manifest.js";
7
- export { loadWorkspacePromptResources } from "./agent/prompt/resources.js";
8
- export { MAIN_PROMPT_SECTIONS } from "./agent/prompt/sections.js";
9
- export { loadPipiclawSkills, resolvePipiclawSkills, } from "./agent/workspace-resources.js";
10
- export { createExecutor } from "./executor.js";
11
- export { buildMemoryCandidates, createMemoryCandidateStore, } from "./memory/candidates.js";
12
- export { runInlineConsolidation, } from "./memory/consolidation.js";
13
- export { ensureChannelMemoryFiles, ensureChannelMemoryFilesSync, getChannelSessionPath, readChannelSession, rewriteChannelSession, } from "./memory/files.js";
14
- export { MemoryLifecycle } from "./memory/lifecycle.js";
15
- export { recallRelevantMemory, } from "./memory/recall.js";
16
- export { renderSessionMemory, updateChannelSessionMemory, } from "./memory/session.js";
17
- export { runSidecarTask, } from "./memory/sidecar-worker.js";
18
- export { getApiKeyForModel } from "./models/api-keys.js";
19
- export { findExactModelReferenceMatch, findModelReferenceMatch, formatModelList, formatModelReference, resolveInitialModel, } from "./models/utils.js";
20
- export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, SUB_AGENTS_DIR, SUB_AGENTS_DIR_NAME, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
21
- export { ensureChannelDir, getChannelDir, getChannelDirName, } from "./runtime/channel-paths.js";
22
- export { createDingTalkContext } from "./runtime/delivery.js";
23
- export { DingTalkBot, finalDeliveryOf, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, progressStyleOf, } from "./runtime/dingtalk.js";
24
- export { createEventsWatcher, EventsWatcher, } from "./runtime/events.js";
25
- export { ChannelStore } from "./runtime/store.js";
26
- export { PipiclawSettingsManager, } from "./settings.js";
27
- export { discoverSubAgents, formatSubAgentList, getSubAgentsDir, resolveSubAgentConfig, } from "./subagents/discovery.js";
28
- export { createSubAgentTool, } from "./subagents/tool.js";
29
- export { DEFAULT_TOOLS_CONFIG, getToolsConfigPath, loadToolsConfig, } from "./tools/config.js";
30
- export { createPipiclawTools, } from "./tools/index.js";
31
- export { createUsageLedger, getUsageLedger, } from "./usage/ledger.js";
32
- export { parseUsageMode, renderUsageReport, usageWindows } from "./usage/render.js";
1
+ /**
2
+ * Public API surface (spec 035 D4).
3
+ *
4
+ * Pipiclaw's product is the CLI/runtime, not an SDK. This barrel therefore
5
+ * supports exactly one use case — embedding the daemon in another process — and
6
+ * nothing else is a compatibility promise. Everything else is internal: import
7
+ * it from its module and expect it to move.
8
+ *
9
+ * Keep this list small. Every name added here also becomes a knip blind spot,
10
+ * because `src/index.ts` is a knip entry point.
11
+ */
12
+ export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
13
+ export { bootstrap, isBootstrapExitError, } from "./runtime/bootstrap.js";
14
+ export { DingTalkBot, } from "./runtime/dingtalk.js";
@@ -143,7 +143,6 @@ export async function runInlineConsolidation(options) {
143
143
  transcriptMaxChars: INLINE_TRANSCRIPT_MAX_CHARS,
144
144
  // Idle passes never write HISTORY.md; only real boundaries summarize the chunk.
145
145
  includeHistoryBlock: mode === "boundary",
146
- includeSkills: false,
147
146
  usageContext: usageContextFor(options.channelId, correlationId),
148
147
  });
149
148
  const timestamp = new Date().toISOString();
@@ -2,15 +2,13 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import { type MemoryOp } from "./files.js";
4
4
  import type { MemoryEntryKind } from "./metadata.js";
5
- import type { MemoryPromotionCandidate, SkillPromotionCandidate } from "./promotion.js";
5
+ import type { MemoryPromotionCandidate } from "./promotion.js";
6
6
  export interface MemoryExtractionPromptOptions {
7
7
  includeHistoryBlock: boolean;
8
- includeSkills: boolean;
9
8
  }
10
9
  export declare function buildMemoryExtractionSystemPrompt(options: MemoryExtractionPromptOptions): string;
11
10
  export interface MemoryExtractionResult {
12
11
  memoryOps: MemoryPromotionCandidate[];
13
- skillCandidates: SkillPromotionCandidate[];
14
12
  historyBlock: string;
15
13
  discarded: Array<{
16
14
  content: string;
@@ -33,10 +31,6 @@ export interface MemoryExtractionRequest extends MemoryExtractionPromptOptions {
33
31
  resolveApiKey: (model: Model<Api>) => Promise<string>;
34
32
  timeoutMs: number;
35
33
  transcriptMaxChars: number;
36
- loadedSkills?: Array<{
37
- name: string;
38
- description?: string;
39
- }>;
40
34
  usageContext?: {
41
35
  channelId: string;
42
36
  correlationId?: string;
@@ -13,7 +13,7 @@ import { sanitizeMessagesForMemory } from "./transcript.js";
13
13
  * applied no confidence gate at all, the standard for MEMORY.md was set by whichever
14
14
  * writer happened to fire. They now share this prompt, this schema, and (via
15
15
  * `shouldAutoWriteMemory`) one bar. Callers still own their own side effects: only
16
- * boundaries write HISTORY.md, only the growth review proposes skills.
16
+ * boundaries write HISTORY.md.
17
17
  */
18
18
  const MEMORY_OPS_RULES = `- memoryOps entries operate on the durable channel MEMORY.md:
19
19
  - {"op":"add","content":"...","kind":"fact|preference|decision|constraint|open-loop|lesson"} for a genuinely new durable fact.
@@ -30,10 +30,6 @@ const MEMORY_OPS_RULES = `- memoryOps entries operate on the durable channel MEM
30
30
  const HISTORY_BLOCK_RULES = `- historyBlock: concise Markdown summarizing the conversation chunk for later recovery.
31
31
  - For any conversation that contains at least one meaningful user request and one meaningful assistant reply, return a non-empty historyBlock with at least one bullet.
32
32
  - Prefer short bullets and short paragraphs. historyBlock is not gated by confidence, so it is the safe place for context that is real but not durable.`;
33
- const SKILL_RULES = `- Workspace skills are procedural memory: reusable workflows, checklists, playbooks, templates, or scripts.
34
- - Propose skill writes only when the workflow is clearly reusable across future tasks.
35
- - Use action=create only for new self-contained skills with YAML frontmatter and a non-empty body.
36
- - Skill names must be lowercase kebab-case.`;
37
33
  export function buildMemoryExtractionSystemPrompt(options) {
38
34
  const schemaFields = [
39
35
  ` "memoryOps": [{"op": "add|supersede|invalidate", "targetId": "required for supersede/invalidate", "content": "standalone durable memory bullet without '-'", "kind": "fact|preference|decision|constraint|open-loop|lesson", "confidence": 0.0, "necessity": "low|medium|high", "reason": "why it should or should not be stored"}]`,
@@ -41,9 +37,6 @@ export function buildMemoryExtractionSystemPrompt(options) {
41
37
  if (options.includeHistoryBlock) {
42
38
  schemaFields.push(` "historyBlock": "string"`);
43
39
  }
44
- if (options.includeSkills) {
45
- schemaFields.push(` "skillCandidates": [{"action": "create|patch|write_file", "name": "skill-name", "content": "full SKILL.md or supporting file content", "filePath": "optional supporting file path", "find": "exact patch find text", "replace": "exact patch replacement text", "confidence": 0.0, "necessity": "low|medium|high", "reason": "why this procedural memory matters"}]`);
46
- }
47
40
  schemaFields.push(` "discarded": [{"content": "string", "reason": "string"}]`);
48
41
  return [
49
42
  "You are Pipiclaw's durable memory extraction worker.",
@@ -58,7 +51,6 @@ export function buildMemoryExtractionSystemPrompt(options) {
58
51
  "Rules:",
59
52
  MEMORY_OPS_RULES,
60
53
  ...(options.includeHistoryBlock ? [HISTORY_BLOCK_RULES] : []),
61
- ...(options.includeSkills ? [SKILL_RULES] : []),
62
54
  ].join("\n");
63
55
  }
64
56
  function normalizeConfidence(value) {
@@ -102,30 +94,6 @@ function normalizeMemoryCandidate(value) {
102
94
  reason: typeof value.reason === "string" ? value.reason.trim() : "",
103
95
  };
104
96
  }
105
- function normalizeSkillCandidate(value) {
106
- if (!isRecord(value)) {
107
- return null;
108
- }
109
- const action = value.action;
110
- if (action !== "create" && action !== "patch" && action !== "write_file") {
111
- return null;
112
- }
113
- const name = typeof value.name === "string" ? value.name.trim() : "";
114
- if (!name) {
115
- return null;
116
- }
117
- return {
118
- action,
119
- name,
120
- content: typeof value.content === "string" ? value.content : undefined,
121
- filePath: typeof value.filePath === "string" ? value.filePath : undefined,
122
- find: typeof value.find === "string" ? value.find : undefined,
123
- replace: typeof value.replace === "string" ? value.replace : undefined,
124
- confidence: normalizeConfidence(value.confidence),
125
- necessity: normalizeNecessity(value.necessity),
126
- reason: typeof value.reason === "string" ? value.reason.trim() : "",
127
- };
128
- }
129
97
  export function parseMemoryExtractionResult(value) {
130
98
  const record = isRecord(value) ? value : {};
131
99
  // `memoryCandidates` is an older field name still emitted by some models.
@@ -138,11 +106,6 @@ export function parseMemoryExtractionResult(value) {
138
106
  memoryOps: rawMemoryOps
139
107
  .map(normalizeMemoryCandidate)
140
108
  .filter((item) => item !== null),
141
- skillCandidates: Array.isArray(record.skillCandidates)
142
- ? record.skillCandidates
143
- .map(normalizeSkillCandidate)
144
- .filter((item) => item !== null)
145
- : [],
146
109
  historyBlock: typeof record.historyBlock === "string" ? record.historyBlock.trim() : "",
147
110
  discarded: Array.isArray(record.discarded)
148
111
  ? record.discarded
@@ -202,21 +165,14 @@ export async function runMemoryExtraction(request) {
202
165
  `Current SESSION.md:\n${clipText(currentSession, 8_000, { headRatio: 0.35 }) || "(empty)"}`,
203
166
  `Current MEMORY.md entries (id — content; reference ids in supersede/invalidate):\n${currentMemory || "(empty)"}`,
204
167
  `Channel history file:\n${clipText(currentHistory, 8_000, { headRatio: 0.35 }) || "(empty)"}`,
168
+ `Conversation chunk to persist:\n${transcript || "(empty)"}`,
205
169
  ];
206
- if (request.includeSkills) {
207
- const skills = (request.loadedSkills ?? [])
208
- .map((skill) => `- ${skill.name}${skill.description ? `: ${skill.description}` : ""}`)
209
- .join("\n");
210
- promptSections.push(`Loaded workspace skills:\n${skills || "(none)"}`);
211
- }
212
- promptSections.push(`Conversation chunk to persist:\n${transcript || "(empty)"}`);
213
170
  const result = await runRetriedSidecarTask({
214
171
  name: request.name,
215
172
  model: request.model,
216
173
  resolveApiKey: request.resolveApiKey,
217
174
  systemPrompt: buildMemoryExtractionSystemPrompt({
218
175
  includeHistoryBlock: request.includeHistoryBlock,
219
- includeSkills: request.includeSkills,
220
176
  }),
221
177
  prompt: promptSections.join("\n\n"),
222
178
  timeoutMs: request.timeoutMs,
@@ -199,7 +199,7 @@ export class MemoryLifecycle {
199
199
  const maintenanceState = this.options.appHomeDir
200
200
  ? await readMemoryMaintenanceState(this.options.appHomeDir, this.options.channelId)
201
201
  : undefined;
202
- const lastEntryId = maintenanceState?.lastConsolidatedEntryId;
202
+ const lastEntryId = maintenanceState?.lastCheckpointEntryId;
203
203
  const sourceWindow = reason === "compaction"
204
204
  ? buildCompactionMemorySourceWindow({
205
205
  entries: sessionEntrySnapshot ?? [],
@@ -221,8 +221,8 @@ export class MemoryLifecycle {
221
221
  if (this.options.appHomeDir && sourceWindow.throughEntryId) {
222
222
  await updateMemoryMaintenanceState(this.options.appHomeDir, this.options.channelId, (current) => ({
223
223
  ...current,
224
- lastConsolidatedEntryId: sourceWindow.throughEntryId,
225
- lastDurableConsolidationAt: new Date().toISOString(),
224
+ lastCheckpointEntryId: sourceWindow.throughEntryId,
225
+ lastCheckpointAt: new Date().toISOString(),
226
226
  failureBackoffUntil: null,
227
227
  }));
228
228
  }
@@ -1,6 +1,6 @@
1
- import type { PipiclawMemoryGrowthSettings, PipiclawMemoryMaintenanceSettings, PipiclawSessionMemorySettings } from "../settings.js";
1
+ import type { PipiclawMemoryMaintenanceSettings, PipiclawSessionMemorySettings } from "../settings.js";
2
2
  import type { MemoryMaintenanceState } from "./maintenance-state.js";
3
- export type MaintenanceJobKind = "session-refresh" | "durable-consolidation" | "growth-review" | "structural-maintenance";
3
+ export type MaintenanceJobKind = "session-refresh" | "memory-checkpoint" | "structural-maintenance";
4
4
  export interface MaintenanceGateDecision {
5
5
  allowed: boolean;
6
6
  skipReason?: string;
@@ -15,7 +15,7 @@ export interface SessionRefreshGateInput {
15
15
  hasNewSessionEntry: boolean;
16
16
  hasMeaningfulMaterial: boolean;
17
17
  }
18
- export interface DurableConsolidationGateInput {
18
+ export interface MemoryCheckpointGateInput {
19
19
  now: Date;
20
20
  state: MemoryMaintenanceState;
21
21
  maintenance: PipiclawMemoryMaintenanceSettings;
@@ -24,17 +24,6 @@ export interface DurableConsolidationGateInput {
24
24
  hasMeaningfulExchange: boolean;
25
25
  batchSize: number;
26
26
  minBatchSize?: number;
27
- coveredByGrowthReview?: boolean;
28
- }
29
- export interface GrowthReviewGateInput {
30
- now: Date;
31
- state: MemoryMaintenanceState;
32
- memoryGrowth: PipiclawMemoryGrowthSettings;
33
- maintenance: PipiclawMemoryMaintenanceSettings;
34
- channelActive: boolean;
35
- hasNewEntry: boolean;
36
- hasMeaningfulMaterial: boolean;
37
- hasPromotionSignal: boolean;
38
27
  }
39
28
  export interface StructuralMaintenanceGateInput {
40
29
  now: Date;
@@ -51,6 +40,5 @@ export interface StructuralMaintenanceGateDecision extends MaintenanceGateDecisi
51
40
  runHistoryFolding: boolean;
52
41
  }
53
42
  export declare function shouldRunSessionRefresh(input: SessionRefreshGateInput): MaintenanceGateDecision;
54
- export declare function shouldRunDurableConsolidation(input: DurableConsolidationGateInput): MaintenanceGateDecision;
55
- export declare function shouldRunGrowthReview(input: GrowthReviewGateInput): MaintenanceGateDecision;
43
+ export declare function shouldRunMemoryCheckpoint(input: MemoryCheckpointGateInput): MaintenanceGateDecision;
56
44
  export declare function shouldRunStructuralMaintenance(input: StructuralMaintenanceGateInput): StructuralMaintenanceGateDecision;
@@ -29,10 +29,6 @@ function sessionRefreshThresholdMet(state, settings) {
29
29
  return (state.turnsSinceSessionRefresh >= settings.minTurnsBetweenUpdate ||
30
30
  state.toolCallsSinceSessionRefresh >= settings.minToolCallsBetweenUpdate);
31
31
  }
32
- function growthReviewThresholdMet(state, settings) {
33
- return (state.turnsSinceGrowthReview >= settings.minTurnsBetweenReview ||
34
- state.toolCallsSinceGrowthReview >= settings.minToolCallsBetweenReview);
35
- }
36
32
  export function shouldRunSessionRefresh(input) {
37
33
  if (!input.sessionMemory.enabled) {
38
34
  return deny("session-refresh", "disabled");
@@ -63,68 +59,32 @@ export function shouldRunSessionRefresh(input) {
63
59
  }
64
60
  return allow("session-refresh");
65
61
  }
66
- export function shouldRunDurableConsolidation(input) {
62
+ export function shouldRunMemoryCheckpoint(input) {
67
63
  if (!input.state.dirty) {
68
- return deny("durable-consolidation", "clean");
64
+ return deny("memory-checkpoint", "clean");
69
65
  }
70
66
  if (isBeforeOptional(input.now, input.state.eligibleAfter)) {
71
- return deny("durable-consolidation", "not-idle-yet");
67
+ return deny("memory-checkpoint", "not-idle-yet");
72
68
  }
73
69
  if (input.channelActive) {
74
- return deny("durable-consolidation", "channel-active");
70
+ return deny("memory-checkpoint", "channel-active");
75
71
  }
76
- if (!hasIntervalElapsed(input.now, input.state.lastDurableConsolidationAt, minutesToMs(input.maintenance.durableConsolidationIntervalMinutes))) {
77
- return deny("durable-consolidation", "interval-not-elapsed");
72
+ if (!hasIntervalElapsed(input.now, input.state.lastCheckpointAt, minutesToMs(input.maintenance.checkpointIntervalMinutes))) {
73
+ return deny("memory-checkpoint", "interval-not-elapsed");
78
74
  }
79
75
  if (isBeforeOptional(input.now, input.state.failureBackoffUntil)) {
80
- return deny("durable-consolidation", "backoff-active");
76
+ return deny("memory-checkpoint", "backoff-active");
81
77
  }
82
78
  if (!input.hasNewEntry) {
83
- return deny("durable-consolidation", "no-new-entry");
79
+ return deny("memory-checkpoint", "no-new-entry");
84
80
  }
85
81
  if (!input.hasMeaningfulExchange) {
86
- return deny("durable-consolidation", "no-meaningful-exchange");
87
- }
88
- if (input.coveredByGrowthReview) {
89
- return deny("durable-consolidation", "covered-by-growth-review");
82
+ return deny("memory-checkpoint", "no-meaningful-exchange");
90
83
  }
91
84
  if (input.batchSize < (input.minBatchSize ?? 2)) {
92
- return deny("durable-consolidation", "batch-threshold-not-met");
93
- }
94
- return allow("durable-consolidation");
95
- }
96
- export function shouldRunGrowthReview(input) {
97
- if (!input.memoryGrowth.postTurnReviewEnabled) {
98
- return deny("growth-review", "disabled");
99
- }
100
- if (!input.state.dirty) {
101
- return deny("growth-review", "clean");
102
- }
103
- if (isBeforeOptional(input.now, input.state.eligibleAfter)) {
104
- return deny("growth-review", "not-idle-yet");
105
- }
106
- if (input.channelActive) {
107
- return deny("growth-review", "channel-active");
108
- }
109
- if (!hasIntervalElapsed(input.now, input.state.lastGrowthReviewAt, minutesToMs(input.maintenance.growthReviewIntervalMinutes))) {
110
- return deny("growth-review", "interval-not-elapsed");
111
- }
112
- if (isBeforeOptional(input.now, input.state.failureBackoffUntil)) {
113
- return deny("growth-review", "backoff-active");
114
- }
115
- if (!growthReviewThresholdMet(input.state, input.memoryGrowth)) {
116
- return deny("growth-review", "threshold-not-met");
117
- }
118
- if (!input.hasNewEntry) {
119
- return deny("growth-review", "no-new-entry");
120
- }
121
- if (!input.hasMeaningfulMaterial) {
122
- return deny("growth-review", "no-meaningful-material");
123
- }
124
- if (!input.hasPromotionSignal) {
125
- return deny("growth-review", "no-promotion-signal");
85
+ return deny("memory-checkpoint", "batch-threshold-not-met");
126
86
  }
127
- return allow("growth-review");
87
+ return allow("memory-checkpoint");
128
88
  }
129
89
  export function shouldRunStructuralMaintenance(input) {
130
90
  const jobKind = "structural-maintenance";