memeloop 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (228) hide show
  1. package/README.md +63 -0
  2. package/dist/browser.cjs +1413 -0
  3. package/dist/browser.cjs.map +1 -0
  4. package/dist/browser.d.cts +3066 -0
  5. package/dist/browser.d.ts +3066 -0
  6. package/dist/browser.js +43 -0
  7. package/dist/chunk-426CJUZP.js +630 -0
  8. package/dist/chunk-426CJUZP.js.map +1 -0
  9. package/dist/chunk-44YHBKDL.js +382 -0
  10. package/dist/chunk-44YHBKDL.js.map +1 -0
  11. package/dist/chunk-7ZDTB4VZ.js +63 -0
  12. package/dist/chunk-7ZDTB4VZ.js.map +1 -0
  13. package/dist/chunk-AZFYDWIN.js +98 -0
  14. package/dist/chunk-AZFYDWIN.js.map +1 -0
  15. package/dist/chunk-BGPU4RR7.js +367 -0
  16. package/dist/chunk-BGPU4RR7.js.map +1 -0
  17. package/dist/chunk-CCEFAOSH.js +496 -0
  18. package/dist/chunk-CCEFAOSH.js.map +1 -0
  19. package/dist/chunk-FWSY5HOA.js +63 -0
  20. package/dist/chunk-FWSY5HOA.js.map +1 -0
  21. package/dist/chunk-GYIOMQMY.js +8726 -0
  22. package/dist/chunk-GYIOMQMY.js.map +1 -0
  23. package/dist/chunk-HVB2BR3H.js +42 -0
  24. package/dist/chunk-HVB2BR3H.js.map +1 -0
  25. package/dist/chunk-K6P63KD4.js +68 -0
  26. package/dist/chunk-K6P63KD4.js.map +1 -0
  27. package/dist/chunk-MRKY4HGF.js +205 -0
  28. package/dist/chunk-MRKY4HGF.js.map +1 -0
  29. package/dist/chunk-QFHAAIIM.js +2657 -0
  30. package/dist/chunk-QFHAAIIM.js.map +1 -0
  31. package/dist/chunk-VZKQX5PP.js +1 -0
  32. package/dist/chunk-VZKQX5PP.js.map +1 -0
  33. package/dist/chunk-WAI6BODI.js +175 -0
  34. package/dist/chunk-WAI6BODI.js.map +1 -0
  35. package/dist/chunk-XHRBV6I3.js +3637 -0
  36. package/dist/chunk-XHRBV6I3.js.map +1 -0
  37. package/dist/chunk-YMNXDNDW.js +798 -0
  38. package/dist/chunk-YMNXDNDW.js.map +1 -0
  39. package/dist/conversation.cjs +208 -0
  40. package/dist/conversation.cjs.map +1 -0
  41. package/dist/conversation.d.cts +100 -0
  42. package/dist/conversation.d.ts +100 -0
  43. package/dist/conversation.js +21 -0
  44. package/dist/conversation.js.map +1 -0
  45. package/dist/device-network-portable.cjs +702 -0
  46. package/dist/device-network-portable.cjs.map +1 -0
  47. package/dist/device-network-portable.d.cts +110 -0
  48. package/dist/device-network-portable.d.ts +110 -0
  49. package/dist/device-network-portable.js +53 -0
  50. package/dist/device-network-portable.js.map +1 -0
  51. package/dist/device-network.cjs +906 -0
  52. package/dist/device-network.cjs.map +1 -0
  53. package/dist/device-network.d.cts +6 -0
  54. package/dist/device-network.d.ts +6 -0
  55. package/dist/device-network.js +59 -0
  56. package/dist/device-network.js.map +1 -0
  57. package/dist/fetchProvider-BpcGVSOG.d.cts +91 -0
  58. package/dist/fetchProvider-Cm0sO4Tl.d.ts +91 -0
  59. package/dist/index.cjs +27957 -5459
  60. package/dist/index.cjs.map +1 -1
  61. package/dist/index.d.cts +94 -1320
  62. package/dist/index.d.ts +94 -1320
  63. package/dist/index.js +10576 -2386
  64. package/dist/index.js.map +1 -1
  65. package/dist/interface-IrKBFtL1.d.cts +493 -0
  66. package/dist/interface-IrKBFtL1.d.ts +493 -0
  67. package/dist/llm-providers.cjs +43 -8
  68. package/dist/llm-providers.cjs.map +1 -1
  69. package/dist/llm-providers.d.cts +2 -1
  70. package/dist/llm-providers.d.ts +2 -1
  71. package/dist/llm-providers.js +4 -2
  72. package/dist/llm-providers.js.map +1 -1
  73. package/dist/loop-api.cjs +5177 -2050
  74. package/dist/loop-api.cjs.map +1 -1
  75. package/dist/loop-api.d.cts +11 -5
  76. package/dist/loop-api.d.ts +11 -5
  77. package/dist/loop-api.js +84 -49
  78. package/dist/mobile.cjs +2625 -0
  79. package/dist/mobile.cjs.map +1 -0
  80. package/dist/mobile.d.cts +6 -0
  81. package/dist/mobile.d.ts +6 -0
  82. package/dist/mobile.js +22 -0
  83. package/dist/mobile.js.map +1 -0
  84. package/dist/orchestration-portable-Bsf8YRfp.d.cts +2192 -0
  85. package/dist/orchestration-portable-Zw0g5tbj.d.ts +2192 -0
  86. package/dist/orchestration-portable.cjs +9553 -0
  87. package/dist/orchestration-portable.cjs.map +1 -0
  88. package/dist/orchestration-portable.d.cts +5 -0
  89. package/dist/orchestration-portable.d.ts +5 -0
  90. package/dist/orchestration-portable.js +290 -0
  91. package/dist/orchestration-portable.js.map +1 -0
  92. package/dist/pairingInvite-BXPWY3aM.d.cts +149 -0
  93. package/dist/pairingInvite-Cuz0wuq9.d.ts +149 -0
  94. package/dist/promptConcat-WTN-uHcz.d.cts +516 -0
  95. package/dist/promptConcat-deDSWZE3.d.ts +516 -0
  96. package/dist/providerRegistry-9trr5aoK.d.ts +86 -0
  97. package/dist/providerRegistry-xk_B1Ekv.d.cts +86 -0
  98. package/dist/registry-8eztoD_r.d.cts +393 -0
  99. package/dist/registry-DV24sI-3.d.ts +393 -0
  100. package/dist/remoteClient-B_spK019.d.ts +87 -0
  101. package/dist/remoteClient-CBggnRy3.d.cts +87 -0
  102. package/dist/runtime-SKSXVYIM.js +18 -0
  103. package/dist/runtime-SKSXVYIM.js.map +1 -0
  104. package/dist/scriptDeploymentPipeline-BAeo1dPb.d.cts +2463 -0
  105. package/dist/scriptDeploymentPipeline-DsnT0AG6.d.ts +2463 -0
  106. package/dist/syncCloudDevices-BEqwgrhD.d.ts +49 -0
  107. package/dist/syncCloudDevices-Ds_Kcgrv.d.cts +49 -0
  108. package/dist/types-7pYti-k9.d.cts +255 -0
  109. package/dist/types-CdFVSntj.d.ts +255 -0
  110. package/package.json +110 -35
  111. package/dist/anthropic.cjs +0 -72
  112. package/dist/anthropic.cjs.map +0 -1
  113. package/dist/anthropic.d.cts +0 -21
  114. package/dist/anthropic.d.ts +0 -21
  115. package/dist/anthropic.js +0 -21
  116. package/dist/anthropic.js.map +0 -1
  117. package/dist/azure.cjs +0 -72
  118. package/dist/azure.cjs.map +0 -1
  119. package/dist/azure.d.cts +0 -21
  120. package/dist/azure.d.ts +0 -21
  121. package/dist/azure.js +0 -21
  122. package/dist/azure.js.map +0 -1
  123. package/dist/chunk-3CN7DFBL.js +0 -4894
  124. package/dist/chunk-3CN7DFBL.js.map +0 -1
  125. package/dist/chunk-4AZ4D7U5.js +0 -32
  126. package/dist/chunk-4AZ4D7U5.js.map +0 -1
  127. package/dist/chunk-6ON4XSOV.js +0 -63
  128. package/dist/chunk-6ON4XSOV.js.map +0 -1
  129. package/dist/chunk-DJQNGIXX.js +0 -4793
  130. package/dist/chunk-DJQNGIXX.js.map +0 -1
  131. package/dist/chunk-FKQP6AOQ.js +0 -32
  132. package/dist/chunk-FKQP6AOQ.js.map +0 -1
  133. package/dist/chunk-OVJ7JJBA.js +0 -35
  134. package/dist/chunk-OVJ7JJBA.js.map +0 -1
  135. package/dist/chunk-P4UZ7IXC.js +0 -42
  136. package/dist/chunk-YHJ2AEFR.js +0 -4933
  137. package/dist/chunk-YHJ2AEFR.js.map +0 -1
  138. package/dist/chunk-YVK7RYRO.js +0 -4973
  139. package/dist/chunk-YVK7RYRO.js.map +0 -1
  140. package/dist/code-assistant.json +0 -114
  141. package/dist/cohere.cjs +0 -72
  142. package/dist/cohere.cjs.map +0 -1
  143. package/dist/cohere.d.cts +0 -21
  144. package/dist/cohere.d.ts +0 -21
  145. package/dist/cohere.js +0 -21
  146. package/dist/cohere.js.map +0 -1
  147. package/dist/deepseek.cjs +0 -72
  148. package/dist/deepseek.cjs.map +0 -1
  149. package/dist/deepseek.d.cts +0 -21
  150. package/dist/deepseek.d.ts +0 -21
  151. package/dist/deepseek.js +0 -21
  152. package/dist/deepseek.js.map +0 -1
  153. package/dist/dist-65U7OYRG.js +0 -1257
  154. package/dist/dist-65U7OYRG.js.map +0 -1
  155. package/dist/fetchProvider-Cu4WkU5O.d.cts +0 -819
  156. package/dist/fetchProvider-Cu4WkU5O.d.ts +0 -819
  157. package/dist/frontend-ui-ux.json +0 -105
  158. package/dist/general-assistant.json +0 -95
  159. package/dist/git-master.json +0 -51
  160. package/dist/google-vertex.cjs +0 -72
  161. package/dist/google-vertex.cjs.map +0 -1
  162. package/dist/google-vertex.d.cts +0 -21
  163. package/dist/google-vertex.d.ts +0 -21
  164. package/dist/google-vertex.js +0 -21
  165. package/dist/google-vertex.js.map +0 -1
  166. package/dist/google.cjs +0 -72
  167. package/dist/google.cjs.map +0 -1
  168. package/dist/google.d.cts +0 -21
  169. package/dist/google.d.ts +0 -21
  170. package/dist/google.js +0 -21
  171. package/dist/google.js.map +0 -1
  172. package/dist/groq.cjs +0 -72
  173. package/dist/groq.cjs.map +0 -1
  174. package/dist/groq.d.cts +0 -21
  175. package/dist/groq.d.ts +0 -21
  176. package/dist/groq.js +0 -21
  177. package/dist/groq.js.map +0 -1
  178. package/dist/index.d.mts +0 -3203
  179. package/dist/index.mjs +0 -7064
  180. package/dist/index.mjs.map +0 -1
  181. package/dist/mistral.cjs +0 -72
  182. package/dist/mistral.cjs.map +0 -1
  183. package/dist/mistral.d.cts +0 -21
  184. package/dist/mistral.d.ts +0 -21
  185. package/dist/mistral.js +0 -21
  186. package/dist/mistral.js.map +0 -1
  187. package/dist/multipart-parser-EJCXIUHC.js +0 -372
  188. package/dist/multipart-parser-EJCXIUHC.js.map +0 -1
  189. package/dist/openai.cjs +0 -72
  190. package/dist/openai.cjs.map +0 -1
  191. package/dist/openai.d.cts +0 -21
  192. package/dist/openai.d.ts +0 -21
  193. package/dist/openai.js +0 -21
  194. package/dist/openai.js.map +0 -1
  195. package/dist/perplexity.cjs +0 -72
  196. package/dist/perplexity.cjs.map +0 -1
  197. package/dist/perplexity.d.cts +0 -21
  198. package/dist/perplexity.d.ts +0 -21
  199. package/dist/perplexity.js +0 -21
  200. package/dist/perplexity.js.map +0 -1
  201. package/dist/playwright.json +0 -52
  202. package/dist/promptConcat-BJdazTg5.d.cts +0 -1832
  203. package/dist/promptConcat-BJdazTg5.d.ts +0 -1832
  204. package/dist/promptConcat-CAkpni_8.d.cts +0 -1834
  205. package/dist/promptConcat-CAkpni_8.d.ts +0 -1834
  206. package/dist/promptConcat-CfH5-GAE.d.cts +0 -1036
  207. package/dist/promptConcat-ChcAZOOL.d.ts +0 -1036
  208. package/dist/promptConcat-G5TnJVRy.d.cts +0 -1800
  209. package/dist/promptConcat-G5TnJVRy.d.ts +0 -1800
  210. package/dist/promptConcat-L72eowzp.d.ts +0 -1090
  211. package/dist/promptConcat-eLHdN7K8.d.cts +0 -1090
  212. package/dist/src-VTSXKG72.js +0 -1409
  213. package/dist/src-VTSXKG72.js.map +0 -1
  214. package/dist/togetherai.cjs +0 -72
  215. package/dist/togetherai.cjs.map +0 -1
  216. package/dist/togetherai.d.cts +0 -21
  217. package/dist/togetherai.d.ts +0 -21
  218. package/dist/togetherai.js +0 -21
  219. package/dist/togetherai.js.map +0 -1
  220. package/dist/types-B0Jm2l38.d.cts +0 -767
  221. package/dist/types-B0Jm2l38.d.ts +0 -767
  222. package/dist/xai.cjs +0 -72
  223. package/dist/xai.cjs.map +0 -1
  224. package/dist/xai.d.cts +0 -21
  225. package/dist/xai.d.ts +0 -21
  226. package/dist/xai.js +0 -21
  227. package/dist/xai.js.map +0 -1
  228. /package/dist/{chunk-P4UZ7IXC.js.map → browser.js.map} +0 -0
package/dist/index.d.mts DELETED
@@ -1,3203 +0,0 @@
1
- import { PublicKey, PrivateKey } from '@libp2p/interface';
2
- import { z } from 'zod';
3
-
4
- interface PromptNode {
5
- id: string;
6
- text?: string;
7
- /** TidGi IPrompt 兼容 */
8
- caption?: string;
9
- role?: 'system' | 'user' | 'assistant' | 'tool';
10
- enabled?: boolean;
11
- children?: PromptNode[];
12
- /** UI 溯源,可选 */
13
- source?: unknown;
14
- /**
15
- * 与插件 `dynamicPosition` 配合:用户轮次 ≥2 时将根级该节点移到列表末尾。
16
- */
17
- dynamicPosition?: 'deferToEnd';
18
- }
19
- /** 与 TidGi `IPrompt` 对齐的别名 */
20
- type IPrompt = PromptNode;
21
- interface PromptPluginConfig {
22
- id: string;
23
- toolId: string;
24
- enabled?: boolean;
25
- /** defineTool:`approval`(mode / allowPatterns / denyPatterns)等,类型见 `tools/types` */
26
- [key: string]: unknown;
27
- }
28
- interface AgentFrameworkConfig {
29
- prompts: PromptNode[];
30
- response?: unknown[];
31
- plugins: PromptPluginConfig[];
32
- }
33
- interface AgentPromptDescription {
34
- agentFrameworkConfig?: AgentFrameworkConfig;
35
- }
36
-
37
- interface AgentDefinitionModelConfig {
38
- provider?: string;
39
- model?: string;
40
- temperature?: number;
41
- maxTokens?: number;
42
- }
43
- interface ModelSelection {
44
- provider: string;
45
- model: string;
46
- [key: string]: unknown;
47
- }
48
- interface ModelParameters {
49
- temperature?: number;
50
- maxTokens?: number;
51
- topP?: number;
52
- [key: string]: unknown;
53
- }
54
- interface AiAPIConfig {
55
- default?: ModelSelection;
56
- embedding?: ModelSelection;
57
- speech?: ModelSelection;
58
- imageGeneration?: ModelSelection;
59
- transcriptions?: ModelSelection;
60
- free?: ModelSelection;
61
- modelParameters: ModelParameters;
62
- [key: string]: unknown;
63
- }
64
- interface AgentHeartbeatConfig {
65
- enabled: boolean;
66
- intervalSeconds: number;
67
- message: string;
68
- activeHoursStart?: string;
69
- activeHoursEnd?: string;
70
- }
71
- interface AgentDefinitionToolConfig {
72
- toolId: string;
73
- enabled?: boolean;
74
- parameters?: Record<string, unknown>;
75
- tags?: string[];
76
- }
77
- type HostAgentToolConfig$1 = AgentDefinitionToolConfig;
78
- interface AgentDefinition {
79
- id: string;
80
- name: string;
81
- description: string;
82
- systemPrompt: string;
83
- tools: string[];
84
- modelConfig?: AgentDefinitionModelConfig;
85
- promptSchema?: unknown;
86
- /**
87
- * TidGi-Desktop / memeloop:prompt 树、插件、maxIterations 等(结构见 memeloop prompt 类型)
88
- * Typed as `AgentFrameworkConfig` so all hosts share a single canonical shape.
89
- */
90
- agentFrameworkConfig?: AgentFrameworkConfig;
91
- /** Host-specific explicit tool configuration. Hosts map this to prompt plugins at runtime. */
92
- agentTools?: AgentDefinitionToolConfig[];
93
- /** Host-specific avatar or icon URL. */
94
- avatarUrl?: string;
95
- /** Host-specific agent handler / framework ID. */
96
- agentFrameworkID?: string;
97
- /** Periodic auto-wake configuration. */
98
- heartbeat?: AgentHeartbeatConfig;
99
- /** Host-specific AI API config override. */
100
- aiApiConfig?: AiAPIConfig;
101
- version: string;
102
- }
103
- interface AgentInstanceMeta {
104
- instanceId: string;
105
- definitionId: string;
106
- nodeId: string;
107
- conversationId: string;
108
- createdAt: number;
109
- updatedAt: number;
110
- definitionDelta?: Partial<AgentDefinition>;
111
- }
112
-
113
- /**
114
- * Unified loop contract for all agent loop types.
115
- * Replaces the old TaskAgentInput / TaskAgentStep naming entirely.
116
- */
117
-
118
- /** Standard input for any agent loop. */
119
- interface AgentLoopInput {
120
- conversationId: string;
121
- message: string;
122
- /** Host-prepared user message, used when the platform needs metadata/attachments on the turn root. */
123
- userMessage?: Omit<Partial<ChatMessage>, 'conversationId' | 'role'> & {
124
- content?: string;
125
- };
126
- /** If provided, these messages are loaded as conversation history on resume. */
127
- resumeSession?: ChatMessage[];
128
- }
129
- /** Standard output step yielded by any agent loop. */
130
- interface AgentLoopStep {
131
- type: 'thinking' | 'tool' | 'message' | 'permission_request';
132
- data: unknown;
133
- }
134
- /** Async iterable signature shared by all loop runners. */
135
- type AgentLoopGenerator = AsyncIterable<AgentLoopStep>;
136
- /** Describes a registered loop type. */
137
- interface AgentLoopDefinition {
138
- /** Unique id, e.g. "llm-io" or "sub-agent". */
139
- id: string;
140
- /** Human-readable display name. */
141
- name: string;
142
- /** Short description of this loop's behaviour. */
143
- description: string;
144
- /** Factory: create a loop runner function for the given context. */
145
- createRunner: (context: {
146
- [key: string]: unknown;
147
- }) => (input: AgentLoopInput) => AgentLoopGenerator;
148
- }
149
- /** Capability extension point for a loop. */
150
- interface LoopPlugin {
151
- /** Unique plugin id, e.g. "fullReplacement" or "wikiTools". */
152
- id: string;
153
- /** Which loop id this plugin targets, or "*" for all loops. */
154
- targetLoopId?: string;
155
- /** Optional schema to validate against profile config. */
156
- schema?: Record<string, unknown>;
157
- /** Install the plugin into the given context. Mutates the context in place. */
158
- install?: (context: {
159
- [key: string]: unknown;
160
- }, config?: Record<string, unknown>) => void;
161
- }
162
- /** A complete agent profile that describes which loop, which .mjs script, prompts, plugins, and hooks to use. */
163
- interface LoopProfile {
164
- /** Unique profile id, e.g. "memeloop:general-assistant". */
165
- id: string;
166
- /** Display name. */
167
- name: string;
168
- /** Description. */
169
- description: string;
170
- /** Which loop to run. Defaults to "llm-io" if omitted. */
171
- loopId?: string;
172
- /** Path (host-resolvable) to the .mjs loop script. */
173
- script?: string;
174
- /** System prompt (concise form; detailed prompts go to `prompts`). */
175
- systemPrompt?: string;
176
- /** Tool allowlist IDs. */
177
- tools?: string[];
178
- /** Agent-level tool configuration. */
179
- agentTools?: Array<{
180
- toolId: string;
181
- enabled?: boolean;
182
- parameters?: Record<string, unknown>;
183
- tags?: string[];
184
- }>;
185
- /** Full agent framework configuration. */
186
- agentFrameworkConfig?: AgentFrameworkConfig;
187
- /** System prompt(s) for the agent. */
188
- prompts?: LoopProfilePrompt[];
189
- /** Tool / prompt / response plugin configs. */
190
- plugins?: LoopProfilePluginEntry[];
191
- /** Hook plugin configs. */
192
- hookPlugins?: LoopProfilePluginEntry[];
193
- /** Model configuration. */
194
- modelConfig?: {
195
- provider?: string;
196
- model?: string;
197
- temperature?: number;
198
- maxTokens?: number;
199
- };
200
- /** Host-specific AI API config override. */
201
- aiApiConfig?: AiAPIConfig;
202
- /** Periodic auto-wake configuration. */
203
- heartbeat?: {
204
- enabled: boolean;
205
- intervalSeconds: number;
206
- message: string;
207
- activeHoursStart?: string;
208
- activeHoursEnd?: string;
209
- };
210
- /** Host-specific handler / framework ID. */
211
- agentFrameworkID?: string;
212
- /** Host-specific avatar or icon URL. */
213
- avatarUrl?: string;
214
- /** Tool permission configuration. */
215
- permissions?: {
216
- default?: 'allow' | 'ask' | 'deny';
217
- rules?: Array<{
218
- pattern: string;
219
- action: 'allow' | 'ask' | 'deny';
220
- }>;
221
- perAgent?: Record<string, {
222
- default?: string;
223
- rules?: Array<{
224
- pattern: string;
225
- action: string;
226
- }>;
227
- }>;
228
- };
229
- /** Open schema for host-specific or loop-specific configuration. */
230
- schema?: Record<string, unknown>;
231
- /** Arbitrary metadata. */
232
- metadata?: Record<string, unknown>;
233
- /** Version string. */
234
- version?: string;
235
- }
236
- interface LoopProfilePrompt {
237
- id: string;
238
- role: string;
239
- text: string;
240
- caption?: string;
241
- children?: LoopProfilePrompt[];
242
- }
243
- interface LoopProfilePluginEntry {
244
- /** Plugin id registered in the plugin registry. */
245
- id: string;
246
- /** Whether this plugin is enabled. */
247
- enabled?: boolean;
248
- /** Plugin-specific configuration. */
249
- config?: Record<string, unknown>;
250
- }
251
- /** Minimal runtime context passed to a loop runner. */
252
- interface AgentLoopRuntime {
253
- /** Resolve a profile by id. */
254
- resolveProfile: (profileId: string) => Promise<LoopProfile | null>;
255
- /** Run a child agent (or sub-loop) and return its result. */
256
- runChildAgent: (input: {
257
- profileId: string;
258
- prompt: string;
259
- conversationId: string;
260
- }) => AgentLoopGenerator;
261
- /** Log an event for observability. */
262
- log: (event: string, data?: Record<string, unknown>) => void;
263
- /** Read/write persistent state for this run. */
264
- state: {
265
- get: <T>(key: string) => Promise<T | undefined>;
266
- set: (key: string, value: unknown) => Promise<void>;
267
- update: (key: string, updater: (previous: unknown) => unknown) => Promise<void>;
268
- };
269
- /** Checkpoint a completed step so it can be skipped on resume. */
270
- checkpoint: (key: string, result: unknown) => Promise<void>;
271
- /** Emit a progress step upstream. */
272
- emit: (step: AgentLoopStep) => void;
273
- /** Signal whether the run has been cancelled. */
274
- signal: {
275
- cancelled: boolean;
276
- };
277
- }
278
-
279
- type ToolCallingMatch = {
280
- found: false;
281
- } | {
282
- found: true;
283
- toolId: string;
284
- parameters: Record<string, unknown>;
285
- originalText: string;
286
- };
287
- declare function matchToolCalling(responseText: string): ToolCallingMatch;
288
- declare function matchAllToolCallings(responseText: string): {
289
- calls: Array<ToolCallingMatch & {
290
- found: true;
291
- }>;
292
- parallel: boolean;
293
- };
294
-
295
- /**
296
- * TidGi-Desktop `agentInstance/tools/types.ts` 迁移并适配 memeloop(无 tapable,用 HookSlot.promise 串行执行)。
297
- */
298
-
299
- /** 供 defineTool / 审批使用:agent 视图包含完整 AgentInstance。 */
300
- type DefineToolAgentFrameworkContext = AgentFrameworkContext & {
301
- agent: AgentInstanceModel;
302
- };
303
- type ToolApprovalMode = 'auto' | 'confirm';
304
- interface ToolApprovalConfig {
305
- mode: ToolApprovalMode;
306
- allowPatterns?: string[];
307
- denyPatterns?: string[];
308
- timeoutMs?: number;
309
- }
310
- type ApprovalDecision = 'allow' | 'deny' | 'pending';
311
- interface ToolApprovalRequest {
312
- approvalId: string;
313
- agentId: string;
314
- toolName: string;
315
- parameters: Record<string, unknown>;
316
- originalText?: string;
317
- created: Date;
318
- }
319
- type YieldNextRoundTarget = 'human' | 'self' | `agent:${string}`;
320
- interface ToolActions {
321
- yieldNextRoundTo?: YieldNextRoundTarget;
322
- newUserMessage?: string;
323
- toolCalling?: ToolCallingMatch;
324
- }
325
- interface BaseToolContext {
326
- agentFrameworkContext: DefineToolAgentFrameworkContext;
327
- metadata?: Record<string, unknown>;
328
- actions?: ToolActions;
329
- }
330
- /** 与 TidGi IPromptConcatTool 对齐的插件行 */
331
- interface FrameworkPluginToolConfig {
332
- id: string;
333
- toolId: string;
334
- enabled?: boolean;
335
- caption?: string;
336
- content?: string;
337
- forbidOverrides?: boolean;
338
- approval?: ToolApprovalConfig;
339
- timeoutMs?: number;
340
- [key: string]: unknown;
341
- }
342
- interface PromptConcatHookContext extends BaseToolContext {
343
- messages: ChatMessage[];
344
- prompts: IPrompt[];
345
- toolConfig: FrameworkPluginToolConfig;
346
- pluginIndex?: number;
347
- }
348
- interface AgentResponse {
349
- id: string;
350
- text?: string;
351
- enabled?: boolean;
352
- children?: AgentResponse[];
353
- }
354
- interface PostProcessContext extends PromptConcatHookContext {
355
- llmResponse: string;
356
- responses?: AgentResponse[];
357
- }
358
- /** 流式响应子集(memeloop ILLMProvider 聚合为最终文本后注入) */
359
- interface AIStreamResponseSubset {
360
- status: 'update' | 'done';
361
- content: string;
362
- }
363
- interface AIResponseContext extends BaseToolContext {
364
- toolConfig: FrameworkPluginToolConfig;
365
- agentFrameworkConfig?: {
366
- plugins?: FrameworkPluginToolConfig[];
367
- };
368
- response: AIStreamResponseSubset;
369
- requestId?: string;
370
- isFinal?: boolean;
371
- }
372
- interface UserMessageContext extends BaseToolContext {
373
- content: {
374
- text: string;
375
- file?: unknown;
376
- wikiTiddlers?: Array<{
377
- workspaceName: string;
378
- tiddlerTitle: string;
379
- }>;
380
- };
381
- messageId: string;
382
- timestamp: Date;
383
- }
384
- interface AgentStatusContext extends BaseToolContext {
385
- status: {
386
- state: 'working' | 'completed' | 'failed' | 'canceled';
387
- modified: Date;
388
- };
389
- }
390
- interface ToolExecutionContext extends BaseToolContext {
391
- toolResult: {
392
- success: boolean;
393
- data?: string;
394
- error?: string;
395
- metadata?: Record<string, unknown>;
396
- };
397
- toolInfo: {
398
- toolId: string;
399
- parameters: Record<string, unknown>;
400
- originalText?: string;
401
- };
402
- requestId?: string;
403
- }
404
- /**
405
- * Hook 槽:与 tapable AsyncSeriesHook 一致 — `tapAsync` 注册,`promise(ctx)` 串行触发。
406
- */
407
- interface HookSlot {
408
- tapAsync(name: string, function_: (context: any, callback: () => void) => void): void;
409
- promise(context: unknown): Promise<void>;
410
- }
411
- interface PromptConcatHooks {
412
- processPrompts: HookSlot;
413
- finalizePrompts: HookSlot;
414
- postProcess: HookSlot;
415
- userMessageReceived: HookSlot;
416
- agentStatusChanged: HookSlot;
417
- toolExecuted: HookSlot;
418
- responseUpdate: HookSlot;
419
- responseComplete: HookSlot;
420
- }
421
- type PromptConcatTool = (hooks: PromptConcatHooks) => void;
422
-
423
- type IMPlatformType = 'telegram' | 'discord' | 'lark' | 'wecom' | 'slack' | 'line' | 'qq';
424
- interface IMChannel {
425
- channelId: string;
426
- platform: IMPlatformType;
427
- nodeId: string;
428
- webhookMode: 'cloud-relay' | 'direct';
429
- webhookUrl?: string;
430
- defaultDefinitionId?: string;
431
- status: 'active' | 'inactive' | 'error';
432
- }
433
- interface IMChannelBinding {
434
- channelId: string;
435
- imUserId: string;
436
- activeConversationId: string;
437
- createdAt: number;
438
- defaultDefinitionId?: string;
439
- /** When set, the user's next inbound message is treated as an askQuestion answer (plan §20.3). */
440
- pendingQuestionId?: string;
441
- }
442
- /** @deprecated Use IMChannelBinding */
443
- type ImChannelBindingRecord = IMChannelBinding;
444
-
445
- type VersionVector = Record<string, number>;
446
- interface ConversationMeta {
447
- conversationId: string;
448
- title: string;
449
- lastMessagePreview: string;
450
- lastMessageTimestamp: number;
451
- messageCount: number;
452
- originNodeId: string;
453
- definitionId: string;
454
- instanceDelta?: Record<string, unknown>;
455
- isUserInitiated: boolean;
456
- sourceChannel?: {
457
- channelId: string;
458
- platform: string;
459
- imUserId: string;
460
- };
461
- }
462
- declare function isConversationMeta(value: unknown): value is ConversationMeta;
463
-
464
- interface CheckpointRecord {
465
- conversationId: string;
466
- messages: ChatMessage[];
467
- savedAt: string;
468
- messageCount: number;
469
- lastMessagePreview: string;
470
- }
471
- interface CheckpointSummary {
472
- conversationId: string;
473
- savedAt: string;
474
- messageCount: number;
475
- lastMessagePreview: string;
476
- }
477
- interface CheckpointStore {
478
- saveCheckpoint(conversationId: string, messages: ChatMessage[]): Promise<CheckpointRecord>;
479
- loadCheckpoint(conversationId: string): Promise<CheckpointRecord | null>;
480
- listCheckpoints(): Promise<CheckpointSummary[]>;
481
- deleteCheckpoint(conversationId: string): Promise<boolean>;
482
- }
483
- interface SessionStorageOptions {
484
- records?: CheckpointRecord[];
485
- }
486
- declare function createCheckpointRecord(conversationId: string, messages: ChatMessage[], savedAt?: string): CheckpointRecord;
487
- declare function parseCheckpointRecord(raw: string): CheckpointRecord | null;
488
- declare function serializeCheckpointRecord(record: CheckpointRecord): string;
489
- declare class InMemoryCheckpointStore implements CheckpointStore {
490
- private readonly records;
491
- constructor(options?: SessionStorageOptions);
492
- saveCheckpoint(conversationId: string, messages: ChatMessage[]): Promise<CheckpointRecord>;
493
- loadCheckpoint(conversationId: string): Promise<CheckpointRecord | null>;
494
- listCheckpoints(): Promise<CheckpointSummary[]>;
495
- deleteCheckpoint(conversationId: string): Promise<boolean>;
496
- }
497
- declare class SessionStorage extends InMemoryCheckpointStore {
498
- }
499
-
500
- type ConversationQueryMode = 'metadata-only' | 'full-content' | 'on-demand';
501
- interface ListConversationsOptions {
502
- limit?: number;
503
- offset?: number;
504
- }
505
- interface GetMessagesOptions {
506
- mode?: ConversationQueryMode;
507
- }
508
- interface IAgentStorage$1 {
509
- listConversations(options?: ListConversationsOptions): Promise<ConversationMeta[]>;
510
- getMessages(conversationId: string, options?: GetMessagesOptions): Promise<ChatMessage[]>;
511
- appendMessage(message: ChatMessage): Promise<void>;
512
- /**
513
- * Upsert conversation directory row (sync / Solid / peer metadata).
514
- */
515
- upsertConversationMetadata(meta: ConversationMeta): Promise<void>;
516
- /**
517
- * Insert messages if messageId not present (merge from remote / Pod); refreshes per-conversation messageCount.
518
- */
519
- insertMessagesIfAbsent(messages: ChatMessage[]): Promise<void>;
520
- getAttachment(contentHash: string): Promise<AttachmentReference | null>;
521
- saveAttachment(reference: AttachmentReference, data: Buffer | Uint8Array): Promise<void>;
522
- /**
523
- * 读取已落库的附件二进制(用于节点间 RPC `memeloop.storage.getAttachmentBlob`)。
524
- * 未实现时远端同步应通过其它通道拉取附件。
525
- */
526
- readAttachmentData?(contentHash: string): Promise<Uint8Array | null>;
527
- getAgentDefinition(id: string): Promise<AgentDefinition | null>;
528
- /**
529
- * 若实现,可用 `SELECT MAX(lamportClock)` 避免为时钟扫描全量消息。
530
- */
531
- getMaxLamportClockForConversation?(conversationId: string): Promise<number>;
532
- saveAgentInstance(meta: AgentInstanceMeta): Promise<void>;
533
- /**
534
- * 读取会话目录行(用于 TaskAgent 解析 definitionId 等)。
535
- */
536
- getConversationMeta(conversationId: string): Promise<ConversationMeta | null>;
537
- /** IM 用户与会话绑定(memeloop-cli + SQLite 持久化)。 */
538
- getImBinding?(channelId: string, imUserId: string): Promise<IMChannelBinding | null>;
539
- setImBinding?(record: IMChannelBinding): Promise<void>;
540
- }
541
- interface MemeLoopLogger {
542
- debug?(message: string, ...arguments_: unknown[]): void;
543
- info?(message: string, ...arguments_: unknown[]): void;
544
- warn?(message: string, ...arguments_: unknown[]): void;
545
- error?(message: string, ...arguments_: unknown[]): void;
546
- }
547
- interface ILLMProvider {
548
- name: string;
549
- model?: unknown;
550
- chat(request: unknown): AsyncIterable<unknown> | Promise<unknown>;
551
- }
552
- /**
553
- * LLM Provider interface - now compatible with Vercel AI SDK's LanguageModelV1.
554
- * The `model` field holds the actual LanguageModelV1 instance from @ai-sdk/openai, @ai-sdk/anthropic, etc.
555
- */
556
- interface IToolRegistry {
557
- registerTool(id: string, impl: unknown): void;
558
- getTool(id: string): unknown | undefined;
559
- listTools(): string[];
560
- /**
561
- * Prompt-concat 插件表(defineTool 注册的 `PromptConcatTool`),按运行时隔离。
562
- * 未实现时回退到进程级默认注册表(见 pluginRegistry)。
563
- */
564
- getPromptPlugins?: () => Map<string, (hooks: PromptConcatHooks) => void>;
565
- }
566
- interface IChatSyncAdapter {
567
- start(): Promise<void>;
568
- stop(): Promise<void>;
569
- }
570
- interface INetworkService {
571
- start(): Promise<void>;
572
- stop(): Promise<void>;
573
- }
574
- interface LlmIoLoopOptions {
575
- /** 最大 LLM↔工具往返次数,0 表示不限制(仍受内部安全上限约束) */
576
- maxIterations?: number;
577
- /** 是否解析 `<tool_use>` / `<function_call>` 并通过 IToolRegistry 执行(默认 true) */
578
- enableToolLoop?: boolean;
579
- /** 取消检查(例如用户点停止);按会话维度 */
580
- isCancelled?: (conversationId: string) => boolean;
581
- /** promptConcat 附件注入(与 PromptConcatOptions 一致) */
582
- readAttachmentFile?: (path: string) => Promise<Uint8Array | Buffer>;
583
- /** 超过该时长的历史消息不送入 LLM(毫秒);0 或未设置表示不裁剪 */
584
- maxHistoryAgeMs?: number;
585
- /**
586
- * 在已配置 `defineTool` / plugins 时,对未被 `onResponseComplete` 处理的 tool 调用回退到 `IToolRegistry`(默认 true)。
587
- */
588
- fallbackRegistryTools?: boolean;
589
- /**
590
- * 工具权限规则(默认 allow)。
591
- * 支持 wildcard,如 "terminal.*" / "file.read"。
592
- */
593
- toolPermissions?: {
594
- default?: 'allow' | 'ask' | 'deny';
595
- rules?: Array<{
596
- pattern: string;
597
- action: 'allow' | 'ask' | 'deny';
598
- }>;
599
- perAgent?: Record<string, {
600
- default?: 'allow' | 'ask' | 'deny';
601
- rules?: Array<{
602
- pattern: string;
603
- action: 'allow' | 'ask' | 'deny';
604
- }>;
605
- }>;
606
- };
607
- /** 相同 tool+input 连续触发阈值(默认 3) */
608
- doomLoopThreshold?: number;
609
- /** 历史压缩窗口:超过后只保留最近 N 条 + 最后一条用户消息 */
610
- contextCompaction?: {
611
- maxMessages?: number;
612
- replayLastUserMessage?: boolean;
613
- };
614
- /**
615
- * Auto-compaction: when message count exceeds threshold, summarizes old
616
- * conversation turns via truncation or LLM summarization. Default: disabled.
617
- */
618
- autoCompact?: {
619
- /** Trigger compaction when message count exceeds this (default: 50) */
620
- threshold?: number;
621
- /** Number of recent turns to preserve (default: 4) */
622
- recentTurnsToKeep?: number;
623
- /** Maximum token estimate before compaction; 0 disables token-based compaction */
624
- maxTokens?: number;
625
- };
626
- /** Session checkpoint: save conversation history after each turn for resume. */
627
- sessionCheckpoint?: {
628
- /** Enable checkpoint saves. Default: false. */
629
- enabled?: boolean;
630
- /** Store provided by the runtime host. */
631
- store?: CheckpointStore;
632
- /** Custom checkpoint directory (default: ~/.memeloop/sessions/) */
633
- directory?: string;
634
- };
635
- /**
636
- * After a tool returns `__memeloopToolResult.awaitSessionId`, TaskAgent waits here before the next LLM round
637
- * (terminal `mode: 'await'`).
638
- */
639
- waitForTerminalSession?: (sessionId: string) => Promise<{
640
- exitCode: number | null;
641
- truncatedOutput: string;
642
- }>;
643
- }
644
- interface AgentFrameworkContext {
645
- storage: IAgentStorage$1;
646
- llmProvider: ILLMProvider;
647
- tools: IToolRegistry;
648
- syncAdapters: IChatSyncAdapter[];
649
- network: INetworkService;
650
- /** Let host runtimes preserve platform-specific message aliases/metadata while core owns the loop. */
651
- normalizeMessage?: (message: ChatMessage) => ChatMessage;
652
- /** TaskAgent ReAct 行为(从 TidGi-Desktop taskAgent 迁移) */
653
- taskAgent?: LlmIoLoopOptions;
654
- /**
655
- * 由宿主注入(如 memeloop-cli):存在时 `createMemeLoopRuntime` 在用户发消息后运行完整 TaskAgent 管线。
656
- */
657
- runTaskAgent?: (input: AgentLoopInput) => AgentLoopGenerator;
658
- /** Run a child agent for orchestration loops such as SubAgent_Loop. */
659
- runChildAgent?: AgentLoopRuntime['runChildAgent'];
660
- /**
661
- * Build the agent view supplied to defineTool hooks for a conversation.
662
- */
663
- resolveAgentRuntimeView?: (conversationId: string, messages: ChatMessage[]) => Promise<AgentInstanceModel>;
664
- /**
665
- * defineTool / TidGi 兼容:当前轮次的 agent 视图(`agent.messages` 与 `ChatMessage` 由 TaskAgent 同步)。
666
- */
667
- agent?: {
668
- id: string;
669
- messages: ChatMessage[];
670
- };
671
- /** 将 `ChatMessage` 持久化(可选,由 runtime 注入) */
672
- persistAgentMessage?: (message: ChatMessage) => Promise<void>;
673
- /**
674
- * 由 `createMemeLoopRuntime` 写入取消标记,`taskAgent.isCancelled` 应与此集合一致(如 memeloop-cli)。
675
- */
676
- conversationCancellation?: Set<string>;
677
- /**
678
- * 解析 AgentDefinition(如节点合并 YAML + 内置 + SQLite)。未设置时仅用 `storage.getAgentDefinition`。
679
- */
680
- resolveAgentDefinition?: (definitionId: string) => Promise<AgentDefinition | null>;
681
- /** 未注入时 TaskAgent 等对关键路径使用 console.warn/error。 */
682
- logger?: MemeLoopLogger;
683
- /** TidGi defineTool compatibility: legacy plugins call this without arguments. */
684
- isCancelled?: () => boolean;
685
- }
686
- type AgentInstanceState = 'submitted' | 'working' | 'input-required' | 'completed' | 'canceled' | 'failed' | 'unknown';
687
- interface AgentInstanceLatestStatus {
688
- state: AgentInstanceState;
689
- message?: ChatMessage;
690
- /** Human-readable sub-status for the header — shown while agent is working. */
691
- progress?: string;
692
- created?: Date;
693
- modified?: Date;
694
- }
695
- interface AgentInstanceModel extends Omit<AgentDefinition, 'name'> {
696
- agentDefId: string;
697
- name?: string;
698
- agentFrameworkConfig?: AgentFrameworkConfig;
699
- messages: ChatMessage[];
700
- status: AgentInstanceLatestStatus;
701
- created: Date;
702
- modified?: Date;
703
- closed?: boolean;
704
- volatile?: boolean;
705
- isSubAgent?: boolean;
706
- parentAgentId?: string;
707
- }
708
-
709
- declare function isUserInitiatedConversation(meta: ConversationMeta): boolean;
710
- declare function createInstanceDeltaFromDefinition(definition: AgentDefinition, overrides: Partial<AgentDefinition>): Partial<AgentDefinition>;
711
-
712
- interface AttachmentReference {
713
- contentHash: string;
714
- filename: string;
715
- mimeType: string;
716
- size: number;
717
- }
718
- type ChatRole = 'user' | 'assistant' | 'tool' | 'agent' | 'error';
719
- interface ToolCall {
720
- id: string;
721
- toolName: string;
722
- arguments: unknown;
723
- }
724
- /** Points to large tool output stored elsewhere (sub-agent log, terminal session, file). */
725
- type DetailRefType = 'sub-agent' | 'terminal-session' | 'file';
726
- interface DetailReference {
727
- type: DetailRefType;
728
- /** Sub-agent / spawn / remote conversation id */
729
- conversationId?: string;
730
- /** Terminal session id (often paired with `terminal:<sessionId>` conversation) */
731
- sessionId?: string;
732
- /** Node that holds the detail payload */
733
- nodeId?: string;
734
- /** e.g. `memeloop://node/.../file/...` from `buildMemeloopFileUri` in `../network/uri.js` */
735
- fileUri?: string;
736
- exitCode?: number;
737
- }
738
- interface ChatMessage {
739
- messageId: string;
740
- conversationId: string;
741
- originNodeId: string;
742
- timestamp: number;
743
- lamportClock: number;
744
- role: ChatRole;
745
- content: string;
746
- toolCalls?: ToolCall[];
747
- attachments?: AttachmentReference[];
748
- /** Summary lives in `content`; full payload fetched via detail ref (plan §5.2.1). */
749
- detailRef?: DetailReference;
750
- /** Reasoning/thinking content */
751
- reasoning_content?: string;
752
- /** Content MIME type */
753
- contentType?: string;
754
- /** Whether message should be hidden in UI */
755
- hidden?: boolean;
756
- /** Message processing duration in ms */
757
- duration?: number | null;
758
- /** Additional metadata */
759
- metadata?: Record<string, unknown>;
760
- }
761
-
762
- /**
763
- * Domain factories for creating canonical ChatMessage and AgentInstance objects.
764
- *
765
- * These factories ensure that every host (Desktop, Mobile, CLI, Cloud)
766
- * constructs messages and instances with the same required fields,
767
- * default values, and clock behavior.
768
- *
769
- * Hosts that need a different originNodeId, message ID scheme, or lamport
770
- * clock source should pass those values explicitly rather than creating
771
- * their own factory.
772
- */
773
-
774
- /**
775
- * Create a canonical ChatMessage with required defaults.
776
- *
777
- * @param input.messageId - Unique message identifier. Use nanoid or equivalent.
778
- * @param input.conversationId - The conversation/agent-instance this message belongs to.
779
- * @param input.role - Message role (user, assistant, tool, agent, error).
780
- * @param input.content - Message text content.
781
- * @param input.originNodeId - Node that originated this message. Core default is "unknown";
782
- * hosts should pass their own identifier (e.g. "tidgi-desktop", "memeloop-cli").
783
- * @param input.contentType - MIME type override (default "text/plain").
784
- * @param input.metadata - Optional metadata map.
785
- * @param input.duration - Processing duration in ms.
786
- * @param input.lamportClock - Lamport clock value. Defaults to `Date.now()`.
787
- * @param input.toolCalls - Tool calls associated with assistant messages.
788
- * @param input.reasoning_content - Reasoning/thinking content.
789
- * @param input.hidden - Whether the message is hidden from the UI.
790
- * @param input.detailRef - Reference to large tool output stored elsewhere.
791
- */
792
- declare function createChatMessage(input: {
793
- messageId: string;
794
- conversationId: string;
795
- role: ChatRole;
796
- content: string;
797
- originNodeId?: string;
798
- contentType?: string;
799
- metadata?: Record<string, unknown>;
800
- duration?: number | null;
801
- lamportClock?: number;
802
- toolCalls?: ChatMessage['toolCalls'];
803
- reasoning_content?: string;
804
- hidden?: boolean;
805
- attachments?: ChatMessage['attachments'];
806
- detailRef?: ChatMessage['detailRef'];
807
- }): ChatMessage;
808
- /**
809
- * Create an AgentInstance from an AgentDefinition.
810
- *
811
- * The returned instance has an empty message list, a default "completed"
812
- * status, and copies all definition-level fields as instance defaults.
813
- *
814
- * @param definition - The AgentDefinition to base the instance on.
815
- * @param overrides - Optional overrides for instance-specific fields:
816
- * - `id`: Instance ID (default: nanoid-equivalent, must be provided by host)
817
- * - `name`: Display name (default: definition.name)
818
- * - `status`: Initial status
819
- * - `volatile`: Whether the instance is ephemeral
820
- * - `closed`: Whether closed on creation
821
- * - `isSubAgent`, `parentAgentId`: Sub-agent relationship
822
- * - `agentFrameworkConfig`: Per-instance framework config override
823
- */
824
- declare function createAgentInstanceFromDefinition(definition: AgentDefinition, overrides: {
825
- id: string;
826
- name?: string;
827
- status?: AgentInstanceLatestStatus;
828
- volatile?: boolean;
829
- closed?: boolean;
830
- isSubAgent?: boolean;
831
- parentAgentId?: string;
832
- agentFrameworkConfig?: AgentFrameworkConfig;
833
- }): AgentInstanceModel;
834
-
835
- interface CompactionOptions {
836
- /** Maximum token count to aim for after compaction (estimated by char count / 3.5). Default: 0 (no limit). */
837
- maxTokens?: number;
838
- /** Number of recent message turns (user+assistant pairs) to preserve. Default: 4. */
839
- recentTurnsToKeep?: number;
840
- /** Whether to attempt LLM summarization. Falls back to truncation if LLM unavailable or fails. Default: true. */
841
- useLlmSummary?: boolean;
842
- /** Optional LLM provider for summarization. */
843
- llmProvider?: ILLMProvider;
844
- }
845
- interface CompactionResult {
846
- /** Compacted messages (summary + recent turns). */
847
- messages: ChatMessage[];
848
- /** True if compaction reduced the message count. */
849
- compacted: boolean;
850
- /** Number of messages dropped. */
851
- droppedCount: number;
852
- /** Summary text generated or fallback notice. */
853
- summaryText: string;
854
- }
855
- /**
856
- * Deterministic compaction: keeps recent N turns and replaces older messages
857
- * with a single summary message.
858
- */
859
- declare function compactMessages(messages: ChatMessage[], options?: Omit<CompactionOptions, 'llmProvider' | 'useLlmSummary'>): CompactionResult;
860
- /**
861
- * Checks whether compaction is needed based on message count threshold.
862
- * @returns true if message count exceeds threshold (default 50).
863
- */
864
- declare function shouldCompact(messages: ChatMessage[], threshold?: number): boolean;
865
- /**
866
- * Auto-compact: estimates token usage, and if it exceeds maxTokens,
867
- * performs compaction to keep the context within bounds.
868
- *
869
- * Uses the LLM provider for summarization if available, falling back to
870
- * simple truncation + turn counting.
871
- */
872
- declare function autoCompact(messages: ChatMessage[], options?: CompactionOptions): Promise<CompactionResult>;
873
-
874
- /**
875
- * TaskAgent:TidGi `basicPromptConcatHandler` 对齐版。
876
- *
877
- * - defineTool:`createHooksWithPlugins` + `responseComplete` + `responseConcat`(postProcess)
878
- * - 回退:`IToolRegistry` 执行未被插件处理的 tool 调用
879
- */
880
- declare function createTaskAgent(context: AgentFrameworkContext): (input: AgentLoopInput) => AgentLoopGenerator;
881
-
882
- /**
883
- * LLM_IO_Loop runner — convenience API for driving a full loop turn.
884
- */
885
-
886
- interface RunTaskAgentTurnCallbacks {
887
- onStep?: (step: AgentLoopStep) => void | Promise<void>;
888
- onProgress?: (status: string, data: Record<string, unknown>, step: AgentLoopStep) => void | Promise<void>;
889
- taskAgent?: (input: AgentLoopInput) => AgentLoopGenerator;
890
- }
891
- interface RunTaskAgentTurnResult {
892
- state: AgentInstanceState;
893
- stepCount: number;
894
- }
895
- declare function resolveTaskAgentTerminalState(step: AgentLoopStep, current: AgentInstanceState): AgentInstanceState;
896
- declare function runTaskAgentTurn(context: AgentFrameworkContext, input: AgentLoopInput, callbacks?: RunTaskAgentTurnCallbacks): Promise<RunTaskAgentTurnResult>;
897
-
898
- /**
899
- * Built-in loop registrations — installed at startup so getLoopRegistry().createRunner('llm-io') works.
900
- *
901
- * This module allows hosts to skip manual registerLoop() for the built-in loop types.
902
- * Hosts can still override by calling registerLoop() with the same id after.
903
- */
904
- declare const LLM_IO_LOOP_ID = "llm-io";
905
- declare const SUB_AGENT_LOOP_ID: string;
906
- /**
907
- * Register the default built-in loops (llm-io and sub-agent) with the loop registry.
908
- * Safe to call multiple times — skips already-registered loops.
909
- */
910
- declare function registerBuiltinLoops(): void;
911
-
912
- /**
913
- * Builtin tool plugins — registers core tools as LoopPlugin entries.
914
- *
915
- * Each tool is a separate LoopPlugin that can be overridden by user/host plugins
916
- * with the same id. The plugin.install callback calls the tool registry to
917
- * register the tool implementation.
918
- *
919
- * These are registered in the loop registry at startup and loaded by
920
- * `registerBuiltinTools` via plugin discovery.
921
- */
922
-
923
- declare const PLUGIN_MCP_CLIENT = "builtin:mcp-client";
924
- declare const PLUGIN_MCP_FORWARD = "builtin:mcp-forward";
925
- declare const PLUGIN_SPAWN_AGENT = "builtin:spawn-agent";
926
- declare const PLUGIN_REMOTE_AGENT = "builtin:remote-agent";
927
- declare const PLUGIN_ASK_QUESTION = "builtin:ask-question";
928
- declare const PLUGIN_TODO_WRITE = "builtin:todo-write";
929
- declare const PLUGIN_ASK_USER_QUESTION = "builtin:ask-user-question";
930
- declare const PLUGIN_TASK = "builtin:task";
931
- declare const BUILTIN_TOOL_PLUGIN_IDS: readonly ["builtin:mcp-client", "builtin:mcp-forward", "builtin:spawn-agent", "builtin:remote-agent", "builtin:ask-question", "builtin:todo-write", "builtin:ask-user-question", "builtin:task"];
932
- declare function getBuiltinToolPlugins(): LoopPlugin[];
933
- /** Register all builtin tool plugins with the loop registry. */
934
- declare function registerBuiltinToolPlugins(): void;
935
-
936
- /**
937
- * Agent loop registry.
938
- *
939
- * Discovers, registers, and resolves loop types, loop profiles, and loop plugins.
940
- * Core does NOT hard-import any loop implementation; all are registered by host or plugin.
941
- */
942
-
943
- type LoopPluginSelection = string | LoopProfilePluginEntry;
944
- declare class LoopRegistryImpl {
945
- private readonly loops;
946
- private readonly profiles;
947
- private readonly plugins;
948
- registerLoop(definition: AgentLoopDefinition): void;
949
- getLoop(id: string): AgentLoopDefinition | undefined;
950
- listLoops(): AgentLoopDefinition[];
951
- registerProfile(profile: LoopProfile): void;
952
- getProfile(id: string): LoopProfile | undefined;
953
- listProfiles(): LoopProfile[];
954
- registerPlugin(plugin: LoopPlugin): void;
955
- getPlugin(id: string): LoopPlugin | undefined;
956
- listPlugins(): LoopPlugin[];
957
- installPluginsForLoop(loopId: string, target: {
958
- [key: string]: unknown;
959
- }, selected?: LoopPluginSelection[]): void;
960
- installPluginsForProfile(profile: LoopProfile, target: {
961
- [key: string]: unknown;
962
- }): void;
963
- createRunnerForProfile(profile: LoopProfile, context?: {
964
- [key: string]: unknown;
965
- }): ((input: AgentLoopInput) => AgentLoopGenerator) | null;
966
- createRunner(loopId: string, context?: {
967
- [key: string]: unknown;
968
- }): ((input: AgentLoopInput) => AgentLoopGenerator) | null;
969
- reset(): void;
970
- }
971
- declare function getLoopRegistry(): LoopRegistryImpl;
972
- declare function resetLoopRegistry(): void;
973
-
974
- /**
975
- * SubAgent_Loop — a loop that orchestrates child agents.
976
- *
977
- * This loop does NOT call the LLM directly. Instead it coordinates child agents:
978
- * - running a child agent and feeding its result to another child agent (review / verify)
979
- * - splitting work across multiple parallel child agents
980
- * - looping back to a child agent with feedback when a reviewer rejects the output
981
- *
982
- * The loop script (.mjs) holds the orchestration logic. This file provides the
983
- * runtime that invokes the script and manages child agent runs.
984
- */
985
-
986
- interface SubAgentLoopScriptArguments {
987
- input: AgentLoopInput;
988
- context: SubAgentLoopContext;
989
- profile?: LoopProfile;
990
- runtime?: Partial<AgentLoopRuntime>;
991
- runAgent: (input: SubAgentRunAgentInput) => Promise<SubAgentRunAgentResult>;
992
- runAgents: (inputs: SubAgentRunAgentInput[]) => Promise<SubAgentRunAgentResult[]>;
993
- emit: (step: AgentLoopStep) => void;
994
- finish: (message: string | AgentLoopStep) => void;
995
- isCancelled: () => boolean;
996
- log: (event: string, data?: Record<string, unknown>) => void;
997
- state: AgentLoopRuntime['state'];
998
- checkpoint: AgentLoopRuntime['checkpoint'];
999
- }
1000
- interface SubAgentRunAgentInput {
1001
- /** Child profile id. `profile` is accepted as an ergonomic alias for scripts. */
1002
- profileId?: string;
1003
- profile?: string;
1004
- prompt: string;
1005
- conversationId?: string;
1006
- }
1007
- interface SubAgentRunAgentResult {
1008
- profileId: string;
1009
- conversationId: string;
1010
- steps: AgentLoopStep[];
1011
- text: string;
1012
- }
1013
- type SubAgentLoopScriptResult = AgentLoopGenerator | AgentLoopStep | AgentLoopStep[] | string | undefined;
1014
- type SubAgentLoopScript = (scriptArguments: SubAgentLoopScriptArguments) => SubAgentLoopScriptResult | Promise<SubAgentLoopScriptResult>;
1015
- interface SubAgentLoopContext {
1016
- [key: string]: unknown;
1017
- profile?: LoopProfile;
1018
- runtime?: Partial<AgentLoopRuntime>;
1019
- childProfiles?: string[];
1020
- script?: SubAgentLoopScript;
1021
- loadScript?: (script: string, context: SubAgentLoopContext) => SubAgentLoopScript | Promise<SubAgentLoopScript>;
1022
- }
1023
- /**
1024
- * Create the SubAgent_Loop definition and register it with the loop registry.
1025
- */
1026
- declare function createSubAgentLoopDefinition(): AgentLoopDefinition;
1027
- /** Export loop id for consumers. */
1028
- declare function getSubAgentLoopId(): string;
1029
-
1030
- interface LoadSubAgentLoopScriptOptions {
1031
- importModule?: (specifier: string) => Promise<unknown>;
1032
- }
1033
- declare function loadSubAgentLoopScript(scriptSpecifier: string, options?: LoadSubAgentLoopScriptOptions): Promise<SubAgentLoopScript>;
1034
-
1035
- interface TokenTrackerConfig {
1036
- /** Maximum context window in tokens (default: 200000) */
1037
- contextWindow?: number;
1038
- /** Trigger compaction when usage exceeds this fraction (default: 0.90) */
1039
- compactionThreshold?: number;
1040
- /** Buffer tokens reserved for output (default: 16000) */
1041
- outputBuffer?: number;
1042
- }
1043
- interface TokenUsage {
1044
- promptTokens: number;
1045
- completionTokens: number;
1046
- totalTokens: number;
1047
- contextWindow: number;
1048
- usagePercent: number;
1049
- shouldCompact: boolean;
1050
- }
1051
- /**
1052
- * Tracks token usage and decides when to trigger auto-compaction.
1053
- */
1054
- declare class TokenTracker {
1055
- private promptTokens;
1056
- private completionTokens;
1057
- private readonly contextWindow;
1058
- private readonly compactionThreshold;
1059
- private readonly outputBuffer;
1060
- private compacting;
1061
- private consecutiveCompactionFailures;
1062
- private maxConsecutiveFailures;
1063
- constructor(config?: TokenTrackerConfig);
1064
- /** Record token usage from an LLM response */
1065
- recordUsage(promptTokens: number, completionTokens: number): void;
1066
- /** Manually set the prompt token count (e.g., from estimation) */
1067
- setPromptTokens(tokens: number): void;
1068
- /** Get current usage */
1069
- getUsage(): TokenUsage;
1070
- /** Check if auto-compaction should be triggered */
1071
- shouldTriggerCompaction(): boolean;
1072
- /** Mark that compaction is starting */
1073
- markCompactionStart(): void;
1074
- /** Mark that compaction succeeded — reset token counts */
1075
- markCompactionSuccess(estimatedPostTokens: number): void;
1076
- /** Mark that compaction failed */
1077
- markCompactionFailure(): void;
1078
- /** Reset all counters */
1079
- reset(): void;
1080
- /** Get a human-readable summary */
1081
- formatUsage(): string;
1082
- }
1083
-
1084
- interface CreateAgentOptions {
1085
- definitionId: string;
1086
- initialMessage?: string;
1087
- }
1088
- interface SendMessageOptions {
1089
- conversationId: string;
1090
- message: string;
1091
- }
1092
- interface MemeLoopRuntime {
1093
- createAgent(options: CreateAgentOptions): Promise<{
1094
- conversationId: string;
1095
- }>;
1096
- sendMessage(options: SendMessageOptions): Promise<void>;
1097
- cancelAgent(conversationId: string): Promise<void>;
1098
- subscribeToUpdates(conversationId: string, listener: (update: unknown) => void): () => void;
1099
- }
1100
- declare function createMemeLoopRuntime(context: AgentFrameworkContext): MemeLoopRuntime;
1101
-
1102
- /**
1103
- * 将节点 RPC `memeloop.storage.getAttachmentBlob` 的返回值解码为同步引擎可用的 BLOB。
1104
- */
1105
- declare function decodeAttachmentBlobRpc(result: unknown): {
1106
- data: Uint8Array;
1107
- filename: string;
1108
- mimeType: string;
1109
- size: number;
1110
- } | null;
1111
-
1112
- interface ChatSyncPeer {
1113
- nodeId: string;
1114
- /**
1115
- * 取远端当前的 versionVector,并返回对方缺失的会话元数据。
1116
- */
1117
- exchangeVersionVector(localVersion: Record<string, number>): Promise<{
1118
- remoteVersion: Record<string, number>;
1119
- missingForRemote: ConversationMeta[];
1120
- }>;
1121
- /**
1122
- * 将本地缺失的 metadata 从该 peer 拉回来。
1123
- */
1124
- pullMissingMetadata(sinceVersion: Record<string, number>): Promise<ConversationMeta[]>;
1125
- /**
1126
- * 按需拉取消息正文(TidGi / 审查单 Phase 4:消息级同步)。
1127
- * 返回远端有而本地 unknownMessageIds 之外的新消息。
1128
- */
1129
- pullMissingMessages?(conversationId: string, knownMessageIds: string[]): Promise<ChatMessage[]>;
1130
- /**
1131
- * 按 contentHash 拉取附件二进制(与 `ChatMessage.attachments` / `AttachmentRef` 对齐)。
1132
- * 典型实现:对 peer 发 `memeloop.storage.getAttachmentBlob` RPC。
1133
- */
1134
- pullAttachmentBlob?(contentHash: string): Promise<{
1135
- data: Uint8Array;
1136
- filename: string;
1137
- mimeType: string;
1138
- size: number;
1139
- } | null>;
1140
- }
1141
- interface ChatSyncEngineOptions {
1142
- nodeId: string;
1143
- storage: IAgentStorage$1;
1144
- peers: () => ChatSyncPeer[];
1145
- }
1146
- declare class ChatSyncEngine {
1147
- private readonly nodeId;
1148
- private readonly storage;
1149
- private readonly getPeers;
1150
- private versionVector;
1151
- constructor(options: ChatSyncEngineOptions);
1152
- /**
1153
- * 在本节点新产生一条消息时调用,增加本节点的 lamportClock。
1154
- */
1155
- bumpLocalVersion(): void;
1156
- /**
1157
- * 执行一次与所有 peer 的增量同步(metadata 级别),并尽力拉取缺失消息。
1158
- */
1159
- syncOnce(): Promise<void>;
1160
- /**
1161
- * Anti-entropy:先 syncOnce,再对已知会话逐个向各 peer 拉取缺失消息(参考审查单「定期对账」)。
1162
- */
1163
- antiEntropyOnce(): Promise<void>;
1164
- private pullMessagesForConversationFromPeers;
1165
- /** 从消息元数据收集 `attachments[].contentHash`,对本地缺失 BLOB 的哈希向各 peer 拉取并 `saveAttachment`。 */
1166
- private ensureAttachmentsFromMessages;
1167
- getVersionVector(): Record<string, number>;
1168
- getStorage(): IAgentStorage$1;
1169
- }
1170
-
1171
- interface PeerNodeTransport {
1172
- nodeId: string;
1173
- exchangeVersionVector(targetNodeId: string, localVersion: Record<string, number>): Promise<{
1174
- remoteVersion: Record<string, number>;
1175
- missingForRemote: ConversationMeta[];
1176
- }>;
1177
- pullMissingMetadata(targetNodeId: string, sinceVersion: Record<string, number>): Promise<ConversationMeta[]>;
1178
- pullMissingMessages?(targetNodeId: string, conversationId: string, knownMessageIds: string[]): Promise<ChatMessage[]>;
1179
- /** 从指定节点拉取附件 BLOB(如 `memeloop.storage.getAttachmentBlob`)。 */
1180
- pullAttachmentBlob?(targetNodeId: string, contentHash: string): Promise<{
1181
- data: Uint8Array;
1182
- filename: string;
1183
- mimeType: string;
1184
- size: number;
1185
- } | null>;
1186
- }
1187
- declare class PeerNodeSyncAdapter implements ChatSyncPeer {
1188
- readonly nodeId: string;
1189
- private readonly transport;
1190
- constructor(nodeId: string, transport: PeerNodeTransport);
1191
- exchangeVersionVector(localVersion: Record<string, number>): Promise<{
1192
- remoteVersion: Record<string, number>;
1193
- missingForRemote: ConversationMeta[];
1194
- }>;
1195
- pullMissingMetadata(sinceVersion: Record<string, number>): Promise<ConversationMeta[]>;
1196
- pullMissingMessages(conversationId: string, knownMessageIds: string[]): Promise<ChatMessage[]>;
1197
- pullAttachmentBlob(contentHash: string): Promise<{
1198
- data: Uint8Array;
1199
- filename: string;
1200
- mimeType: string;
1201
- size: number;
1202
- } | null>;
1203
- }
1204
-
1205
- /**
1206
- * Built-in Loop Profiles.
1207
- *
1208
- * Each profile defines which agent loop to run, which .mjs script to load,
1209
- * which prompts, plugins, and hook plugins to enable.
1210
- *
1211
- * Replaces the old `src/prompt/loadBuiltins.ts`.
1212
- */
1213
-
1214
- /** Get all built-in Loop Profiles. */
1215
- declare function getBuiltinLoopProfiles(): LoopProfile[];
1216
- /** Get a built-in Loop Profile by id. */
1217
- declare function getBuiltinLoopProfile(id: string): LoopProfile | undefined;
1218
-
1219
- /**
1220
- * Extended agent definition used by the agent profile registry.
1221
- * Wraps the protocol-level AgentDefinition with additional runtime metadata.
1222
- */
1223
- interface AgentProfile {
1224
- /** Unique ID for this agent (matches protocol id convention like "memeloop:build") */
1225
- id: string;
1226
- /** Display name */
1227
- name: string;
1228
- /** Agent type / role */
1229
- type: AgentProfileType;
1230
- /** System prompt / instructions for the agent */
1231
- prompt: string;
1232
- /** Tool permission rules (mutually exclusive with permissive defaults) */
1233
- permissions: ToolPermissionRules;
1234
- /** Optional model override (provider/model string) */
1235
- model?: string;
1236
- /** Underlying protocol-compatible definition for framework integration */
1237
- protocolDef: AgentDefinition;
1238
- }
1239
- type AgentProfileType = 'build' | 'plan' | 'explore' | 'oracle' | 'librarian';
1240
- interface ToolPermissionRules {
1241
- /** Default action for tools not matching any rule */
1242
- default: 'allow' | 'ask' | 'deny';
1243
- /** Per-tool or wildcard rules */
1244
- rules: Array<{
1245
- pattern: string;
1246
- action: 'allow' | 'ask' | 'deny';
1247
- }>;
1248
- }
1249
- /**
1250
- * Build agent: full access, default model.
1251
- * Primary agent for executing tasks, writing code, running commands.
1252
- */
1253
- declare const buildAgent: AgentProfile;
1254
- /**
1255
- * Plan agent: read-only, denies file edits and terminal execution.
1256
- * Used for high-level planning and task decomposition.
1257
- */
1258
- declare const planAgent: AgentProfile;
1259
- /**
1260
- * Explore agent: read + search tools only.
1261
- * Fast search and codebase exploration without modification.
1262
- */
1263
- declare const exploreAgent: AgentProfile;
1264
- /**
1265
- * Oracle agent: read-only, for architecture consultation and code review.
1266
- */
1267
- declare const oracleAgent: AgentProfile;
1268
- /**
1269
- * Librarian agent: read + web search tools only.
1270
- * External documentation lookup and context gathering.
1271
- */
1272
- declare const librarianAgent: AgentProfile;
1273
- /** Built-in agent profiles used by the task delegation tool. */
1274
- declare const BUILTIN_AGENT_PROFILES: AgentProfile[];
1275
-
1276
- /**
1277
- * Registry for agent profiles used by task delegation.
1278
- * Pre-seeded with built-in profiles (build, plan, explore, oracle, librarian).
1279
- */
1280
- declare class AgentProfileRegistry {
1281
- private readonly profiles;
1282
- constructor();
1283
- /** Seed the registry with built-in agent profiles. */
1284
- private seedDefaults;
1285
- /**
1286
- * Register a new agent profile or override an existing one.
1287
- * Throws if the profile is invalid.
1288
- */
1289
- registerAgentProfile(profile: AgentProfile): void;
1290
- /**
1291
- * Get an agent profile by ID.
1292
- * Returns undefined if not found.
1293
- */
1294
- getAgentProfile(id: string): AgentProfile | undefined;
1295
- /**
1296
- * List all registered agent profiles.
1297
- */
1298
- listAgentProfiles(): AgentProfile[];
1299
- /**
1300
- * List agent profiles filtered by type.
1301
- */
1302
- listAgentProfilesByType(type: AgentProfileType): AgentProfile[];
1303
- /**
1304
- * Remove an agent profile by ID.
1305
- */
1306
- unregisterAgentProfile(id: string): boolean;
1307
- /**
1308
- * Reset the registry to only built-in defaults.
1309
- */
1310
- reset(): void;
1311
- }
1312
- declare function getAgentProfileRegistry(): AgentProfileRegistry;
1313
- declare function resetAgentProfileRegistry(): void;
1314
-
1315
- /**
1316
- * Task category system for routing tasks to appropriate agent configurations.
1317
- * Each category maps to a model, temperature, and description for delegation decisions.
1318
- */
1319
- type TaskCategory = 'visual-engineering' | 'ultrabrain' | 'artistry' | 'quick' | 'unspecified-low' | 'unspecified-high' | 'writing';
1320
- interface CategoryConfig {
1321
- /** Model identifier (e.g., "default", "gpt-4o", "claude-opus") */
1322
- model: string;
1323
- /** LLM temperature (0.0 = deterministic, 1.0 = creative) */
1324
- temperature: number;
1325
- /** Human-readable description of the category's purpose */
1326
- description: string;
1327
- }
1328
- /**
1329
- * Get the configuration for a task category.
1330
- * @throws {Error} if the category is unknown
1331
- */
1332
- declare function getCategoryConfig(category: TaskCategory): CategoryConfig;
1333
- /**
1334
- * Type guard: check if a string is a valid TaskCategory.
1335
- */
1336
- declare function isTaskCategory(value: string): value is TaskCategory;
1337
- /** All registered category identifiers (read-only). */
1338
- declare const ALL_CATEGORIES: TaskCategory[];
1339
- /**
1340
- * Resolve a category string (or fallback to "unspecified-low").
1341
- * Never throws; always returns a valid config.
1342
- */
1343
- declare function resolveCategory(category: string): CategoryConfig;
1344
-
1345
- /**
1346
- * Convert TiddlyWiki tiddler fields into memeloop AgentDefinition.
1347
- *
1348
- * Tiddlers tagged `$:/tags/AI/Template` carry agent configuration in their text field (JSON).
1349
- * This pure function handles the parsing and field mapping.
1350
- */
1351
-
1352
- /** Minimal tiddler fields shape consumed by the converter. */
1353
- interface TiddlerFieldsForAgent {
1354
- title: string;
1355
- text?: string;
1356
- caption?: string;
1357
- description?: string;
1358
- avatar_url?: string;
1359
- handler_id?: string;
1360
- agentFrameworkID?: string;
1361
- ai_api_config?: string | Record<string, unknown>;
1362
- agent_tools?: string | unknown[];
1363
- }
1364
- /**
1365
- * Validate and convert a wiki tiddler to an AgentDefinition.
1366
- * Returns null if the tiddler cannot be parsed.
1367
- */
1368
- declare function tiddlerToAgentDefinition(tiddler: TiddlerFieldsForAgent, workspaceName?: string): AgentDefinition | null;
1369
-
1370
- /**
1371
- * Headless agent management contracts.
1372
- *
1373
- * Environment-neutral interfaces for managing agent definitions, agent instances,
1374
- * conversations, prompt previews, and scheduled tasks.
1375
- *
1376
- * Designed to be consumed by:
1377
- * - Desktop (via Electron IPC adapters)
1378
- * - Cloud (via REST API adapters)
1379
- * - CLI (via Ink + local or remote adapters)
1380
- */
1381
-
1382
- /** Attachment metadata for a wiki tiddler selected in the composer. */
1383
- interface WikiTiddlerAttachment {
1384
- workspaceName: string;
1385
- tiddlerTitle: string;
1386
- }
1387
- /** Data passed when a wiki tiddler chip is clicked in a message. */
1388
- interface WikiTiddlerClickData {
1389
- workspaceId: string;
1390
- workspaceName: string;
1391
- tiddlerTitle: string;
1392
- renderedContent?: string;
1393
- }
1394
- /** Storage contract for agent definition CRUD and template queries. */
1395
- interface AgentDefinitionRepository {
1396
- createAgentDef(agent: AgentDefinition): Promise<AgentDefinition>;
1397
- updateAgentDef(agent: Partial<AgentDefinition> & {
1398
- id: string;
1399
- }): Promise<AgentDefinition>;
1400
- getAgentDefs(): Promise<AgentDefinition[]>;
1401
- getAgentDef(id?: string): Promise<AgentDefinition | undefined>;
1402
- getAgentTemplates(): Promise<AgentDefinition[]>;
1403
- deleteAgentDef(id: string): Promise<void>;
1404
- }
1405
- /** Observable agent runtime metadata exposed to the UI layer. */
1406
- interface AgentRuntimeView {
1407
- id: string;
1408
- name: string;
1409
- agentDefId: string;
1410
- status: {
1411
- state: 'idle' | 'working' | 'completed' | 'failed' | 'canceled' | 'input-required';
1412
- progress?: string;
1413
- };
1414
- aiApiConfig?: AgentDefinition['aiApiConfig'];
1415
- /** If applicable, the agent definition merged with instance overrides. */
1416
- definition?: AgentDefinition;
1417
- }
1418
- /** Subscription callback for agent updates. */
1419
- type AgentUpdateListener = (update: Partial<AgentRuntimeView>) => void;
1420
- /** Client contract for creating, controlling, and subscribing to agent instances. */
1421
- interface AgentInstanceClient {
1422
- /**
1423
- * Create a new agent instance from a definition.
1424
- * @param agentDefinitionId The definition ID to instantiate from
1425
- * @param options Optional creation flags (e.g. { preview: true })
1426
- */
1427
- createAgent(agentDefinitionId: string, options?: {
1428
- preview?: boolean;
1429
- }): Promise<{
1430
- id: string;
1431
- }>;
1432
- /**
1433
- * Fetch a full agent runtime view (messages excluded, available via conversation client).
1434
- */
1435
- fetchAgent(agentId: string): Promise<AgentRuntimeView>;
1436
- /**
1437
- * Update an agent instance with partial data.
1438
- */
1439
- updateAgent(agentId: string, data: Partial<AgentDefinition>): Promise<AgentRuntimeView>;
1440
- /**
1441
- * Cancel the current operation for an agent instance.
1442
- */
1443
- cancelAgent(agentId: string): Promise<void>;
1444
- /**
1445
- * Delete an agent instance and its associated conversation.
1446
- */
1447
- deleteAgent(agentId: string): Promise<void>;
1448
- /**
1449
- * Subscribe to live updates for an agent instance.
1450
- * Returns an unsubscribe function.
1451
- */
1452
- subscribeToUpdates(agentId: string, listener: AgentUpdateListener): () => void;
1453
- /**
1454
- * Get the framework (handler) ID for an agent instance.
1455
- */
1456
- getAgentFrameworkId(agentId: string): Promise<string>;
1457
- /**
1458
- * Get the JSON Schema for the framework configuration.
1459
- */
1460
- getFrameworkConfigSchema(frameworkId: string): Promise<Record<string, unknown>>;
1461
- }
1462
- /** Client contract for conversation operations on an agent instance. */
1463
- interface AgentConversationClient {
1464
- /** Load all messages for an agent's conversation. */
1465
- getMessages(agentId: string): Promise<ChatMessage[]>;
1466
- /** Send a user message to the agent. Returns the list of message IDs that were appended. */
1467
- sendMessage(agentId: string, content: string, file?: File, wikiTiddlers?: WikiTiddlerAttachment[]): Promise<void>;
1468
- /** Subscribe to new message notifications. */
1469
- subscribeToMessages(agentId: string, listener: (message: ChatMessage) => void): () => void;
1470
- /** Delete an agent turn — removes the user message and all subsequent agent responses. */
1471
- deleteTurn(userMessageId: string): Promise<string | undefined>;
1472
- /** Retry an agent turn — delete agent responses and re-send the user message. */
1473
- retryTurn(userMessageId: string): Promise<void>;
1474
- }
1475
- /** Progress callback for prompt preview generation. */
1476
- interface PromptPreviewProgress {
1477
- progress: number;
1478
- step: string;
1479
- currentPlugin?: string;
1480
- }
1481
- /** Result of a prompt preview generation. */
1482
- interface PromptPreviewResult {
1483
- flatPrompts: unknown[];
1484
- processedPrompts: unknown[];
1485
- }
1486
- /** Client contract for generating prompt previews. */
1487
- interface PromptPreviewClient {
1488
- /**
1489
- * Generate a preview of the prompt tree for the given agent state.
1490
- * @param agentFrameworkConfig The agent's framework configuration
1491
- * @param messages Current conversation messages
1492
- * @param inputText Optional input text to include in the preview
1493
- * @param onProgress Optional progress callback
1494
- */
1495
- generatePreview(agentFrameworkConfig: AgentFrameworkConfig, messages: ChatMessage[], inputText?: string, onProgress?: (progress: PromptPreviewProgress) => void): Promise<PromptPreviewResult | null>;
1496
- }
1497
- /** Scheduled task input. */
1498
- interface CreateScheduledTaskInput {
1499
- agentInstanceId: string;
1500
- agentDefinitionId: string;
1501
- name: string;
1502
- scheduleKind: 'interval' | 'cron' | 'at';
1503
- schedule: {
1504
- kind: 'interval';
1505
- intervalSeconds: number;
1506
- } | {
1507
- kind: 'cron';
1508
- expression: string;
1509
- timezone?: string;
1510
- } | {
1511
- kind: 'at';
1512
- wakeAtISO: string;
1513
- };
1514
- payload?: {
1515
- message: string;
1516
- };
1517
- activeHoursStart?: string;
1518
- activeHoursEnd?: string;
1519
- createdBy?: string;
1520
- enabled?: boolean;
1521
- }
1522
- /** Scheduled task model. */
1523
- interface ScheduledTask {
1524
- id: string;
1525
- agentInstanceId: string;
1526
- agentDefinitionId: string;
1527
- name: string;
1528
- schedule: CreateScheduledTaskInput['schedule'];
1529
- payload?: {
1530
- message?: string;
1531
- };
1532
- activeHoursStart?: string;
1533
- activeHoursEnd?: string;
1534
- enabled: boolean;
1535
- createdBy?: string;
1536
- }
1537
- /** Client contract for managing scheduled tasks. */
1538
- interface ScheduledTaskClient {
1539
- listScheduledTasksForAgent(agentInstanceId: string): Promise<ScheduledTask[]>;
1540
- createScheduledTask(input: CreateScheduledTaskInput): Promise<ScheduledTask>;
1541
- updateScheduledTask(id: string, input: Partial<CreateScheduledTaskInput>): Promise<ScheduledTask>;
1542
- deleteScheduledTask(id: string): Promise<void>;
1543
- getCronPreviewDates(expression: string, timezone?: string, count?: number): Promise<string[]>;
1544
- }
1545
- /** State for the "Create New Agent" wizard. */
1546
- interface AgentCreationState {
1547
- /** Current step index in the creation wizard. */
1548
- currentStep: number;
1549
- /** Agent name entered by the user. */
1550
- agentName: string;
1551
- /** Selected template definition, if any. */
1552
- selectedTemplate: AgentDefinition | null;
1553
- /** Temporary agent definition being built. */
1554
- temporaryAgentDefinition: AgentDefinition | null;
1555
- /** ID of the preview agent instance created for testing. */
1556
- previewAgentId: string | null;
1557
- /** Whether a loading operation is in progress. */
1558
- isLoading: boolean;
1559
- /** JSON Schema for the selected agent framework, if loaded. */
1560
- promptSchema: Record<string, unknown> | null;
1561
- }
1562
- /** State for the "Edit Agent Definition" view. */
1563
- interface AgentDefinitionEditorState {
1564
- /** The agent definition being edited. */
1565
- agentDefinition: AgentDefinition | null;
1566
- /** Agent name. */
1567
- agentName: string;
1568
- /** ID of the preview agent instance. */
1569
- previewAgentId: string | null;
1570
- /** Whether a loading operation is in progress. */
1571
- isLoading: boolean;
1572
- /** Whether a save operation is in progress. */
1573
- isSaving: boolean;
1574
- /** JSON Schema for the selected agent framework, if loaded. */
1575
- promptSchema: Record<string, unknown> | null;
1576
- }
1577
- /** State for the prompt preview/edit dialog. */
1578
- interface PromptPreviewDialogState {
1579
- open: boolean;
1580
- baseMode: 'preview' | 'edit';
1581
- activeTab: 'flat' | 'tree';
1582
- loading: boolean;
1583
- progress: number;
1584
- currentStep: string;
1585
- currentPlugin: string | null;
1586
- result: PromptPreviewResult | null;
1587
- lastUpdated: Date | null;
1588
- formFieldsToScrollTo: string[];
1589
- }
1590
-
1591
- /**
1592
- * AgentSessionController — headless controller for an active agent conversation session.
1593
- *
1594
- * Manages agent runtime state, message sending, streaming, delete/retry turns,
1595
- * and subscription to live agent updates.
1596
- *
1597
- * No React, DOM, Electron, MUI, Zustand, or RxJS dependency.
1598
- */
1599
-
1600
- /** Read-only snapshot of the session state. */
1601
- interface AgentSessionSnapshot {
1602
- agent: AgentRuntimeView | null;
1603
- loading: boolean;
1604
- error: Error | null;
1605
- messages: ChatMessage[];
1606
- orderedMessageIds: string[];
1607
- streamingMessageIds: Set<string>;
1608
- }
1609
- /** Listener for snapshot changes. */
1610
- type AgentSessionListener = (snapshot: AgentSessionSnapshot) => void;
1611
- /** Options for creating an AgentSessionController. */
1612
- interface AgentSessionControllerOptions {
1613
- agentInstanceClient: AgentInstanceClient;
1614
- conversationClient: AgentConversationClient;
1615
- /** Polling interval in ms for agent status updates. Default 500. */
1616
- pollInterval?: number;
1617
- }
1618
- /**
1619
- * Headless controller for an agent conversation session.
1620
- *
1621
- * Call {@link start} to load an agent, then {@link subscribe} to receive snapshot
1622
- * updates. Use {@link sendMessage}, {@link deleteTurn}, {@link retryTurn}, {@link cancel}
1623
- * to drive the conversation.
1624
- *
1625
- * Host UI frameworks (React, Ink) subscribe via {@link subscribe} and render
1626
- * the snapshot.
1627
- */
1628
- declare class AgentSessionController {
1629
- private readonly options;
1630
- private listener;
1631
- private snapshot;
1632
- private unsubAgentUpdates;
1633
- private unsubMessages;
1634
- private pollingTimer;
1635
- private agentId;
1636
- constructor(options: AgentSessionControllerOptions);
1637
- /**
1638
- * Start a session for the given agent ID.
1639
- * Fetches the agent, subscribes to live updates, and loads messages.
1640
- */
1641
- start(agentId: string): Promise<void>;
1642
- /** Stop the session and clean up subscriptions. */
1643
- stop(): void;
1644
- /** Send a user message. */
1645
- sendMessage(content: string, file?: File, wikiTiddlers?: WikiTiddlerAttachment[]): Promise<void>;
1646
- /** Cancel the current agent operation. */
1647
- cancel(): Promise<void>;
1648
- /** Delete a turn starting at the given user message ID. */
1649
- deleteTurn(userMessageId: string): Promise<string | undefined>;
1650
- /** Retry a turn starting at the given user message ID. */
1651
- retryTurn(userMessageId: string): Promise<void>;
1652
- /** Subscribe to snapshot changes. Returns unsubscribe function. */
1653
- subscribe(listener: AgentSessionListener): () => void;
1654
- /** Get current snapshot without subscribing. */
1655
- getSnapshot(): AgentSessionSnapshot;
1656
- private emitPartial;
1657
- private handleAgentUpdate;
1658
- private handleNewMessage;
1659
- private startPolling;
1660
- private stopPolling;
1661
- }
1662
-
1663
- /**
1664
- * AgentDefinitionEditorController — headless controller for editing an agent definition.
1665
- *
1666
- * Manages definition loading, autosave, schema loading, preview agent lifecycle,
1667
- * and scheduled task CRUD.
1668
- *
1669
- * No React, DOM, Electron, MUI, Zustand, or RxJS dependency.
1670
- */
1671
-
1672
- /** Partial state emitted to the listener. */
1673
- type EditorStateChange = Partial<AgentDefinitionEditorState>;
1674
- /** Listener for editor state changes. */
1675
- type EditorStateListener = (change: EditorStateChange) => void;
1676
- /** Schedule editor sub-state for the UI layer. */
1677
- interface ScheduleEditorState {
1678
- mode: 'none' | 'interval' | 'daily' | 'cron';
1679
- intervalValue: number;
1680
- intervalUnit: 's' | 'min' | 'h';
1681
- dailyTime: string;
1682
- activeHoursStart: string;
1683
- activeHoursEnd: string;
1684
- cronExpression: string;
1685
- timezone: string;
1686
- message: string;
1687
- existingTaskId?: string;
1688
- }
1689
- /** Options for creating an AgentDefinitionEditorController. */
1690
- interface AgentDefinitionEditorControllerOptions {
1691
- definitionRepository: AgentDefinitionRepository;
1692
- agentInstanceClient: AgentInstanceClient;
1693
- scheduledTaskClient: ScheduledTaskClient;
1694
- /** Debounce interval for autosave in ms. Default 1000. */
1695
- autosaveDebounceMs?: number;
1696
- }
1697
- /**
1698
- * Headless controller for editing an agent definition.
1699
- *
1700
- * Call {@link loadDefinition} to start, then {@link subscribe} for state updates.
1701
- */
1702
- declare class AgentDefinitionEditorController {
1703
- private readonly options;
1704
- private listener;
1705
- private state;
1706
- private autosaveTimer;
1707
- constructor(options: AgentDefinitionEditorControllerOptions);
1708
- /** Load an agent definition and its prompt schema. */
1709
- loadDefinition(definitionId: string): Promise<void>;
1710
- /** Update the agent definition field. Triggers debounced autosave. */
1711
- updateDefinition(change: Partial<AgentDefinition> & {
1712
- id: string;
1713
- }): void;
1714
- /** Force an immediate save to the repository. */
1715
- saveNow(): Promise<void>;
1716
- /** Reload the prompt schema for a framework ID. */
1717
- reloadSchema(frameworkId: string): Promise<void>;
1718
- /** Get or create a preview agent instance tied to this definition. */
1719
- private findOrCreatePreviewAgent;
1720
- loadScheduledTasks(): Promise<ScheduledTask[]>;
1721
- saveScheduledTask(input: CreateScheduledTaskInput): Promise<ScheduledTask>;
1722
- deleteScheduledTask(taskId: string): Promise<void>;
1723
- subscribe(listener: EditorStateListener): () => void;
1724
- getState(): AgentDefinitionEditorState;
1725
- private emit;
1726
- private scheduleAutosave;
1727
- }
1728
-
1729
- /**
1730
- * AgentCreationController — headless controller for the "Create New Agent" wizard.
1731
- *
1732
- * Manages creation wizard state: current step, template selection, temporary
1733
- * agent definition lifecycle, and preview agent setup.
1734
- *
1735
- * No React, DOM, Electron, MUI, Zustand, or RxJS dependency.
1736
- */
1737
-
1738
- /** Listener for creation state changes. */
1739
- type CreationStateListener = (state: AgentCreationState) => void;
1740
- /** Options for creating an AgentCreationController. */
1741
- interface AgentCreationControllerOptions {
1742
- definitionRepository: AgentDefinitionRepository;
1743
- agentInstanceClient: AgentInstanceClient;
1744
- /** Default framework ID for new agents. */
1745
- defaultFrameworkId?: string;
1746
- }
1747
- /**
1748
- * Headless controller for the agent creation wizard.
1749
- *
1750
- * Call {@link start}, {@link selectTemplate}, {@link nextStep}, etc. to drive
1751
- * the wizard. Subscribe via {@link subscribe} for state updates.
1752
- */
1753
- declare class AgentCreationController {
1754
- private readonly options;
1755
- private listener;
1756
- private state;
1757
- constructor(options: AgentCreationControllerOptions);
1758
- /** Initialize the creation wizard, optionally from a saved tab state. */
1759
- start(definitionId?: string, templateDefinitionId?: string): Promise<void>;
1760
- /** Select a template for the new agent. */
1761
- selectTemplate(template: AgentDefinition): void;
1762
- /** Update the agent name. */
1763
- setAgentName(name: string): void;
1764
- /** Advance to the next wizard step. */
1765
- nextStep(): void;
1766
- /** Go back to the previous wizard step. */
1767
- previousStep(): void;
1768
- /** Set the current wizard step directly. */
1769
- setStep(step: number): void;
1770
- /** Update the temporary agent definition. */
1771
- updateTemporaryDefinition(change: Partial<AgentDefinition>): void;
1772
- /** Set the prompt schema for the selected framework. */
1773
- setPromptSchema(schema: Record<string, unknown> | null): void;
1774
- /**
1775
- * Create a preview agent instance for the chat-preview step.
1776
- * Should be called when entering step 2 (or the chat preview step).
1777
- */
1778
- createPreviewAgent(definitionId: string): Promise<void>;
1779
- /**
1780
- * Finalize creation: persist the temporary definition and create the actual
1781
- * agent instance. Returns the final agent instance ID, or null on failure.
1782
- */
1783
- finalize(): Promise<string | null>;
1784
- /** Clean up temporary resources. */
1785
- cleanup(): Promise<void>;
1786
- subscribe(listener: CreationStateListener): () => void;
1787
- getState(): AgentCreationState;
1788
- private emit;
1789
- }
1790
-
1791
- /**
1792
- * PromptPreviewController — headless controller for generating prompt previews.
1793
- *
1794
- * Manages preview dialog state, progress tracking, and result accumulation.
1795
- *
1796
- * No React, DOM, Electron, MUI, Zustand, or RxJS dependency.
1797
- */
1798
-
1799
- /** Listener for preview dialog state changes. */
1800
- type PreviewDialogListener = (state: PromptPreviewDialogState) => void;
1801
- /** Options for creating a PromptPreviewController. */
1802
- interface PromptPreviewControllerOptions {
1803
- previewClient: PromptPreviewClient;
1804
- }
1805
- /**
1806
- * Headless controller for the prompt preview/edit dialog.
1807
- *
1808
- * Call {@link open}, {@link close}, {@link generate} to drive the dialog.
1809
- * Subscribe via {@link subscribe} for state updates.
1810
- */
1811
- declare class PromptPreviewController {
1812
- private readonly options;
1813
- private listener;
1814
- private state;
1815
- constructor(options: PromptPreviewControllerOptions);
1816
- /** Open the dialog with an optional base mode. */
1817
- open(baseMode?: 'preview' | 'edit'): void;
1818
- /** Close the dialog. */
1819
- close(): void;
1820
- /** Set the active tab in the dialog. */
1821
- setActiveTab(tab: 'flat' | 'tree'): void;
1822
- /** Set form fields to scroll to (for edit mode navigation). */
1823
- setFormFieldsToScrollTo(fieldPaths: string[]): void;
1824
- /**
1825
- * Generate a preview of the prompt tree.
1826
- * @param agentFrameworkConfig The agent's framework configuration
1827
- * @param messages Current conversation messages
1828
- * @param inputText Optional input text to include in the preview
1829
- */
1830
- generate(agentFrameworkConfig: AgentFrameworkConfig, messages: ChatMessage[], inputText?: string): Promise<PromptPreviewResult | null>;
1831
- subscribe(listener: PreviewDialogListener): () => void;
1832
- getState(): PromptPreviewDialogState;
1833
- private emit;
1834
- }
1835
-
1836
- interface ProviderConfig {
1837
- name: string;
1838
- baseUrl?: string;
1839
- apiKey?: string;
1840
- }
1841
- interface RegisteredProvider {
1842
- provider: ILLMProvider;
1843
- config: ProviderConfig;
1844
- }
1845
- declare class ProviderRegistry {
1846
- private providers;
1847
- register(provider: ILLMProvider, config?: Omit<ProviderConfig, 'name'>): void;
1848
- unregister(name: string): void;
1849
- get(name: string): ILLMProvider | undefined;
1850
- getConfig(name: string): ProviderConfig | undefined;
1851
- upsertConfig(config: ProviderConfig): void;
1852
- list(): string[];
1853
- listConfigs(): ProviderConfig[];
1854
- resolve(modelId: string): {
1855
- provider: ILLMProvider;
1856
- providerName: string;
1857
- modelName?: string;
1858
- };
1859
- }
1860
-
1861
- /**
1862
- * Git HTTP 反向代理目标校验:降低 SSRF 风险(内网/metadata 等)。
1863
- * 仍依赖 getBackendUrl 返回可信基础 URL;此处拦截明显危险的解析结果。
1864
- */
1865
- /** 若目标 URL 不允许作为 Git 代理上游,返回简短原因;否则 null。 */
1866
- declare function gitProxyTargetBlockReason(url: URL): string | null;
1867
-
1868
- declare const MEMELOOP_SERVICE_TYPE = "_memeloop._tcp";
1869
- interface MemeloopServiceInfo {
1870
- name: string;
1871
- host: string;
1872
- port: number;
1873
- nodeId?: string;
1874
- wsPath?: string;
1875
- txt?: Record<string, string>;
1876
- }
1877
- interface LanDiscoveryRegisterOptions {
1878
- name: string;
1879
- port: number;
1880
- nodeId?: string;
1881
- wsPath?: string;
1882
- txt?: Record<string, string>;
1883
- }
1884
- interface LanDiscoveryBrowseOptions {
1885
- onServiceUp: (info: MemeloopServiceInfo) => void;
1886
- onServiceDown?: (name: string) => void;
1887
- }
1888
-
1889
- type DevicePlatform = 'desktop' | 'mobile' | 'cli';
1890
- type DeviceTrustMode = 'local-pairing' | 'cloud-account';
1891
- type DeviceReachabilityState = 'nearby' | 'online' | 'offline' | 'connecting';
1892
- type DeviceNetworkPath = 'lan' | 'direct' | 'relay';
1893
- type MemeLoopProtocol = '/memeloop/rpc/1.0.0' | '/memeloop/sync/1.0.0' | '/memeloop/agent/1.0.0' | '/memeloop/pairing/1.0.0';
1894
- interface DeviceCapabilities {
1895
- tools: string[];
1896
- mcpServers: string[];
1897
- hasWiki: boolean;
1898
- imChannels: string[];
1899
- wikis: Array<{
1900
- wikiId: string;
1901
- title?: string;
1902
- pathHint?: string;
1903
- }>;
1904
- }
1905
- interface LocalDeviceIdentity {
1906
- peerId: string;
1907
- publicKeyMultibase: string;
1908
- privateKeyRef: string;
1909
- privateKeyPkcs8Base64Url?: string;
1910
- privateKeyRawSeedBase64Url?: string;
1911
- createdAt: number;
1912
- deviceName: string;
1913
- platform: DevicePlatform;
1914
- }
1915
- interface DeviceNetworkListenOptions {
1916
- addresses: string[];
1917
- announce?: string[];
1918
- }
1919
- interface DeviceReachability {
1920
- state: DeviceReachabilityState;
1921
- paths: DeviceNetworkPath[];
1922
- }
1923
- interface Device {
1924
- peerId: string;
1925
- displayName: string;
1926
- platform: DevicePlatform;
1927
- trustMode: DeviceTrustMode;
1928
- reachability: DeviceReachability;
1929
- capabilities: DeviceCapabilities;
1930
- lastSeen?: number;
1931
- }
1932
- interface TrustedDeviceRecord {
1933
- peerId: string;
1934
- publicKeyMultibase: string;
1935
- deviceName: string;
1936
- platform: DevicePlatform;
1937
- trustMode: DeviceTrustMode;
1938
- accountId?: string;
1939
- createdAt: number;
1940
- lastSeen?: number;
1941
- revokedAt?: number;
1942
- }
1943
- interface DeviceAccountBindingRequest {
1944
- peerId: string;
1945
- publicKeyMultibase: string;
1946
- deviceName: string;
1947
- platform: DevicePlatform;
1948
- cloudNonce: string;
1949
- signature: string;
1950
- }
1951
- interface CloudDeviceRecord {
1952
- accountId: string;
1953
- peerId: string;
1954
- publicKeyMultibase: string;
1955
- deviceName: string;
1956
- platform: DevicePlatform;
1957
- capabilities: DeviceCapabilities;
1958
- multiaddrs: string[];
1959
- relayReservations: string[];
1960
- lastSeen: number;
1961
- revokedAt?: number;
1962
- }
1963
- interface DeviceConnectionGrant {
1964
- issuer: 'memeloop-cloud';
1965
- accountId: string;
1966
- subjectPeerId: string;
1967
- allowedPeerIds: string[];
1968
- issuedAt: number;
1969
- expiresAt: number;
1970
- signature: string;
1971
- }
1972
- interface PairingSession {
1973
- sessionId: string;
1974
- localPeerId: string;
1975
- remotePeerId: string;
1976
- confirmCode: string;
1977
- expiresAt: number;
1978
- }
1979
- interface SyncResult {
1980
- ok: boolean;
1981
- peerId: string;
1982
- syncedAt: number;
1983
- }
1984
- interface MemeLoopDuplexStream {
1985
- source: AsyncIterable<Uint8Array>;
1986
- sink(source: AsyncIterable<Uint8Array>): Promise<void>;
1987
- close(): Promise<void>;
1988
- }
1989
- interface DeviceAuthorizer {
1990
- canOpenProtocol(input: {
1991
- remotePeerId: string;
1992
- protocol: MemeLoopProtocol;
1993
- presentedGrant?: DeviceConnectionGrant;
1994
- }): Promise<boolean>;
1995
- }
1996
- interface DeviceNetworkService {
1997
- start(): Promise<void>;
1998
- stop(): Promise<void>;
1999
- getLocalDevice(): Promise<Device>;
2000
- listDevices(): Promise<Device[]>;
2001
- observeDevices(listener: (devices: Device[]) => void): () => void;
2002
- requestLocalPairing(peerId: string): Promise<PairingSession>;
2003
- acceptPairing(sessionId: string): Promise<void>;
2004
- rejectPairing(sessionId: string): Promise<void>;
2005
- removeTrustedDevice(peerId: string): Promise<void>;
2006
- openStream(peerId: string, protocol: MemeLoopProtocol): Promise<MemeLoopDuplexStream>;
2007
- sendRpc<T>(peerId: string, method: string, parameters: unknown): Promise<T>;
2008
- syncWithDevice(peerId: string): Promise<SyncResult>;
2009
- }
2010
- interface ExchangeVersionVectorResult {
2011
- remoteVersion: VersionVector;
2012
- missingForRemote: ConversationMeta[];
2013
- }
2014
- interface AttachmentBlob {
2015
- data: Uint8Array;
2016
- filename: string;
2017
- mimeType: string;
2018
- size: number;
2019
- }
2020
- interface DeviceSyncTransport {
2021
- listPeers(): Promise<Device[]>;
2022
- exchangeVersionVector(peerId: string, localVersion: VersionVector): Promise<ExchangeVersionVectorResult>;
2023
- pullMissingMetadata(peerId: string, sinceVersion: VersionVector): Promise<ConversationMeta[]>;
2024
- pullMissingMessages(peerId: string, conversationId: string, knownMessageIds: string[]): Promise<ChatMessage[]>;
2025
- pullAttachmentBlob(peerId: string, contentHash: string): Promise<AttachmentBlob | null>;
2026
- }
2027
-
2028
- interface RawSeedDeviceIdentity extends LocalDeviceIdentity {
2029
- privateKeyRawSeedBase64Url: string;
2030
- }
2031
- declare function encodePublicKeyMultibase(publicKey: PublicKey): string;
2032
- declare function decodePublicKeyMultibase(multibase: string): PublicKey;
2033
- declare function createDeviceIdentity(platform: DevicePlatform, deviceName: string): Promise<RawSeedDeviceIdentity>;
2034
- declare function privateKeyFromIdentity(identity: LocalDeviceIdentity): Promise<PrivateKey>;
2035
- declare function buildDeviceBindingMessage(input: {
2036
- accountId: string;
2037
- peerId: string;
2038
- publicKeyMultibase: string;
2039
- nonce: string;
2040
- }): Uint8Array;
2041
- declare function signDeviceBinding(input: {
2042
- identity: LocalDeviceIdentity;
2043
- accountId: string;
2044
- nonce: string;
2045
- }): Promise<string>;
2046
- declare function verifyDeviceBinding(input: DeviceAccountBindingRequest & {
2047
- accountId: string;
2048
- }): Promise<boolean>;
2049
-
2050
- interface Libp2pDeviceNetworkServiceOptions {
2051
- identity: LocalDeviceIdentity;
2052
- capabilities?: DeviceCapabilities;
2053
- trustedDevices?: TrustedDeviceRecord[];
2054
- listen?: DeviceNetworkListenOptions;
2055
- enableMdns?: boolean;
2056
- autoDialDiscoveredPeers?: boolean;
2057
- }
2058
- declare class Libp2pDeviceNetworkService implements DeviceNetworkService {
2059
- private readonly options;
2060
- private libp2p?;
2061
- private readonly capabilities;
2062
- private readonly discoveredDevices;
2063
- private readonly trustedDevices;
2064
- private readonly pairingSessions;
2065
- private readonly listeners;
2066
- constructor(options: Libp2pDeviceNetworkServiceOptions);
2067
- start(): Promise<void>;
2068
- stop(): Promise<void>;
2069
- getLocalDevice(): Promise<Device>;
2070
- listDevices(): Promise<Device[]>;
2071
- observeDevices(listener: (devices: Device[]) => void): () => void;
2072
- requestLocalPairing(peerId: string): Promise<PairingSession>;
2073
- acceptPairing(sessionId: string): Promise<void>;
2074
- rejectPairing(sessionId: string): Promise<void>;
2075
- removeTrustedDevice(peerId: string): Promise<void>;
2076
- openStream(peerId: string, protocol: MemeLoopProtocol): Promise<MemeLoopDuplexStream>;
2077
- sendRpc<T>(peerId: string, method: string, parameters: unknown): Promise<T>;
2078
- syncWithDevice(peerId: string): Promise<SyncResult>;
2079
- getMultiaddrs(): string[];
2080
- private createNode;
2081
- private registerDiscoveryListeners;
2082
- private registerProtocolHandlers;
2083
- private wrapStream;
2084
- private streamSource;
2085
- private markPeerOnline;
2086
- private markPeerOffline;
2087
- private updateDeviceTrust;
2088
- private confirmCode;
2089
- private emitDevices;
2090
- private requireNode;
2091
- }
2092
-
2093
- interface MemoryDeviceNetworkServiceOptions {
2094
- identity: LocalDeviceIdentity;
2095
- capabilities?: DeviceCapabilities;
2096
- trustedDevices?: TrustedDeviceRecord[];
2097
- }
2098
- declare class MemoryDeviceNetworkService implements DeviceNetworkService {
2099
- private readonly options;
2100
- private started;
2101
- private readonly capabilities;
2102
- private readonly trustedDevices;
2103
- private readonly pairingSessions;
2104
- private readonly listeners;
2105
- constructor(options: MemoryDeviceNetworkServiceOptions);
2106
- start(): Promise<void>;
2107
- stop(): Promise<void>;
2108
- getLocalDevice(): Promise<Device>;
2109
- listDevices(): Promise<Device[]>;
2110
- observeDevices(listener: (devices: Device[]) => void): () => void;
2111
- requestLocalPairing(peerId: string): Promise<PairingSession>;
2112
- acceptPairing(sessionId: string): Promise<void>;
2113
- rejectPairing(sessionId: string): Promise<void>;
2114
- removeTrustedDevice(peerId: string): Promise<void>;
2115
- openStream(peerId: string, _protocol: MemeLoopProtocol): Promise<MemeLoopDuplexStream>;
2116
- sendRpc<T>(peerId: string, _method: string, _parameters: unknown): Promise<T>;
2117
- syncWithDevice(peerId: string): Promise<SyncResult>;
2118
- private confirmCode;
2119
- private emitDevices;
2120
- }
2121
-
2122
- /**
2123
- * IM 接入框架(平台无关):适配器负责验签/解析;ChannelManager 负责会话路由。
2124
- */
2125
-
2126
- /** 平台 Webhook 解析后的统一入站消息 */
2127
- interface ImInboundMessage {
2128
- channelId: string;
2129
- platform: IMPlatformType;
2130
- imUserId: string;
2131
- text: string;
2132
- /** 平台原始结构,便于调试或扩展富媒体 */
2133
- raw: unknown;
2134
- }
2135
- interface ImWebhookContext {
2136
- headers: Record<string, string | string[] | undefined>;
2137
- body: Uint8Array;
2138
- /** GET/POST query(如企业微信密文回调的 msg_signature、timestamp、nonce) */
2139
- query?: Record<string, string>;
2140
- }
2141
- /**
2142
- * 单平台适配器:verify 失败应返回 false;parse 失败返回 null。
2143
- */
2144
- interface IIMAdapter {
2145
- readonly platform: IMPlatformType;
2146
- verify(context: ImWebhookContext): boolean;
2147
- parse(channelId: string, context: ImWebhookContext): ImInboundMessage | null;
2148
- }
2149
- /** 将 Agent 输出格式化为 IM 可发送的纯文本 */
2150
- interface IIMMessageRenderer {
2151
- renderPlainText(content: string): string;
2152
- /** 单行工具调用摘要(IM 默认不展示完整工具参数/结果) */
2153
- renderToolCallSummary(toolName: string, arguments_: unknown): string;
2154
- /**
2155
- * 工具结果摘要(返回 null 表示隐藏)。
2156
- * 规则摘要优先:避免把大结果刷到 IM。
2157
- */
2158
- renderToolResultSummary(toolName: string, result: unknown): string | null;
2159
- renderToolApproval(toolName: string, arguments_: unknown): string;
2160
- renderAskQuestion(question: string, options?: string[]): string;
2161
- /** IM 默认隐藏 thinking,若要显示由实现自行决定。 */
2162
- renderThinking(content: string): string | null;
2163
- renderError(error: string): string;
2164
- renderTodoList(todos: Array<{
2165
- id: string;
2166
- text: string;
2167
- done?: boolean;
2168
- }>): string;
2169
- }
2170
- /** 节点侧驱动 Agent 的最小能力(避免循环依赖 MemeLoopRuntime 类型) */
2171
- interface ImAgentDriver {
2172
- createAgent(options: {
2173
- definitionId: string;
2174
- initialMessage?: string;
2175
- }): Promise<{
2176
- conversationId: string;
2177
- }>;
2178
- sendMessage(options: {
2179
- conversationId: string;
2180
- message: string;
2181
- }): Promise<void>;
2182
- }
2183
-
2184
- /**
2185
- * 管理 IM 用户与会话的绑定;可选 `storage` 使用 IAgentStorage 的 IM 绑定持久化。
2186
- */
2187
- declare class IMChannelManager {
2188
- private readonly storage?;
2189
- private readonly bindings;
2190
- constructor(storage?: {
2191
- getImBinding?(c: string, u: string): Promise<IMChannelBinding | null>;
2192
- setImBinding?(r: IMChannelBinding): Promise<void>;
2193
- } | undefined);
2194
- private key;
2195
- getBinding(channelId: string, imUserId: string): Promise<IMChannelBinding | undefined>;
2196
- setBinding(record: IMChannelBinding): Promise<void>;
2197
- /**
2198
- * 处理入站文本:无 binding 时创建会话并发送首条用户消息。
2199
- */
2200
- dispatchInbound(message: ImInboundMessage, driver: ImAgentDriver, options: {
2201
- defaultDefinitionId: string;
2202
- }): Promise<{
2203
- conversationId: string;
2204
- }>;
2205
- switchConversation(channelId: string, imUserId: string, conversationId: string): Promise<void>;
2206
- }
2207
- declare function pickAdapter(adapters: IIMAdapter[], platform: string): IIMAdapter | undefined;
2208
-
2209
- /** Plan §20.6.1 — chunk assistant text before sending to IM APIs. */
2210
- declare function imPlatformMaxMessageChars(platform: string): number;
2211
-
2212
- interface IAgentStorage {
2213
- listConversations(options?: ListConversationsOptions): Promise<ConversationMeta[]>;
2214
- getMessages(conversationId: string, options?: GetMessagesOptions): Promise<ChatMessage[]>;
2215
- appendMessage(message: ChatMessage): Promise<void>;
2216
- upsertConversationMetadata(meta: ConversationMeta): Promise<void>;
2217
- insertMessagesIfAbsent(messages: ChatMessage[]): Promise<void>;
2218
- getAttachment(contentHash: string): Promise<AttachmentReference | null>;
2219
- saveAttachment(reference: AttachmentReference, data: Buffer | Uint8Array): Promise<void>;
2220
- readAttachmentData?(contentHash: string): Promise<Uint8Array | null>;
2221
- getAgentDefinition(id: string): Promise<AgentDefinition | null>;
2222
- getMaxLamportClockForConversation?(conversationId: string): Promise<number>;
2223
- saveAgentInstance(meta: AgentInstanceMeta): Promise<void>;
2224
- getConversationMeta(conversationId: string): Promise<ConversationMeta | null>;
2225
- getImBinding?(channelId: string, imUserId: string): Promise<IMChannelBinding | null>;
2226
- setImBinding?(record: IMChannelBinding): Promise<void>;
2227
- }
2228
-
2229
- interface ImSlashCommandContext {
2230
- rawText: string;
2231
- channelId: string;
2232
- imUserId: string;
2233
- manager: IMChannelManager;
2234
- storage: IAgentStorage;
2235
- driver: ImAgentDriver;
2236
- runtime: MemeLoopRuntime;
2237
- defaultDefinitionId: string;
2238
- }
2239
- /**
2240
- * Plan §20.6.4 — parse `/list`, `/switch`, `/new`, `/agent`, `/status`, `/cancel` locally (no LLM).
2241
- */
2242
- declare function tryHandleImSlashCommand(context: ImSlashCommandContext): Promise<{
2243
- handled: boolean;
2244
- messages: string[];
2245
- }>;
2246
-
2247
- /** 通用文本/Markdown 友好输出(IM 端以纯文本展示) */
2248
- declare class TextMessageRenderer implements IIMMessageRenderer {
2249
- renderPlainText(content: string): string;
2250
- renderToolCallSummary(toolName: string, arguments_: unknown): string;
2251
- renderToolResultSummary(toolName: string, result: unknown): string | null;
2252
- renderToolApproval(toolName: string, arguments_: unknown): string;
2253
- renderAskQuestion(question: string, options?: string[]): string;
2254
- renderThinking(_content: string): string | null;
2255
- renderError(error: string): string;
2256
- renderTodoList(todos: Array<{
2257
- id: string;
2258
- text: string;
2259
- done?: boolean;
2260
- }>): string;
2261
- }
2262
-
2263
- type ImStreamFlush = (text: string) => Promise<void>;
2264
- /**
2265
- * Subscribe to `runtime` agent updates and forward assistant text + light tool summaries to IM,
2266
- * flushing when the buffer reaches the platform limit (plan §20.6.1).
2267
- */
2268
- declare function streamRuntimeAgentReplyToIm(options: {
2269
- runtime: MemeLoopRuntime;
2270
- conversationId: string;
2271
- platform: string;
2272
- renderer: TextMessageRenderer;
2273
- flush: ImStreamFlush;
2274
- }): Promise<void>;
2275
-
2276
- /**
2277
- * IM 会话控制工具(计划 20.4):在带 IM binding 的会话中注入。
2278
- * 这里仅导出工具 schema 描述,实际注册由上层 ToolRegistry 完成。
2279
- */
2280
- declare const imToolDefinitions: readonly [{
2281
- readonly name: "im.listConversations";
2282
- readonly description: "列出可切换的会话(由 memeloop-cli registerImSessionTools 注册,仅 IM 来源会话可用)。";
2283
- }, {
2284
- readonly name: "im.switchConversation";
2285
- readonly description: "切换当前 IM 用户绑定的活跃会话。参数:{ conversationId: string }";
2286
- }, {
2287
- readonly name: "im.newConversation";
2288
- readonly description: "创建新会话并切换绑定。参数:{ definitionId?: string }";
2289
- }, {
2290
- readonly name: "im.summarizeHistory";
2291
- readonly description: "返回当前会话最近消息的纯文本摘要(规则拼接,非 LLM)。参数:{ maxMessages?: number }";
2292
- }];
2293
- interface ImToolsRuntime {
2294
- channelId: string;
2295
- imUserId: string;
2296
- manager: IMChannelManager;
2297
- driver: ImAgentDriver;
2298
- defaultDefinitionId: string;
2299
- }
2300
- /** 供工具实现层调用的命令式 API(避免在 core 内耦合 defineTool) */
2301
- declare function imSwitchConversation(rt: ImToolsRuntime, conversationId: string): Promise<void>;
2302
-
2303
- /**
2304
- * Layered permission system types.
2305
- *
2306
- * Permissions are resolved by merging rule sets from multiple layers
2307
- * (default → agent → user → session), where later layers override earlier ones.
2308
- */
2309
- /** Permission action for a tool invocation. */
2310
- type PermissionAction = 'allow' | 'deny' | 'ask';
2311
- /** A single permission rule: matches a tool name pattern to an action. */
2312
- interface PermissionRule {
2313
- /** Wildcard-capable pattern, e.g. `"file.*"`, `"shell(rm)"`, `"*"`. */
2314
- toolPattern: string;
2315
- action: PermissionAction;
2316
- }
2317
- /** A set of permission rules belonging to a specific source/layer. */
2318
- interface PermissionSet {
2319
- rules: PermissionRule[];
2320
- /** Human-readable source identifier for debugging (e.g. "default", "agent:cli-buddy", "user"). */
2321
- source: string;
2322
- }
2323
- /**
2324
- * Result of merging multiple `PermissionSet` layers.
2325
- * Each array contains flattened, deduplicated tool patterns for that action.
2326
- */
2327
- interface MergedPermissions {
2328
- allow: string[];
2329
- deny: string[];
2330
- ask: string[];
2331
- }
2332
-
2333
- /**
2334
- * Hook system types for memeloop.
2335
- * Hooks are lifecycle callbacks that execute before/after key events in the agent loop.
2336
- */
2337
-
2338
- /** Context passed to all hook handlers. */
2339
- type HookContext = AgentFrameworkContext;
2340
- /** Result returned by a hook handler. */
2341
- interface HookResult {
2342
- /** Whether to allow the action to proceed (false = block/deny) */
2343
- allowed: boolean;
2344
- /** Optional message explaining why the action was blocked */
2345
- reason?: string;
2346
- /** Optional data modified by the hook (e.g., transformed tool args) */
2347
- modified?: Record<string, unknown>;
2348
- /** Optional tool permission action. Interpreted by PreToolUse callers. */
2349
- permissionAction?: PermissionAction;
2350
- }
2351
- /** Signature of a hook handler function. */
2352
- type HookHandler = (context: HookContext, data: Record<string, unknown>) => Promise<HookResult>;
2353
- /** Enum of supported hook event types. */
2354
- type HookType = 'PreToolUse' | 'PostToolUse' | 'UserPromptSubmit' | 'ContextCompaction' | 'AgentStart' | 'AgentStop';
2355
- /** Data passed to PreToolUse hooks. */
2356
- interface PreToolUseData extends Record<string, unknown> {
2357
- toolId: string;
2358
- parameters: Record<string, unknown>;
2359
- conversationId: string;
2360
- }
2361
- /** Data passed to PostToolUse hooks. */
2362
- interface PostToolUseData extends Record<string, unknown> {
2363
- toolId: string;
2364
- parameters: Record<string, unknown>;
2365
- result: string;
2366
- isError: boolean;
2367
- conversationId: string;
2368
- }
2369
- /** Data passed to UserPromptSubmit hooks. */
2370
- interface UserPromptSubmitData extends Record<string, unknown> {
2371
- message: string;
2372
- conversationId: string;
2373
- }
2374
- /** Data passed to ContextCompaction hooks before built-in history compaction. */
2375
- interface ContextCompactionData extends Record<string, unknown> {
2376
- conversationId: string;
2377
- iteration: number;
2378
- history: ChatMessage[];
2379
- autoCompact?: AgentFrameworkContext['taskAgent'] extends infer Options ? Options extends {
2380
- autoCompact?: infer AutoCompact;
2381
- } ? AutoCompact : never : never;
2382
- contextCompaction?: AgentFrameworkContext['taskAgent'] extends infer Options ? Options extends {
2383
- contextCompaction?: infer ContextCompaction;
2384
- } ? ContextCompaction : never : never;
2385
- }
2386
- /** Data passed to AgentStart hooks. */
2387
- interface AgentStartData extends Record<string, unknown> {
2388
- conversationId: string;
2389
- definitionId?: string;
2390
- }
2391
- /** Data passed to AgentStop hooks. */
2392
- interface AgentStopData extends Record<string, unknown> {
2393
- conversationId: string;
2394
- reason: 'completed' | 'cancelled' | 'max-iterations' | 'error';
2395
- }
2396
-
2397
- /**
2398
- * Hook registry for managing lifecycle hook handlers.
2399
- * Hooks execute in registration order (first registered, first executed).
2400
- *
2401
- * Converted from module-level singletons to an instance class for test isolation
2402
- * and multi-runtime support. Backward-compatible function exports delegate to a
2403
- * default global instance.
2404
- */
2405
-
2406
- /**
2407
- * Instance-level hook registry. Each instance maintains its own handler state.
2408
- */
2409
- declare class HookRegistry {
2410
- private readonly hookRegistry;
2411
- private readonly hookOrder;
2412
- /**
2413
- * Register a hook handler for a specific lifecycle event.
2414
- */
2415
- registerHook(type: HookType, handler: HookHandler, name?: string): void;
2416
- /**
2417
- * Unregister a specific hook handler by name.
2418
- */
2419
- unregisterHook(type: HookType, name: string): boolean;
2420
- /**
2421
- * Execute all registered hooks for a given type in registration order.
2422
- */
2423
- executeHooks(type: HookType, context: HookContext, data: Record<string, unknown>): Promise<HookResult>;
2424
- /**
2425
- * Check if any hooks are registered for a given type.
2426
- */
2427
- hasHooks(type: HookType): boolean;
2428
- /**
2429
- * Remove all registered hooks of all types.
2430
- */
2431
- clearHooks(): void;
2432
- /**
2433
- * List all hook types that have at least one registered handler.
2434
- */
2435
- listRegisteredHookTypes(): HookType[];
2436
- /**
2437
- * Get the count of registered handlers for a hook type.
2438
- */
2439
- getHookCount(type: HookType): number;
2440
- }
2441
- declare function getDefaultHookRegistry(): HookRegistry;
2442
- declare function registerHook(type: HookType, handler: HookHandler, name?: string): void;
2443
- declare function unregisterHook(type: HookType, name: string): boolean;
2444
- declare function executeHooks(type: HookType, context: HookContext, data: Record<string, unknown>): Promise<HookResult>;
2445
- declare function hasHooks(type: HookType): boolean;
2446
- declare function clearHooks(): void;
2447
- declare function listRegisteredHookTypes(): HookType[];
2448
- /**
2449
- * Get the count of registered handlers for a hook type.
2450
- */
2451
- declare function getHookCount(type: HookType): number;
2452
-
2453
- /**
2454
- * Test whether a tool name matches a wildcard pattern.
2455
- *
2456
- * Supported patterns:
2457
- * - `*` → matches everything
2458
- * - `file.*` → matches any tool starting with `file.`
2459
- * - `shell(*)` → matches tools like `shell(rm)`, `shell(ls)` (literal parens)
2460
- * - exact name → matches only that exact tool name
2461
- *
2462
- * Patterns are converted to anchored regexes internally.
2463
- */
2464
- declare function matchPattern(toolName: string, pattern: string): boolean;
2465
- /**
2466
- * Merge multiple permission sets from lowest to highest priority.
2467
- *
2468
- * Sets are processed in order; later rules override earlier ones for the same tool pattern.
2469
- * Within a single set, rules are processed in order (last wins).
2470
- *
2471
- * @param sets - Ordered from lowest to highest priority (e.g. default → agent → user → session)
2472
- * @returns Flattened `MergedPermissions` with all unique patterns per action.
2473
- */
2474
- declare function mergePermissionSets(sets: PermissionSet[]): MergedPermissions;
2475
- /**
2476
- * Check what action applies to a given tool name under merged permissions.
2477
- *
2478
- * Precedence: exact patterns always beat wildcards.
2479
- * Within same specificity: deny > ask > allow.
2480
- */
2481
- declare function checkPermission(toolName: string, merged: MergedPermissions): PermissionAction;
2482
-
2483
- interface PermissionSqlStatement {
2484
- get(...arguments_: unknown[]): unknown;
2485
- run(...arguments_: unknown[]): unknown;
2486
- }
2487
- interface PermissionSqlDatabase {
2488
- prepare(sql: string): PermissionSqlStatement;
2489
- }
2490
- /**
2491
- * Load user-level permission set from SQLite.
2492
- *
2493
- * The `permissions` table stores JSON blobs keyed by `source`.
2494
- * Returns an empty set if no persisted rules exist.
2495
- */
2496
- declare function loadUserPermissions(database: PermissionSqlDatabase): PermissionSet;
2497
- /**
2498
- * Persist user-level permission set to SQLite.
2499
- *
2500
- * Uses INSERT OR REPLACE so first-time saves work without explicit table detection.
2501
- */
2502
- declare function saveUserPermissions(database: PermissionSqlDatabase, set: PermissionSet): void;
2503
- /** SQL statement to create the permissions table during migration. */
2504
- declare const PERMISSIONS_TABLE_DDL = "\n CREATE TABLE IF NOT EXISTS permissions (\n source TEXT PRIMARY KEY,\n rulesJson TEXT NOT NULL,\n updatedAt INTEGER NOT NULL\n );\n";
2505
-
2506
- /**
2507
- * Plugin marketplace architecture types.
2508
- * Plugins can provide tools and hooks to extend memeloop.
2509
- */
2510
-
2511
- /**
2512
- * Plugin manifest schema.
2513
- * Host adapters may read this from files or construct it programmatically.
2514
- */
2515
- interface PluginManifest {
2516
- /** Unique plugin identifier (e.g. "plugin-hello", "@scope/my-plugin") */
2517
- name: string;
2518
- /** Semantic version */
2519
- version: string;
2520
- /** Human-readable description */
2521
- description: string;
2522
- /** Declared exports: what the plugin provides */
2523
- exports?: PluginExports;
2524
- /** Plugin author */
2525
- author?: string;
2526
- /** Minimum memeloop version requirement (semver range) */
2527
- minMemeloopVersion?: string;
2528
- }
2529
- /** Declared capabilities a plugin may export. */
2530
- interface PluginExports {
2531
- /** Tool IDs this plugin implements */
2532
- tools?: string[];
2533
- /** Hook types this plugin listens for */
2534
- hooks?: HookType[];
2535
- }
2536
- /**
2537
- * Shape of a loaded plugin module's default export.
2538
- * Plugins must export default an object conforming to this interface.
2539
- */
2540
- interface PluginModule {
2541
- /** Plugin identity (must match manifest name) */
2542
- name: string;
2543
- /**
2544
- * Called when the plugin is loaded. Receives the PluginAPI for registering
2545
- * tools and hooks. Return a cleanup function for teardown.
2546
- */
2547
- activate: (api: PluginAPI) => (() => void) | Promise<() => void> | undefined;
2548
- }
2549
- /**
2550
- * API surface exposed to plugins. Plugins call these methods in their
2551
- * `activate` function to register their capabilities.
2552
- */
2553
- interface PluginAPI {
2554
- /**
2555
- * Register a tool implementation.
2556
- * @param toolId - Unique tool ID (e.g. "plugin-hello.sayHi")
2557
- * @param impl - Tool implementation function
2558
- * @param schema - Optional parameter schema (Zod type)
2559
- */
2560
- registerTool(toolId: string, impl: (...arguments_: unknown[]) => unknown, schema?: unknown): void;
2561
- /**
2562
- * Register a lifecycle hook handler.
2563
- * @param type - Hook event type
2564
- * @param handler - Async handler function
2565
- * @param name - Optional handler name (enables dedup/unregistration)
2566
- */
2567
- registerHook(type: HookType, handler: HookHandler, name?: string): void;
2568
- /** Log to memeloop's logger (falls back to console). */
2569
- logger: {
2570
- debug: (message: string, ...arguments_: unknown[]) => void;
2571
- info: (message: string, ...arguments_: unknown[]) => void;
2572
- warn: (message: string, ...arguments_: unknown[]) => void;
2573
- error: (message: string, ...arguments_: unknown[]) => void;
2574
- };
2575
- }
2576
- /** Metadata about a loaded plugin instance. */
2577
- interface LoadedPlugin {
2578
- /** Manifest data */
2579
- manifest: PluginManifest;
2580
- /** Optional host-provided source identifier, e.g. package name or file path. */
2581
- source: string;
2582
- /** The loaded plugin module */
2583
- module: PluginModule;
2584
- /** Cleanup function returned by activate(), if any */
2585
- cleanup: (() => void) | undefined;
2586
- /** When the plugin was loaded */
2587
- loadedAt: Date;
2588
- }
2589
-
2590
- declare function validatePluginManifest(object: unknown): PluginManifest | null;
2591
- interface LoadPluginModuleOptions {
2592
- manifest: PluginManifest;
2593
- module: PluginModule;
2594
- api?: unknown;
2595
- source?: string;
2596
- }
2597
- declare function loadPluginModule(options: LoadPluginModuleOptions): Promise<LoadedPlugin | null>;
2598
- declare function loadPluginModules(plugins: LoadPluginModuleOptions[]): Promise<LoadedPlugin[]>;
2599
- declare function unloadPlugin(name: string): boolean;
2600
- declare function listPlugins(): LoadedPlugin[];
2601
- declare function getLoadedPlugin(name: string): LoadedPlugin | undefined;
2602
- declare function isPluginLoaded(name: string): boolean;
2603
- declare function unloadAllPlugins(): void;
2604
-
2605
- /**
2606
- * Plugin registry: bridges plugin exports to memeloop's tool and hook registries.
2607
- *
2608
- * Provides a `createPluginAPI()` factory that plugins call during `activate()`
2609
- * to register their tools and hooks with the host runtime.
2610
- *
2611
- * Converted from module-level singletons to an instance class for test isolation
2612
- * and multi-runtime support.
2613
- */
2614
-
2615
- /** Plugin API factory options. */
2616
- interface PluginAPIOptions {
2617
- toolRegistry?: {
2618
- registerTool(id: string, impl: unknown): void;
2619
- };
2620
- logger?: PluginAPI['logger'];
2621
- }
2622
- /**
2623
- * Track which tools/plugins belong to each plugin so we can clean up on unload.
2624
- */
2625
- interface PluginRegistration {
2626
- pluginName: string;
2627
- tools: string[];
2628
- hooks: Array<{
2629
- type: HookType;
2630
- name: string;
2631
- }>;
2632
- }
2633
- declare function createPluginAPI(options?: PluginAPIOptions): PluginAPI;
2634
- declare function registerPluginTools(pluginName: string, tools: Array<readonly [string, (...arguments_: unknown[]) => unknown, unknown?]>): void;
2635
- declare function registerPluginHooks(pluginName: string, hooks: Array<readonly [HookType, HookHandler, string?]>): void;
2636
- declare function getPluginRegistrations(pluginName: string): PluginRegistration | undefined;
2637
- declare function clearPluginRegistrations(): void;
2638
-
2639
- /**
2640
- * 注册内置 prompt 插件(fullReplacement、dynamicPosition)。
2641
- * @param target 若传入(如节点 `ToolRegistry` 上的 Map),只写入该表;否则写入活动注册表(全局或 ALS)。
2642
- */
2643
- declare function registerBuiltinPromptPlugins(target?: Map<string, PromptConcatTool>): void;
2644
-
2645
- /** 扁平化后的 LLM 消息(不依赖 peer `ai` 包导出,避免 d.ts 与 SDK 主版本不一致) */
2646
- type PromptFlatModelMessage = {
2647
- role: 'system' | 'user' | 'assistant' | 'tool';
2648
- content: unknown;
2649
- };
2650
- declare function findPromptById(prompts: PromptNode[], id: string): {
2651
- prompt: PromptNode;
2652
- parent: PromptNode[];
2653
- index: number;
2654
- } | undefined;
2655
- declare function flattenPrompts(prompts: PromptNode[]): PromptFlatModelMessage[];
2656
- interface PromptConcatPluginPreview {
2657
- id: string;
2658
- toolId?: string;
2659
- caption?: string;
2660
- }
2661
- interface PromptConcatStreamState {
2662
- processedPrompts: PromptNode[];
2663
- flatPrompts: PromptFlatModelMessage[];
2664
- step: 'flatten' | 'complete' | 'plugin' | 'finalize';
2665
- isComplete: boolean;
2666
- /** prompt 节点 id → JSON 路径(如 agentFrameworkConfig.prompts.0) */
2667
- sourcePaths?: Record<string, string>;
2668
- /** Desktop UI: plugin currently being processed. */
2669
- currentPlugin?: PromptConcatPluginPreview;
2670
- /** Desktop UI: progress value between 0 and 1. */
2671
- progress?: number;
2672
- }
2673
- interface PromptConcatOptions {
2674
- readAttachmentFile?: (path: string) => Promise<Uint8Array | Buffer>;
2675
- }
2676
- declare function promptConcatStream(agentConfig: Pick<AgentPromptDescription, 'agentFrameworkConfig'>, messages: ChatMessage[], agentFrameworkContext: AgentFrameworkContext, options?: PromptConcatOptions): AsyncGenerator<PromptConcatStreamState, PromptConcatStreamState, unknown>;
2677
-
2678
- /**
2679
- * TidGi `approval.ts` 逐行迁移(pending 队列 + UI 监听)。
2680
- */
2681
-
2682
- declare function onApprovalRequest(listener: (request: ToolApprovalRequest) => void): () => void;
2683
- declare function evaluateApproval(approval: ToolApprovalConfig | undefined, toolName: string, parameters: Record<string, unknown>): ApprovalDecision;
2684
- declare function requestApproval(request: ToolApprovalRequest, timeoutMs?: number): Promise<'allow' | 'deny'>;
2685
- declare function resolveApproval(approvalId: string, decision: 'allow' | 'deny'): void;
2686
- declare function getPendingApprovals(): ToolApprovalRequest[];
2687
- declare function cancelPendingApprovals(agentId: string): void;
2688
-
2689
- interface NodeIdentity {
2690
- nodeId: string;
2691
- userId: string;
2692
- name: string;
2693
- type: 'desktop' | 'node' | 'mobile';
2694
- }
2695
- /** 节点暴露的 Wiki / 知识库条目(与计划「能力发现」对齐)。 */
2696
- interface WikiInfo {
2697
- wikiId: string;
2698
- title?: string;
2699
- /** 可选:相对节点配置的根路径说明,不含敏感绝对路径 */
2700
- pathHint?: string;
2701
- }
2702
- interface NodeCapabilities {
2703
- tools: string[];
2704
- mcpServers: string[];
2705
- hasWiki: boolean;
2706
- imChannels: string[];
2707
- /** 已挂载的 Wiki 列表(无 Wiki 能力时可为空数组) */
2708
- wikis: WikiInfo[];
2709
- }
2710
- interface NodeConnectivity {
2711
- publicIP?: string;
2712
- frpAddress?: string;
2713
- lanAddress?: string;
2714
- }
2715
- interface NodeStatus {
2716
- identity: NodeIdentity;
2717
- capabilities: NodeCapabilities;
2718
- connectivity: NodeConnectivity;
2719
- status: 'online' | 'offline' | 'unknown';
2720
- lastSeen: number;
2721
- }
2722
-
2723
- /**
2724
- * Context passed to builtin tool implementations.
2725
- * Extends AgentFrameworkContext with optional capabilities for MCP proxy, spawn and remote agent.
2726
- */
2727
- interface BuiltinToolContext extends AgentFrameworkContext {
2728
- /**
2729
- * 当前工具执行时对应的 conversationId(由宿主/运行时注入)。
2730
- * IM 会话工具依赖该值定位会话来源;缺失时工具返回错误而不是抛异常。
2731
- */
2732
- activeToolConversationId?: string;
2733
- /**
2734
- * Run the local task agent (for spawnAgent). If not provided, spawnAgent tool will return an error.
2735
- */
2736
- runLocalAgent?(input: AgentLoopInput): AgentLoopGenerator;
2737
- /**
2738
- * List known peer nodes (for remoteAgent). If not provided, remoteAgent returns empty list / "not configured".
2739
- */
2740
- getPeers?(): Promise<NodeStatus[]>;
2741
- /**
2742
- * Send JSON-RPC to a peer node (for remoteAgent and MCP proxy). If not provided, remote calls fail.
2743
- */
2744
- sendRpcToNode?(nodeId: string, method: string, parameters: unknown): Promise<unknown>;
2745
- /**
2746
- * Call a tool on a remote MCP server on the given node (for mcpClient). If not provided, mcpClient returns error.
2747
- */
2748
- mcpCallRemote?(nodeId: string, serverName: string, toolName: string, arguments_: Record<string, unknown>): Promise<unknown>;
2749
- /**
2750
- * `remoteAgent` 等待远端流式输出的超时(毫秒)。默认 30000。
2751
- */
2752
- remoteAgentStreamTimeoutMs?: number;
2753
- /** 本节点 ID(用于 `spawnAgent` / `remoteAgent` 的 `detailRef.nodeId`)。未设时 spawn 使用 `"local"`。 */
2754
- localNodeId?: string;
2755
- /** `askQuestion` 阻塞前回调(可将 questionId 推送到 IM / UI,供 `resolveQuestion` RPC 回填)。 */
2756
- notifyAskQuestion?(payload: {
2757
- questionId: string;
2758
- question: string;
2759
- conversationId?: string;
2760
- inputType?: 'single-select' | 'multi-select' | 'text';
2761
- options?: Array<{
2762
- label: string;
2763
- description?: string;
2764
- }>;
2765
- allowFreeform?: boolean;
2766
- }): void;
2767
- }
2768
- /** Tool implementation: (args, context) => result. Context is bound at registration time. */
2769
- type BuiltinToolImpl = (arguments_: Record<string, unknown>, context: BuiltinToolContext) => Promise<unknown> | AsyncIterable<unknown>;
2770
-
2771
- declare const askQuestionConfigSchema: z.ZodObject<{
2772
- question: z.ZodString;
2773
- conversationId: z.ZodOptional<z.ZodString>;
2774
- timeoutMs: z.ZodOptional<z.ZodNumber>;
2775
- inputType: z.ZodOptional<z.ZodEnum<{
2776
- text: "text";
2777
- "single-select": "single-select";
2778
- "multi-select": "multi-select";
2779
- }>>;
2780
- options: z.ZodOptional<z.ZodArray<z.ZodObject<{
2781
- label: z.ZodString;
2782
- description: z.ZodOptional<z.ZodString>;
2783
- }, z.core.$strip>>>;
2784
- allowFreeform: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
2785
- }, z.core.$strip>;
2786
- /**
2787
- * Must match `tool_use name="ask-question"` extracted by responsePatternUtility.
2788
- */
2789
- declare const ASK_QUESTION_TOOL_ID = "ask-question";
2790
- declare function askQuestionImpl(arguments_: Record<string, unknown>, context: BuiltinToolContext): Promise<{
2791
- result: string;
2792
- } | {
2793
- error: string;
2794
- }>;
2795
-
2796
- /**
2797
- * AskUserQuestion Tool — Pause agent execution and ask user for input.
2798
- *
2799
- * Uses the existing askQuestion pattern (notifyAskQuestion + waitForQuestionAnswer)
2800
- * but provides a dedicated tool ID for explicit user question prompting.
2801
- */
2802
-
2803
- declare const askUserQuestionConfigSchema: z.ZodObject<{
2804
- question: z.ZodString;
2805
- inputType: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
2806
- text: "text";
2807
- "single-select": "single-select";
2808
- "multi-select": "multi-select";
2809
- }>>>;
2810
- options: z.ZodOptional<z.ZodArray<z.ZodObject<{
2811
- label: z.ZodString;
2812
- description: z.ZodOptional<z.ZodString>;
2813
- }, z.core.$strip>>>;
2814
- allowFreeform: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
2815
- timeoutMs: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
2816
- }, z.core.$strip>;
2817
- declare const ASK_USER_QUESTION_TOOL_ID = "askUserQuestion";
2818
- declare function askUserQuestionImpl(arguments_: Record<string, unknown>, context: BuiltinToolContext): Promise<{
2819
- result: string;
2820
- } | {
2821
- error: string;
2822
- }>;
2823
-
2824
- declare const IM_SESSION_TOOL_IDS: readonly ["im.listConversations", "im.switchConversation", "im.newConversation", "im.summarizeHistory"];
2825
- interface ImSessionBuiltinRegistration {
2826
- imChannelManager: IMChannelManager;
2827
- getMemeLoopRuntime: () => MemeLoopRuntime;
2828
- }
2829
- /**
2830
- * 注册 IM 会话专用工具(需节点传入 `imChannelManager` 与 `getMemeLoopRuntime`)。
2831
- */
2832
- declare function registerImSessionBuiltinTools(registry: IToolRegistry, context: BuiltinToolContext, reg: ImSessionBuiltinRegistration): void;
2833
-
2834
- declare const mcpClientConfigSchema: {
2835
- readonly type: "object";
2836
- readonly properties: {
2837
- readonly nodeId: {
2838
- readonly type: "string";
2839
- readonly description: "Target node ID";
2840
- };
2841
- readonly serverName: {
2842
- readonly type: "string";
2843
- readonly description: "MCP server name on that node";
2844
- };
2845
- readonly toolName: {
2846
- readonly type: "string";
2847
- readonly description: "Tool to invoke";
2848
- };
2849
- readonly args: {
2850
- readonly type: "object";
2851
- readonly description: "Tool arguments";
2852
- };
2853
- };
2854
- readonly required: readonly ["nodeId", "serverName", "toolName"];
2855
- };
2856
- declare const mcpClientImpl: BuiltinToolImpl;
2857
- declare function getMcpClientToolId(): string;
2858
-
2859
- declare const mcpForwardConfigSchema: {
2860
- readonly type: "object";
2861
- readonly properties: {
2862
- readonly action: {
2863
- readonly type: "string";
2864
- readonly enum: readonly ["list", "listTools"];
2865
- readonly description: "Action: 'list' returns nodes with MCP servers, 'listTools' returns all available MCP tools across nodes";
2866
- };
2867
- };
2868
- };
2869
- /**
2870
- * MCP forwarding tool: discover MCP servers and tools on connected nodes.
2871
- * - action=list: returns nodes with their MCP servers
2872
- * - action=listTools: returns all available MCP tools across all nodes
2873
- */
2874
- declare const mcpForwardImpl: BuiltinToolImpl;
2875
- declare function getMcpForwardToolId(): string;
2876
-
2877
- declare function resolveQuestionAnswer(questionId: string, answer: string): boolean;
2878
-
2879
- declare const remoteAgentConfigSchema: {
2880
- readonly type: "object";
2881
- readonly properties: {
2882
- readonly nodeId: {
2883
- readonly type: "string";
2884
- readonly description: "Target node ID to run the sub-agent on";
2885
- };
2886
- readonly definitionId: {
2887
- readonly type: "string";
2888
- readonly description: "Agent definition ID on that node";
2889
- };
2890
- readonly message: {
2891
- readonly type: "string";
2892
- readonly description: "Task message for the remote agent";
2893
- };
2894
- };
2895
- readonly required: readonly ["nodeId", "definitionId", "message"];
2896
- };
2897
- /** List nodes and their definitions (for tool description / agent choice). No args. */
2898
- declare const remoteAgentListImpl: BuiltinToolImpl;
2899
- declare const remoteAgentImpl: BuiltinToolImpl;
2900
- declare function getRemoteAgentToolId(): string;
2901
-
2902
- declare const spawnAgentConfigSchema: {
2903
- readonly type: "object";
2904
- readonly properties: {
2905
- readonly definitionId: {
2906
- readonly type: "string";
2907
- readonly description: "Agent definition ID to use for the sub-agent";
2908
- };
2909
- readonly message: {
2910
- readonly type: "string";
2911
- readonly description: "User message / task for the sub-agent";
2912
- };
2913
- };
2914
- readonly required: readonly ["definitionId", "message"];
2915
- };
2916
- declare const spawnAgentImpl: BuiltinToolImpl;
2917
- declare function getSpawnAgentToolId(): string;
2918
-
2919
- declare const taskToolConfigSchema: {
2920
- readonly type: "object";
2921
- readonly properties: {
2922
- readonly agent: {
2923
- readonly type: "string";
2924
- readonly description: "Agent ID to delegate to (e.g. 'memeloop:build', 'memeloop:explore')";
2925
- };
2926
- readonly prompt: {
2927
- readonly type: "string";
2928
- readonly description: "Task prompt / instructions for the delegated agent";
2929
- };
2930
- readonly background: {
2931
- readonly type: "boolean";
2932
- readonly description: "If true, runs asynchronously and returns a task ID immediately";
2933
- };
2934
- };
2935
- readonly required: readonly ["agent", "prompt"];
2936
- };
2937
- declare const taskToolImpl: BuiltinToolImpl;
2938
- declare function getTaskToolId(): string;
2939
-
2940
- /**
2941
- * TodoWrite Tool — Manage structured todo lists stored in conversation context.
2942
- *
2943
- * Supports operations: create, update, complete, list, remove.
2944
- * Todo state is stored in-memory per conversation, keyed by conversationId.
2945
- */
2946
-
2947
- declare const todoWriteConfigSchema: z.ZodObject<{
2948
- action: z.ZodEnum<{
2949
- update: "update";
2950
- complete: "complete";
2951
- list: "list";
2952
- create: "create";
2953
- remove: "remove";
2954
- }>;
2955
- id: z.ZodOptional<z.ZodString>;
2956
- content: z.ZodOptional<z.ZodString>;
2957
- status: z.ZodOptional<z.ZodEnum<{
2958
- pending: "pending";
2959
- completed: "completed";
2960
- cancelled: "cancelled";
2961
- in_progress: "in_progress";
2962
- }>>;
2963
- priority: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
2964
- high: "high";
2965
- medium: "medium";
2966
- low: "low";
2967
- }>>>;
2968
- }, z.core.$strip>;
2969
- declare const TODO_WRITE_TOOL_ID = "todoWrite";
2970
- /** Exported for test cleanup. */
2971
- declare function __clearTodoStore(): void;
2972
- declare function todoWriteImpl(arguments_: Record<string, unknown>, context: BuiltinToolContext): Promise<{
2973
- result: string;
2974
- } | {
2975
- error: string;
2976
- }>;
2977
-
2978
- /**
2979
- * Register framework-level builtin tools (agent orchestration, user interaction, MCP).
2980
- *
2981
- * Environment-specific tools (bash, file*, grep, glob, git, webFetch, webSearch, lsp)
2982
- * must be registered by the host environment (e.g. memeloop-cli via registerNodeEnvironmentTools).
2983
- */
2984
- declare function registerBuiltinTools(registry: IToolRegistry, context: BuiltinToolContext): void;
2985
-
2986
- /**
2987
- * TidGi `defineToolTypes.ts` 迁移(路径改为 memeloop)。
2988
- */
2989
-
2990
- interface ToolDefinition<TConfigSchema extends z.ZodType = z.ZodType, TLLMToolSchemas extends Record<string, z.ZodType> = Record<string, z.ZodType>> {
2991
- toolId: string;
2992
- displayName: string;
2993
- description: string;
2994
- configSchema: TConfigSchema;
2995
- llmToolSchemas?: TLLMToolSchemas;
2996
- onProcessPrompts?: (context: ToolHandlerContext<TConfigSchema>) => Promise<void> | void;
2997
- onResponseComplete?: (context: ResponseHandlerContext<TConfigSchema, TLLMToolSchemas>) => Promise<void> | void;
2998
- onPostProcess?: (context: PostProcessHandlerContext<TConfigSchema>) => Promise<void> | void;
2999
- }
3000
- interface ToolHandlerContext<TConfigSchema extends z.ZodType> {
3001
- config: z.infer<TConfigSchema>;
3002
- toolConfig: PromptConcatHookContext['toolConfig'];
3003
- prompts: IPrompt[];
3004
- messages: PromptConcatHookContext['messages'];
3005
- agentFrameworkContext: DefineToolAgentFrameworkContext;
3006
- findPrompt: (id: string) => ReturnType<typeof findPromptById>;
3007
- injectToolList: (options: InjectToolListOptions) => void;
3008
- injectContent: (options: InjectContentOptions) => void;
3009
- }
3010
- interface ResponseHandlerContext<TConfigSchema extends z.ZodType, TLLMToolSchemas extends Record<string, z.ZodType>> extends Omit<ToolHandlerContext<TConfigSchema>, 'prompts' | 'config'> {
3011
- config: z.infer<TConfigSchema> | undefined;
3012
- response: AIResponseContext['response'];
3013
- toolCall: ToolCallingMatch | null;
3014
- allToolCalls: Array<ToolCallingMatch & {
3015
- found: true;
3016
- }>;
3017
- isParallel: boolean;
3018
- agentFrameworkConfig: AIResponseContext['agentFrameworkConfig'];
3019
- executeToolCall: <TToolName extends keyof TLLMToolSchemas>(toolName: TToolName, executor: (parameters: z.infer<TLLMToolSchemas[TToolName]>) => Promise<ToolExecutionResult>) => Promise<boolean>;
3020
- executeAllMatchingToolCalls: <TToolName extends keyof TLLMToolSchemas>(toolName: TToolName, executor: (parameters: z.infer<TLLMToolSchemas[TToolName]>) => Promise<ToolExecutionResult>, options?: {
3021
- timeoutMs?: number;
3022
- }) => Promise<number>;
3023
- addToolResult: (options: AddToolResultOptions) => void;
3024
- yieldToSelf: () => void;
3025
- yieldToHuman: () => void;
3026
- hooks: PromptConcatHooks;
3027
- requestId?: string;
3028
- }
3029
- interface PostProcessHandlerContext<TConfigSchema extends z.ZodType> extends Omit<ToolHandlerContext<TConfigSchema>, never> {
3030
- llmResponse: string;
3031
- responses: PostProcessContext['responses'];
3032
- }
3033
- interface InjectToolListOptions {
3034
- targetId: string;
3035
- position: 'before' | 'after' | 'child';
3036
- toolSchemas?: z.ZodType[];
3037
- caption?: string;
3038
- }
3039
- interface InjectContentOptions {
3040
- targetId: string;
3041
- position: 'before' | 'after' | 'child';
3042
- content: string;
3043
- caption?: string;
3044
- id?: string;
3045
- }
3046
- interface AddToolResultOptions {
3047
- toolName: string;
3048
- parameters: unknown;
3049
- result: string;
3050
- isError?: boolean;
3051
- duration?: number;
3052
- }
3053
- interface ToolExecutionResult {
3054
- success: boolean;
3055
- data?: string;
3056
- error?: string;
3057
- metadata?: Record<string, unknown>;
3058
- }
3059
- interface DefinedTool<TConfigSchema extends z.ZodType = z.ZodType, TLLMToolSchemas extends Record<string, z.ZodType> = Record<string, z.ZodType>> {
3060
- tool: PromptConcatTool;
3061
- toolId: string;
3062
- configSchema: TConfigSchema;
3063
- llmToolSchemas: TLLMToolSchemas | undefined;
3064
- displayName: string;
3065
- description: string;
3066
- }
3067
-
3068
- /**
3069
- * TidGi `defineTool.ts` 逐行迁移;持久化改为 `AgentFrameworkContext.persistAgentMessage`(memeloop)。
3070
- */
3071
-
3072
- declare function defineTool<TConfigSchema extends z.ZodType, TLLMToolSchemas extends Record<string, z.ZodType> = Record<string, z.ZodType>>(definition: ToolDefinition<TConfigSchema, TLLMToolSchemas>): {
3073
- tool: PromptConcatTool;
3074
- toolId: string;
3075
- configSchema: TConfigSchema;
3076
- llmToolSchemas: TLLMToolSchemas | undefined;
3077
- displayName: string;
3078
- description: string;
3079
- };
3080
-
3081
- /**
3082
- * Host agent tool configuration → prompt plugin mapping.
3083
- * Every host (Desktop, CLI, Cloud) that defines agent tools needs this merge logic.
3084
- * Defined once in memeloop so each host doesn't reimplement it.
3085
- */
3086
-
3087
- type HostAgentToolConfig = AgentDefinitionToolConfig;
3088
- declare function mergeAgentToolsIntoFrameworkConfig(frameworkConfig: AgentFrameworkConfig | undefined, agentTools: HostAgentToolConfig[] | undefined): AgentFrameworkConfig;
3089
-
3090
- /**
3091
- * TidGi `parallelExecution.ts` 迁移。
3092
- */
3093
-
3094
- interface ToolCallEntry {
3095
- call: ToolCallingMatch & {
3096
- found: true;
3097
- };
3098
- executor: (parameters: Record<string, unknown>) => Promise<ToolExecutionResult>;
3099
- timeoutMs?: number;
3100
- }
3101
- interface ToolCallResult {
3102
- call: ToolCallingMatch & {
3103
- found: true;
3104
- };
3105
- status: 'fulfilled' | 'rejected' | 'timeout';
3106
- result?: ToolExecutionResult;
3107
- error?: string;
3108
- }
3109
- declare function executeToolCallsParallel(entries: ToolCallEntry[], batchTimeoutMs?: number): Promise<ToolCallResult[]>;
3110
- declare function executeToolCallsSequential(entries: ToolCallEntry[]): Promise<ToolCallResult[]>;
3111
-
3112
- /**
3113
- * 默认全局注册表。生产与常规定义工具共用此 Map。
3114
- * 测试或沙箱可用 {@link runWithPluginRegistry} 替换为独立 Map,避免用例间泄漏。
3115
- */
3116
- declare const pluginRegistry: Map<string, PromptConcatTool>;
3117
- declare function getActivePluginRegistry(): Map<string, PromptConcatTool>;
3118
- declare function runWithPluginRegistry<T>(registry: Map<string, PromptConcatTool>, function_: () => T): T;
3119
- declare function createAgentFrameworkHooks(): PromptConcatHooks;
3120
- declare function runProcessPromptsHooks<TContext>(_hooks: PromptConcatHooks, context: TContext): Promise<TContext>;
3121
- declare function runResponseCompleteHooks(hooks: PromptConcatHooks, context: unknown): Promise<void>;
3122
- declare function runPostProcessHooks(hooks: PromptConcatHooks, context: unknown): Promise<void>;
3123
- declare function runToolExecutedHooks(hooks: PromptConcatHooks, context: unknown): Promise<void>;
3124
- /**
3125
- * TidGi `createHooksWithPlugins`:按 agentFrameworkConfig.plugins 把插件注册表里的工具挂到 hooks。
3126
- */
3127
- /** 从 Agent 上下文解析插件表:优先 `tools.getPromptPlugins()`,否则 ALS / 全局默认。 */
3128
- declare function resolvePromptPluginMap(context: {
3129
- tools?: {
3130
- getPromptPlugins?: () => Map<string, PromptConcatTool>;
3131
- };
3132
- }): Map<string, PromptConcatTool>;
3133
- declare function createHooksWithPlugins(agentFrameworkConfig: {
3134
- plugins?: Array<{
3135
- toolId: string;
3136
- [key: string]: unknown;
3137
- }>;
3138
- }, options?: {
3139
- pluginRegistry?: Map<string, PromptConcatTool>;
3140
- }): Promise<{
3141
- hooks: PromptConcatHooks;
3142
- pluginConfigs: Array<{
3143
- toolId: string;
3144
- [key: string]: unknown;
3145
- }>;
3146
- }>;
3147
-
3148
- declare function registerToolParameterSchema(toolId: string, schema: unknown, metadata?: {
3149
- displayName: string;
3150
- description: string;
3151
- }): void;
3152
- declare function getToolParameterSchema(toolId: string): unknown;
3153
- declare function getToolMetadata(toolId: string): {
3154
- displayName: string;
3155
- description: string;
3156
- } | undefined;
3157
-
3158
- /**
3159
- * Generate tool description for prompt injection from zod v4 schema definitions.
3160
- */
3161
-
3162
- declare function schemaToToolContent(schema: z.ZodType): string;
3163
-
3164
- /**
3165
- * Tools may attach this key to their return object so `taskAgent` persists
3166
- * `summary` + optional `detailRef` instead of `JSON.stringify` of the whole payload (plan §5.2.1).
3167
- */
3168
- declare const MEMELOOP_STRUCTURED_TOOL_KEY: "__memeloopToolResult";
3169
- /** Truncate tool summary for persisted `ChatMessage` / LLM context (plan §5.2.1). */
3170
- declare function truncateToolSummary(s: string, max?: number): string;
3171
- interface MemeloopStructuredToolPayload {
3172
- /** Short text for the tool message body (≤2000 chars recommended). */
3173
- summary: string;
3174
- detailRef?: DetailReference;
3175
- /**
3176
- * When set, `taskAgent` pauses after persisting this tool row until `waitForTerminalSession` resolves
3177
- * (terminal `await` mode, plan §16.4.1).
3178
- */
3179
- awaitSessionId?: string;
3180
- }
3181
- declare function extractMemeloopStructuredToolPayload(raw: unknown): MemeloopStructuredToolPayload | null;
3182
-
3183
- /**
3184
- * Tool definition registry.
3185
- * Converted from module-level singletons to an instance class for test isolation
3186
- * and multi-runtime support.
3187
- */
3188
-
3189
- /**
3190
- * Instance-level tool definition registry.
3191
- */
3192
- declare class ToolDefinitionRegistry {
3193
- private readonly registry;
3194
- registerToolDefinition<TConfigSchema extends z.ZodType, TLLMToolSchemas extends Record<string, z.ZodType>>(definition: ToolDefinition<TConfigSchema, TLLMToolSchemas>): DefinedTool<TConfigSchema, TLLMToolSchemas>;
3195
- getAllToolDefinitions(): Map<string, DefinedTool>;
3196
- getToolDefinition(toolId: string): DefinedTool | undefined;
3197
- }
3198
- declare function getDefaultToolDefinitionRegistry(): ToolDefinitionRegistry;
3199
- declare function registerToolDefinition<TConfigSchema extends z.ZodType, TLLMToolSchemas extends Record<string, z.ZodType>>(definition: ToolDefinition<TConfigSchema, TLLMToolSchemas>): DefinedTool<TConfigSchema, TLLMToolSchemas>;
3200
- declare function getAllToolDefinitions(): Map<string, DefinedTool>;
3201
- declare function getToolDefinition(toolId: string): DefinedTool | undefined;
3202
-
3203
- export { type AIResponseContext, type AIStreamResponseSubset, ALL_CATEGORIES, ASK_QUESTION_TOOL_ID, ASK_USER_QUESTION_TOOL_ID, type AddToolResultOptions, type AgentConversationClient, AgentCreationController, type AgentCreationControllerOptions, type AgentCreationState, type AgentDefinition, AgentDefinitionEditorController, type AgentDefinitionEditorControllerOptions, type AgentDefinitionEditorState, type AgentDefinitionModelConfig, type AgentDefinitionRepository, type AgentDefinitionToolConfig, type AgentFrameworkConfig, type AgentFrameworkContext, type AgentHeartbeatConfig, type AgentInstanceModel as AgentInstance, type AgentInstanceClient, type AgentInstanceLatestStatus, type AgentInstanceMeta, type AgentInstanceModel, type AgentInstanceState, type AgentLoopDefinition, type AgentLoopGenerator, type AgentLoopInput, type AgentLoopRuntime, type AgentLoopStep, type AgentProfile, AgentProfileRegistry, type AgentProfileType, type AgentPromptDescription, type AgentResponse, type AgentRuntimeView, AgentSessionController, type AgentSessionControllerOptions, type AgentSessionListener, type AgentSessionSnapshot, type AgentStartData, type AgentStatusContext, type AgentStopData, type AgentUpdateListener, type AiAPIConfig, type ApprovalDecision, type AttachmentBlob, type AttachmentReference, BUILTIN_AGENT_PROFILES, BUILTIN_TOOL_PLUGIN_IDS, type BaseToolContext, type BuiltinToolContext, type BuiltinToolImpl, type CategoryConfig, type ChatMessage, type ChatRole, ChatSyncEngine, type ChatSyncEngineOptions, type ChatSyncPeer, type CheckpointRecord, type CheckpointStore, type CloudDeviceRecord, type CompactionOptions, type CompactionResult, type ContextCompactionData, type ConversationMeta, type ConversationQueryMode, type CreateAgentOptions, type CreateScheduledTaskInput, type CreationStateListener, type DefineToolAgentFrameworkContext, type DefinedTool, type DetailRefType, type DetailReference, type Device, type DeviceAccountBindingRequest, type DeviceAuthorizer, type DeviceCapabilities, type DeviceConnectionGrant, type DeviceNetworkListenOptions, type DeviceNetworkPath, type DeviceNetworkService, type DevicePlatform, type DeviceReachability, type DeviceReachabilityState, type DeviceSyncTransport, type DeviceTrustMode, type EditorStateChange, type EditorStateListener, type ExchangeVersionVectorResult, type FrameworkPluginToolConfig, type GetMessagesOptions, type HookContext, type HookHandler, HookRegistry, type HookResult, type HookSlot, type HookType, type HostAgentToolConfig$1 as HostAgentToolConfig, type IAgentStorage$1 as IAgentStorage, type IChatSyncAdapter, type IIMAdapter, type IIMMessageRenderer, type ILLMProvider, type IMChannel, type IMChannelBinding, IMChannelManager, type IMPlatformType, IM_SESSION_TOOL_IDS, type INetworkService, type IPrompt, type IToolRegistry, type ImAgentDriver, type ImChannelBindingRecord, type ImInboundMessage, type ImSessionBuiltinRegistration, type ImSlashCommandContext, type ImStreamFlush, type ImToolsRuntime, type ImWebhookContext, type InjectContentOptions, type InjectToolListOptions, LLM_IO_LOOP_ID, type LanDiscoveryBrowseOptions, type LanDiscoveryRegisterOptions, Libp2pDeviceNetworkService, type Libp2pDeviceNetworkServiceOptions, type ListConversationsOptions, type LlmIoLoopOptions, type LoadPluginModuleOptions, type LoadSubAgentLoopScriptOptions, type LoadedPlugin, type LocalDeviceIdentity, type LoopPlugin, type LoopProfile, type LoopProfilePluginEntry, type LoopProfilePrompt, LoopRegistryImpl, MEMELOOP_SERVICE_TYPE, MEMELOOP_STRUCTURED_TOOL_KEY, type MemeLoopDuplexStream, type MemeLoopLogger, type MemeLoopProtocol, type MemeLoopRuntime, type MemeloopServiceInfo, type MemeloopStructuredToolPayload, MemoryDeviceNetworkService, type MemoryDeviceNetworkServiceOptions, type MergedPermissions, type ModelParameters, type ModelSelection, PERMISSIONS_TABLE_DDL, PLUGIN_ASK_QUESTION, PLUGIN_ASK_USER_QUESTION, PLUGIN_MCP_CLIENT, PLUGIN_MCP_FORWARD, PLUGIN_REMOTE_AGENT, PLUGIN_SPAWN_AGENT, PLUGIN_TASK, PLUGIN_TODO_WRITE, type PairingSession, PeerNodeSyncAdapter, type PeerNodeTransport, type PermissionAction, type PermissionRule, type PermissionSet, type PermissionSqlDatabase, type PermissionSqlStatement, type PluginAPI, type PluginAPIOptions, type PluginExports, type PluginManifest, type PluginModule, type PostProcessContext, type PostProcessHandlerContext, type PostToolUseData, type PreToolUseData, type PreviewDialogListener, type PromptConcatHookContext, type PromptConcatHooks, type PromptConcatPluginPreview, type PromptConcatStreamState, type PromptConcatTool, type PromptNode, type PromptPluginConfig, type PromptPreviewClient, PromptPreviewController, type PromptPreviewControllerOptions, type PromptPreviewDialogState, type PromptPreviewProgress, type PromptPreviewResult, type ProviderConfig, ProviderRegistry, type RawSeedDeviceIdentity, type RegisteredProvider, type ResponseHandlerContext, type RunTaskAgentTurnCallbacks, type RunTaskAgentTurnResult, SUB_AGENT_LOOP_ID, type ScheduleEditorState, type ScheduledTask, type ScheduledTaskClient, type SendMessageOptions, SessionStorage, type SubAgentLoopContext, type SubAgentLoopScript, type SubAgentLoopScriptArguments, type SyncResult, TODO_WRITE_TOOL_ID, type TaskCategory, TextMessageRenderer, type TiddlerFieldsForAgent, TokenTracker, type ToolActions, type ToolApprovalConfig, type ToolApprovalMode, type ToolApprovalRequest, type ToolCall, type ToolCallEntry, type ToolCallResult, type ToolCallingMatch, type ToolDefinition, ToolDefinitionRegistry, type ToolExecutionContext, type ToolExecutionResult, type ToolHandlerContext, type ToolPermissionRules, type TrustedDeviceRecord, type UserMessageContext, type UserPromptSubmitData, type VersionVector, type WikiTiddlerAttachment, type WikiTiddlerClickData, type YieldNextRoundTarget, __clearTodoStore, askQuestionConfigSchema, askQuestionImpl, askUserQuestionConfigSchema, askUserQuestionImpl, autoCompact, buildAgent, buildDeviceBindingMessage, cancelPendingApprovals, checkPermission, clearHooks, clearPluginRegistrations, compactMessages, createAgentFrameworkHooks, createAgentInstanceFromDefinition, createChatMessage, createCheckpointRecord, createDeviceIdentity, createHooksWithPlugins, createInstanceDeltaFromDefinition, createMemeLoopRuntime, createPluginAPI, createSubAgentLoopDefinition, createTaskAgent, decodeAttachmentBlobRpc, decodePublicKeyMultibase, defineTool, encodePublicKeyMultibase, evaluateApproval, executeHooks, executeToolCallsParallel, executeToolCallsSequential, exploreAgent, extractMemeloopStructuredToolPayload, findPromptById, flattenPrompts, getActivePluginRegistry, getAgentProfileRegistry, getAllToolDefinitions, getBuiltinLoopProfile, getBuiltinLoopProfiles, getBuiltinToolPlugins, getCategoryConfig, getDefaultHookRegistry, getDefaultToolDefinitionRegistry, getHookCount, getLoadedPlugin, getLoopRegistry, getMcpClientToolId, getMcpForwardToolId, getPendingApprovals, getPluginRegistrations, getRemoteAgentToolId, getSpawnAgentToolId, getSubAgentLoopId, getTaskToolId, getToolDefinition, getToolMetadata, getToolParameterSchema, gitProxyTargetBlockReason, hasHooks, imPlatformMaxMessageChars, imSwitchConversation, imToolDefinitions, isConversationMeta, isPluginLoaded, isTaskCategory, isUserInitiatedConversation, librarianAgent, listPlugins, listRegisteredHookTypes, loadPluginModule, loadPluginModules, loadSubAgentLoopScript, loadUserPermissions, matchAllToolCallings, matchPattern, matchToolCalling, mcpClientConfigSchema, mcpClientImpl, mcpForwardConfigSchema, mcpForwardImpl, mergeAgentToolsIntoFrameworkConfig, mergePermissionSets, onApprovalRequest, oracleAgent, parseCheckpointRecord, pickAdapter, planAgent, pluginRegistry, privateKeyFromIdentity, promptConcatStream, registerBuiltinLoops, registerBuiltinPromptPlugins, registerBuiltinToolPlugins, registerBuiltinTools, registerHook, registerImSessionBuiltinTools, registerPluginHooks, registerPluginTools, registerToolDefinition, registerToolParameterSchema, remoteAgentConfigSchema, remoteAgentImpl, remoteAgentListImpl, requestApproval, resetAgentProfileRegistry, resetLoopRegistry, resolveApproval, resolveCategory, resolvePromptPluginMap, resolveQuestionAnswer, resolveTaskAgentTerminalState, runPostProcessHooks, runProcessPromptsHooks, runResponseCompleteHooks, runTaskAgentTurn, runToolExecutedHooks, runWithPluginRegistry, saveUserPermissions, schemaToToolContent, serializeCheckpointRecord, shouldCompact, signDeviceBinding, spawnAgentConfigSchema, spawnAgentImpl, streamRuntimeAgentReplyToIm, taskToolConfigSchema, taskToolImpl, tiddlerToAgentDefinition, todoWriteConfigSchema, todoWriteImpl, truncateToolSummary, tryHandleImSlashCommand, unloadAllPlugins, unloadPlugin, unregisterHook, validatePluginManifest, verifyDeviceBinding };