@oyasmi/pipiclaw 0.9.6-beta.2 → 0.9.6-beta.3

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 (78) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/dist/agent/channel-runner.js +2 -0
  4. package/dist/agent/maintenance-context.js +21 -2
  5. package/dist/agent/turn/turn-context.js +10 -6
  6. package/dist/config/settings.d.ts +0 -2
  7. package/dist/config/settings.js +0 -2
  8. package/dist/config/tools.d.ts +8 -2
  9. package/dist/config/tools.js +35 -19
  10. package/dist/memory/anchors.d.ts +5 -0
  11. package/dist/memory/anchors.js +49 -0
  12. package/dist/memory/boundary-work.d.ts +1 -0
  13. package/dist/memory/boundary-work.js +1 -0
  14. package/dist/memory/commands.js +23 -6
  15. package/dist/memory/index-budget.d.ts +16 -0
  16. package/dist/memory/index-budget.js +24 -2
  17. package/dist/memory/journal.d.ts +7 -12
  18. package/dist/memory/journal.js +9 -41
  19. package/dist/memory/lifecycle.d.ts +1 -0
  20. package/dist/memory/lifecycle.js +2 -0
  21. package/dist/memory/reflect-job.d.ts +1 -0
  22. package/dist/memory/reflect-job.js +1 -0
  23. package/dist/memory/reflect.d.ts +10 -0
  24. package/dist/memory/reflect.js +103 -20
  25. package/dist/memory/render.d.ts +4 -1
  26. package/dist/memory/render.js +6 -4
  27. package/dist/memory/review-log.d.ts +2 -2
  28. package/dist/memory/scheduler.d.ts +7 -0
  29. package/dist/memory/scheduler.js +70 -3
  30. package/dist/memory/search-index-db.d.ts +15 -0
  31. package/dist/memory/search-index-db.js +247 -0
  32. package/dist/memory/search-index-files.d.ts +11 -0
  33. package/dist/memory/search-index-files.js +26 -0
  34. package/dist/memory/search-index-notes.d.ts +11 -0
  35. package/dist/memory/search-index-notes.js +155 -0
  36. package/dist/memory/search-index-sync.d.ts +19 -0
  37. package/dist/memory/search-index-sync.js +267 -0
  38. package/dist/memory/search-terms.d.ts +12 -0
  39. package/dist/memory/search-terms.js +185 -0
  40. package/dist/memory/search.d.ts +8 -28
  41. package/dist/memory/search.js +18 -278
  42. package/dist/memory/session-corpus.d.ts +15 -26
  43. package/dist/memory/session-corpus.js +120 -327
  44. package/dist/memory/session-search.d.ts +5 -3
  45. package/dist/memory/session-search.js +119 -171
  46. package/dist/memory/sidecar-worker.d.ts +2 -0
  47. package/dist/memory/sidecar-worker.js +25 -1
  48. package/dist/memory/store.d.ts +4 -0
  49. package/dist/memory/store.js +22 -1
  50. package/dist/memory/task-archive-digest.d.ts +61 -0
  51. package/dist/memory/task-archive-digest.js +366 -0
  52. package/dist/models/provider-login.d.ts +1 -1
  53. package/dist/models/provider-login.js +1 -1
  54. package/dist/playbooks/memory-operations.md +2 -2
  55. package/dist/shared/text-utils.d.ts +0 -1
  56. package/dist/shared/text-utils.js +0 -1
  57. package/dist/subagents/runs.d.ts +1 -1
  58. package/dist/subagents/task-envelope.js +6 -8
  59. package/dist/tools/memory-manage.d.ts +1 -0
  60. package/dist/tools/memory-manage.js +9 -23
  61. package/dist/tools/registry.js +2 -0
  62. package/dist/tools/session-search.d.ts +1 -0
  63. package/dist/tools/session-search.js +12 -6
  64. package/dist/tools/web-search.d.ts +13 -7
  65. package/dist/tools/web-search.js +62 -19
  66. package/dist/web/client.d.ts +2 -0
  67. package/dist/web/client.js +7 -3
  68. package/dist/web/config.d.ts +17 -4
  69. package/dist/web/config.js +42 -4
  70. package/dist/web/format.d.ts +2 -1
  71. package/dist/web/format.js +7 -3
  72. package/dist/web/search-providers.d.ts +15 -8
  73. package/dist/web/search-providers.js +208 -139
  74. package/dist/web/search.d.ts +13 -3
  75. package/dist/web/search.js +86 -40
  76. package/package.json +1 -1
  77. package/dist/memory/chinese-words.d.ts +0 -1
  78. package/dist/memory/chinese-words.js +0 -273
package/README.en.md CHANGED
@@ -388,7 +388,7 @@ Explore the full user guides in **[docs/README.md](https://github.com/oyasmi/pip
388
388
  | 🧠 Manage long-term memory, journals, probation & forgetting | [Memory Guide](https://github.com/oyasmi/pipiclaw/blob/master/docs/memory.md) |
389
389
  | 🧩 Package reusable personal or project workflows as Skills | [Skills Guide](https://github.com/oyasmi/pipiclaw/blob/master/docs/skills.md) · [Built-In Tools](https://github.com/oyasmi/pipiclaw/blob/master/docs/tools.md) |
390
390
  | 🔌 Connect Python/JS scripts or custom UIs via OpenAI SDK | [Web API Guide](https://github.com/oyasmi/pipiclaw/blob/master/docs/webapi.md) |
391
- | 💡 Best practices for high-leverage autonomous delivery | [Leverage Notes](https://github.com/oyasmi/pipiclaw/blob/master/docs/leverage/README.md) · [Design Philosophy](https://github.com/oyasmi/pipiclaw/blob/master/docs/design-philosophy.md) |
391
+ | 💡 Best practices for high-leverage autonomous delivery | [Leverage Notes](https://github.com/oyasmi/pipiclaw/blob/master/docs/leverage/README.md) |
392
392
  | 🚀 Host 24/7 with systemd/pm2, review guards & troubleshoot | [Deployment & Operations](https://github.com/oyasmi/pipiclaw/blob/master/docs/deployment-and-operations.md) · [Security Guide](https://github.com/oyasmi/pipiclaw/blob/master/docs/security.md) · [Scaling & Concurrency](https://github.com/oyasmi/pipiclaw/blob/master/docs/scaling-and-concurrency.md) |
393
393
 
394
394
  ---
@@ -403,7 +403,7 @@ cd pipiclaw
403
403
  npm install && npm run build && npm run check
404
404
  ```
405
405
 
406
- For module boundaries, runtime internals, and engineering conventions, see [Architecture](https://github.com/oyasmi/pipiclaw/blob/master/docs/architecture.md), [Runtime Mechanisms](https://github.com/oyasmi/pipiclaw/blob/master/docs/runtime-mechanisms.md), and [AGENTS.md](https://github.com/oyasmi/pipiclaw/blob/master/AGENTS.md). Issues and Pull Requests are welcome!
406
+ Find the architecture, engineering conventions, behavior evaluation guide, and design records in the [project development docs](https://github.com/oyasmi/pipiclaw/blob/master/dev-docs/README.md). Issues and Pull Requests are welcome!
407
407
 
408
408
  ---
409
409
 
package/README.md CHANGED
@@ -385,7 +385,7 @@ Pipiclaw 本身不收取任何中转费用,它直接调用你本机已安装
385
385
  | 🧠 管理长期记忆、工作日记、观察期与彻底遗忘 | [记忆管理](https://github.com/oyasmi/pipiclaw/blob/master/docs/memory.md) |
386
386
  | 🧩 把常用研发流程打包成可复用的个人/项目技能 | [Skills 指南](https://github.com/oyasmi/pipiclaw/blob/master/docs/skills.md) · [内置工具总览](https://github.com/oyasmi/pipiclaw/blob/master/docs/tools.md) |
387
387
  | 🔌 用官方 OpenAI SDK 从外部脚本或自定义前端接入 | [Web API 手册](https://github.com/oyasmi/pipiclaw/blob/master/docs/webapi.md) |
388
- | 💡 进阶实践:如何真正把 AI 助手从“扳手”用成“车床” | [使用杠杆(Leverage)](https://github.com/oyasmi/pipiclaw/blob/master/docs/leverage/README.md) · [设计哲学](https://github.com/oyasmi/pipiclaw/blob/master/docs/design-philosophy.md) |
388
+ | 💡 进阶实践:如何真正把 AI 助手从“扳手”用成“车床” | [使用杠杆(Leverage)](https://github.com/oyasmi/pipiclaw/blob/master/docs/leverage/README.md) |
389
389
  | 🚀 24 小时后台托管、备份迁移、权限守卫与故障排查 | [部署与运维](https://github.com/oyasmi/pipiclaw/blob/master/docs/deployment-and-operations.md) · [安全指南](https://github.com/oyasmi/pipiclaw/blob/master/docs/security.md) · [并发与容量](https://github.com/oyasmi/pipiclaw/blob/master/docs/scaling-and-concurrency.md) |
390
390
 
391
391
  ---
@@ -400,7 +400,7 @@ cd pipiclaw
400
400
  npm install && npm run build && npm run check
401
401
  ```
402
402
 
403
- 了解模块架构、运行机制与开发规范,请阅读[架构文档](https://github.com/oyasmi/pipiclaw/blob/master/docs/architecture.md)、[运行机制](https://github.com/oyasmi/pipiclaw/blob/master/docs/runtime-mechanisms.md)与 [AGENTS.md](https://github.com/oyasmi/pipiclaw/blob/master/AGENTS.md)。欢迎提交 Issue 与 Pull Request!
403
+ 源码架构、工程规范、行为评测和设计记录见[项目开发文档](https://github.com/oyasmi/pipiclaw/blob/master/dev-docs/README.md)。欢迎提交 Issue 与 Pull Request!
404
404
 
405
405
  ---
406
406
 
@@ -122,6 +122,7 @@ export class ChannelRunner {
122
122
  ensureAuth: (model, signal) => this.host.modelRequests.ensureAuth(model, signal),
123
123
  stream: (model, context, options) => this.host.modelRequests.stream(model, context, options),
124
124
  },
125
+ resolveFallbackModel: () => this.models.resolveFallbackModel(),
125
126
  recordMemoryActivity: (event) => this.recordMemoryActivity(event),
126
127
  });
127
128
  this.host = new SessionHost({
@@ -368,6 +369,7 @@ export class ChannelRunner {
368
369
  sessionEntries: () => [...this.sessionManager.getBranch()],
369
370
  model: this.session.model ?? this.models.activeModel,
370
371
  modelRequests: this.host.modelRequests,
372
+ resolveFallbackModel: () => this.models.resolveFallbackModel(),
371
373
  settings: { memoryMaintenance: this.settingsManager.getMemoryMaintenanceSettings() },
372
374
  };
373
375
  }
@@ -3,8 +3,9 @@ import { join } from "node:path";
3
3
  import { SessionManager } from "@earendil-works/pi-coding-agent";
4
4
  import { peekActiveSessionFile } from "../channel/active-session-store.js";
5
5
  import { enqueueBoundaryReflectEntries } from "../memory/boundary-work.js";
6
+ import { findExactModelReferenceMatch } from "../models/reference.js";
6
7
  import { createModelRequests } from "../models/requests.js";
7
- import { createModelRuntime, resolveInitialModel, wrapModelRegistry } from "../models/runtime.js";
8
+ import { createModelRuntime, refreshModelRegistry, resolveInitialModel, wrapModelRegistry } from "../models/runtime.js";
8
9
  /** /new's local persistence path: no runner, credentials, inference, or memory queue. */
9
10
  export async function preserveMemoryBeforeNewSession(conversation) {
10
11
  const file = join(conversation.conversationDir, peekActiveSessionFile(conversation.conversationDir));
@@ -70,6 +71,7 @@ export async function loadDetachedMaintenanceContext(options) {
70
71
  });
71
72
  const modelRegistry = wrapModelRegistry(modelRuntime);
72
73
  const model = resolveInitialModel(modelRegistry, options.settingsManager);
74
+ const modelRequests = createModelRequests(modelRuntime);
73
75
  options.settingsManager.reload();
74
76
  return {
75
77
  conversation,
@@ -77,7 +79,24 @@ export async function loadDetachedMaintenanceContext(options) {
77
79
  messages: () => [...cachedTranscript.messages],
78
80
  sessionEntries: () => [...cachedTranscript.sessionEntries],
79
81
  model,
80
- modelRequests: createModelRequests(modelRuntime),
82
+ modelRequests,
83
+ resolveFallbackModel: async () => {
84
+ options.settingsManager.reload();
85
+ const reference = options.settingsManager.getFallbackModelReference();
86
+ if (!reference)
87
+ return null;
88
+ await refreshModelRegistry(modelRuntime);
89
+ const { match } = findExactModelReferenceMatch(reference, modelRegistry.getAvailable());
90
+ if (!match)
91
+ return null;
92
+ try {
93
+ await modelRequests.ensureAuth(match);
94
+ return match;
95
+ }
96
+ catch {
97
+ return null;
98
+ }
99
+ },
81
100
  settings: { memoryMaintenance: options.settingsManager.getMemoryMaintenanceSettings() },
82
101
  };
83
102
  }
@@ -6,8 +6,8 @@
6
6
  import { readFile } from "node:fs/promises";
7
7
  import { join } from "node:path";
8
8
  import { TASK_DIGEST_SETTINGS } from "../../config/settings.js";
9
- import { buildMemoryIndexForBootstrap, clipJournalTailForBootstrap, clipWorkspaceMemoryForBootstrap, } from "../../memory/index-budget.js";
10
- import { readJournalDay } from "../../memory/journal.js";
9
+ import { buildJournalBlocksForBootstrap, buildMemoryIndexForBootstrap, clipWorkspaceMemoryForBootstrap, } from "../../memory/index-budget.js";
10
+ import { readRecentJournalForBootstrap } from "../../memory/journal.js";
11
11
  import { renderMemoryBootstrap } from "../../memory/render.js";
12
12
  import { listMemoryEntries } from "../../memory/store.js";
13
13
  import { localDayKey } from "../../shared/local-time.js";
@@ -55,16 +55,20 @@ export async function buildFirstTurnMemoryBootstrap(deskDir, workspaceDir) {
55
55
  }
56
56
  };
57
57
  const today = localDayKey();
58
- const [entries, workspaceMemory, journalToday] = await Promise.all([
58
+ const [entries, workspaceMemory, recentJournal] = await Promise.all([
59
59
  listMemoryEntries(deskDir).catch(() => []),
60
60
  readOptionalFile(join(workspaceDir, "MEMORY.md")),
61
- readJournalDay(deskDir, today).catch(() => ""),
61
+ readRecentJournalForBootstrap(deskDir, today).catch(() => ({ todayText: "" })),
62
62
  ]);
63
63
  const index = buildMemoryIndexForBootstrap(entries);
64
- const journalTail = clipJournalTailForBootstrap(journalToday);
64
+ const journal = buildJournalBlocksForBootstrap({
65
+ todayDate: today,
66
+ todayText: recentJournal.todayText,
67
+ previous: recentJournal.previous,
68
+ });
65
69
  return renderMemoryBootstrap({
66
70
  workspaceMemory: clipWorkspaceMemoryForBootstrap(workspaceMemory),
67
71
  memoryIndex: entries.length > 0 ? index.text : "",
68
- journal: journalTail ? { date: today, text: journalTail } : undefined,
72
+ journal: journal.length > 0 ? journal : undefined,
69
73
  });
70
74
  }
@@ -32,8 +32,6 @@ export interface PipiclawLoggingSettings {
32
32
  };
33
33
  }
34
34
  export interface PipiclawSessionSearchSettings {
35
- maxFiles: number;
36
- maxChunks: number;
37
35
  maxCharsPerChunk: number;
38
36
  summarizeWithModel: boolean;
39
37
  timeoutMs: number;
@@ -49,8 +49,6 @@ export const TASK_DIGEST_SETTINGS = {
49
49
  maxChars: 1000,
50
50
  };
51
51
  const DEFAULT_SESSION_SEARCH = {
52
- maxFiles: 12,
53
- maxChunks: 80,
54
52
  maxCharsPerChunk: 1200,
55
53
  summarizeWithModel: false,
56
54
  timeoutMs: 12_000,
@@ -1,9 +1,14 @@
1
1
  import { type ConfigDiagnostic } from "../shared/config-diagnostic.js";
2
- export type WebSearchProvider = "tavily" | "jina" | "searxng" | "duckduckgo";
3
- export interface PipiclawWebSearchConfig {
2
+ declare const WEB_SEARCH_PROVIDERS: readonly ["tavily", "jina", "searxng", "duckduckgo", "parallel"];
3
+ export type WebSearchProvider = (typeof WEB_SEARCH_PROVIDERS)[number];
4
+ export interface WebSearchBackendConfig {
4
5
  provider: WebSearchProvider;
5
6
  apiKey: string;
6
7
  baseUrl: string;
8
+ }
9
+ export interface PipiclawWebSearchConfig extends WebSearchBackendConfig {
10
+ fallback: WebSearchBackendConfig | null;
11
+ parallelMode: "fast" | "advanced";
7
12
  maxResults: number;
8
13
  timeoutMs: number;
9
14
  }
@@ -61,3 +66,4 @@ export declare const DEFAULT_TOOLS_CONFIG: PipiclawToolsConfig;
61
66
  export declare function getToolsConfigPath(appHomeDir?: string): string;
62
67
  export declare function loadToolsConfigWithDiagnostics(appHomeDir?: string): LoadedToolsConfig;
63
68
  export declare function loadToolsConfig(appHomeDir?: string): PipiclawToolsConfig;
69
+ export {};
@@ -7,6 +7,7 @@ import { APP_HOME_DIR } from "../paths.js";
7
7
  import { loadJsonConfig, pushConfigWarning } from "../shared/config-diagnostic.js";
8
8
  import { clampInteger } from "../shared/format.js";
9
9
  import { isRecord } from "../shared/type-guards.js";
10
+ const WEB_SEARCH_PROVIDERS = ["tavily", "jina", "searxng", "duckduckgo", "parallel"];
10
11
  /**
11
12
  * Every `tools.<key>` section in `tools.json`. Kept in sync with
12
13
  * `PipiclawToolsConfig["tools"]` by `satisfies` (rejects an extra/misspelled entry) and
@@ -21,16 +22,17 @@ export const TOOLS_CONFIG_SECTION_KEYS = [
21
22
  ];
22
23
  const _toolsConfigKeysComplete = true;
23
24
  void _toolsConfigKeysComplete;
24
- const WEB_SEARCH_PROVIDERS = ["tavily", "jina", "searxng", "duckduckgo"];
25
+ const MAX_SEARCH_TIMEOUT_MS = 2_147_483_647;
26
+ const DEFAULT_SEARCH_BACKEND = { provider: "duckduckgo", apiKey: "", baseUrl: "" };
25
27
  export const DEFAULT_TOOLS_CONFIG = {
26
28
  tools: {
27
29
  web: {
28
30
  enable: false,
29
31
  proxy: null,
30
32
  search: {
31
- provider: "duckduckgo",
32
- apiKey: "",
33
- baseUrl: "",
33
+ ...DEFAULT_SEARCH_BACKEND,
34
+ fallback: DEFAULT_SEARCH_BACKEND,
35
+ parallelMode: "fast",
34
36
  maxResults: 5,
35
37
  timeoutMs: 30_000,
36
38
  },
@@ -74,6 +76,13 @@ function asOptionalProxy(value) {
74
76
  function pushInvalidValueDiagnostic(diagnostics, configPath, field, message) {
75
77
  pushConfigWarning(diagnostics, "tools", configPath, field, message);
76
78
  }
79
+ function readSearchBackend(value) {
80
+ const name = asTrimmedString(value.provider).toLowerCase();
81
+ const provider = WEB_SEARCH_PROVIDERS.find((candidate) => candidate === name);
82
+ return provider
83
+ ? { provider, apiKey: asTrimmedString(value.apiKey), baseUrl: asTrimmedString(value.baseUrl) }
84
+ : null;
85
+ }
77
86
  function mergeToolsConfig(source, configPath, diagnostics) {
78
87
  if (!isRecord(source)) {
79
88
  pushInvalidValueDiagnostic(diagnostics, configPath, "root", "expected a JSON object; using defaults");
@@ -87,15 +96,22 @@ function mergeToolsConfig(source, configPath, diagnostics) {
87
96
  const subagentInline = isRecord(tools.subagentInline) ? tools.subagentInline : {};
88
97
  const search = isRecord(web.search) ? web.search : {};
89
98
  const fetch = isRecord(web.fetch) ? web.fetch : {};
90
- const providerValue = asTrimmedString(search.provider, DEFAULT_TOOLS_CONFIG.tools.web.search.provider).toLowerCase();
91
- const provider = WEB_SEARCH_PROVIDERS.includes(providerValue)
92
- ? providerValue
93
- : (() => {
94
- if (search.provider !== undefined) {
95
- pushInvalidValueDiagnostic(diagnostics, configPath, "tools.web.search.provider", `unknown provider "${String(search.provider)}"; using ${DEFAULT_TOOLS_CONFIG.tools.web.search.provider}`);
96
- }
97
- return DEFAULT_TOOLS_CONFIG.tools.web.search.provider;
98
- })();
99
+ const backend = readSearchBackend(search);
100
+ if (!backend && search.provider !== undefined) {
101
+ pushInvalidValueDiagnostic(diagnostics, configPath, "tools.web.search.provider", `unknown provider "${String(search.provider)}"; using duckduckgo`);
102
+ }
103
+ const fallback = search.fallback === undefined
104
+ ? DEFAULT_SEARCH_BACKEND
105
+ : isRecord(search.fallback)
106
+ ? readSearchBackend(search.fallback)
107
+ : null;
108
+ if (search.fallback != null && !fallback) {
109
+ pushInvalidValueDiagnostic(diagnostics, configPath, "tools.web.search.fallback", "expected null or a known provider object; disabling fallback");
110
+ }
111
+ const parallelMode = search.parallelMode === "advanced" ? "advanced" : "fast";
112
+ if (search.parallelMode !== undefined && search.parallelMode !== parallelMode) {
113
+ pushInvalidValueDiagnostic(diagnostics, configPath, "tools.web.search.parallelMode", 'expected "fast" or "advanced"; using fast');
114
+ }
99
115
  const defaultExtractMode = asTrimmedString(fetch.defaultExtractMode, DEFAULT_TOOLS_CONFIG.tools.web.fetch.defaultExtractMode);
100
116
  if (web.proxy !== undefined && web.proxy !== null && typeof web.proxy !== "string") {
101
117
  pushInvalidValueDiagnostic(diagnostics, configPath, "tools.web.proxy", "expected a string or null; using null");
@@ -103,8 +119,8 @@ function mergeToolsConfig(source, configPath, diagnostics) {
103
119
  if (search.maxResults !== undefined && clampInteger(search.maxResults, -1, 1, 10) === -1) {
104
120
  pushInvalidValueDiagnostic(diagnostics, configPath, "tools.web.search.maxResults", "expected an integer between 1 and 10; using default");
105
121
  }
106
- if (search.timeoutMs !== undefined && clampInteger(search.timeoutMs, -1, 1) === -1) {
107
- pushInvalidValueDiagnostic(diagnostics, configPath, "tools.web.search.timeoutMs", "expected a positive integer; using default");
122
+ if (search.timeoutMs !== undefined && clampInteger(search.timeoutMs, -1, 1, MAX_SEARCH_TIMEOUT_MS) === -1) {
123
+ pushInvalidValueDiagnostic(diagnostics, configPath, "tools.web.search.timeoutMs", `expected an integer between 1 and ${MAX_SEARCH_TIMEOUT_MS}; using default`);
108
124
  }
109
125
  if (fetch.maxChars !== undefined && clampInteger(fetch.maxChars, -1, 100) === -1) {
110
126
  pushInvalidValueDiagnostic(diagnostics, configPath, "tools.web.fetch.maxChars", "expected an integer >= 100; using default");
@@ -127,11 +143,11 @@ function mergeToolsConfig(source, configPath, diagnostics) {
127
143
  enable: typeof web.enable === "boolean" ? web.enable : DEFAULT_TOOLS_CONFIG.tools.web.enable,
128
144
  proxy: asOptionalProxy(web.proxy),
129
145
  search: {
130
- provider,
131
- apiKey: asTrimmedString(search.apiKey),
132
- baseUrl: asTrimmedString(search.baseUrl),
146
+ ...(backend ?? DEFAULT_SEARCH_BACKEND),
147
+ fallback,
148
+ parallelMode,
133
149
  maxResults: clampInteger(search.maxResults, DEFAULT_TOOLS_CONFIG.tools.web.search.maxResults, 1, 10),
134
- timeoutMs: clampInteger(search.timeoutMs, DEFAULT_TOOLS_CONFIG.tools.web.search.timeoutMs, 1),
150
+ timeoutMs: clampInteger(search.timeoutMs, DEFAULT_TOOLS_CONFIG.tools.web.search.timeoutMs, 1, MAX_SEARCH_TIMEOUT_MS),
135
151
  },
136
152
  fetch: {
137
153
  maxChars: clampInteger(fetch.maxChars, DEFAULT_TOOLS_CONFIG.tools.web.fetch.maxChars, 100),
@@ -0,0 +1,5 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ export declare function extractAnchors(text: string): string[];
3
+ export declare function findUnanchored(anchors: string[], provenance: string, home?: string): string[];
4
+ /** Tool output in the same source window can corroborate an identifier without entering the prompt. */
5
+ export declare function toolResultProvenance(messages: AgentMessage[]): string[];
@@ -0,0 +1,49 @@
1
+ import { homedir } from "node:os";
2
+ import { contentText } from "@earendil-works/pi-ai";
3
+ import { buildStandardMessages } from "../shared/type-guards.js";
4
+ import { redactSecrets } from "./secret-redaction.js";
5
+ const URL = /https?:\/\/[^\s<>"'`))】\],;:!?。]+/giu;
6
+ const SEGMENT = String.raw `[\p{L}\p{N}_@%+~.-]+`;
7
+ const PATH = new RegExp(String.raw `(?<![\w./~$-])(?:(?:~|\$HOME)?/(?:${SEGMENT}/)+${SEGMENT}|(?:${SEGMENT}/)+${SEGMENT}\.[a-z0-9]{1,8}(?![\p{L}\p{N}_-]|\.[\p{L}\p{N}]))`, "giu");
8
+ const HOST_PORT = /\b(?:localhost|(?:[a-z0-9-]+\.)+[a-z0-9-]+):\d{2,5}\b/gi;
9
+ const LABELLED_PORT = /(?:端口\s*|\bport\s+)(\d{2,5})(?!\d)/gi;
10
+ const VERSION = /\b(?:v\d+(?:\.\d+)+|\d+(?:\.\d+){2,})\b/g;
11
+ const COMMIT = /\b(?=[a-f\d]*[a-f])(?=[a-f\d]*\d)[a-f\d]{7,40}\b/gi;
12
+ const TERMINAL_PUNCTUATION = /[.,;:!?。,;:!?]+$/u;
13
+ const CSS_RATIO = /^\d+(?:px|rem|em|pt)\/\d+\.\d+$/i;
14
+ export function extractAnchors(text) {
15
+ const hits = [];
16
+ let remaining = text.normalize("NFKC");
17
+ // Mask composite identifiers before looking for paths, hashes, versions, or port numbers
18
+ // embedded inside them. Preserve offsets so the first unsupported anchor is deterministic.
19
+ for (const pattern of [URL, PATH, HOST_PORT, LABELLED_PORT, VERSION, COMMIT]) {
20
+ for (const match of remaining.matchAll(pattern)) {
21
+ if (pattern === PATH && CSS_RATIO.test(match[0]))
22
+ continue;
23
+ const value = (match[1] ?? match[0]).replace(TERMINAL_PUNCTUATION, "");
24
+ hits.push({ offset: match.index, value });
25
+ }
26
+ remaining = remaining.replaceAll(pattern, (match) => " ".repeat(match.length));
27
+ }
28
+ return [...new Set(hits.sort((a, b) => a.offset - b.offset).map(({ value }) => value))];
29
+ }
30
+ function anchorForms(anchor, home) {
31
+ if (/^https?:\/\//i.test(anchor)) {
32
+ const stem = anchor.replace(/\/$/, "");
33
+ return [stem, `${stem}/`];
34
+ }
35
+ const homePrefix = `${home.replace(/\/$/, "")}/`;
36
+ const prefix = ["~/", "$HOME/", homePrefix].find((candidate) => anchor.startsWith(candidate));
37
+ if (!prefix)
38
+ return [anchor];
39
+ const rest = anchor.slice(prefix.length);
40
+ return [`~/${rest}`, `$HOME/${rest}`, `${homePrefix}${rest}`];
41
+ }
42
+ export function findUnanchored(anchors, provenance, home = homedir()) {
43
+ const source = provenance.normalize("NFKC");
44
+ return anchors.filter((anchor) => !anchorForms(anchor, home).some((form) => source.includes(form)));
45
+ }
46
+ /** Tool output in the same source window can corroborate an identifier without entering the prompt. */
47
+ export function toolResultProvenance(messages) {
48
+ return buildStandardMessages(messages).flatMap((message) => message.role === "toolResult" ? [redactSecrets(contentText(message.content))] : []);
49
+ }
@@ -14,6 +14,7 @@ export interface BoundaryReflectOptions {
14
14
  appHomeDir: string;
15
15
  model: Model<Api>;
16
16
  modelRequests: ModelRequests;
17
+ resolveFallbackModel?: () => Promise<Model<Api> | null>;
17
18
  queue?: DeskMemoryQueue;
18
19
  }
19
20
  /** Called by the live lifecycle and the startup/idle scheduler, including when idle maintenance is off. */
@@ -140,6 +140,7 @@ export async function drainBoundaryReflectWork(options) {
140
140
  workspaceDir: options.workspaceDir,
141
141
  model: options.model,
142
142
  modelRequests: options.modelRequests,
143
+ resolveFallbackModel: options.resolveFallbackModel,
143
144
  messages: batch.messages,
144
145
  sourceClosed: true,
145
146
  usageContext: {
@@ -6,7 +6,7 @@ import { buildMemoryIndexForBootstrap, MEMORY_INDEX_MAX_UNITS } from "./index-bu
6
6
  import { listJournalDates, readJournalDay } from "./journal.js";
7
7
  import { readMemoryMaintenanceState } from "./maintenance-state.js";
8
8
  import { appendMemoryReviewLog } from "./review-log.js";
9
- import { applyMemoryOps, isValidMemoryName, listMemoryEntries, MEMORY_TYPE_ORDER, readMemoryEntry, } from "./store.js";
9
+ import { applyMemoryOps, isValidMemoryName, listMemoryEntries, MEMORY_TYPE_ORDER, memoryActivityDate, readMemoryEntry, } from "./store.js";
10
10
  import { hashMemoryContent } from "./tombstones.js";
11
11
  function renderUsage() {
12
12
  return renderSubcommandUsage("memory");
@@ -14,8 +14,17 @@ function renderUsage() {
14
14
  function isMemoryType(value) {
15
15
  return value !== undefined && MEMORY_TYPE_ORDER.includes(value);
16
16
  }
17
+ const STALE_UNCONFIRMED_DAYS = 90;
18
+ function isStaleAgentEntry(entry, today) {
19
+ if (entry.source !== "agent" || entry.expires)
20
+ return false;
21
+ const activity = memoryActivityDate(entry);
22
+ const diffDays = (Date.parse(`${today}T00:00:00Z`) - Date.parse(`${activity}T00:00:00Z`)) / 86_400_000;
23
+ return Number.isFinite(diffDays) && diffDays >= STALE_UNCONFIRMED_DAYS;
24
+ }
17
25
  async function handleStatus(options) {
18
26
  const entries = await listMemoryEntries(options.conversation.deskDir);
27
+ const today = localDayKey();
19
28
  const byType = new Map(MEMORY_TYPE_ORDER.map((type) => [type, 0]));
20
29
  for (const entry of entries) {
21
30
  byType.set(entry.type, (byType.get(entry.type) ?? 0) + 1);
@@ -24,19 +33,27 @@ async function handleStatus(options) {
24
33
  .filter((entry) => Boolean(entry.expires))
25
34
  .sort((a, b) => a.expires.localeCompare(b.expires));
26
35
  const malformed = entries.filter((entry) => entry.malformed);
36
+ const stale = entries.filter((entry) => isStaleAgentEntry(entry, today));
27
37
  const tiered = buildMemoryIndexForBootstrap(entries, MEMORY_INDEX_MAX_UNITS);
28
38
  const state = options.appHomeDir
29
39
  ? await readMemoryMaintenanceState(options.appHomeDir, options.conversation)
30
40
  : undefined;
31
- return [
41
+ const lines = [
32
42
  "**记忆状态**",
33
43
  "",
34
44
  `- 记忆条目:\`${entries.length}\`(${MEMORY_TYPE_ORDER.map((type) => `${type} ${byType.get(type) ?? 0}`).join(" / ")})`,
35
45
  `- 观察期条目:\`${probationary.length}\`${probationary.length > 0 ? `(最早到期 \`${probationary[0].expires}\`)` : ""}`,
36
46
  `- 文件头解析异常:\`${malformed.length}\`${malformed.length > 0 ? `(${malformed.map((e) => e.name).join("、")})` : ""}`,
37
- `- 上次后台整理:\`${state?.lastReflectAt ?? "从未"}\``,
38
- `- 索引大小:${tiered.overBudget ? "超出预算,注入时优先带最近更新的条目;下次整理会尝试合并" : "未超出预算,整份注入"}`,
39
- ].join("\n");
47
+ ];
48
+ if (stale.length > 0) {
49
+ const preview = stale
50
+ .slice(0, 5)
51
+ .map((e) => e.name)
52
+ .join("、");
53
+ lines.push(`- 久未印证(>${STALE_UNCONFIRMED_DAYS}天):\`${stale.length}\`(${preview}${stale.length > 5 ? "…" : ""})`);
54
+ }
55
+ lines.push(`- 上次后台整理:\`${state?.lastReflectAt ?? "从未"}\``, `- 索引大小:${tiered.overBudget ? "超出预算,注入时优先带最近更新或印证的条目;下次整理会尝试合并" : "未超出预算,整份注入"}`);
56
+ return lines.join("\n");
40
57
  }
41
58
  async function handleList(options, typeArg) {
42
59
  if (typeArg && !isMemoryType(typeArg)) {
@@ -71,7 +88,7 @@ async function handleShow(options, name) {
71
88
  "",
72
89
  `- 类型(type):\`${entry.type}\``,
73
90
  `- 来源(source):\`${entry.source}\``,
74
- `- 创建(created):\`${entry.created}\`;更新(updated):\`${entry.updated}\``,
91
+ `- 创建(created):\`${entry.created}\`;更新(updated):\`${entry.updated}\`${entry.confirmed ? `;印证(confirmed):\`${entry.confirmed}\`` : ""}`,
75
92
  ];
76
93
  if (entry.expires)
77
94
  lines.push(`- 观察期至(expires):\`${entry.expires}\``);
@@ -8,6 +8,7 @@ import { type MemoryEntry } from "./store.js";
8
8
  export declare const WORKSPACE_MEMORY_MAX_UNITS = 500;
9
9
  export declare const MEMORY_INDEX_MAX_UNITS = 1400;
10
10
  export declare const JOURNAL_TAIL_MAX_UNITS = 400;
11
+ export declare const JOURNAL_BACKFILL_MIN_UNITS = 150;
11
12
  export interface TieredIndexResult {
12
13
  text: string;
13
14
  includedNames: string[];
@@ -25,3 +26,18 @@ export declare function buildMemoryIndexForBootstrap(entries: MemoryEntry[], max
25
26
  export declare function clipWorkspaceMemoryForBootstrap(workspaceMemory: string, maxUnits?: number): string;
26
27
  /** Tail of a journal day, clipped to the injection budget (head dropped, newest kept). */
27
28
  export declare function clipJournalTailForBootstrap(journalText: string, maxUnits?: number): string;
29
+ /**
30
+ * B2: when today's journal is empty or shorter than `JOURNAL_BACKFILL_MIN_UNITS`, fill the
31
+ * remaining budget with the tail of the most recent earlier day so morning sessions keep context.
32
+ */
33
+ export declare function buildJournalBlocksForBootstrap(input: {
34
+ todayDate: string;
35
+ todayText: string;
36
+ previous?: {
37
+ date: string;
38
+ text: string;
39
+ };
40
+ }, maxUnits?: number): Array<{
41
+ date: string;
42
+ text: string;
43
+ }>;
@@ -1,7 +1,7 @@
1
1
  import { splitH2Sections } from "../shared/markdown-sections.js";
2
2
  import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
3
3
  import { stripCrAndTrim } from "../shared/text-utils.js";
4
- import { renderMemoryIndex } from "./store.js";
4
+ import { memoryActivityDate, renderMemoryIndex } from "./store.js";
5
5
  /**
6
6
  * Spec 050, D1/D4/D11: what actually goes into `<memory_bootstrap>` on the first turn, and the
7
7
  * budget tiering when the desk memory index does not fit.
@@ -11,6 +11,8 @@ import { renderMemoryIndex } from "./store.js";
11
11
  export const WORKSPACE_MEMORY_MAX_UNITS = 500;
12
12
  export const MEMORY_INDEX_MAX_UNITS = 1_400;
13
13
  export const JOURNAL_TAIL_MAX_UNITS = 400;
14
+ export const JOURNAL_BACKFILL_MIN_UNITS = 150;
15
+ const JOURNAL_BACKFILL_MIN_REMAINING_UNITS = 40;
14
16
  const WORKSPACE_MEMORY_MAX_CHARS = 4_000;
15
17
  const JOURNAL_TAIL_MAX_CHARS = 3_000;
16
18
  const ALWAYS_INCLUDED = new Set(["user", "feedback"]);
@@ -27,7 +29,7 @@ export function buildMemoryIndexForBootstrap(entries, maxUnits = MEMORY_INDEX_MA
27
29
  const pinned = entries.filter((e) => ALWAYS_INCLUDED.has(e.type));
28
30
  const droppable = entries
29
31
  .filter((e) => !ALWAYS_INCLUDED.has(e.type))
30
- .sort((a, b) => b.updated.localeCompare(a.updated) || a.name.localeCompare(b.name));
32
+ .sort((a, b) => memoryActivityDate(b).localeCompare(memoryActivityDate(a)) || a.name.localeCompare(b.name));
31
33
  let kept = droppable.length;
32
34
  let rendered = "";
33
35
  while (true) {
@@ -100,3 +102,23 @@ export function clipJournalTailForBootstrap(journalText, maxUnits = JOURNAL_TAIL
100
102
  marker: "[... earlier entries omitted ...]\n",
101
103
  }).text;
102
104
  }
105
+ /**
106
+ * B2: when today's journal is empty or shorter than `JOURNAL_BACKFILL_MIN_UNITS`, fill the
107
+ * remaining budget with the tail of the most recent earlier day so morning sessions keep context.
108
+ */
109
+ export function buildJournalBlocksForBootstrap(input, maxUnits = JOURNAL_TAIL_MAX_UNITS) {
110
+ const todayClipped = clipJournalTailForBootstrap(input.todayText, maxUnits);
111
+ const todayUnits = todayClipped ? countPromptUnits(todayClipped) : 0;
112
+ const blocks = [];
113
+ if (input.previous && todayUnits < Math.min(JOURNAL_BACKFILL_MIN_UNITS, maxUnits)) {
114
+ const remaining = maxUnits - todayUnits;
115
+ if (remaining >= JOURNAL_BACKFILL_MIN_REMAINING_UNITS) {
116
+ const prevClipped = clipJournalTailForBootstrap(input.previous.text, remaining);
117
+ if (prevClipped)
118
+ blocks.push({ date: input.previous.date, text: prevClipped });
119
+ }
120
+ }
121
+ if (todayClipped)
122
+ blocks.push({ date: input.todayDate, text: todayClipped });
123
+ return blocks;
124
+ }
@@ -6,19 +6,14 @@ export declare function getJournalDir(deskDir: string): string;
6
6
  export declare function getJournalPath(deskDir: string, date: string): string;
7
7
  export declare function readJournalDay(deskDir: string, date?: string): Promise<string>;
8
8
  export declare function listJournalDates(deskDir: string): Promise<string[]>;
9
- /** Search stays bounded even after years of journals, or one unusually busy day. */
10
- export declare const JOURNAL_SEARCH_MAX_DAYS = 30;
11
- export declare const JOURNAL_SEARCH_DAY_BYTES: number;
12
- export interface JournalSearchWindow {
13
- days: Array<{
9
+ /** Read today's journal and, when present, the most recent earlier day for morning backfill (B2). */
10
+ export declare function readRecentJournalForBootstrap(deskDir: string, today?: string): Promise<{
11
+ todayText: string;
12
+ previous?: {
14
13
  date: string;
15
- content: string;
16
- }>;
17
- omittedDays: number;
18
- truncatedDates: string[];
19
- }
20
- /** Newest day files first; retain only whole lines when a day's older bytes are omitted. */
21
- export declare function readJournalForSearch(deskDir: string): Promise<JournalSearchWindow>;
14
+ text: string;
15
+ };
16
+ }>;
22
17
  export interface JournalAppendResult {
23
18
  appended: number;
24
19
  skippedDuplicate: number;
@@ -1,4 +1,4 @@
1
- import { mkdir, open, readdir } from "node:fs/promises";
1
+ import { mkdir, readdir } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { writeFileAtomically } from "../shared/atomic-file.js";
4
4
  import { localDayKey } from "../shared/local-time.js";
@@ -31,46 +31,14 @@ export async function listJournalDates(deskDir) {
31
31
  throw error;
32
32
  }
33
33
  }
34
- /** Search stays bounded even after years of journals, or one unusually busy day. */
35
- export const JOURNAL_SEARCH_MAX_DAYS = 30;
36
- export const JOURNAL_SEARCH_DAY_BYTES = 64 * 1024;
37
- /** Newest day files first; retain only whole lines when a day's older bytes are omitted. */
38
- export async function readJournalForSearch(deskDir) {
39
- const dates = (await listJournalDates(deskDir)).reverse();
40
- const window = {
41
- days: [],
42
- omittedDays: Math.max(0, dates.length - JOURNAL_SEARCH_MAX_DAYS),
43
- truncatedDates: [],
44
- };
45
- for (const date of dates.slice(0, JOURNAL_SEARCH_MAX_DAYS)) {
46
- try {
47
- const file = await open(getJournalPath(deskDir, date), "r");
48
- try {
49
- const stat = await file.stat();
50
- if (!stat.isFile())
51
- continue;
52
- const start = Math.max(0, stat.size - JOURNAL_SEARCH_DAY_BYTES);
53
- const buffer = Buffer.alloc(Math.min(stat.size, JOURNAL_SEARCH_DAY_BYTES));
54
- const { bytesRead } = await file.read(buffer, 0, buffer.length, start);
55
- let content = buffer.subarray(0, bytesRead).toString("utf-8");
56
- if (start > 0) {
57
- window.truncatedDates.push(date);
58
- const newline = content.indexOf("\n");
59
- content = newline < 0 ? "" : content.slice(newline + 1);
60
- }
61
- window.days.push({ date, content });
62
- }
63
- finally {
64
- await file.close();
65
- }
66
- }
67
- catch (error) {
68
- // A day can disappear between listing and opening; real IO failures must stay visible.
69
- if (!isNodeError(error) || error.code !== "ENOENT")
70
- throw error;
71
- }
72
- }
73
- return window;
34
+ /** Read today's journal and, when present, the most recent earlier day for morning backfill (B2). */
35
+ export async function readRecentJournalForBootstrap(deskDir, today = localDayKey()) {
36
+ const [todayText, dates] = await Promise.all([readJournalDay(deskDir, today), listJournalDates(deskDir)]);
37
+ const previousDate = dates.filter((date) => date < today).at(-1);
38
+ if (!previousDate)
39
+ return { todayText };
40
+ const previousText = await readJournalDay(deskDir, previousDate);
41
+ return previousText.trim() ? { todayText, previous: { date: previousDate, text: previousText } } : { todayText };
74
42
  }
75
43
  function normalizeLine(line) {
76
44
  return line
@@ -18,6 +18,7 @@ export interface MemoryLifecycleOptions {
18
18
  getSessionEntries: () => SessionEntry[];
19
19
  getModel: () => Model<Api>;
20
20
  modelRequests: ModelRequests;
21
+ resolveFallbackModel?: () => Promise<Model<Api> | null>;
21
22
  recordMemoryActivity?: (event: MemoryActivityEvent) => Promise<void> | void;
22
23
  memoryQueue?: DeskMemoryQueue;
23
24
  }
@@ -130,6 +130,7 @@ export class MemoryLifecycle {
130
130
  workspaceDir: this.options.workspaceDir,
131
131
  model: this.options.getModel(),
132
132
  modelRequests: this.options.modelRequests,
133
+ resolveFallbackModel: this.options.resolveFallbackModel,
133
134
  messages: sourceWindow.messages,
134
135
  sourceClosed: true,
135
136
  usageContext: {
@@ -190,6 +191,7 @@ export class MemoryLifecycle {
190
191
  appHomeDir: this.options.appHomeDir,
191
192
  model: this.options.getModel(),
192
193
  modelRequests: this.options.modelRequests,
194
+ resolveFallbackModel: this.options.resolveFallbackModel,
193
195
  queue: this.memoryQueue,
194
196
  });
195
197
  }
@@ -23,6 +23,7 @@ export interface ReflectJobInput {
23
23
  };
24
24
  model: Model<Api>;
25
25
  modelRequests: ModelRequests;
26
+ resolveFallbackModel?: () => Promise<Model<Api> | null>;
26
27
  /** Transcript accessors: only called once the gate has decided the job may actually run. */
27
28
  messages: () => AgentMessage[];
28
29
  sessionEntries: () => SessionEntry[];