memeloop 0.0.1

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 (137) hide show
  1. package/dist/anthropic.cjs +72 -0
  2. package/dist/anthropic.cjs.map +1 -0
  3. package/dist/anthropic.d.cts +21 -0
  4. package/dist/anthropic.d.ts +21 -0
  5. package/dist/anthropic.js +21 -0
  6. package/dist/anthropic.js.map +1 -0
  7. package/dist/azure.cjs +72 -0
  8. package/dist/azure.cjs.map +1 -0
  9. package/dist/azure.d.cts +21 -0
  10. package/dist/azure.d.ts +21 -0
  11. package/dist/azure.js +21 -0
  12. package/dist/azure.js.map +1 -0
  13. package/dist/chunk-3CN7DFBL.js +4894 -0
  14. package/dist/chunk-3CN7DFBL.js.map +1 -0
  15. package/dist/chunk-4AZ4D7U5.js +32 -0
  16. package/dist/chunk-4AZ4D7U5.js.map +1 -0
  17. package/dist/chunk-6ON4XSOV.js +63 -0
  18. package/dist/chunk-6ON4XSOV.js.map +1 -0
  19. package/dist/chunk-DJQNGIXX.js +4793 -0
  20. package/dist/chunk-DJQNGIXX.js.map +1 -0
  21. package/dist/chunk-FKQP6AOQ.js +32 -0
  22. package/dist/chunk-FKQP6AOQ.js.map +1 -0
  23. package/dist/chunk-OVJ7JJBA.js +35 -0
  24. package/dist/chunk-OVJ7JJBA.js.map +1 -0
  25. package/dist/chunk-P4UZ7IXC.js +42 -0
  26. package/dist/chunk-P4UZ7IXC.js.map +1 -0
  27. package/dist/chunk-YHJ2AEFR.js +4933 -0
  28. package/dist/chunk-YHJ2AEFR.js.map +1 -0
  29. package/dist/chunk-YVK7RYRO.js +4973 -0
  30. package/dist/chunk-YVK7RYRO.js.map +1 -0
  31. package/dist/code-assistant.json +114 -0
  32. package/dist/cohere.cjs +72 -0
  33. package/dist/cohere.cjs.map +1 -0
  34. package/dist/cohere.d.cts +21 -0
  35. package/dist/cohere.d.ts +21 -0
  36. package/dist/cohere.js +21 -0
  37. package/dist/cohere.js.map +1 -0
  38. package/dist/deepseek.cjs +72 -0
  39. package/dist/deepseek.cjs.map +1 -0
  40. package/dist/deepseek.d.cts +21 -0
  41. package/dist/deepseek.d.ts +21 -0
  42. package/dist/deepseek.js +21 -0
  43. package/dist/deepseek.js.map +1 -0
  44. package/dist/dist-65U7OYRG.js +1257 -0
  45. package/dist/dist-65U7OYRG.js.map +1 -0
  46. package/dist/fetchProvider-Cu4WkU5O.d.cts +819 -0
  47. package/dist/fetchProvider-Cu4WkU5O.d.ts +819 -0
  48. package/dist/frontend-ui-ux.json +105 -0
  49. package/dist/general-assistant.json +95 -0
  50. package/dist/git-master.json +51 -0
  51. package/dist/google-vertex.cjs +72 -0
  52. package/dist/google-vertex.cjs.map +1 -0
  53. package/dist/google-vertex.d.cts +21 -0
  54. package/dist/google-vertex.d.ts +21 -0
  55. package/dist/google-vertex.js +21 -0
  56. package/dist/google-vertex.js.map +1 -0
  57. package/dist/google.cjs +72 -0
  58. package/dist/google.cjs.map +1 -0
  59. package/dist/google.d.cts +21 -0
  60. package/dist/google.d.ts +21 -0
  61. package/dist/google.js +21 -0
  62. package/dist/google.js.map +1 -0
  63. package/dist/groq.cjs +72 -0
  64. package/dist/groq.cjs.map +1 -0
  65. package/dist/groq.d.cts +21 -0
  66. package/dist/groq.d.ts +21 -0
  67. package/dist/groq.js +21 -0
  68. package/dist/groq.js.map +1 -0
  69. package/dist/index.cjs +8916 -0
  70. package/dist/index.cjs.map +1 -0
  71. package/dist/index.d.cts +1816 -0
  72. package/dist/index.d.mts +3203 -0
  73. package/dist/index.d.ts +1816 -0
  74. package/dist/index.js +4040 -0
  75. package/dist/index.js.map +1 -0
  76. package/dist/index.mjs +7064 -0
  77. package/dist/index.mjs.map +1 -0
  78. package/dist/llm-providers.cjs +311 -0
  79. package/dist/llm-providers.cjs.map +1 -0
  80. package/dist/llm-providers.d.cts +111 -0
  81. package/dist/llm-providers.d.ts +111 -0
  82. package/dist/llm-providers.js +232 -0
  83. package/dist/llm-providers.js.map +1 -0
  84. package/dist/loop-api.cjs +4924 -0
  85. package/dist/loop-api.cjs.map +1 -0
  86. package/dist/loop-api.d.cts +11 -0
  87. package/dist/loop-api.d.ts +11 -0
  88. package/dist/loop-api.js +189 -0
  89. package/dist/loop-api.js.map +1 -0
  90. package/dist/mistral.cjs +72 -0
  91. package/dist/mistral.cjs.map +1 -0
  92. package/dist/mistral.d.cts +21 -0
  93. package/dist/mistral.d.ts +21 -0
  94. package/dist/mistral.js +21 -0
  95. package/dist/mistral.js.map +1 -0
  96. package/dist/multipart-parser-EJCXIUHC.js +372 -0
  97. package/dist/multipart-parser-EJCXIUHC.js.map +1 -0
  98. package/dist/openai.cjs +72 -0
  99. package/dist/openai.cjs.map +1 -0
  100. package/dist/openai.d.cts +21 -0
  101. package/dist/openai.d.ts +21 -0
  102. package/dist/openai.js +21 -0
  103. package/dist/openai.js.map +1 -0
  104. package/dist/perplexity.cjs +72 -0
  105. package/dist/perplexity.cjs.map +1 -0
  106. package/dist/perplexity.d.cts +21 -0
  107. package/dist/perplexity.d.ts +21 -0
  108. package/dist/perplexity.js +21 -0
  109. package/dist/perplexity.js.map +1 -0
  110. package/dist/playwright.json +52 -0
  111. package/dist/promptConcat-BJdazTg5.d.cts +1832 -0
  112. package/dist/promptConcat-BJdazTg5.d.ts +1832 -0
  113. package/dist/promptConcat-CAkpni_8.d.cts +1834 -0
  114. package/dist/promptConcat-CAkpni_8.d.ts +1834 -0
  115. package/dist/promptConcat-CfH5-GAE.d.cts +1036 -0
  116. package/dist/promptConcat-ChcAZOOL.d.ts +1036 -0
  117. package/dist/promptConcat-G5TnJVRy.d.cts +1800 -0
  118. package/dist/promptConcat-G5TnJVRy.d.ts +1800 -0
  119. package/dist/promptConcat-L72eowzp.d.ts +1090 -0
  120. package/dist/promptConcat-eLHdN7K8.d.cts +1090 -0
  121. package/dist/src-VTSXKG72.js +1409 -0
  122. package/dist/src-VTSXKG72.js.map +1 -0
  123. package/dist/togetherai.cjs +72 -0
  124. package/dist/togetherai.cjs.map +1 -0
  125. package/dist/togetherai.d.cts +21 -0
  126. package/dist/togetherai.d.ts +21 -0
  127. package/dist/togetherai.js +21 -0
  128. package/dist/togetherai.js.map +1 -0
  129. package/dist/types-B0Jm2l38.d.cts +767 -0
  130. package/dist/types-B0Jm2l38.d.ts +767 -0
  131. package/dist/xai.cjs +72 -0
  132. package/dist/xai.cjs.map +1 -0
  133. package/dist/xai.d.cts +21 -0
  134. package/dist/xai.d.ts +21 -0
  135. package/dist/xai.js +21 -0
  136. package/dist/xai.js.map +1 -0
  137. package/package.json +87 -0
@@ -0,0 +1,767 @@
1
+ interface PromptNode {
2
+ id: string;
3
+ text?: string;
4
+ /** TidGi IPrompt 兼容 */
5
+ caption?: string;
6
+ role?: 'system' | 'user' | 'assistant' | 'tool';
7
+ enabled?: boolean;
8
+ children?: PromptNode[];
9
+ /** UI 溯源,可选 */
10
+ source?: unknown;
11
+ /**
12
+ * 与插件 `dynamicPosition` 配合:用户轮次 ≥2 时将根级该节点移到列表末尾。
13
+ */
14
+ dynamicPosition?: 'deferToEnd';
15
+ }
16
+ /** 与 TidGi `IPrompt` 对齐的别名 */
17
+ type IPrompt = PromptNode;
18
+ interface PromptPluginConfig {
19
+ id: string;
20
+ toolId: string;
21
+ enabled?: boolean;
22
+ /** defineTool:`approval`(mode / allowPatterns / denyPatterns)等,类型见 `tools/types` */
23
+ [key: string]: unknown;
24
+ }
25
+ interface AgentFrameworkConfig {
26
+ prompts: PromptNode[];
27
+ response?: unknown[];
28
+ plugins: PromptPluginConfig[];
29
+ }
30
+ interface AgentPromptDescription {
31
+ agentFrameworkConfig?: AgentFrameworkConfig;
32
+ }
33
+
34
+ interface AgentDefinitionModelConfig {
35
+ provider?: string;
36
+ model?: string;
37
+ temperature?: number;
38
+ maxTokens?: number;
39
+ }
40
+ interface ModelSelection {
41
+ provider: string;
42
+ model: string;
43
+ [key: string]: unknown;
44
+ }
45
+ interface ModelParameters {
46
+ temperature?: number;
47
+ maxTokens?: number;
48
+ topP?: number;
49
+ [key: string]: unknown;
50
+ }
51
+ interface AiAPIConfig {
52
+ default?: ModelSelection;
53
+ embedding?: ModelSelection;
54
+ speech?: ModelSelection;
55
+ imageGeneration?: ModelSelection;
56
+ transcriptions?: ModelSelection;
57
+ free?: ModelSelection;
58
+ modelParameters: ModelParameters;
59
+ [key: string]: unknown;
60
+ }
61
+ interface AgentHeartbeatConfig {
62
+ enabled: boolean;
63
+ intervalSeconds: number;
64
+ message: string;
65
+ activeHoursStart?: string;
66
+ activeHoursEnd?: string;
67
+ }
68
+ interface AgentDefinitionToolConfig {
69
+ toolId: string;
70
+ enabled?: boolean;
71
+ parameters?: Record<string, unknown>;
72
+ tags?: string[];
73
+ }
74
+ type HostAgentToolConfig = AgentDefinitionToolConfig;
75
+ interface AgentDefinition {
76
+ id: string;
77
+ name: string;
78
+ description: string;
79
+ systemPrompt: string;
80
+ tools: string[];
81
+ modelConfig?: AgentDefinitionModelConfig;
82
+ promptSchema?: unknown;
83
+ /**
84
+ * TidGi-Desktop / memeloop:prompt 树、插件、maxIterations 等(结构见 memeloop prompt 类型)
85
+ * Typed as `AgentFrameworkConfig` so all hosts share a single canonical shape.
86
+ */
87
+ agentFrameworkConfig?: AgentFrameworkConfig;
88
+ /** Host-specific explicit tool configuration. Hosts map this to prompt plugins at runtime. */
89
+ agentTools?: AgentDefinitionToolConfig[];
90
+ /** Host-specific avatar or icon URL. */
91
+ avatarUrl?: string;
92
+ /** Host-specific agent handler / framework ID. */
93
+ agentFrameworkID?: string;
94
+ /** Periodic auto-wake configuration. */
95
+ heartbeat?: AgentHeartbeatConfig;
96
+ /** Host-specific AI API config override. */
97
+ aiApiConfig?: AiAPIConfig;
98
+ version: string;
99
+ }
100
+ interface AgentInstanceMeta {
101
+ instanceId: string;
102
+ definitionId: string;
103
+ nodeId: string;
104
+ conversationId: string;
105
+ createdAt: number;
106
+ updatedAt: number;
107
+ definitionDelta?: Partial<AgentDefinition>;
108
+ }
109
+
110
+ type ToolCallingMatch = {
111
+ found: false;
112
+ } | {
113
+ found: true;
114
+ toolId: string;
115
+ parameters: Record<string, unknown>;
116
+ originalText: string;
117
+ };
118
+ declare function matchToolCalling(responseText: string): ToolCallingMatch;
119
+ declare function matchAllToolCallings(responseText: string): {
120
+ calls: Array<ToolCallingMatch & {
121
+ found: true;
122
+ }>;
123
+ parallel: boolean;
124
+ };
125
+
126
+ /**
127
+ * TidGi-Desktop `agentInstance/tools/types.ts` 迁移并适配 memeloop(无 tapable,用 HookSlot.promise 串行执行)。
128
+ */
129
+
130
+ /** 供 defineTool / 审批使用:agent 视图包含完整 AgentInstance。 */
131
+ type DefineToolAgentFrameworkContext = AgentFrameworkContext & {
132
+ agent: AgentInstanceModel;
133
+ };
134
+ type ToolApprovalMode = 'auto' | 'confirm';
135
+ interface ToolApprovalConfig {
136
+ mode: ToolApprovalMode;
137
+ allowPatterns?: string[];
138
+ denyPatterns?: string[];
139
+ timeoutMs?: number;
140
+ }
141
+ type ApprovalDecision = 'allow' | 'deny' | 'pending';
142
+ interface ToolApprovalRequest {
143
+ approvalId: string;
144
+ agentId: string;
145
+ toolName: string;
146
+ parameters: Record<string, unknown>;
147
+ originalText?: string;
148
+ created: Date;
149
+ }
150
+ type YieldNextRoundTarget = 'human' | 'self' | `agent:${string}`;
151
+ interface ToolActions {
152
+ yieldNextRoundTo?: YieldNextRoundTarget;
153
+ newUserMessage?: string;
154
+ toolCalling?: ToolCallingMatch;
155
+ }
156
+ interface BaseToolContext {
157
+ agentFrameworkContext: DefineToolAgentFrameworkContext;
158
+ metadata?: Record<string, unknown>;
159
+ actions?: ToolActions;
160
+ }
161
+ /** 与 TidGi IPromptConcatTool 对齐的插件行 */
162
+ interface FrameworkPluginToolConfig {
163
+ id: string;
164
+ toolId: string;
165
+ enabled?: boolean;
166
+ caption?: string;
167
+ content?: string;
168
+ forbidOverrides?: boolean;
169
+ approval?: ToolApprovalConfig;
170
+ timeoutMs?: number;
171
+ [key: string]: unknown;
172
+ }
173
+ interface PromptConcatHookContext extends BaseToolContext {
174
+ messages: ChatMessage[];
175
+ prompts: IPrompt[];
176
+ toolConfig: FrameworkPluginToolConfig;
177
+ pluginIndex?: number;
178
+ }
179
+ interface AgentResponse {
180
+ id: string;
181
+ text?: string;
182
+ enabled?: boolean;
183
+ children?: AgentResponse[];
184
+ }
185
+ interface PostProcessContext extends PromptConcatHookContext {
186
+ llmResponse: string;
187
+ responses?: AgentResponse[];
188
+ }
189
+ /** 流式响应子集(memeloop ILLMProvider 聚合为最终文本后注入) */
190
+ interface AIStreamResponseSubset {
191
+ status: 'update' | 'done';
192
+ content: string;
193
+ }
194
+ interface AIResponseContext extends BaseToolContext {
195
+ toolConfig: FrameworkPluginToolConfig;
196
+ agentFrameworkConfig?: {
197
+ plugins?: FrameworkPluginToolConfig[];
198
+ };
199
+ response: AIStreamResponseSubset;
200
+ requestId?: string;
201
+ isFinal?: boolean;
202
+ }
203
+ interface UserMessageContext extends BaseToolContext {
204
+ content: {
205
+ text: string;
206
+ file?: unknown;
207
+ wikiTiddlers?: Array<{
208
+ workspaceName: string;
209
+ tiddlerTitle: string;
210
+ }>;
211
+ };
212
+ messageId: string;
213
+ timestamp: Date;
214
+ }
215
+ interface AgentStatusContext extends BaseToolContext {
216
+ status: {
217
+ state: 'working' | 'completed' | 'failed' | 'canceled';
218
+ modified: Date;
219
+ };
220
+ }
221
+ interface ToolExecutionContext extends BaseToolContext {
222
+ toolResult: {
223
+ success: boolean;
224
+ data?: string;
225
+ error?: string;
226
+ metadata?: Record<string, unknown>;
227
+ };
228
+ toolInfo: {
229
+ toolId: string;
230
+ parameters: Record<string, unknown>;
231
+ originalText?: string;
232
+ };
233
+ requestId?: string;
234
+ }
235
+ /**
236
+ * Hook 槽:与 tapable AsyncSeriesHook 一致 — `tapAsync` 注册,`promise(ctx)` 串行触发。
237
+ */
238
+ interface HookSlot {
239
+ tapAsync(name: string, function_: (context: any, callback: () => void) => void): void;
240
+ promise(context: unknown): Promise<void>;
241
+ }
242
+ interface PromptConcatHooks {
243
+ processPrompts: HookSlot;
244
+ finalizePrompts: HookSlot;
245
+ postProcess: HookSlot;
246
+ userMessageReceived: HookSlot;
247
+ agentStatusChanged: HookSlot;
248
+ toolExecuted: HookSlot;
249
+ responseUpdate: HookSlot;
250
+ responseComplete: HookSlot;
251
+ }
252
+ type PromptConcatTool = (hooks: PromptConcatHooks) => void;
253
+
254
+ type IMPlatformType = 'telegram' | 'discord' | 'lark' | 'wecom' | 'slack' | 'line' | 'qq';
255
+ interface IMChannel {
256
+ channelId: string;
257
+ platform: IMPlatformType;
258
+ nodeId: string;
259
+ webhookMode: 'cloud-relay' | 'direct';
260
+ webhookUrl?: string;
261
+ defaultDefinitionId?: string;
262
+ status: 'active' | 'inactive' | 'error';
263
+ }
264
+ interface IMChannelBinding {
265
+ channelId: string;
266
+ imUserId: string;
267
+ activeConversationId: string;
268
+ createdAt: number;
269
+ defaultDefinitionId?: string;
270
+ /** When set, the user's next inbound message is treated as an askQuestion answer (plan §20.3). */
271
+ pendingQuestionId?: string;
272
+ }
273
+ /** @deprecated Use IMChannelBinding */
274
+ type ImChannelBindingRecord = IMChannelBinding;
275
+
276
+ type VersionVector = Record<string, number>;
277
+ interface ConversationMeta {
278
+ conversationId: string;
279
+ title: string;
280
+ lastMessagePreview: string;
281
+ lastMessageTimestamp: number;
282
+ messageCount: number;
283
+ originNodeId: string;
284
+ definitionId: string;
285
+ instanceDelta?: Record<string, unknown>;
286
+ isUserInitiated: boolean;
287
+ sourceChannel?: {
288
+ channelId: string;
289
+ platform: string;
290
+ imUserId: string;
291
+ };
292
+ }
293
+ declare function isConversationMeta(value: unknown): value is ConversationMeta;
294
+
295
+ interface CheckpointRecord {
296
+ conversationId: string;
297
+ messages: ChatMessage[];
298
+ savedAt: string;
299
+ messageCount: number;
300
+ lastMessagePreview: string;
301
+ }
302
+ interface CheckpointSummary {
303
+ conversationId: string;
304
+ savedAt: string;
305
+ messageCount: number;
306
+ lastMessagePreview: string;
307
+ }
308
+ interface CheckpointStore {
309
+ saveCheckpoint(conversationId: string, messages: ChatMessage[]): Promise<CheckpointRecord>;
310
+ loadCheckpoint(conversationId: string): Promise<CheckpointRecord | null>;
311
+ listCheckpoints(): Promise<CheckpointSummary[]>;
312
+ deleteCheckpoint(conversationId: string): Promise<boolean>;
313
+ }
314
+ interface SessionStorageOptions {
315
+ records?: CheckpointRecord[];
316
+ }
317
+ declare function createCheckpointRecord(conversationId: string, messages: ChatMessage[], savedAt?: string): CheckpointRecord;
318
+ declare function parseCheckpointRecord(raw: string): CheckpointRecord | null;
319
+ declare function serializeCheckpointRecord(record: CheckpointRecord): string;
320
+ declare class InMemoryCheckpointStore implements CheckpointStore {
321
+ private readonly records;
322
+ constructor(options?: SessionStorageOptions);
323
+ saveCheckpoint(conversationId: string, messages: ChatMessage[]): Promise<CheckpointRecord>;
324
+ loadCheckpoint(conversationId: string): Promise<CheckpointRecord | null>;
325
+ listCheckpoints(): Promise<CheckpointSummary[]>;
326
+ deleteCheckpoint(conversationId: string): Promise<boolean>;
327
+ }
328
+ declare class SessionStorage extends InMemoryCheckpointStore {
329
+ }
330
+
331
+ type ConversationQueryMode = 'metadata-only' | 'full-content' | 'on-demand';
332
+ interface ListConversationsOptions {
333
+ limit?: number;
334
+ offset?: number;
335
+ }
336
+ interface GetMessagesOptions {
337
+ mode?: ConversationQueryMode;
338
+ }
339
+ interface IAgentStorage {
340
+ listConversations(options?: ListConversationsOptions): Promise<ConversationMeta[]>;
341
+ getMessages(conversationId: string, options?: GetMessagesOptions): Promise<ChatMessage[]>;
342
+ appendMessage(message: ChatMessage): Promise<void>;
343
+ /**
344
+ * Upsert conversation directory row (sync / Solid / peer metadata).
345
+ */
346
+ upsertConversationMetadata(meta: ConversationMeta): Promise<void>;
347
+ /**
348
+ * Insert messages if messageId not present (merge from remote / Pod); refreshes per-conversation messageCount.
349
+ */
350
+ insertMessagesIfAbsent(messages: ChatMessage[]): Promise<void>;
351
+ getAttachment(contentHash: string): Promise<AttachmentReference | null>;
352
+ saveAttachment(reference: AttachmentReference, data: Buffer | Uint8Array): Promise<void>;
353
+ /** Read persisted attachment bytes for cross-node RPC `memeloop.storage.getAttachmentBlob`. */
354
+ readAttachmentData?(contentHash: string): Promise<Uint8Array | null>;
355
+ getAgentDefinition(id: string): Promise<AgentDefinition | null>;
356
+ /** Optional optimization: use `SELECT MAX(lamportClock)` instead of scanning all messages for clock state. */
357
+ getMaxLamportClockForConversation?(conversationId: string): Promise<number>;
358
+ saveAgentInstance(meta: AgentInstanceMeta): Promise<void>;
359
+ /** Read the conversation metadata row used by AgentToolLoop to resolve `definitionId`. */
360
+ getConversationMeta(conversationId: string): Promise<ConversationMeta | null>;
361
+ /** IM user-to-conversation binding (persisted by memeloop-cli + SQLite). */
362
+ getImBinding?(channelId: string, imUserId: string): Promise<IMChannelBinding | null>;
363
+ setImBinding?(record: IMChannelBinding): Promise<void>;
364
+ }
365
+ interface MemeLoopLogger {
366
+ debug?(message: string, ...arguments_: unknown[]): void;
367
+ info?(message: string, ...arguments_: unknown[]): void;
368
+ warn?(message: string, ...arguments_: unknown[]): void;
369
+ error?(message: string, ...arguments_: unknown[]): void;
370
+ }
371
+ interface ILLMProvider {
372
+ name: string;
373
+ model?: unknown;
374
+ chat(request: unknown): AsyncIterable<unknown> | Promise<unknown>;
375
+ }
376
+ /**
377
+ * LLM Provider interface - now compatible with Vercel AI SDK's LanguageModelV1.
378
+ * The `model` field holds the actual LanguageModelV1 instance from @ai-sdk/openai, @ai-sdk/anthropic, etc.
379
+ */
380
+ interface IToolRegistry {
381
+ registerTool(id: string, impl: unknown): void;
382
+ getTool(id: string): unknown | undefined;
383
+ listTools(): string[];
384
+ /** Prompt-concat plugin registry, isolated per runtime. Falls back to the process-level default registry. */
385
+ getPromptPlugins?: () => Map<string, (hooks: PromptConcatHooks) => void>;
386
+ }
387
+ interface IChatSyncAdapter {
388
+ start(): Promise<void>;
389
+ stop(): Promise<void>;
390
+ }
391
+ interface INetworkService {
392
+ start(): Promise<void>;
393
+ stop(): Promise<void>;
394
+ }
395
+ interface AgentToolLoopOptions {
396
+ /** Maximum LLM-to-tool round-trips. `0` means unlimited, still capped internally. */
397
+ maxIterations?: number;
398
+ /** Whether to parse `<tool_use>` / `<function_call>` and execute through `IToolRegistry` (default true). */
399
+ enableToolLoop?: boolean;
400
+ /** Cancellation check, e.g. when the user stops a run. */
401
+ isCancelled?: (conversationId: string) => boolean;
402
+ /** Attachment injection for promptConcat, aligned with `PromptConcatOptions`. */
403
+ readAttachmentFile?: (path: string) => Promise<Uint8Array | Buffer>;
404
+ /** Omit history older than this many milliseconds when building LLM input. `0` disables trimming. */
405
+ maxHistoryAgeMs?: number;
406
+ /**
407
+ * When `defineTool` / plugins are configured, fall back to `IToolRegistry` for tool calls not handled by `onResponseComplete`.
408
+ */
409
+ fallbackRegistryTools?: boolean;
410
+ /**
411
+ * Tool permission rules (default allow).
412
+ * Supports wildcards such as "terminal.*" and "file.read".
413
+ */
414
+ toolPermissions?: {
415
+ default?: 'allow' | 'ask' | 'deny';
416
+ rules?: Array<{
417
+ pattern: string;
418
+ action: 'allow' | 'ask' | 'deny';
419
+ }>;
420
+ perAgent?: Record<string, {
421
+ default?: 'allow' | 'ask' | 'deny';
422
+ rules?: Array<{
423
+ pattern: string;
424
+ action: 'allow' | 'ask' | 'deny';
425
+ }>;
426
+ }>;
427
+ };
428
+ /** Threshold for repeated identical tool+input calls (default 3). */
429
+ doomLoopThreshold?: number;
430
+ /** History compaction window: keep the most recent N turns plus the last user message. */
431
+ contextCompaction?: {
432
+ maxMessages?: number;
433
+ replayLastUserMessage?: boolean;
434
+ };
435
+ /**
436
+ * Auto-compaction: when message count exceeds threshold, summarizes old
437
+ * conversation turns via truncation or LLM summarization. Default: disabled.
438
+ */
439
+ autoCompact?: {
440
+ /** Trigger compaction when message count exceeds this (default: 50) */
441
+ threshold?: number;
442
+ /** Number of recent turns to preserve (default: 4) */
443
+ recentTurnsToKeep?: number;
444
+ /** Maximum token estimate before compaction; 0 disables token-based compaction */
445
+ maxTokens?: number;
446
+ };
447
+ /** Session checkpoint: save conversation history after each turn for resume. */
448
+ sessionCheckpoint?: {
449
+ /** Enable checkpoint saves. Default: false. */
450
+ enabled?: boolean;
451
+ /** Store provided by the runtime host. */
452
+ store?: CheckpointStore;
453
+ /** Custom checkpoint directory (default: ~/.memeloop/sessions/) */
454
+ directory?: string;
455
+ };
456
+ /**
457
+ * After a tool returns `__memeloopToolResult.awaitSessionId`, AgentToolLoop waits here before the next LLM round.
458
+ */
459
+ waitForTerminalSession?: (sessionId: string) => Promise<{
460
+ exitCode: number | null;
461
+ truncatedOutput: string;
462
+ }>;
463
+ }
464
+ interface AgentFrameworkContext {
465
+ storage: IAgentStorage;
466
+ llmProvider: ILLMProvider;
467
+ tools: IToolRegistry;
468
+ syncAdapters: IChatSyncAdapter[];
469
+ network: INetworkService;
470
+ /** Let host runtimes preserve platform-specific message aliases/metadata while core owns the loop. */
471
+ normalizeMessage?: (message: ChatMessage) => ChatMessage;
472
+ /** AgentToolLoop ReAct behavior, migrated from the TidGi-Desktop agentToolLoop integration. */
473
+ agentToolLoop?: AgentToolLoopOptions;
474
+ /**
475
+ * Host-injected runner used by `createMemeLoopRuntime` after a user sends a message.
476
+ */
477
+ runAgentToolLoop?: (input: AgentLoopInput) => AgentLoopGenerator;
478
+ /** Run a child agent for orchestration loops such as AgentAgentLoop. */
479
+ runChildAgent?: AgentLoopRuntime['runChildAgent'];
480
+ /** Policy for loading script-backed loops. Defaults to bundled scripts + import specifiers only. */
481
+ loopScriptPolicy?: AgentLoopScriptPolicy;
482
+ /**
483
+ * Build the agent view supplied to defineTool hooks for a conversation.
484
+ */
485
+ resolveAgentRuntimeView?: (conversationId: string, messages: ChatMessage[]) => Promise<AgentInstanceModel>;
486
+ /** Current agent view for defineTool / TidGi compatibility. */
487
+ agent?: {
488
+ id: string;
489
+ messages: ChatMessage[];
490
+ };
491
+ /** Persist a `ChatMessage` if the runtime host supplies this hook. */
492
+ persistAgentMessage?: (message: ChatMessage) => Promise<void>;
493
+ /** Cancellation markers written by `createMemeLoopRuntime`. */
494
+ conversationCancellation?: Set<string>;
495
+ /** Resolve an AgentDefinition from host-specific sources. */
496
+ resolveAgentDefinition?: (definitionId: string) => Promise<AgentDefinition | null>;
497
+ /** Fallback logger used when the host does not inject one. */
498
+ logger?: MemeLoopLogger;
499
+ /** TidGi defineTool compatibility: legacy plugins call this without arguments. */
500
+ isCancelled?: () => boolean;
501
+ }
502
+ type AgentInstanceState = 'submitted' | 'working' | 'input-required' | 'completed' | 'canceled' | 'failed' | 'unknown';
503
+ interface AgentInstanceLatestStatus {
504
+ state: AgentInstanceState;
505
+ message?: ChatMessage;
506
+ /** Human-readable sub-status for the header — shown while agent is working. */
507
+ progress?: string;
508
+ created?: Date;
509
+ modified?: Date;
510
+ }
511
+ interface AgentInstanceModel extends Omit<AgentDefinition, 'name'> {
512
+ agentDefId: string;
513
+ name?: string;
514
+ agentFrameworkConfig?: AgentFrameworkConfig;
515
+ messages: ChatMessage[];
516
+ status: AgentInstanceLatestStatus;
517
+ created: Date;
518
+ modified?: Date;
519
+ closed?: boolean;
520
+ volatile?: boolean;
521
+ isDelegatedAgentRun?: boolean;
522
+ parentAgentRunId?: string;
523
+ }
524
+
525
+ declare function isUserInitiatedConversation(meta: ConversationMeta): boolean;
526
+ declare function createInstanceDeltaFromDefinition(definition: AgentDefinition, overrides: Partial<AgentDefinition>): Partial<AgentDefinition>;
527
+
528
+ interface AttachmentReference {
529
+ contentHash: string;
530
+ filename: string;
531
+ mimeType: string;
532
+ size: number;
533
+ }
534
+ type ChatRole = 'user' | 'assistant' | 'tool' | 'agent' | 'error';
535
+ interface ToolCall {
536
+ id: string;
537
+ toolName: string;
538
+ arguments: unknown;
539
+ }
540
+ /** Points to large tool output stored elsewhere (agent-run log, terminal session, file). */
541
+ type DetailRefType = 'agent-run' | 'terminal-session' | 'file';
542
+ interface DetailReference {
543
+ type: DetailRefType;
544
+ /** Delegated agent / spawn / remote conversation id */
545
+ conversationId?: string;
546
+ /** Terminal session id (often paired with `terminal:<sessionId>` conversation) */
547
+ sessionId?: string;
548
+ /** Node that holds the detail payload */
549
+ nodeId?: string;
550
+ /** e.g. `memeloop://node/.../file/...` from `buildMemeloopFileUri` in `../network/uri.js` */
551
+ fileUri?: string;
552
+ exitCode?: number;
553
+ }
554
+ interface ChatMessage {
555
+ messageId: string;
556
+ conversationId: string;
557
+ originNodeId: string;
558
+ timestamp: number;
559
+ lamportClock: number;
560
+ role: ChatRole;
561
+ content: string;
562
+ toolCalls?: ToolCall[];
563
+ attachments?: AttachmentReference[];
564
+ /** Summary lives in `content`; full payload fetched via detail ref (plan §5.2.1). */
565
+ detailRef?: DetailReference;
566
+ /** Reasoning/thinking content */
567
+ reasoning_content?: string;
568
+ /** Content MIME type */
569
+ contentType?: string;
570
+ /** Whether message should be hidden in UI */
571
+ hidden?: boolean;
572
+ /** Message processing duration in ms */
573
+ duration?: number | null;
574
+ /** Additional metadata */
575
+ metadata?: Record<string, unknown>;
576
+ }
577
+
578
+ /**
579
+ * Unified loop contract for all agent loop types.
580
+ * Replaces the old AgentToolLoopInput / AgentToolLoopStep naming entirely.
581
+ */
582
+
583
+ /** Standard input for any agent loop. */
584
+ interface AgentLoopInput {
585
+ conversationId: string;
586
+ message: string;
587
+ /** Host-prepared user message, used when the platform needs metadata/attachments on the turn root. */
588
+ userMessage?: Omit<Partial<ChatMessage>, 'conversationId' | 'role'> & {
589
+ content?: string;
590
+ };
591
+ /** If provided, these messages are loaded as conversation history on resume. */
592
+ resumeSession?: ChatMessage[];
593
+ }
594
+ /** Standard output step yielded by any agent loop. */
595
+ interface AgentLoopStep {
596
+ type: 'thinking' | 'tool' | 'message' | 'permission_request';
597
+ data: unknown;
598
+ }
599
+ /** Async iterable signature shared by all loop runners. */
600
+ type AgentLoopGenerator = AsyncIterable<AgentLoopStep>;
601
+ /** Describes a registered loop type. */
602
+ interface AgentLoopDefinition {
603
+ /** Unique id, e.g. "agent-tool-loop" or "agent-agent-loop". */
604
+ id: string;
605
+ /** Human-readable display name. */
606
+ name: string;
607
+ /** Short description of this loop's behaviour. */
608
+ description: string;
609
+ /** Factory: create a loop runner function for the given context. */
610
+ createRunner: (context: {
611
+ [key: string]: unknown;
612
+ }) => (input: AgentLoopInput) => AgentLoopGenerator;
613
+ }
614
+ type LoopProfileScriptReference = {
615
+ kind: 'builtin';
616
+ id: string;
617
+ } | {
618
+ kind: 'specifier';
619
+ specifier: string;
620
+ } | {
621
+ kind: 'source';
622
+ source: string;
623
+ name?: string;
624
+ };
625
+ interface AgentLoopScriptPolicy {
626
+ allowBuiltin?: boolean;
627
+ allowFile?: boolean;
628
+ allowNetwork?: boolean;
629
+ allowSource?: boolean;
630
+ allowSpecifier?: boolean;
631
+ importModule?: (specifier: string) => Promise<unknown>;
632
+ }
633
+ /** Capability extension point for a loop. */
634
+ interface LoopPlugin {
635
+ /** Unique plugin id, e.g. "fullReplacement" or "wikiTools". */
636
+ id: string;
637
+ /** Which loop id this plugin targets, or "*" for all loops. */
638
+ targetLoopId?: string;
639
+ /** Optional schema to validate against profile config. */
640
+ schema?: Record<string, unknown>;
641
+ /** Install the plugin into the given context. Mutates the context in place. */
642
+ install?: (context: {
643
+ [key: string]: unknown;
644
+ }, config?: Record<string, unknown>) => void;
645
+ }
646
+ /** A complete agent profile that describes which loop, which .mjs script, prompts, plugins, and hooks to use. */
647
+ interface LoopProfile {
648
+ /** Unique profile id, e.g. "memeloop:general-assistant". */
649
+ id: string;
650
+ /** Display name. */
651
+ name: string;
652
+ /** Description. */
653
+ description: string;
654
+ /** Which loop to run. Defaults to "agent-tool-loop" if omitted. */
655
+ loopId?: string;
656
+ /** Structured reference to the loop script. Prefer this over `script` for new profiles. */
657
+ scriptReference?: LoopProfileScriptReference;
658
+ /** Legacy alias for `scriptReference`. */
659
+ scriptRef?: LoopProfileScriptReference;
660
+ /** Legacy path/specifier to the .mjs loop script. */
661
+ script?: string;
662
+ /** System prompt (concise form; detailed prompts go to `prompts`). */
663
+ systemPrompt?: string;
664
+ /** Tool allowlist IDs. */
665
+ tools?: string[];
666
+ /** Agent-level tool configuration. */
667
+ agentTools?: Array<{
668
+ toolId: string;
669
+ enabled?: boolean;
670
+ parameters?: Record<string, unknown>;
671
+ tags?: string[];
672
+ }>;
673
+ /** Full agent framework configuration. */
674
+ agentFrameworkConfig?: AgentFrameworkConfig;
675
+ /** System prompt(s) for the agent. */
676
+ prompts?: LoopProfilePrompt[];
677
+ /** Tool / prompt / response plugin configs. */
678
+ plugins?: LoopProfilePluginEntry[];
679
+ /** Hook plugin configs. */
680
+ hookPlugins?: LoopProfilePluginEntry[];
681
+ /** Model configuration. */
682
+ modelConfig?: {
683
+ provider?: string;
684
+ model?: string;
685
+ temperature?: number;
686
+ maxTokens?: number;
687
+ };
688
+ /** Host-specific AI API config override. */
689
+ aiApiConfig?: AiAPIConfig;
690
+ /** Periodic auto-wake configuration. */
691
+ heartbeat?: {
692
+ enabled: boolean;
693
+ intervalSeconds: number;
694
+ message: string;
695
+ activeHoursStart?: string;
696
+ activeHoursEnd?: string;
697
+ };
698
+ /** Host-specific handler / framework ID. */
699
+ agentFrameworkID?: string;
700
+ /** Host-specific avatar or icon URL. */
701
+ avatarUrl?: string;
702
+ /** Tool permission configuration. */
703
+ permissions?: {
704
+ default?: 'allow' | 'ask' | 'deny';
705
+ rules?: Array<{
706
+ pattern: string;
707
+ action: 'allow' | 'ask' | 'deny';
708
+ }>;
709
+ perAgent?: Record<string, {
710
+ default?: string;
711
+ rules?: Array<{
712
+ pattern: string;
713
+ action: string;
714
+ }>;
715
+ }>;
716
+ };
717
+ /** Open schema for host-specific or loop-specific configuration. */
718
+ schema?: Record<string, unknown>;
719
+ /** Arbitrary metadata. */
720
+ metadata?: Record<string, unknown>;
721
+ /** Version string. */
722
+ version?: string;
723
+ }
724
+ interface LoopProfilePrompt {
725
+ id: string;
726
+ role: string;
727
+ text: string;
728
+ caption?: string;
729
+ children?: LoopProfilePrompt[];
730
+ }
731
+ interface LoopProfilePluginEntry {
732
+ /** Plugin id registered in the plugin registry. */
733
+ id: string;
734
+ /** Whether this plugin is enabled. */
735
+ enabled?: boolean;
736
+ /** Plugin-specific configuration. */
737
+ config?: Record<string, unknown>;
738
+ }
739
+ /** Minimal runtime context passed to a loop runner. */
740
+ interface AgentLoopRuntime {
741
+ /** Resolve a profile by id. */
742
+ resolveProfile: (profileId: string) => Promise<LoopProfile | null>;
743
+ /** Run a child agent (or sub-loop) and return its result. */
744
+ runChildAgent: (input: {
745
+ profileId: string;
746
+ prompt: string;
747
+ conversationId: string;
748
+ }) => AgentLoopGenerator;
749
+ /** Log an event for observability. */
750
+ log: (event: string, data?: Record<string, unknown>) => void;
751
+ /** Read/write persistent state for this run. */
752
+ state: {
753
+ get: <T>(key: string) => Promise<T | undefined>;
754
+ set: (key: string, value: unknown) => Promise<void>;
755
+ update: (key: string, updater: (previous: unknown) => unknown) => Promise<void>;
756
+ };
757
+ /** Checkpoint a completed step so it can be skipped on resume. */
758
+ checkpoint: (key: string, result: unknown) => Promise<void>;
759
+ /** Emit a progress step upstream. */
760
+ emit: (step: AgentLoopStep) => void;
761
+ /** Signal whether the run has been cancelled. */
762
+ signal: {
763
+ cancelled: boolean;
764
+ };
765
+ }
766
+
767
+ export { type IChatSyncAdapter as $, type AgentDefinition as A, type AgentLoopDefinition as B, type ConversationMeta as C, type DefineToolAgentFrameworkContext as D, type AgentLoopRuntime as E, type AgentLoopScriptPolicy as F, type GetMessagesOptions as G, type AgentLoopStep as H, type IAgentStorage as I, type AgentPromptDescription as J, type AgentResponse as K, type ListConversationsOptions as L, type AgentStatusContext as M, type AgentToolLoopOptions as N, type AiAPIConfig as O, type PromptConcatTool as P, type BaseToolContext as Q, type ChatRole as R, type CheckpointRecord as S, type ToolApprovalConfig as T, type CheckpointStore as U, type VersionVector as V, type ConversationQueryMode as W, type DetailRefType as X, type FrameworkPluginToolConfig as Y, type HookSlot as Z, type HostAgentToolConfig as _, type ChatMessage as a, type ILLMProvider as a0, type IMChannel as a1, type INetworkService as a2, type ImChannelBindingRecord as a3, type LoopPlugin as a4, type LoopProfile as a5, type LoopProfilePluginEntry as a6, type LoopProfilePrompt as a7, type LoopProfileScriptReference as a8, type MemeLoopLogger as a9, type ModelParameters as aa, type ModelSelection as ab, type PromptNode as ac, type PromptPluginConfig as ad, SessionStorage as ae, type ToolActions as af, type ToolApprovalMode as ag, type ToolCall as ah, type ToolExecutionContext as ai, type UserMessageContext as aj, type YieldNextRoundTarget as ak, createCheckpointRecord as al, createInstanceDeltaFromDefinition as am, isConversationMeta as an, isUserInitiatedConversation as ao, matchAllToolCallings as ap, matchToolCalling as aq, parseCheckpointRecord as ar, serializeCheckpointRecord as as, type AgentFrameworkConfig as b, type IMPlatformType as c, type IMChannelBinding as d, type AttachmentReference as e, type AgentInstanceMeta as f, type ApprovalDecision as g, type ToolApprovalRequest as h, type AgentFrameworkContext as i, type AgentLoopInput as j, type AgentLoopGenerator as k, type IToolRegistry as l, type PromptConcatHookContext as m, type IPrompt as n, type PostProcessContext as o, type AIResponseContext as p, type ToolCallingMatch as q, type PromptConcatHooks as r, type AgentDefinitionToolConfig as s, type DetailReference as t, type AIStreamResponseSubset as u, type AgentDefinitionModelConfig as v, type AgentHeartbeatConfig as w, type AgentInstanceModel as x, type AgentInstanceLatestStatus as y, type AgentInstanceState as z };