@oyasmi/pipiclaw 0.5.0 → 0.5.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 (173) hide show
  1. package/dist/agent/channel-runner.d.ts +46 -0
  2. package/dist/agent/channel-runner.d.ts.map +1 -0
  3. package/dist/agent/channel-runner.js +434 -0
  4. package/dist/agent/channel-runner.js.map +1 -0
  5. package/dist/agent/index.d.ts +4 -0
  6. package/dist/agent/index.d.ts.map +1 -0
  7. package/dist/agent/index.js +3 -0
  8. package/dist/agent/index.js.map +1 -0
  9. package/dist/agent/progress-formatter.d.ts +5 -0
  10. package/dist/agent/progress-formatter.d.ts.map +1 -0
  11. package/dist/agent/progress-formatter.js +53 -0
  12. package/dist/agent/progress-formatter.js.map +1 -0
  13. package/dist/agent/run-queue.d.ts +8 -0
  14. package/dist/agent/run-queue.d.ts.map +1 -0
  15. package/dist/agent/run-queue.js +27 -0
  16. package/dist/agent/run-queue.js.map +1 -0
  17. package/dist/agent/runner-factory.d.ts +4 -0
  18. package/dist/agent/runner-factory.d.ts.map +1 -0
  19. package/dist/agent/runner-factory.js +11 -0
  20. package/dist/agent/runner-factory.js.map +1 -0
  21. package/dist/agent/session-events.d.ts +15 -0
  22. package/dist/agent/session-events.d.ts.map +1 -0
  23. package/dist/agent/session-events.js +216 -0
  24. package/dist/agent/session-events.js.map +1 -0
  25. package/dist/agent/type-guards.d.ts +23 -0
  26. package/dist/agent/type-guards.d.ts.map +1 -0
  27. package/dist/agent/type-guards.js +107 -0
  28. package/dist/agent/type-guards.js.map +1 -0
  29. package/dist/agent/types.d.ts +161 -0
  30. package/dist/agent/types.d.ts.map +1 -0
  31. package/dist/agent/types.js +23 -0
  32. package/dist/agent/types.js.map +1 -0
  33. package/dist/agent.d.ts +2 -15
  34. package/dist/agent.d.ts.map +1 -1
  35. package/dist/agent.js +1 -781
  36. package/dist/agent.js.map +1 -1
  37. package/dist/context.d.ts +58 -14
  38. package/dist/context.d.ts.map +1 -1
  39. package/dist/context.js +50 -7
  40. package/dist/context.js.map +1 -1
  41. package/dist/index.d.ts +12 -12
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +12 -12
  44. package/dist/index.js.map +1 -1
  45. package/dist/main.js +5 -404
  46. package/dist/main.js.map +1 -1
  47. package/dist/memory/bootstrap.d.ts +7 -0
  48. package/dist/memory/bootstrap.d.ts.map +1 -0
  49. package/dist/memory/bootstrap.js +47 -0
  50. package/dist/memory/bootstrap.js.map +1 -0
  51. package/dist/{memory-candidates.d.ts → memory/candidates.d.ts} +2 -1
  52. package/dist/memory/candidates.d.ts.map +1 -0
  53. package/dist/{memory-candidates.js → memory/candidates.js} +34 -21
  54. package/dist/memory/candidates.js.map +1 -0
  55. package/dist/memory/chinese-words.d.ts +2 -0
  56. package/dist/memory/chinese-words.d.ts.map +1 -0
  57. package/dist/memory/chinese-words.js +210 -0
  58. package/dist/memory/chinese-words.js.map +1 -0
  59. package/dist/{memory-consolidation.d.ts → memory/consolidation.d.ts} +1 -1
  60. package/dist/memory/consolidation.d.ts.map +1 -0
  61. package/dist/{memory-consolidation.js → memory/consolidation.js} +27 -35
  62. package/dist/memory/consolidation.js.map +1 -0
  63. package/dist/{memory-files.d.ts → memory/files.d.ts} +1 -6
  64. package/dist/memory/files.d.ts.map +1 -0
  65. package/dist/{memory-files.js → memory/files.js} +12 -36
  66. package/dist/memory/files.js.map +1 -0
  67. package/dist/{memory-lifecycle.d.ts → memory/lifecycle.d.ts} +24 -6
  68. package/dist/memory/lifecycle.d.ts.map +1 -0
  69. package/dist/memory/lifecycle.js +247 -0
  70. package/dist/memory/lifecycle.js.map +1 -0
  71. package/dist/{memory-recall.d.ts → memory/recall.d.ts} +2 -2
  72. package/dist/memory/recall.d.ts.map +1 -0
  73. package/dist/memory/recall.js +435 -0
  74. package/dist/memory/recall.js.map +1 -0
  75. package/dist/{session-memory.d.ts → memory/session.d.ts} +2 -1
  76. package/dist/memory/session.d.ts.map +1 -0
  77. package/dist/{session-memory.js → memory/session.js} +32 -62
  78. package/dist/memory/session.js.map +1 -0
  79. package/dist/runtime/bootstrap.d.ts +48 -0
  80. package/dist/runtime/bootstrap.d.ts.map +1 -0
  81. package/dist/runtime/bootstrap.js +451 -0
  82. package/dist/runtime/bootstrap.js.map +1 -0
  83. package/dist/runtime/delivery.d.ts.map +1 -0
  84. package/dist/{delivery.js → runtime/delivery.js} +1 -1
  85. package/dist/runtime/delivery.js.map +1 -0
  86. package/dist/{dingtalk.d.ts → runtime/dingtalk.d.ts} +10 -0
  87. package/dist/runtime/dingtalk.d.ts.map +1 -0
  88. package/dist/{dingtalk.js → runtime/dingtalk.js} +87 -27
  89. package/dist/runtime/dingtalk.js.map +1 -0
  90. package/dist/runtime/events.d.ts.map +1 -0
  91. package/dist/{events.js → runtime/events.js} +1 -1
  92. package/dist/runtime/events.js.map +1 -0
  93. package/dist/{store.d.ts → runtime/store.d.ts} +5 -0
  94. package/dist/runtime/store.d.ts.map +1 -0
  95. package/dist/{store.js → runtime/store.js} +60 -19
  96. package/dist/runtime/store.js.map +1 -0
  97. package/dist/shared/markdown-sections.d.ts +7 -0
  98. package/dist/shared/markdown-sections.d.ts.map +1 -0
  99. package/dist/{markdown-sections.js → shared/markdown-sections.js} +10 -3
  100. package/dist/shared/markdown-sections.js.map +1 -0
  101. package/dist/shared/text-utils.d.ts +10 -0
  102. package/dist/shared/text-utils.d.ts.map +1 -0
  103. package/dist/shared/text-utils.js +37 -0
  104. package/dist/shared/text-utils.js.map +1 -0
  105. package/dist/shared/type-guards.d.ts +6 -0
  106. package/dist/shared/type-guards.d.ts.map +1 -0
  107. package/dist/shared/type-guards.js +13 -0
  108. package/dist/shared/type-guards.js.map +1 -0
  109. package/dist/shared/types.d.ts +15 -0
  110. package/dist/shared/types.d.ts.map +1 -0
  111. package/dist/shared/types.js +2 -0
  112. package/dist/shared/types.js.map +1 -0
  113. package/dist/sidecar-worker.d.ts.map +1 -1
  114. package/dist/sidecar-worker.js +1 -7
  115. package/dist/sidecar-worker.js.map +1 -1
  116. package/dist/{sub-agents.d.ts → subagents/discovery.d.ts} +1 -1
  117. package/dist/subagents/discovery.d.ts.map +1 -0
  118. package/dist/{sub-agents.js → subagents/discovery.js} +3 -3
  119. package/dist/subagents/discovery.js.map +1 -0
  120. package/dist/{tools/subagent.d.ts → subagents/tool.d.ts} +3 -16
  121. package/dist/{tools/subagent.d.ts.map → subagents/tool.d.ts.map} +1 -1
  122. package/dist/{tools/subagent.js → subagents/tool.js} +17 -38
  123. package/dist/subagents/tool.js.map +1 -0
  124. package/dist/tools/index.d.ts +1 -1
  125. package/dist/tools/index.d.ts.map +1 -1
  126. package/dist/tools/index.js +1 -1
  127. package/dist/tools/index.js.map +1 -1
  128. package/docs/memory-audit.md +330 -0
  129. package/docs/memory-optimization-round2.md +319 -0
  130. package/package.json +1 -1
  131. package/dist/delivery.d.ts.map +0 -1
  132. package/dist/delivery.js.map +0 -1
  133. package/dist/dingtalk.d.ts.map +0 -1
  134. package/dist/dingtalk.js.map +0 -1
  135. package/dist/events.d.ts.map +0 -1
  136. package/dist/events.js.map +0 -1
  137. package/dist/markdown-sections.d.ts +0 -6
  138. package/dist/markdown-sections.d.ts.map +0 -1
  139. package/dist/markdown-sections.js.map +0 -1
  140. package/dist/memory-candidates.d.ts.map +0 -1
  141. package/dist/memory-candidates.js.map +0 -1
  142. package/dist/memory-consolidation.d.ts.map +0 -1
  143. package/dist/memory-consolidation.js.map +0 -1
  144. package/dist/memory-files.d.ts.map +0 -1
  145. package/dist/memory-files.js.map +0 -1
  146. package/dist/memory-lifecycle.d.ts.map +0 -1
  147. package/dist/memory-lifecycle.js +0 -150
  148. package/dist/memory-lifecycle.js.map +0 -1
  149. package/dist/memory-recall.d.ts.map +0 -1
  150. package/dist/memory-recall.js +0 -218
  151. package/dist/memory-recall.js.map +0 -1
  152. package/dist/session-memory-files.d.ts +0 -2
  153. package/dist/session-memory-files.d.ts.map +0 -1
  154. package/dist/session-memory-files.js +0 -2
  155. package/dist/session-memory-files.js.map +0 -1
  156. package/dist/session-memory.d.ts.map +0 -1
  157. package/dist/session-memory.js.map +0 -1
  158. package/dist/store.d.ts.map +0 -1
  159. package/dist/store.js.map +0 -1
  160. package/dist/sub-agents.d.ts.map +0 -1
  161. package/dist/sub-agents.js.map +0 -1
  162. package/dist/tools/subagent.js.map +0 -1
  163. package/docs/proj-review.md +0 -188
  164. package/docs/test-supplementation-plan.md +0 -553
  165. /package/dist/{delivery.d.ts → runtime/delivery.d.ts} +0 -0
  166. /package/dist/{events.d.ts → runtime/events.d.ts} +0 -0
  167. /package/docs/{memory-rfc.md → specs/001-implement-memory/memory-rfc.md} +0 -0
  168. /package/docs/{subagent → specs/002-subagent}/pi-subagent-analyse.txt +0 -0
  169. /package/docs/{subagent → specs/002-subagent}/pi-subagent-design.txt +0 -0
  170. /package/docs/{subagent → specs/002-subagent}/pi-subagent-phase1-plan.txt +0 -0
  171. /package/docs/{improve-memory → specs/003-improve-memory}/design.md +0 -0
  172. /package/docs/{improve-memory → specs/003-improve-memory}/interfaces-and-tests.md +0 -0
  173. /package/docs/{improve-memory → specs/003-improve-memory}/spec.md +0 -0
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACjE,OAAO,EACN,0BAA0B,EAC1B,sBAAsB,GAEtB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAgD,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACrH,OAAO,EACN,cAAc,EACd,iBAAiB,EACjB,OAAO,EACP,kBAAkB,GAClB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAIN,uBAAuB,GACvB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAEN,WAAW,GAKX,MAAM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AND_RESULT_CUSTOM_TYPE,\n\tcreateCommandExtension,\n\ttype PipiclawCommandExtensionOptions,\n} from \"./command-extension.js\";\nexport { type BuiltInCommand, type BuiltInCommandName, parseBuiltInCommand, renderBuiltInHelp } from \"./commands.js\";\nexport {\n\tgetAgentConfig,\n\tgetApiKeyForModel,\n\tgetSoul,\n\tloadPipiclawSkills,\n} from \"./config-loader.js\";\nexport {\n\ttype PipiclawMemoryRecallSettings,\n\ttype PipiclawSessionMemorySettings,\n\ttype PipiclawSettings,\n\tPipiclawSettingsManager,\n} from \"./context.js\";\nexport { createDingTalkContext } from \"./delivery.js\";\nexport {\n\ttype BusyMessageMode,\n\tDingTalkBot,\n\ttype DingTalkConfig,\n\ttype DingTalkContext,\n\ttype DingTalkEvent,\n\ttype DingTalkHandler,\n} from \"./dingtalk.js\";\nexport {\n\tcreateEventsWatcher,\n\tEventsWatcher,\n\ttype ImmediateEvent,\n\ttype OneShotEvent,\n\ttype PeriodicEvent,\n\ttype ScheduledEvent,\n} from \"./events.js\";\nexport {\n\ttype BuildMemoryCandidatesOptions,\n\tbuildMemoryCandidates,\n\ttype MemoryCandidate,\n} from \"./memory-candidates.js\";\nexport {\n\ttype BackgroundMaintenanceResult,\n\ttype ConsolidationRunOptions,\n\ttype InlineConsolidationResult,\n\trunBackgroundMaintenance,\n\trunInlineConsolidation,\n} from \"./memory-consolidation.js\";\nexport {\n\tensureChannelMemoryFiles,\n\tensureChannelMemoryFilesSync,\n\tgetChannelSessionPath,\n\treadChannelSession,\n\trewriteChannelSession,\n} from \"./memory-files.js\";\nexport { type ConsolidationReason, MemoryLifecycle, type MemoryLifecycleOptions } from \"./memory-lifecycle.js\";\nexport {\n\ttype RecalledMemory,\n\ttype RecallRequest,\n\ttype RecallResult,\n\trecallRelevantMemory,\n} from \"./memory-recall.js\";\nexport {\n\tfindExactModelReferenceMatch,\n\tformatModelList,\n\tformatModelReference,\n\tresolveInitialModel,\n} from \"./model-utils.js\";\nexport {\n\tAPP_HOME_DIR,\n\tAPP_NAME,\n\tAUTH_CONFIG_PATH,\n\tCHANNEL_CONFIG_PATH,\n\tMODELS_CONFIG_PATH,\n\tSETTINGS_CONFIG_PATH,\n\tSUB_AGENTS_DIR,\n\tSUB_AGENTS_DIR_NAME,\n\tWORKSPACE_DIR,\n} from \"./paths.js\";\nexport { type AppendSystemPromptOptions, buildAppendSystemPrompt } from \"./prompt-builder.js\";\nexport {\n\tcreateExecutor,\n\ttype ExecOptions,\n\ttype ExecResult,\n\ttype Executor,\n\tparseSandboxArg,\n\ttype SandboxConfig,\n\tvalidateSandbox,\n} from \"./sandbox.js\";\nexport {\n\trenderSessionMemory,\n\ttype SessionMemoryState,\n\ttype SessionMemoryUpdateOptions,\n\tupdateChannelSessionMemory,\n} from \"./session-memory.js\";\nexport {\n\trunSidecarTask,\n\ttype SidecarResult,\n\ttype SidecarTask,\n} from \"./sidecar-worker.js\";\nexport { ChannelStore, type LoggedMessage, type LoggedSubAgentRun } from \"./store.js\";\nexport {\n\tdiscoverSubAgents,\n\tformatSubAgentList,\n\tgetSubAgentsDir,\n\ttype ResolvedSubAgentConfig,\n\tresolveSubAgentConfig,\n\ttype SubAgentConfig,\n\ttype SubAgentContextMode,\n\ttype SubAgentDiscoveryResult,\n\ttype SubAgentInvocationOverrides,\n\ttype SubAgentMemoryMode,\n\ttype SubAgentToolName,\n} from \"./sub-agents.js\";\nexport {\n\ttype CreatePipiclawToolsOptions,\n\tcreatePipiclawBaseTools,\n\tcreatePipiclawTools,\n} from \"./tools/index.js\";\nexport {\n\tcreateSubAgentTool,\n\ttype SubAgentToolDetails,\n\ttype SubAgentToolOptions,\n} from \"./tools/subagent.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACjE,OAAO,EACN,0BAA0B,EAC1B,sBAAsB,GAEtB,MAAM,wBAAwB,CAAC;AAChC,OAAO,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,qBAAqB,CAAC;AAC7B,OAAO,EACN,iBAAiB,EACjB,kBAAkB,EAClB,eAAe,EAEf,qBAAqB,GAOrB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACN,kBAAkB,GAGlB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEN,uBAAuB,EACvB,mBAAmB,GACnB,MAAM,kBAAkB,CAAC","sourcesContent":["export { type AgentRunner, getOrCreateRunner } from \"./agent.js\";\nexport {\n\tCOMMAND_RESULT_CUSTOM_TYPE,\n\tcreateCommandExtension,\n\ttype PipiclawCommandExtensionOptions,\n} from \"./command-extension.js\";\nexport { type BuiltInCommand, type BuiltInCommandName, parseBuiltInCommand, renderBuiltInHelp } from \"./commands.js\";\nexport {\n\tgetAgentConfig,\n\tgetApiKeyForModel,\n\tgetSoul,\n\tloadPipiclawSkills,\n} from \"./config-loader.js\";\nexport {\n\ttype PipiclawMemoryRecallSettings,\n\ttype PipiclawSessionMemorySettings,\n\ttype PipiclawSettings,\n\tPipiclawSettingsManager,\n} from \"./context.js\";\nexport {\n\ttype BuildMemoryCandidatesOptions,\n\tbuildMemoryCandidates,\n\ttype MemoryCandidate,\n} from \"./memory/candidates.js\";\nexport {\n\ttype BackgroundMaintenanceResult,\n\ttype ConsolidationRunOptions,\n\ttype InlineConsolidationResult,\n\trunBackgroundMaintenance,\n\trunInlineConsolidation,\n} from \"./memory/consolidation.js\";\nexport {\n\tensureChannelMemoryFiles,\n\tensureChannelMemoryFilesSync,\n\tgetChannelSessionPath,\n\treadChannelSession,\n\trewriteChannelSession,\n} from \"./memory/files.js\";\nexport { type ConsolidationReason, MemoryLifecycle, type MemoryLifecycleOptions } from \"./memory/lifecycle.js\";\nexport {\n\ttype RecalledMemory,\n\ttype RecallRequest,\n\ttype RecallResult,\n\trecallRelevantMemory,\n} from \"./memory/recall.js\";\nexport {\n\trenderSessionMemory,\n\ttype SessionMemoryState,\n\ttype SessionMemoryUpdateOptions,\n\tupdateChannelSessionMemory,\n} from \"./memory/session.js\";\nexport {\n\tfindExactModelReferenceMatch,\n\tformatModelList,\n\tformatModelReference,\n\tresolveInitialModel,\n} from \"./model-utils.js\";\nexport {\n\tAPP_HOME_DIR,\n\tAPP_NAME,\n\tAUTH_CONFIG_PATH,\n\tCHANNEL_CONFIG_PATH,\n\tMODELS_CONFIG_PATH,\n\tSETTINGS_CONFIG_PATH,\n\tSUB_AGENTS_DIR,\n\tSUB_AGENTS_DIR_NAME,\n\tWORKSPACE_DIR,\n} from \"./paths.js\";\nexport { type AppendSystemPromptOptions, buildAppendSystemPrompt } from \"./prompt-builder.js\";\nexport { createDingTalkContext } from \"./runtime/delivery.js\";\nexport {\n\ttype BusyMessageMode,\n\tDingTalkBot,\n\ttype DingTalkConfig,\n\ttype DingTalkContext,\n\ttype DingTalkEvent,\n\ttype DingTalkHandler,\n} from \"./runtime/dingtalk.js\";\nexport {\n\tcreateEventsWatcher,\n\tEventsWatcher,\n\ttype ImmediateEvent,\n\ttype OneShotEvent,\n\ttype PeriodicEvent,\n\ttype ScheduledEvent,\n} from \"./runtime/events.js\";\nexport { ChannelStore, type LoggedMessage, type LoggedSubAgentRun } from \"./runtime/store.js\";\nexport {\n\tcreateExecutor,\n\ttype ExecOptions,\n\ttype ExecResult,\n\ttype Executor,\n\tparseSandboxArg,\n\ttype SandboxConfig,\n\tvalidateSandbox,\n} from \"./sandbox.js\";\nexport {\n\trunSidecarTask,\n\ttype SidecarResult,\n\ttype SidecarTask,\n} from \"./sidecar-worker.js\";\nexport {\n\tdiscoverSubAgents,\n\tformatSubAgentList,\n\tgetSubAgentsDir,\n\ttype ResolvedSubAgentConfig,\n\tresolveSubAgentConfig,\n\ttype SubAgentConfig,\n\ttype SubAgentContextMode,\n\ttype SubAgentDiscoveryResult,\n\ttype SubAgentInvocationOverrides,\n\ttype SubAgentMemoryMode,\n\ttype SubAgentToolName,\n} from \"./subagents/discovery.js\";\nexport {\n\tcreateSubAgentTool,\n\ttype SubAgentToolDetails,\n\ttype SubAgentToolOptions,\n} from \"./subagents/tool.js\";\nexport {\n\ttype CreatePipiclawToolsOptions,\n\tcreatePipiclawBaseTools,\n\tcreatePipiclawTools,\n} from \"./tools/index.js\";\n"]}
package/dist/main.js CHANGED
@@ -1,409 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
3
- import { join } from "path";
4
- import { getOrCreateRunner } from "./agent.js";
5
- import { parseBuiltInCommand } from "./commands.js";
6
- import { createDingTalkContext } from "./delivery.js";
7
- import { DingTalkBot, } from "./dingtalk.js";
8
- import { createEventsWatcher } from "./events.js";
9
- import * as log from "./log.js";
10
- import { ensureChannelMemoryFilesSync } from "./memory-files.js";
11
- import { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SETTINGS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
12
- import { parseSandboxArg, validateSandbox } from "./sandbox.js";
13
- import { ChannelStore } from "./store.js";
14
- if (process.env.DINGTALK_FORCE_PROXY !== "true") {
15
- delete process.env.http_proxy;
16
- delete process.env.https_proxy;
17
- delete process.env.all_proxy;
18
- delete process.env.HTTP_PROXY;
19
- delete process.env.HTTPS_PROXY;
20
- delete process.env.ALL_PROXY;
21
- }
22
- const DEFAULT_SOUL = `# SOUL.md
23
-
24
- Configure Pipiclaw's identity, voice, and communication style here.
25
-
26
- Suggested sections:
27
-
28
- - Who the assistant is
29
- - Default language
30
- - Tone and personality
31
- - Reply style
32
- - Formatting preferences
33
-
34
- Example topics you may want to define:
35
-
36
- - "Answer in Chinese by default."
37
- - "Be concise and direct."
38
- - "Prefer Markdown."
39
- - "Act as an engineering assistant for our team."
40
-
41
- Replace this template with your actual identity prompt.
42
- `;
43
- const DEFAULT_AGENT = `# AGENTS.md
44
-
45
- Configure Pipiclaw's operating rules here.
46
-
47
- This file should define behavior and workflow. Identity, tone, and personality belong in \`SOUL.md\`.
48
-
49
- Suggested sections:
50
-
51
- - Tool usage policy
52
- - Security constraints
53
- - Scheduling/reminder policy
54
- - Project-specific workflows
55
- - Things the assistant must always or never do
56
-
57
- Replace this template with your actual operating instructions.
58
- `;
59
- const DEFAULT_MEMORY = `# Workspace Memory
60
-
61
- This file stores stable workspace-level memory.
62
-
63
- - It is intended to be managed by a human administrator.
64
- - It is not automatically rewritten by normal runtime consolidation.
65
- - Store durable shared background here when it should apply across channels.
66
- - Keep this file focused on stable facts, policies, and shared context, not transient conversation history.
67
-
68
- ## Shared Context
69
-
70
- <!-- Put team-wide or workspace-wide background here. -->
71
-
72
- ## Tooling And Environment
73
-
74
- <!-- Put durable tool usage rules, environment assumptions, or shared operational conventions here. -->
75
-
76
- ## Project Notes
77
-
78
- <!-- Put long-lived project facts here. -->
79
- `;
80
- const CHANNEL_CONFIG_TEMPLATE = {
81
- clientId: "your-dingtalk-client-id",
82
- clientSecret: "your-dingtalk-client-secret",
83
- robotCode: "your-robot-code",
84
- cardTemplateId: "your-card-template-id",
85
- cardTemplateKey: "content",
86
- allowFrom: ["your-staff-id"],
87
- };
88
- const MODELS_CONFIG_TEMPLATE = { providers: {} };
89
- function writeTextFileIfMissing(path, content, label, created) {
90
- if (existsSync(path)) {
91
- return false;
2
+ import { bootstrap, isBootstrapExitError } from "./runtime/bootstrap.js";
3
+ void bootstrap(process.argv).catch((error) => {
4
+ if (isBootstrapExitError(error)) {
5
+ process.exit(error.code);
92
6
  }
93
- writeFileSync(path, content, "utf-8");
94
- created.push(label);
95
- return true;
96
- }
97
- function writeJsonFileIfMissing(path, value, label, created) {
98
- return writeTextFileIfMissing(path, `${JSON.stringify(value, null, 2)}\n`, label, created);
99
- }
100
- function bootstrapAppHome() {
101
- const created = [];
102
- if (!existsSync(APP_HOME_DIR)) {
103
- mkdirSync(APP_HOME_DIR, { recursive: true });
104
- created.push("app home");
105
- }
106
- if (!existsSync(WORKSPACE_DIR)) {
107
- mkdirSync(WORKSPACE_DIR, { recursive: true });
108
- created.push("workspace/");
109
- }
110
- for (const dir of ["skills", "events", "sub-agents"]) {
111
- const dirPath = join(WORKSPACE_DIR, dir);
112
- if (!existsSync(dirPath)) {
113
- mkdirSync(dirPath, { recursive: true });
114
- created.push(`workspace/${dir}/`);
115
- }
116
- }
117
- writeTextFileIfMissing(join(WORKSPACE_DIR, "SOUL.md"), DEFAULT_SOUL, "workspace/SOUL.md", created);
118
- writeTextFileIfMissing(join(WORKSPACE_DIR, "AGENTS.md"), DEFAULT_AGENT, "workspace/AGENTS.md", created);
119
- writeTextFileIfMissing(join(WORKSPACE_DIR, "MEMORY.md"), DEFAULT_MEMORY, "workspace/MEMORY.md", created);
120
- const channelTemplateCreated = writeJsonFileIfMissing(CHANNEL_CONFIG_PATH, CHANNEL_CONFIG_TEMPLATE, "channel.json", created);
121
- writeJsonFileIfMissing(AUTH_CONFIG_PATH, {}, "auth.json", created);
122
- writeJsonFileIfMissing(MODELS_CONFIG_PATH, MODELS_CONFIG_TEMPLATE, "models.json", created);
123
- writeJsonFileIfMissing(SETTINGS_CONFIG_PATH, {}, "settings.json", created);
124
- return { created, channelTemplateCreated };
125
- }
126
- function isPlaceholderString(value) {
127
- return value.trim().startsWith("your-");
128
- }
129
- function listChannelConfigIssues(config) {
130
- const issues = [];
131
- if (!config.clientId) {
132
- issues.push("Missing required field `clientId`.");
133
- }
134
- else if (isPlaceholderString(config.clientId)) {
135
- issues.push("Replace placeholder value for `clientId`.");
136
- }
137
- if (!config.clientSecret) {
138
- issues.push("Missing required field `clientSecret`.");
139
- }
140
- else if (isPlaceholderString(config.clientSecret)) {
141
- issues.push("Replace placeholder value for `clientSecret`.");
142
- }
143
- if (config.robotCode && isPlaceholderString(config.robotCode)) {
144
- issues.push("Replace placeholder value for `robotCode`, or set it to an empty string to reuse `clientId`.");
145
- }
146
- if (config.cardTemplateId && isPlaceholderString(config.cardTemplateId)) {
147
- issues.push("Replace placeholder value for `cardTemplateId`, or set it to an empty string to disable AI Card streaming.");
148
- }
149
- if (Array.isArray(config.allowFrom) && config.allowFrom.some((value) => isPlaceholderString(value))) {
150
- issues.push("Replace placeholder values in `allowFrom`, or set it to an empty array to allow all users.");
151
- }
152
- return issues;
153
- }
154
- function printBootstrapSummary(result) {
155
- if (result.created.length === 0) {
156
- return;
157
- }
158
- console.log(`Initialized ${APP_NAME} under ${APP_HOME_DIR}:`);
159
- for (const item of result.created) {
160
- console.log(` - ${item}`);
161
- }
162
- console.log("");
163
- }
164
- function loadConfig() {
165
- let parsed;
166
- try {
167
- parsed = JSON.parse(readFileSync(CHANNEL_CONFIG_PATH, "utf-8"));
168
- }
169
- catch (err) {
170
- console.error(`Failed to parse configuration: ${CHANNEL_CONFIG_PATH}`);
171
- console.error(err instanceof Error ? err.message : String(err));
172
- process.exit(1);
173
- }
174
- const issues = listChannelConfigIssues(parsed);
175
- if (issues.length > 0) {
176
- console.error(`Configuration is not ready: ${CHANNEL_CONFIG_PATH}`);
177
- for (const issue of issues) {
178
- console.error(` - ${issue}`);
179
- }
180
- console.error("");
181
- console.error(`Fill in ${CHANNEL_CONFIG_PATH} and run \`${APP_NAME}\` again.`);
182
- process.exit(1);
183
- }
184
- parsed.cardTemplateKey = parsed.cardTemplateKey || "content";
185
- parsed.robotCode = parsed.robotCode?.trim() ? parsed.robotCode : parsed.clientId;
186
- if (Array.isArray(parsed.allowFrom)) {
187
- parsed.allowFrom = parsed.allowFrom.filter((value) => value.trim().length > 0);
188
- }
189
- return parsed;
190
- }
191
- function parseArgs() {
192
- const args = process.argv.slice(2);
193
- let sandbox = { type: "host" };
194
- for (let i = 0; i < args.length; i++) {
195
- const arg = args[i];
196
- if (arg.startsWith("--sandbox=")) {
197
- sandbox = parseSandboxArg(arg.slice("--sandbox=".length));
198
- }
199
- else if (arg === "--sandbox") {
200
- sandbox = parseSandboxArg(args[++i] || "");
201
- }
202
- else if (arg === "--help" || arg === "-h") {
203
- console.log(`Usage: ${APP_NAME} [options]`);
204
- console.log("");
205
- console.log("Options:");
206
- console.log(" --sandbox=host Run tools on host (default)");
207
- console.log(" --sandbox=docker:<name> Run tools in Docker container");
208
- console.log("");
209
- console.log(`Config: ${CHANNEL_CONFIG_PATH}`);
210
- console.log(`Workspace: ${WORKSPACE_DIR}`);
211
- process.exit(0);
212
- }
213
- }
214
- return { sandbox };
215
- }
216
- const parsedArgs = parseArgs();
217
- const sandbox = parsedArgs.sandbox;
218
- const bootstrapResult = bootstrapAppHome();
219
- printBootstrapSummary(bootstrapResult);
220
- if (bootstrapResult.channelTemplateCreated) {
221
- console.error(`Fill in ${CHANNEL_CONFIG_PATH} and run \`${APP_NAME}\` again.`);
7
+ console.error(error);
222
8
  process.exit(1);
223
- }
224
- const dingtalkConfig = loadConfig();
225
- dingtalkConfig.stateDir = WORKSPACE_DIR;
226
- await validateSandbox(sandbox);
227
- const channelStates = new Map();
228
- const activeTasks = new Set();
229
- const SHUTDOWN_WAIT_MS = 15000;
230
- const SHUTDOWN_ABORT_WAIT_MS = 5000;
231
- let shuttingDown = false;
232
- let shutdownPromise = null;
233
- function getState(channelId) {
234
- let state = channelStates.get(channelId);
235
- if (!state) {
236
- const channelDir = join(WORKSPACE_DIR, channelId);
237
- ensureChannelMemoryFilesSync(channelDir);
238
- state = {
239
- running: false,
240
- runner: getOrCreateRunner(sandbox, channelId, channelDir),
241
- store: new ChannelStore({ workingDir: WORKSPACE_DIR }),
242
- stopRequested: false,
243
- };
244
- channelStates.set(channelId, state);
245
- }
246
- return state;
247
- }
248
- const handler = {
249
- isRunning(channelId) {
250
- const state = channelStates.get(channelId);
251
- return state?.running ?? false;
252
- },
253
- async handleStop(channelId, _bot) {
254
- const state = channelStates.get(channelId);
255
- if (state?.running) {
256
- state.stopRequested = true;
257
- void state.runner.abort().catch((err) => {
258
- log.logWarning(`[${channelId}] Failed to abort run`, err instanceof Error ? err.message : String(err));
259
- });
260
- log.logInfo(`[${channelId}] Stop requested`);
261
- }
262
- },
263
- async handleBusyMessage(event, bot, mode, queueText) {
264
- if (shuttingDown) {
265
- return;
266
- }
267
- const state = getState(event.channelId);
268
- const trimmedQueueText = queueText.trim();
269
- await state.store.logMessage(event.channelId, {
270
- date: new Date().toISOString(),
271
- ts: event.ts,
272
- user: event.user,
273
- userName: event.userName,
274
- text: event.text,
275
- isBot: false,
276
- deliveryMode: mode,
277
- skipContextSync: true,
278
- });
279
- try {
280
- if (mode === "followUp") {
281
- await state.runner.queueFollowUp(trimmedQueueText, event.userName);
282
- }
283
- else {
284
- await state.runner.queueSteer(trimmedQueueText, event.userName);
285
- }
286
- const confirmation = mode === "followUp"
287
- ? "Queued as follow-up. I’ll handle it after the current task completes."
288
- : event.text.trim().startsWith("/")
289
- ? "Queued as steer. I’ll apply it after the current tool step finishes."
290
- : "Queued as steer. I’ll apply this after the current tool step finishes. Use `/followup <message>` to queue it after completion.";
291
- await bot.sendPlain(event.channelId, confirmation);
292
- log.logInfo(`[${event.channelId}] Queued ${mode}: ${trimmedQueueText.substring(0, 80)}`);
293
- }
294
- catch (err) {
295
- const errMsg = err instanceof Error ? err.message : String(err);
296
- log.logWarning(`[${event.channelId}] Failed to queue ${mode}`, errMsg);
297
- await bot.sendPlain(event.channelId, `Could not queue this message: ${errMsg}`);
298
- }
299
- },
300
- async handleEvent(event, bot, _isEvent) {
301
- if (shuttingDown) {
302
- log.logInfo(`[${event.channelId}] Ignoring event during shutdown`);
303
- return;
304
- }
305
- const state = getState(event.channelId);
306
- const task = (async () => {
307
- state.running = true;
308
- state.stopRequested = false;
309
- await state.store.logMessage(event.channelId, {
310
- date: new Date().toISOString(),
311
- ts: event.ts,
312
- user: event.user,
313
- userName: event.userName,
314
- text: event.text,
315
- isBot: false,
316
- });
317
- try {
318
- const ctx = createDingTalkContext(event, bot, state.store);
319
- const builtInCommand = parseBuiltInCommand(event.text);
320
- if (builtInCommand) {
321
- log.logInfo(`[${event.channelId}] Executing command: ${builtInCommand.rawText}`);
322
- await state.runner.handleBuiltinCommand(ctx, builtInCommand);
323
- return;
324
- }
325
- log.logInfo(`[${event.channelId}] Starting run: ${event.text.substring(0, 50)}`);
326
- const result = await state.runner.run(ctx, state.store);
327
- if (result.stopReason === "aborted" && state.stopRequested) {
328
- log.logInfo(`[${event.channelId}] Stopped`);
329
- }
330
- }
331
- catch (err) {
332
- log.logWarning(`[${event.channelId}] Run error`, err instanceof Error ? err.message : String(err));
333
- }
334
- finally {
335
- state.running = false;
336
- }
337
- })();
338
- activeTasks.add(task);
339
- try {
340
- await task;
341
- }
342
- finally {
343
- activeTasks.delete(task);
344
- }
345
- },
346
- };
347
- log.logStartup(WORKSPACE_DIR, sandbox.type === "host" ? "host" : `docker:${sandbox.container}`);
348
- const bot = new DingTalkBot(handler, dingtalkConfig);
349
- const eventsWatcher = createEventsWatcher(WORKSPACE_DIR, bot);
350
- eventsWatcher.start();
351
- function waitForTasks(tasks, timeoutMs) {
352
- if (tasks.length === 0) {
353
- return Promise.resolve(true);
354
- }
355
- return Promise.race([
356
- Promise.allSettled(tasks).then(() => true),
357
- new Promise((resolve) => {
358
- setTimeout(() => resolve(false), timeoutMs);
359
- }),
360
- ]);
361
- }
362
- async function shutdown(signal) {
363
- if (shutdownPromise) {
364
- return shutdownPromise;
365
- }
366
- shutdownPromise = (async () => {
367
- shuttingDown = true;
368
- log.logInfo(`Shutting down (${signal})...`);
369
- eventsWatcher.stop();
370
- await bot.stop();
371
- const runningTasks = Array.from(activeTasks);
372
- if (runningTasks.length > 0) {
373
- log.logInfo(`Waiting for ${runningTasks.length} active task(s) to finish`);
374
- const completed = await waitForTasks(runningTasks, SHUTDOWN_WAIT_MS);
375
- if (!completed) {
376
- log.logWarning(`Shutdown grace period exceeded ${SHUTDOWN_WAIT_MS}ms, aborting active runs`);
377
- const aborts = [];
378
- for (const [channelId, state] of channelStates) {
379
- if (!state.running)
380
- continue;
381
- state.stopRequested = true;
382
- log.logInfo(`[${channelId}] Aborting active run for shutdown`);
383
- aborts.push(state.runner.abort().catch((err) => {
384
- log.logWarning(`[${channelId}] Failed to abort run during shutdown`, err instanceof Error ? err.message : String(err));
385
- }));
386
- }
387
- await Promise.allSettled(aborts);
388
- const remainingTasks = Array.from(activeTasks);
389
- if (remainingTasks.length > 0) {
390
- const abortedCompleted = await waitForTasks(remainingTasks, SHUTDOWN_ABORT_WAIT_MS);
391
- if (!abortedCompleted) {
392
- log.logWarning(`Shutdown forced exit with ${remainingTasks.length} task(s) still active`);
393
- }
394
- }
395
- }
396
- }
397
- })().finally(() => {
398
- process.exit(0);
399
- });
400
- return shutdownPromise;
401
- }
402
- process.once("SIGINT", () => {
403
- void shutdown("SIGINT");
404
- });
405
- process.once("SIGTERM", () => {
406
- void shutdown("SIGTERM");
407
9
  });
408
- void bot.start();
409
10
  //# sourceMappingURL=main.js.map
package/dist/main.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACxE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAoB,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAEN,WAAW,GAIX,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EACN,YAAY,EACZ,QAAQ,EACR,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,aAAa,GACb,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,eAAe,EAAsB,eAAe,EAAE,MAAM,cAAc,CAAC;AACpF,OAAO,EAAE,YAAY,EAAE,MAAM,Y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{ existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { type AgentRunner, getOrCreateRunner } from \"./agent.js\";\nimport { parseBuiltInCommand } from \"./commands.js\";\nimport { createDingTalkContext } from \"./delivery.js\";\nimport {\n\ttype BusyMessageMode,\n\tDingTalkBot,\n\ttype DingTalkConfig,\n\ttype DingTalkEvent,\n\ttype DingTalkHandler,\n} from \"./dingtalk.js\";\nimport { createEventsWatcher } from \"./events.js\";\nimport * as log from \"./log.js\";\nimport { ensureChannelMemoryFilesSync } from \"./memory-files.js\";\nimport {\n\tAPP_HOME_DIR,\n\tAPP_NAME,\n\tAUTH_CONFIG_PATH,\n\tCHANNEL_CONFIG_PATH,\n\tMODELS_CONFIG_PATH,\n\tSETTINGS_CONFIG_PATH,\n\tWORKSPACE_DIR,\n} from \"./paths.js\";\nimport { parseSandboxArg, type SandboxConfig, validateSandbox } from \"./sandbox.js\";\nimport { ChannelStore } from \"./store.js\";\n\nif (process.env.DINGTALK_FORCE_PROXY !== \"true\") {\n\tdelete process.env.http_proxy;\n\tdelete process.env.https_proxy;\n\tdelete process.env.all_proxy;\n\tdelete process.env.HTTP_PROXY;\n\tdelete process.env.HTTPS_PROXY;\n\tdelete process.env.ALL_PROXY;\n}\n\ninterface ParsedArgs {\n\tsandbox: SandboxConfig;\n}\n\ninterface BootstrapResult {\n\tcreated: string[];\n\tchannelTemplateCreated: boolean;\n}\n\nconst DEFAULT_SOUL = `# SOUL.md\n\nConfigure Pipiclaw's identity, voice, and communication style here.\n\nSuggested sections:\n\n- Who the assistant is\n- Default language\n- Tone and personality\n- Reply style\n- Formatting preferences\n\nExample topics you may want to define:\n\n- \"Answer in Chinese by default.\"\n- \"Be concise and direct.\"\n- \"Prefer Markdown.\"\n- \"Act as an engineering assistant for our team.\"\n\nReplace this template with your actual identity prompt.\n`;\n\nconst DEFAULT_AGENT = `# AGENTS.md\n\nConfigure Pipiclaw's operating rules here.\n\nThis file should define behavior and workflow. Identity, tone, and personality belong in \\`SOUL.md\\`.\n\nSuggested sections:\n\n- Tool usage policy\n- Security constraints\n- Scheduling/reminder policy\n- Project-specific workflows\n- Things the assistant must always or never do\n\nReplace this template with your actual operating instructions.\n`;\n\nconst DEFAULT_MEMORY = `# Workspace Memory\n\nThis file stores stable workspace-level memory.\n\n- It is intended to be managed by a human administrator.\n- It is not automatically rewritten by normal runtime consolidation.\n- Store durable shared background here when it should apply across channels.\n- Keep this file focused on stable facts, policies, and shared context, not transient conversation history.\n\n## Shared Context\n\n<!-- Put team-wide or workspace-wide background here. -->\n\n## Tooling And Environment\n\n<!-- Put durable tool usage rules, environment assumptions, or shared operational conventions here. -->\n\n## Project Notes\n\n<!-- Put long-lived project facts here. -->\n`;\n\nconst CHANNEL_CONFIG_TEMPLATE = {\n\tclientId: \"your-dingtalk-client-id\",\n\tclientSecret: \"your-dingtalk-client-secret\",\n\trobotCode: \"your-robot-code\",\n\tcardTemplateId: \"your-card-template-id\",\n\tcardTemplateKey: \"content\",\n\tallowFrom: [\"your-staff-id\"],\n} satisfies DingTalkConfig;\n\nconst MODELS_CONFIG_TEMPLATE = { providers: {} };\n\nfunction writeTextFileIfMissing(path: string, content: string, label: string, created: string[]): boolean {\n\tif (existsSync(path)) {\n\t\treturn false;\n\t}\n\twriteFileSync(path, content, \"utf-8\");\n\tcreated.push(label);\n\treturn true;\n}\n\nfunction writeJsonFileIfMissing(path: string, value: unknown, label: string, created: string[]): boolean {\n\treturn writeTextFileIfMissing(path, `${JSON.stringify(value, null, 2)}\\n`, label, created);\n}\n\nfunction bootstrapAppHome(): BootstrapResult {\n\tconst created: string[] = [];\n\n\tif (!existsSync(APP_HOME_DIR)) {\n\t\tmkdirSync(APP_HOME_DIR, { recursive: true });\n\t\tcreated.push(\"app home\");\n\t}\n\tif (!existsSync(WORKSPACE_DIR)) {\n\t\tmkdirSync(WORKSPACE_DIR, { recursive: true });\n\t\tcreated.push(\"workspace/\");\n\t}\n\n\tfor (const dir of [\"skills\", \"events\", \"sub-agents\"]) {\n\t\tconst dirPath = join(WORKSPACE_DIR, dir);\n\t\tif (!existsSync(dirPath)) {\n\t\t\tmkdirSync(dirPath, { recursive: true });\n\t\t\tcreated.push(`workspace/${dir}/`);\n\t\t}\n\t}\n\n\twriteTextFileIfMissing(join(WORKSPACE_DIR, \"SOUL.md\"), DEFAULT_SOUL, \"workspace/SOUL.md\", created);\n\twriteTextFileIfMissing(join(WORKSPACE_DIR, \"AGENTS.md\"), DEFAULT_AGENT, \"workspace/AGENTS.md\", created);\n\twriteTextFileIfMissing(join(WORKSPACE_DIR, \"MEMORY.md\"), DEFAULT_MEMORY, \"workspace/MEMORY.md\", created);\n\n\tconst channelTemplateCreated = writeJsonFileIfMissing(\n\t\tCHANNEL_CONFIG_PATH,\n\t\tCHANNEL_CONFIG_TEMPLATE,\n\t\t\"channel.json\",\n\t\tcreated,\n\t);\n\twriteJsonFileIfMissing(AUTH_CONFIG_PATH, {}, \"auth.json\", created);\n\twriteJsonFileIfMissing(MODELS_CONFIG_PATH, MODELS_CONFIG_TEMPLATE, \"models.json\", created);\n\twriteJsonFileIfMissing(SETTINGS_CONFIG_PATH, {}, \"settings.json\", created);\n\n\treturn { created, channelTemplateCreated };\n}\n\nfunction isPlaceholderString(value: string): boolean {\n\treturn value.trim().startsWith(\"your-\");\n}\n\nfunction listChannelConfigIssues(config: Partial<DingTalkConfig>): string[] {\n\tconst issues: string[] = [];\n\n\tif (!config.clientId) {\n\t\tissues.push(\"Missing required field `clientId`.\");\n\t} else if (isPlaceholderString(config.clientId)) {\n\t\tissues.push(\"Replace placeholder value for `clientId`.\");\n\t}\n\n\tif (!config.clientSecret) {\n\t\tissues.push(\"Missing required field `clientSecret`.\");\n\t} else if (isPlaceholderString(config.clientSecret)) {\n\t\tissues.push(\"Replace placeholder value for `clientSecret`.\");\n\t}\n\n\tif (config.robotCode && isPlaceholderString(config.robotCode)) {\n\t\tissues.push(\"Replace placeholder value for `robotCode`, or set it to an empty string to reuse `clientId`.\");\n\t}\n\n\tif (config.cardTemplateId && isPlaceholderString(config.cardTemplateId)) {\n\t\tissues.push(\n\t\t\t\"Replace placeholder value for `cardTemplateId`, or set it to an empty string to disable AI Card streaming.\",\n\t\t);\n\t}\n\n\tif (Array.isArray(config.allowFrom) && config.allowFrom.some((value) => isPlaceholderString(value))) {\n\t\tissues.push(\"Replace placeholder values in `allowFrom`, or set it to an empty array to allow all users.\");\n\t}\n\n\treturn issues;\n}\n\nfunction printBootstrapSummary(result: BootstrapResult): void {\n\tif (result.created.length === 0) {\n\t\treturn;\n\t}\n\n\tconsole.log(`Initialized ${APP_NAME} under ${APP_HOME_DIR}:`);\n\tfor (const item of result.created) {\n\t\tconsole.log(` - ${item}`);\n\t}\n\tconsole.log(\"\");\n}\n\nfunction loadConfig(): DingTalkConfig {\n\tlet parsed: DingTalkConfig;\n\n\ttry {\n\t\tparsed = JSON.parse(readFileSync(CHANNEL_CONFIG_PATH, \"utf-8\")) as DingTalkConfig;\n\t} catch (err) {\n\t\tconsole.error(`Failed to parse configuration: ${CHANNEL_CONFIG_PATH}`);\n\t\tconsole.error(err instanceof Error ? err.message : String(err));\n\t\tprocess.exit(1);\n\t}\n\n\tconst issues = listChannelConfigIssues(parsed);\n\tif (issues.length > 0) {\n\t\tconsole.error(`Configuration is not ready: ${CHANNEL_CONFIG_PATH}`);\n\t\tfor (const issue of issues) {\n\t\t\tconsole.error(` - ${issue}`);\n\t\t}\n\t\tconsole.error(\"\");\n\t\tconsole.error(`Fill in ${CHANNEL_CONFIG_PATH} and run \\`${APP_NAME}\\` again.`);\n\t\tprocess.exit(1);\n\t}\n\n\tparsed.cardTemplateKey = parsed.cardTemplateKey || \"content\";\n\tparsed.robotCode = parsed.robotCode?.trim() ? parsed.robotCode : parsed.clientId;\n\tif (Array.isArray(parsed.allowFrom)) {\n\t\tparsed.allowFrom = parsed.allowFrom.filter((value) => value.trim().length > 0);\n\t}\n\n\treturn parsed;\n}\n\nfunction parseArgs(): ParsedArgs {\n\tconst args = process.argv.slice(2);\n\tlet sandbox: SandboxConfig = { type: \"host\" };\n\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\t\tif (arg.startsWith(\"--sandbox=\")) {\n\t\t\tsandbox = parseSandboxArg(arg.slice(\"--sandbox=\".length));\n\t\t} else if (arg === \"--sandbox\") {\n\t\t\tsandbox = parseSandboxArg(args[++i] || \"\");\n\t\t} else if (arg === \"--help\" || arg === \"-h\") {\n\t\t\tconsole.log(`Usage: ${APP_NAME} [options]`);\n\t\t\tconsole.log(\"\");\n\t\t\tconsole.log(\"Options:\");\n\t\t\tconsole.log(\" --sandbox=host Run tools on host (default)\");\n\t\t\tconsole.log(\" --sandbox=docker:<name> Run tools in Docker container\");\n\t\t\tconsole.log(\"\");\n\t\t\tconsole.log(`Config: ${CHANNEL_CONFIG_PATH}`);\n\t\t\tconsole.log(`Workspace: ${WORKSPACE_DIR}`);\n\t\t\tprocess.exit(0);\n\t\t}\n\t}\n\n\treturn { sandbox };\n}\n\nconst parsedArgs = parseArgs();\nconst sandbox = parsedArgs.sandbox;\nconst bootstrapResult = bootstrapAppHome();\nprintBootstrapSummary(bootstrapResult);\n\nif (bootstrapResult.channelTemplateCreated) {\n\tconsole.error(`Fill in ${CHANNEL_CONFIG_PATH} and run \\`${APP_NAME}\\` again.`);\n\tprocess.exit(1);\n}\n\nconst dingtalkConfig = loadConfig();\ndingtalkConfig.stateDir = WORKSPACE_DIR;\n\nawait validateSandbox(sandbox);\n\ninterface ChannelState {\n\trunning: boolean;\n\trunner: AgentRunner;\n\tstore: ChannelStore;\n\tstopRequested: boolean;\n}\n\nconst channelStates = new Map<string, ChannelState>();\nconst activeTasks = new Set<Promise<void>>();\nconst SHUTDOWN_WAIT_MS = 15000;\nconst SHUTDOWN_ABORT_WAIT_MS = 5000;\nlet shuttingDown = false;\nlet shutdownPromise: Promise<void> | null = null;\n\nfunction getState(channelId: string): ChannelState {\n\tlet state = channelStates.get(channelId);\n\tif (!state) {\n\t\tconst channelDir = join(WORKSPACE_DIR, channelId);\n\t\tensureChannelMemoryFilesSync(channelDir);\n\t\tstate = {\n\t\t\trunning: false,\n\t\t\trunner: getOrCreateRunner(sandbox, channelId, channelDir),\n\t\t\tstore: new ChannelStore({ workingDir: WORKSPACE_DIR }),\n\t\t\tstopRequested: false,\n\t\t};\n\t\tchannelStates.set(channelId, state);\n\t}\n\treturn state;\n}\n\nconst handler: DingTalkHandler = {\n\tisRunning(channelId: string): boolean {\n\t\tconst state = channelStates.get(channelId);\n\t\treturn state?.running ?? false;\n\t},\n\n\tasync handleStop(channelId: string, _bot: DingTalkBot): Promise<void> {\n\t\tconst state = channelStates.get(channelId);\n\t\tif (state?.running) {\n\t\t\tstate.stopRequested = true;\n\t\t\tvoid state.runner.abort().catch((err) => {\n\t\t\t\tlog.logWarning(`[${channelId}] Failed to abort run`, err instanceof Error ? err.message : String(err));\n\t\t\t});\n\t\t\tlog.logInfo(`[${channelId}] Stop requested`);\n\t\t}\n\t},\n\n\tasync handleBusyMessage(\n\t\tevent: DingTalkEvent,\n\t\tbot: DingTalkBot,\n\t\tmode: BusyMessageMode,\n\t\tqueueText: string,\n\t): Promise<void> {\n\t\tif (shuttingDown) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst state = getState(event.channelId);\n\t\tconst trimmedQueueText = queueText.trim();\n\n\t\tawait state.store.logMessage(event.channelId, {\n\t\t\tdate: new Date().toISOString(),\n\t\t\tts: event.ts,\n\t\t\tuser: event.user,\n\t\t\tuserName: event.userName,\n\t\t\ttext: event.text,\n\t\t\tisBot: false,\n\t\t\tdeliveryMode: mode,\n\t\t\tskipContextSync: true,\n\t\t});\n\n\t\ttry {\n\t\t\tif (mode === \"followUp\") {\n\t\t\t\tawait state.runner.queueFollowUp(trimmedQueueText, event.userName);\n\t\t\t} else {\n\t\t\t\tawait state.runner.queueSteer(trimmedQueueText, event.userName);\n\t\t\t}\n\n\t\t\tconst confirmation =\n\t\t\t\tmode === \"followUp\"\n\t\t\t\t\t? \"Queued as follow-up. I’ll handle it after the current task completes.\"\n\t\t\t\t\t: event.text.trim().startsWith(\"/\")\n\t\t\t\t\t\t? \"Queued as steer. I’ll apply it after the current tool step finishes.\"\n\t\t\t\t\t\t: \"Queued as steer. I’ll apply this after the current tool step finishes. Use `/followup <message>` to queue it after completion.\";\n\t\t\tawait bot.sendPlain(event.channelId, confirmation);\n\t\t\tlog.logInfo(`[${event.channelId}] Queued ${mode}: ${trimmedQueueText.substring(0, 80)}`);\n\t\t} catch (err) {\n\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\tlog.logWarning(`[${event.channelId}] Failed to queue ${mode}`, errMsg);\n\t\t\tawait bot.sendPlain(event.channelId, `Could not queue this message: ${errMsg}`);\n\t\t}\n\t},\n\n\tasync handleEvent(event: DingTalkEvent, bot: DingTalkBot, _isEvent?: boolean): Promise<void> {\n\t\tif (shuttingDown) {\n\t\t\tlog.logInfo(`[${event.channelId}] Ignoring event during shutdown`);\n\t\t\treturn;\n\t\t}\n\n\t\tconst state = getState(event.channelId);\n\t\tconst task = (async () => {\n\t\t\tstate.running = true;\n\t\t\tstate.stopRequested = false;\n\n\t\t\tawait state.store.logMessage(event.channelId, {\n\t\t\t\tdate: new Date().toISOString(),\n\t\t\t\tts: event.ts,\n\t\t\t\tuser: event.user,\n\t\t\t\tuserName: event.userName,\n\t\t\t\ttext: event.text,\n\t\t\t\tisBot: false,\n\t\t\t});\n\n\t\t\ttry {\n\t\t\t\tconst ctx = createDingTalkContext(event, bot, state.store);\n\t\t\t\tconst builtInCommand = parseBuiltInCommand(event.text);\n\n\t\t\t\tif (builtInCommand) {\n\t\t\t\t\tlog.logInfo(`[${event.channelId}] Executing command: ${builtInCommand.rawText}`);\n\t\t\t\t\tawait state.runner.handleBuiltinCommand(ctx, builtInCommand);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlog.logInfo(`[${event.channelId}] Starting run: ${event.text.substring(0, 50)}`);\n\t\t\t\tconst result = await state.runner.run(ctx, state.store);\n\n\t\t\t\tif (result.stopReason === \"aborted\" && state.stopRequested) {\n\t\t\t\t\tlog.logInfo(`[${event.channelId}] Stopped`);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tlog.logWarning(`[${event.channelId}] Run error`, err instanceof Error ? err.message : String(err));\n\t\t\t} finally {\n\t\t\t\tstate.running = false;\n\t\t\t}\n\t\t})();\n\n\t\tactiveTasks.add(task);\n\t\ttry {\n\t\t\tawait task;\n\t\t} finally {\n\t\t\tactiveTasks.delete(task);\n\t\t}\n\t},\n};\n\nlog.logStartup(WORKSPACE_DIR, sandbox.type === \"host\" ? \"host\" : `docker:${sandbox.container}`);\n\nconst bot = new DingTalkBot(handler, dingtalkConfig);\nconst eventsWatcher = createEventsWatcher(WORKSPACE_DIR, bot);\neventsWatcher.start();\n\nfunction waitForTasks(tasks: Promise<void>[], timeoutMs: number): Promise<boolean> {\n\tif (tasks.length === 0) {\n\t\treturn Promise.resolve(true);\n\t}\n\n\treturn Promise.race([\n\t\tPromise.allSettled(tasks).then(() => true),\n\t\tnew Promise<boolean>((resolve) => {\n\t\t\tsetTimeout(() => resolve(false), timeoutMs);\n\t\t}),\n\t]);\n}\n\nasync function shutdown(signal: NodeJS.Signals): Promise<void> {\n\tif (shutdownPromise) {\n\t\treturn shutdownPromise;\n\t}\n\n\tshutdownPromise = (async () => {\n\t\tshuttingDown = true;\n\t\tlog.logInfo(`Shutting down (${signal})...`);\n\n\t\teventsWatcher.stop();\n\t\tawait bot.stop();\n\n\t\tconst runningTasks = Array.from(activeTasks);\n\t\tif (runningTasks.length > 0) {\n\t\t\tlog.logInfo(`Waiting for ${runningTasks.length} active task(s) to finish`);\n\t\t\tconst completed = await waitForTasks(runningTasks, SHUTDOWN_WAIT_MS);\n\n\t\t\tif (!completed) {\n\t\t\t\tlog.logWarning(`Shutdown grace period exceeded ${SHUTDOWN_WAIT_MS}ms, aborting active runs`);\n\t\t\t\tconst aborts: Promise<void>[] = [];\n\t\t\t\tfor (const [channelId, state] of channelStates) {\n\t\t\t\t\tif (!state.running) continue;\n\t\t\t\t\tstate.stopRequested = true;\n\t\t\t\t\tlog.logInfo(`[${channelId}] Aborting active run for shutdown`);\n\t\t\t\t\taborts.push(\n\t\t\t\t\t\tstate.runner.abort().catch((err) => {\n\t\t\t\t\t\t\tlog.logWarning(\n\t\t\t\t\t\t\t\t`[${channelId}] Failed to abort run during shutdown`,\n\t\t\t\t\t\t\t\terr instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait Promise.allSettled(aborts);\n\n\t\t\t\tconst remainingTasks = Array.from(activeTasks);\n\t\t\t\tif (remainingTasks.length > 0) {\n\t\t\t\t\tconst abortedCompleted = await waitForTasks(remainingTasks, SHUTDOWN_ABORT_WAIT_MS);\n\t\t\t\t\tif (!abortedCompleted) {\n\t\t\t\t\t\tlog.logWarning(`Shutdown forced exit with ${remainingTasks.length} task(s) still active`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})().finally(() => {\n\t\tprocess.exit(0);\n\t});\n\n\treturn shutdownPromise;\n}\n\nprocess.once(\"SIGINT\", () => {\n\tvoid shutdown(\"SIGINT\");\n});\n\nprocess.once(\"SIGTERM\", () => {\n\tvoid shutdown(\"SIGTERM\");\n});\n\nvoid bot.start();\n"]}
1
+ {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAEzE,KAAK,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IACrD,IAAI,oBAAoB,CAAC,KAAK,CAAC,EAAE,CAAC;QACjC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;IAED,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACrB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACjB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport { bootstrap, isBootstrapExitError } from \"./runtime/bootstrap.js\";\n\nvoid bootstrap(process.argv).catch((error: unknown) => {\n\tif (isBootstrapExitError(error)) {\n\t\tprocess.exit(error.code);\n\t}\n\n\tconsole.error(error);\n\tprocess.exit(1);\n});\n"]}
@@ -0,0 +1,7 @@
1
+ export interface FirstTurnMemoryBootstrapOptions {
2
+ channelMemory: string;
3
+ workspaceMemory: string;
4
+ maxChars?: number;
5
+ }
6
+ export declare function buildFirstTurnMemoryBootstrap(options: FirstTurnMemoryBootstrapOptions): string;
7
+ //# sourceMappingURL=bootstrap.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../../src/memory/bootstrap.ts"],"names":[],"mappings":"AA2BA,MAAM,WAAW,+BAA+B;IAC/C,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,wBAAgB,6BAA6B,CAAC,OAAO,EAAE,+BAA+B,GAAG,MAAM,CA8B9F"}
@@ -0,0 +1,47 @@
1
+ import { clipText } from "../shared/text-utils.js";
2
+ const FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS = 3_000;
3
+ const MIN_SECTION_BUDGET = 600;
4
+ const CHANNEL_MEMORY_WEIGHT = 0.6;
5
+ function normalizeContent(content) {
6
+ return content.replace(/\r/g, "").trim();
7
+ }
8
+ function allocateBudgets(channelMemory, workspaceMemory, maxChars) {
9
+ if (!channelMemory && !workspaceMemory) {
10
+ return [0, 0];
11
+ }
12
+ if (!channelMemory) {
13
+ return [0, maxChars];
14
+ }
15
+ if (!workspaceMemory) {
16
+ return [maxChars, 0];
17
+ }
18
+ const channelBudget = Math.max(MIN_SECTION_BUDGET, Math.floor(maxChars * CHANNEL_MEMORY_WEIGHT));
19
+ const workspaceBudget = Math.max(MIN_SECTION_BUDGET, maxChars - channelBudget);
20
+ const remainder = maxChars - channelBudget - workspaceBudget;
21
+ return [channelBudget + Math.max(0, remainder), workspaceBudget];
22
+ }
23
+ export function buildFirstTurnMemoryBootstrap(options) {
24
+ const maxChars = options.maxChars ?? FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS;
25
+ const channelMemory = normalizeContent(options.channelMemory);
26
+ const workspaceMemory = normalizeContent(options.workspaceMemory);
27
+ if (!channelMemory && !workspaceMemory) {
28
+ return "";
29
+ }
30
+ const [channelBudget, workspaceBudget] = allocateBudgets(channelMemory, workspaceMemory, maxChars);
31
+ const sections = [
32
+ "<durable_memory_snapshot>",
33
+ "Durable memory bootstrap for the first user turn in this session.",
34
+ "Use it as background context together with any turn-specific recalled snippets.",
35
+ ];
36
+ if (channelMemory) {
37
+ sections.push("", "[Channel MEMORY.md]");
38
+ sections.push(channelBudget > 0 ? clipText(channelMemory, channelBudget, { headRatio: 1 }) : channelMemory);
39
+ }
40
+ if (workspaceMemory) {
41
+ sections.push("", "[Workspace MEMORY.md]");
42
+ sections.push(workspaceBudget > 0 ? clipText(workspaceMemory, workspaceBudget, { headRatio: 1 }) : workspaceMemory);
43
+ }
44
+ sections.push("</durable_memory_snapshot>");
45
+ return sections.join("\n");
46
+ }
47
+ //# sourceMappingURL=bootstrap.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../src/memory/bootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AAEnD,MAAM,oCAAoC,GAAG,KAAK,CAAC;AACnD,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAElC,SAAS,gBAAgB,CAAC,OAAe;IACxC,OAAO,OAAO,CAA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,EAAE,eAAe,EAAE,QAAQ,CAAC,CAAC;IACnG,MAAM,QAAQ,GAAa;QAC1B,2BAA2B;QAC3B,mEAAmE;QACnE,iFAAiF;KACjF,CAAC;IAEF,IAAI,aAAa,EAAE,CAAC;QACnB,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,qBAAqB,CAAC,CAAC;QACzC,QAAQ,CAAC,IAAI,CAAC,aAAa,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,aAAa,EAAE,aAAa,EAAE,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC;IAC7G,CAAC;IAED,IAAI,eAAe,EAAE,CAAC;QACrB,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,uBAAuB,CAAC,CAAC;QAC3C,QAAQ,CAAC,IAAI,CACZ,eAAe,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,eAAe,EAAE,eAAe,EAAE,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,eAAe,CACpG,CAAC;IACH,CAAC;IAED,QAAQ,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;IAC5C,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import { clipText } from \"../shared/text-utils.js\";\n\nconst FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS = 3_000;\nconst MIN_SECTION_BUDGET = 600;\nconst CHANNEL_MEMORY_WEIGHT = 0.6;\n\nfunction normalizeContent(content: string): string {\n\treturn content.replace(/\\r/g, \"\").trim();\n}\n\nfunction allocateBudgets(channelMemory: string, workspaceMemory: string, maxChars: number): [number, number] {\n\tif (!channelMemory && !workspaceMemory) {\n\t\treturn [0, 0];\n\t}\n\tif (!channelMemory) {\n\t\treturn [0, maxChars];\n\t}\n\tif (!workspaceMemory) {\n\t\treturn [maxChars, 0];\n\t}\n\n\tconst channelBudget = Math.max(MIN_SECTION_BUDGET, Math.floor(maxChars * CHANNEL_MEMORY_WEIGHT));\n\tconst workspaceBudget = Math.max(MIN_SECTION_BUDGET, maxChars - channelBudget);\n\tconst remainder = maxChars - channelBudget - workspaceBudget;\n\treturn [channelBudget + Math.max(0, remainder), workspaceBudget];\n}\n\nexport interface FirstTurnMemoryBootstrapOptions {\n\tchannelMemory: string;\n\tworkspaceMemory: string;\n\tmaxChars?: number;\n}\n\nexport function buildFirstTurnMemoryBootstrap(options: FirstTurnMemoryBootstrapOptions): string {\n\tconst maxChars = options.maxChars ?? FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS;\n\tconst channelMemory = normalizeContent(options.channelMemory);\n\tconst workspaceMemory = normalizeContent(options.workspaceMemory);\n\n\tif (!channelMemory && !workspaceMemory) {\n\t\treturn \"\";\n\t}\n\n\tconst [channelBudget, workspaceBudget] = allocateBudgets(channelMemory, workspaceMemory, maxChars);\n\tconst sections: string[] = [\n\t\t\"<durable_memory_snapshot>\",\n\t\t\"Durable memory bootstrap for the first user turn in this session.\",\n\t\t\"Use it as background context together with any turn-specific recalled snippets.\",\n\t];\n\n\tif (channelMemory) {\n\t\tsections.push(\"\", \"[Channel MEMORY.md]\");\n\t\tsections.push(channelBudget > 0 ? clipText(channelMemory, channelBudget, { headRatio: 1 }) : channelMemory);\n\t}\n\n\tif (workspaceMemory) {\n\t\tsections.push(\"\", \"[Workspace MEMORY.md]\");\n\t\tsections.push(\n\t\t\tworkspaceBudget > 0 ? clipText(workspaceMemory, workspaceBudget, { headRatio: 1 }) : workspaceMemory,\n\t\t);\n\t}\n\n\tsections.push(\"</durable_memory_snapshot>\");\n\treturn sections.join(\"\\n\");\n}\n"]}
@@ -4,6 +4,7 @@ export interface MemoryCandidate {
4
4
  path: string;
5
5
  title: string;
6
6
  content: string;
7
+ searchText?: string;
7
8
  timestamp?: string;
8
9
  sectionKind?: string;
9
10
  priority: number;
@@ -18,4 +19,4 @@ export interface MemoryCandidateCache {
18
19
  }
19
20
  export declare function createMemoryCandidateCache(): MemoryCandidateCache;
20
21
  export declare function buildMemoryCandidates(options: BuildMemoryCandidatesOptions): Promise<MemoryCandidate[]>;
21
- //# sourceMappingURL=memory-candidates.d.ts.map
22
+ //# sourceMappingURL=candidates.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"candidates.d.ts","sourceRoot":"","sources":["../../src/memory/candidates.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,eAAe;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,kBAAkB,GAAG,gBAAgB,GAAG,iBAAiB,GAAG,iBAAiB,CAAC;IACtF,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,4BAA4B;IAC5C,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,oBAAoB,CAAC;CAC7B;AAED,MAAM,WAAW,oBAAoB;IACpC,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,eAAe,EAAE,CAAC,CAAC,CAAC;CACjD;AAED,wBAAgB,0BAA0B,IAAI,oBAAoB,CAIjE;AAyID,wBAAsB,qBAAqB,CAAC,OAAO,EAAE,4BAA4B,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC,CAiB7G"}