hackwriter 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +55 -0
  3. package/dist/agent/Agent.d.ts +9 -0
  4. package/dist/agent/Agent.d.ts.map +1 -0
  5. package/dist/agent/Agent.js +2 -0
  6. package/dist/agent/Agent.js.map +1 -0
  7. package/dist/agent/AgentExecutor.d.ts +36 -0
  8. package/dist/agent/AgentExecutor.d.ts.map +1 -0
  9. package/dist/agent/AgentExecutor.js +306 -0
  10. package/dist/agent/AgentExecutor.js.map +1 -0
  11. package/dist/agent/ApprovalManager.d.ts +8 -0
  12. package/dist/agent/ApprovalManager.d.ts.map +1 -0
  13. package/dist/agent/ApprovalManager.js +45 -0
  14. package/dist/agent/ApprovalManager.js.map +1 -0
  15. package/dist/agent/ContextCompressor.d.ts +9 -0
  16. package/dist/agent/ContextCompressor.d.ts.map +1 -0
  17. package/dist/agent/ContextCompressor.js +58 -0
  18. package/dist/agent/ContextCompressor.js.map +1 -0
  19. package/dist/agent/ConversationContext.d.ts +19 -0
  20. package/dist/agent/ConversationContext.d.ts.map +1 -0
  21. package/dist/agent/ConversationContext.js +236 -0
  22. package/dist/agent/ConversationContext.js.map +1 -0
  23. package/dist/agent/ModelFactory.d.ts +4 -0
  24. package/dist/agent/ModelFactory.d.ts.map +1 -0
  25. package/dist/agent/ModelFactory.js +32 -0
  26. package/dist/agent/ModelFactory.js.map +1 -0
  27. package/dist/cli.d.ts +3 -0
  28. package/dist/cli.d.ts.map +1 -0
  29. package/dist/cli.js +146 -0
  30. package/dist/cli.js.map +1 -0
  31. package/dist/commands/setup.d.ts +2 -0
  32. package/dist/commands/setup.d.ts.map +1 -0
  33. package/dist/commands/setup.js +110 -0
  34. package/dist/commands/setup.js.map +1 -0
  35. package/dist/config/ConfigSchema.d.ts +75 -0
  36. package/dist/config/ConfigSchema.d.ts.map +1 -0
  37. package/dist/config/ConfigSchema.js +54 -0
  38. package/dist/config/ConfigSchema.js.map +1 -0
  39. package/dist/config/Configuration.d.ts +30 -0
  40. package/dist/config/Configuration.d.ts.map +1 -0
  41. package/dist/config/Configuration.js +2 -0
  42. package/dist/config/Configuration.js.map +1 -0
  43. package/dist/config/ConfigurationLoader.d.ts +8 -0
  44. package/dist/config/ConfigurationLoader.d.ts.map +1 -0
  45. package/dist/config/ConfigurationLoader.js +75 -0
  46. package/dist/config/ConfigurationLoader.js.map +1 -0
  47. package/dist/messaging/MessageBus.d.ts +11 -0
  48. package/dist/messaging/MessageBus.d.ts.map +1 -0
  49. package/dist/messaging/MessageBus.js +23 -0
  50. package/dist/messaging/MessageBus.js.map +1 -0
  51. package/dist/messaging/MessageTypes.d.ts +39 -0
  52. package/dist/messaging/MessageTypes.d.ts.map +1 -0
  53. package/dist/messaging/MessageTypes.js +2 -0
  54. package/dist/messaging/MessageTypes.js.map +1 -0
  55. package/dist/session/SessionManager.d.ts +11 -0
  56. package/dist/session/SessionManager.d.ts.map +1 -0
  57. package/dist/session/SessionManager.js +56 -0
  58. package/dist/session/SessionManager.js.map +1 -0
  59. package/dist/tools/base/Tool.d.ts +19 -0
  60. package/dist/tools/base/Tool.d.ts.map +1 -0
  61. package/dist/tools/base/Tool.js +15 -0
  62. package/dist/tools/base/Tool.js.map +1 -0
  63. package/dist/tools/base/ToolRegistry.d.ts +16 -0
  64. package/dist/tools/base/ToolRegistry.d.ts.map +1 -0
  65. package/dist/tools/base/ToolRegistry.js +29 -0
  66. package/dist/tools/base/ToolRegistry.js.map +1 -0
  67. package/dist/tools/file/ListFilesTool.d.ts +17 -0
  68. package/dist/tools/file/ListFilesTool.d.ts.map +1 -0
  69. package/dist/tools/file/ListFilesTool.js +80 -0
  70. package/dist/tools/file/ListFilesTool.js.map +1 -0
  71. package/dist/tools/file/ReadFileTool.d.ts +13 -0
  72. package/dist/tools/file/ReadFileTool.d.ts.map +1 -0
  73. package/dist/tools/file/ReadFileTool.js +32 -0
  74. package/dist/tools/file/ReadFileTool.js.map +1 -0
  75. package/dist/tools/file/WriteFileTool.d.ts +18 -0
  76. package/dist/tools/file/WriteFileTool.d.ts.map +1 -0
  77. package/dist/tools/file/WriteFileTool.js +54 -0
  78. package/dist/tools/file/WriteFileTool.js.map +1 -0
  79. package/dist/tools/file/index.d.ts +4 -0
  80. package/dist/tools/file/index.d.ts.map +1 -0
  81. package/dist/tools/file/index.js +4 -0
  82. package/dist/tools/file/index.js.map +1 -0
  83. package/dist/tools/hackmd/CreateNoteTool.d.ts +27 -0
  84. package/dist/tools/hackmd/CreateNoteTool.d.ts.map +1 -0
  85. package/dist/tools/hackmd/CreateNoteTool.js +85 -0
  86. package/dist/tools/hackmd/CreateNoteTool.js.map +1 -0
  87. package/dist/tools/hackmd/DeleteNoteTool.d.ts +19 -0
  88. package/dist/tools/hackmd/DeleteNoteTool.d.ts.map +1 -0
  89. package/dist/tools/hackmd/DeleteNoteTool.js +54 -0
  90. package/dist/tools/hackmd/DeleteNoteTool.js.map +1 -0
  91. package/dist/tools/hackmd/ExportNoteTool.d.ts +18 -0
  92. package/dist/tools/hackmd/ExportNoteTool.d.ts.map +1 -0
  93. package/dist/tools/hackmd/ExportNoteTool.js +75 -0
  94. package/dist/tools/hackmd/ExportNoteTool.js.map +1 -0
  95. package/dist/tools/hackmd/GetHistoryTool.d.ts +16 -0
  96. package/dist/tools/hackmd/GetHistoryTool.d.ts.map +1 -0
  97. package/dist/tools/hackmd/GetHistoryTool.js +51 -0
  98. package/dist/tools/hackmd/GetHistoryTool.js.map +1 -0
  99. package/dist/tools/hackmd/GetUserInfoTool.d.ts +13 -0
  100. package/dist/tools/hackmd/GetUserInfoTool.d.ts.map +1 -0
  101. package/dist/tools/hackmd/GetUserInfoTool.js +30 -0
  102. package/dist/tools/hackmd/GetUserInfoTool.js.map +1 -0
  103. package/dist/tools/hackmd/ListNotesTool.d.ts +17 -0
  104. package/dist/tools/hackmd/ListNotesTool.d.ts.map +1 -0
  105. package/dist/tools/hackmd/ListNotesTool.js +48 -0
  106. package/dist/tools/hackmd/ListNotesTool.js.map +1 -0
  107. package/dist/tools/hackmd/ListTeamsTool.d.ts +13 -0
  108. package/dist/tools/hackmd/ListTeamsTool.d.ts.map +1 -0
  109. package/dist/tools/hackmd/ListTeamsTool.js +34 -0
  110. package/dist/tools/hackmd/ListTeamsTool.js.map +1 -0
  111. package/dist/tools/hackmd/ReadNoteTool.d.ts +16 -0
  112. package/dist/tools/hackmd/ReadNoteTool.d.ts.map +1 -0
  113. package/dist/tools/hackmd/ReadNoteTool.js +36 -0
  114. package/dist/tools/hackmd/ReadNoteTool.js.map +1 -0
  115. package/dist/tools/hackmd/SearchNotesTool.d.ts +17 -0
  116. package/dist/tools/hackmd/SearchNotesTool.d.ts.map +1 -0
  117. package/dist/tools/hackmd/SearchNotesTool.js +49 -0
  118. package/dist/tools/hackmd/SearchNotesTool.js.map +1 -0
  119. package/dist/tools/hackmd/UpdateNoteTool.d.ts +20 -0
  120. package/dist/tools/hackmd/UpdateNoteTool.d.ts.map +1 -0
  121. package/dist/tools/hackmd/UpdateNoteTool.js +62 -0
  122. package/dist/tools/hackmd/UpdateNoteTool.js.map +1 -0
  123. package/dist/tools/hackmd/errorHandler.d.ts +6 -0
  124. package/dist/tools/hackmd/errorHandler.d.ts.map +1 -0
  125. package/dist/tools/hackmd/errorHandler.js +59 -0
  126. package/dist/tools/hackmd/errorHandler.js.map +1 -0
  127. package/dist/tools/hackmd/index.d.ts +11 -0
  128. package/dist/tools/hackmd/index.d.ts.map +1 -0
  129. package/dist/tools/hackmd/index.js +24 -0
  130. package/dist/tools/hackmd/index.js.map +1 -0
  131. package/dist/ui/shell/CommandRegistry.d.ts +20 -0
  132. package/dist/ui/shell/CommandRegistry.d.ts.map +1 -0
  133. package/dist/ui/shell/CommandRegistry.js +77 -0
  134. package/dist/ui/shell/CommandRegistry.js.map +1 -0
  135. package/dist/ui/shell/InteractiveShell.d.ts +15 -0
  136. package/dist/ui/shell/InteractiveShell.d.ts.map +1 -0
  137. package/dist/ui/shell/InteractiveShell.js +94 -0
  138. package/dist/ui/shell/InteractiveShell.js.map +1 -0
  139. package/dist/ui/shell/OutputRenderer.d.ts +8 -0
  140. package/dist/ui/shell/OutputRenderer.d.ts.map +1 -0
  141. package/dist/ui/shell/OutputRenderer.js +85 -0
  142. package/dist/ui/shell/OutputRenderer.js.map +1 -0
  143. package/dist/utils/ErrorTypes.d.ts +58 -0
  144. package/dist/utils/ErrorTypes.d.ts.map +1 -0
  145. package/dist/utils/ErrorTypes.js +156 -0
  146. package/dist/utils/ErrorTypes.js.map +1 -0
  147. package/dist/utils/Logger.d.ts +13 -0
  148. package/dist/utils/Logger.d.ts.map +1 -0
  149. package/dist/utils/Logger.js +72 -0
  150. package/dist/utils/Logger.js.map +1 -0
  151. package/package.json +66 -0
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Michael Wang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # HackWriter
2
+
3
+ Writing agent for HackMD
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npx hackwriter
9
+ ```
10
+
11
+ Or install globally:
12
+
13
+ ```sh
14
+ npm i -g hackwriter
15
+ ```
16
+
17
+ ## Configure
18
+
19
+ First run will prompt for setup:
20
+
21
+ ```sh
22
+ hackwriter
23
+ ```
24
+
25
+ You'll need:
26
+
27
+ - HackMD API token
28
+ - LLM provider API key (OpenAI or Anthropic)
29
+
30
+ ## Usage
31
+
32
+ ```sh
33
+ hackwriter # interactive shell
34
+ hackwriter -c "list notes" # single command
35
+ hackwriter --continue # resume session
36
+ hackwriter --yolo # auto-approve all
37
+ hackwriter --debug # detailed logs
38
+ ```
39
+
40
+ Inside shell: `/help`, `/status`, `/clear`, `exit`
41
+
42
+ ## Features
43
+
44
+ - Lists, reads, creates, updates, deletes HackMD notes (personal & team)
45
+ - Streams agent thoughts with tool-call status
46
+ - Persists sessions in `~/.hackwriter/sessions`
47
+ - Asks confirmation before destructive actions (unless `--yolo`)
48
+
49
+ ## Development
50
+
51
+ ```sh
52
+ pnpm install
53
+ pnpm run dev
54
+ pnpm run test
55
+ ```
@@ -0,0 +1,9 @@
1
+ import type { ToolRegistry } from '../tools/base/ToolRegistry';
2
+ export interface Agent {
3
+ name: string;
4
+ modelName: string;
5
+ maxContextSize: number;
6
+ systemPrompt: string;
7
+ toolRegistry: ToolRegistry;
8
+ }
9
+ //# sourceMappingURL=Agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Agent.d.ts","sourceRoot":"","sources":["../../src/agent/Agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE/D,MAAM,WAAW,KAAK;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,YAAY,CAAC;CAC5B"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Agent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Agent.js","sourceRoot":"","sources":["../../src/agent/Agent.ts"],"names":[],"mappings":""}
@@ -0,0 +1,36 @@
1
+ import type { LanguageModel } from 'ai';
2
+ import type { Agent } from './Agent';
3
+ import type { ConversationContext } from './ConversationContext';
4
+ export interface ExecutorStatus {
5
+ contextUsage: number;
6
+ tokenCount: number;
7
+ currentStep: number;
8
+ }
9
+ export declare class AgentExecutor {
10
+ private context;
11
+ private agent;
12
+ private model;
13
+ private messageBus;
14
+ private compressor;
15
+ private maxSteps;
16
+ private maxRetriesPerStep;
17
+ private reservedTokens;
18
+ private currentStep;
19
+ constructor(agent: Agent, context: ConversationContext, model: LanguageModel, loopControl?: {
20
+ maxStepsPerRun?: number;
21
+ maxRetriesPerStep?: number;
22
+ });
23
+ get status(): ExecutorStatus;
24
+ execute(userInput: string): Promise<void>;
25
+ private runLoop;
26
+ private executeStep;
27
+ private executeTools;
28
+ private shouldCompressContext;
29
+ private compressContext;
30
+ private buildToolSet;
31
+ private normalizeToolInput;
32
+ private createAssistantMessage;
33
+ private createToolResultPart;
34
+ private calculateUsageTokens;
35
+ }
36
+ //# sourceMappingURL=AgentExecutor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AgentExecutor.d.ts","sourceRoot":"","sources":["../../src/agent/AgentExecutor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EAOd,MAAM,IAAI,CAAC;AAGZ,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAMjE,MAAM,WAAW,cAAc;IAC7B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;CACrB;AAqBD,qBAAa,aAAa;IACxB,OAAO,CAAC,OAAO,CAAsB;IACrC,OAAO,CAAC,KAAK,CAAQ;IACrB,OAAO,CAAC,KAAK,CAAgB;IAC7B,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,UAAU,CAAoB;IAEtC,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,iBAAiB,CAAS;IAClC,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,WAAW,CAAK;gBAGtB,KAAK,EAAE,KAAK,EACZ,OAAO,EAAE,mBAAmB,EAC5B,KAAK,EAAE,aAAa,EACpB,WAAW,CAAC,EAAE;QACZ,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;KAC5B;IAWH,IAAI,MAAM,IAAI,cAAc,CAM3B;IAEK,OAAO,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;YAqBjC,OAAO;YA2CP,WAAW;YA2GX,YAAY;IA6D1B,OAAO,CAAC,qBAAqB;YAOf,eAAe;IAc7B,OAAO,CAAC,YAAY;IAWpB,OAAO,CAAC,kBAAkB;IAO1B,OAAO,CAAC,sBAAsB;IAY9B,OAAO,CAAC,oBAAoB;IA2B5B,OAAO,CAAC,oBAAoB;CAS7B"}
@@ -0,0 +1,306 @@
1
+ import { jsonSchema, streamText } from 'ai';
2
+ import { MessageBus } from '../messaging/MessageBus';
3
+ import { ContextCompressor } from './ContextCompressor';
4
+ import { Logger } from '../utils/Logger';
5
+ export class AgentExecutor {
6
+ context;
7
+ agent;
8
+ model;
9
+ messageBus;
10
+ compressor;
11
+ maxSteps;
12
+ maxRetriesPerStep;
13
+ reservedTokens = 50000;
14
+ currentStep = 0;
15
+ constructor(agent, context, model, loopControl) {
16
+ this.agent = agent;
17
+ this.context = context;
18
+ this.model = model;
19
+ this.messageBus = MessageBus.getInstance();
20
+ this.compressor = new ContextCompressor(model);
21
+ this.maxSteps = loopControl?.maxStepsPerRun ?? 100;
22
+ this.maxRetriesPerStep = loopControl?.maxRetriesPerStep ?? 2;
23
+ }
24
+ get status() {
25
+ return {
26
+ contextUsage: this.context.tokenCount / this.agent.maxContextSize,
27
+ tokenCount: this.context.tokenCount,
28
+ currentStep: this.currentStep,
29
+ };
30
+ }
31
+ async execute(userInput) {
32
+ Logger.debug('AgentExecutor', 'Starting execution', {
33
+ input: userInput.slice(0, 100),
34
+ currentTokens: this.context.tokenCount
35
+ });
36
+ const userMessage = {
37
+ role: 'user',
38
+ content: userInput,
39
+ };
40
+ await this.context.createCheckpoint();
41
+ await this.context.addMessage(userMessage);
42
+ await this.runLoop();
43
+ Logger.debug('AgentExecutor', 'Execution completed', {
44
+ finalTokens: this.context.tokenCount,
45
+ totalSteps: this.currentStep
46
+ });
47
+ }
48
+ async runLoop() {
49
+ this.currentStep = 1;
50
+ while (true) {
51
+ Logger.debug('AgentExecutor', `Step ${this.currentStep}/${this.maxSteps}`);
52
+ this.messageBus.publish({
53
+ type: 'step_started',
54
+ stepNumber: this.currentStep
55
+ });
56
+ // Check if context compression needed
57
+ if (this.shouldCompressContext()) {
58
+ Logger.info('AgentExecutor', 'Context compression triggered', {
59
+ currentTokens: this.context.tokenCount,
60
+ maxTokens: this.agent.maxContextSize
61
+ });
62
+ this.messageBus.publish({ type: 'compression_started' });
63
+ await this.compressContext();
64
+ this.messageBus.publish({ type: 'compression_completed' });
65
+ Logger.info('AgentExecutor', 'Context compression completed', {
66
+ newTokenCount: this.context.tokenCount
67
+ });
68
+ }
69
+ await this.context.createCheckpoint();
70
+ // Execute single step
71
+ const shouldContinue = await this.executeStep();
72
+ if (!shouldContinue) {
73
+ Logger.debug('AgentExecutor', 'No tool calls - execution finished');
74
+ this.messageBus.publish({ type: 'step_completed' });
75
+ return;
76
+ }
77
+ this.currentStep++;
78
+ if (this.currentStep > this.maxSteps) {
79
+ throw new Error(`Maximum steps (${this.maxSteps}) reached`);
80
+ }
81
+ }
82
+ }
83
+ async executeStep() {
84
+ const stream = streamText({
85
+ model: this.model,
86
+ system: this.agent.systemPrompt,
87
+ messages: this.context.getHistory(),
88
+ tools: this.buildToolSet(),
89
+ maxRetries: this.maxRetriesPerStep,
90
+ });
91
+ const toolCalls = [];
92
+ const assistantParts = [];
93
+ let pendingText = '';
94
+ const flushText = () => {
95
+ if (!pendingText.length) {
96
+ return;
97
+ }
98
+ assistantParts.push({ type: 'text', text: pendingText });
99
+ pendingText = '';
100
+ };
101
+ try {
102
+ const streamIterator = stream.fullStream;
103
+ for await (const chunk of streamIterator) {
104
+ switch (chunk.type) {
105
+ case 'text-delta': {
106
+ pendingText += chunk.text;
107
+ this.messageBus.publish({ type: 'text_chunk', text: chunk.text });
108
+ break;
109
+ }
110
+ case 'text-end': {
111
+ flushText();
112
+ break;
113
+ }
114
+ case 'tool-input-delta': {
115
+ this.messageBus.publish({
116
+ type: 'tool_arguments_chunk',
117
+ toolCallId: chunk.toolCallId,
118
+ chunk: chunk.inputTextDelta,
119
+ });
120
+ break;
121
+ }
122
+ case 'tool-call': {
123
+ flushText();
124
+ const normalizedInput = this.normalizeToolInput(chunk.input);
125
+ const toolCall = {
126
+ id: chunk.toolCallId,
127
+ name: chunk.toolName,
128
+ input: normalizedInput,
129
+ };
130
+ toolCalls.push(toolCall);
131
+ assistantParts.push({
132
+ type: 'tool-call',
133
+ toolCallId: chunk.toolCallId,
134
+ toolName: chunk.toolName,
135
+ input: normalizedInput,
136
+ });
137
+ this.messageBus.publish({
138
+ type: 'tool_call_started',
139
+ toolCall: {
140
+ id: toolCall.id,
141
+ name: toolCall.name,
142
+ },
143
+ });
144
+ break;
145
+ }
146
+ case 'tool-result': {
147
+ flushText();
148
+ assistantParts.push({
149
+ type: 'tool-result',
150
+ toolCallId: chunk.toolCallId,
151
+ toolName: chunk.toolName,
152
+ output: chunk.output,
153
+ });
154
+ break;
155
+ }
156
+ case 'error': {
157
+ throw chunk.error instanceof Error ? chunk.error : new Error(String(chunk.error));
158
+ }
159
+ default:
160
+ // Ignore other chunk types (start/finish markers, reasoning, sources, etc.)
161
+ break;
162
+ }
163
+ }
164
+ }
165
+ finally {
166
+ flushText();
167
+ }
168
+ const assistantMessage = this.createAssistantMessage(assistantParts);
169
+ await this.context.addMessage(assistantMessage);
170
+ const usage = await stream.usage;
171
+ await this.context.updateTokenCount(this.calculateUsageTokens(usage));
172
+ if (toolCalls.length > 0) {
173
+ const results = await this.executeTools(toolCalls);
174
+ const toolResultMessage = {
175
+ role: 'tool',
176
+ content: results.map(result => this.createToolResultPart(result)),
177
+ };
178
+ await this.context.addMessage(toolResultMessage);
179
+ return true;
180
+ }
181
+ return false;
182
+ }
183
+ async executeTools(toolCalls) {
184
+ Logger.debug('AgentExecutor', `Executing ${toolCalls.length} tool(s): ${toolCalls.map(t => t.name).join(', ')}`);
185
+ return await Promise.all(toolCalls.map(async (call) => {
186
+ const tool = this.agent.toolRegistry.get(call.name);
187
+ if (!tool) {
188
+ const errorResult = {
189
+ toolCallId: call.id,
190
+ toolName: call.name,
191
+ ok: false,
192
+ output: `Tool ${call.name} not found`,
193
+ };
194
+ this.messageBus.publish({
195
+ type: 'tool_failed',
196
+ toolCallId: call.id,
197
+ error: errorResult.output,
198
+ });
199
+ return errorResult;
200
+ }
201
+ try {
202
+ const result = await tool.call(call.input);
203
+ Logger.debug('AgentExecutor', `Tool ${call.name}: ${result.ok ? '✓' : '✗'} ${result.brief ?? ''}`);
204
+ this.messageBus.publish({
205
+ type: 'tool_completed',
206
+ toolCallId: call.id,
207
+ result,
208
+ });
209
+ return {
210
+ toolCallId: call.id,
211
+ toolName: call.name,
212
+ ...result,
213
+ };
214
+ }
215
+ catch (error) {
216
+ Logger.error('AgentExecutor', `Tool ${call.name} failed`, error);
217
+ const errorResult = {
218
+ toolCallId: call.id,
219
+ toolName: call.name,
220
+ ok: false,
221
+ output: error instanceof Error ? error.message : String(error),
222
+ };
223
+ this.messageBus.publish({
224
+ type: 'tool_failed',
225
+ toolCallId: call.id,
226
+ error: errorResult.output,
227
+ });
228
+ return errorResult;
229
+ }
230
+ }));
231
+ }
232
+ shouldCompressContext() {
233
+ return (this.context.tokenCount + this.reservedTokens >=
234
+ this.agent.maxContextSize);
235
+ }
236
+ async compressContext() {
237
+ const compressed = await this.compressor.compress(this.context.getHistory(), this.agent.systemPrompt);
238
+ await this.context.revertToCheckpoint(0);
239
+ await this.context.createCheckpoint();
240
+ await this.context.addMessage({
241
+ role: 'assistant',
242
+ content: `<system>Previous context compressed:\n${compressed}</system>`,
243
+ });
244
+ }
245
+ buildToolSet() {
246
+ const tools = {};
247
+ for (const tool of this.agent.toolRegistry.getAll()) {
248
+ tools[tool.name] = {
249
+ description: tool.description,
250
+ inputSchema: jsonSchema(tool.inputSchema),
251
+ };
252
+ }
253
+ return tools;
254
+ }
255
+ normalizeToolInput(input) {
256
+ if (input && typeof input === 'object' && !Array.isArray(input)) {
257
+ return input;
258
+ }
259
+ return {};
260
+ }
261
+ createAssistantMessage(parts) {
262
+ if (parts.length === 0) {
263
+ return { role: 'assistant', content: '' };
264
+ }
265
+ if (parts.length === 1 && parts[0].type === 'text') {
266
+ return { role: 'assistant', content: parts[0].text };
267
+ }
268
+ return { role: 'assistant', content: parts };
269
+ }
270
+ createToolResultPart(result) {
271
+ return {
272
+ type: 'tool-result',
273
+ toolCallId: result.toolCallId,
274
+ toolName: result.toolName,
275
+ output: result.ok
276
+ ? {
277
+ type: 'json',
278
+ value: {
279
+ ok: true,
280
+ output: result.output,
281
+ message: result.message ?? null,
282
+ brief: result.brief ?? null,
283
+ },
284
+ }
285
+ : {
286
+ type: 'error-json',
287
+ value: {
288
+ ok: false,
289
+ output: result.output,
290
+ message: result.message ?? null,
291
+ brief: result.brief ?? null,
292
+ },
293
+ },
294
+ };
295
+ }
296
+ calculateUsageTokens(usage) {
297
+ if (!usage) {
298
+ return 0;
299
+ }
300
+ if (typeof usage.totalTokens === 'number') {
301
+ return usage.totalTokens;
302
+ }
303
+ return (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0);
304
+ }
305
+ }
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wBAC/B,KAAK,EAAE,MAAM,CAAC,KAAK,IAAI,IAAI;qBAC5B;iBACF;SACmB,CAAC;IAC7B,CAAC;IAEO,oBAAoB,CAAC,KAAqC;QAChE,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,OAAO,CAAC,CAAC;QACX,CAAC;QACD,IAAI,OAAO,KAAK,CAAC,WAAW,KAAK,QAAQ,EAAE,CAAC;YAC1C,OAAO,KAAK,CAAC,WAAW,CAAC;QAC3B,CAAC;QACD,OAAO,CAAC,KAAK,CAAC,WAAW,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,YAAY,IAAI,CAAC,CAAC,CAAC;IAC9D,CAAC;CACF"}
@@ -0,0 +1,8 @@
1
+ export declare class ApprovalManager {
2
+ private yolo;
3
+ private autoApproveActions;
4
+ constructor(yolo?: boolean);
5
+ request(toolName: string, action: string, description: string): Promise<boolean>;
6
+ setYolo(yolo: boolean): void;
7
+ }
8
+ //# sourceMappingURL=ApprovalManager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ApprovalManager.d.ts","sourceRoot":"","sources":["../../src/agent/ApprovalManager.ts"],"names":[],"mappings":"AAEA,qBAAa,eAAe;IAC1B,OAAO,CAAC,IAAI,CAAU;IACtB,OAAO,CAAC,kBAAkB,CAAqB;gBAEnC,IAAI,UAAQ;IAIlB,OAAO,CACX,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,OAAO,CAAC;IAwCnB,OAAO,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI;CAG7B"}
@@ -0,0 +1,45 @@
1
+ import * as readline from 'readline';
2
+ export class ApprovalManager {
3
+ yolo;
4
+ autoApproveActions = new Set();
5
+ constructor(yolo = false) {
6
+ this.yolo = yolo;
7
+ }
8
+ async request(toolName, action, description) {
9
+ if (this.yolo) {
10
+ return true;
11
+ }
12
+ if (this.autoApproveActions.has(action)) {
13
+ return true;
14
+ }
15
+ console.log('\n⚠️ Approval Required');
16
+ console.log(`Tool: ${toolName}`);
17
+ console.log(`Action: ${description}`);
18
+ console.log('\nOptions:');
19
+ console.log(' 1. Approve once');
20
+ console.log(' 2. Approve for this session');
21
+ console.log(' 3. Reject');
22
+ const rl = readline.createInterface({
23
+ input: process.stdin,
24
+ output: process.stdout,
25
+ });
26
+ const answer = await new Promise(resolve => {
27
+ rl.question('\nYour choice (1-3): ', resolve);
28
+ });
29
+ rl.close();
30
+ switch (answer.trim()) {
31
+ case '1':
32
+ return true;
33
+ case '2':
34
+ this.autoApproveActions.add(action);
35
+ return true;
36
+ case '3':
37
+ default:
38
+ return false;
39
+ }
40
+ }
41
+ setYolo(yolo) {
42
+ this.yolo = yolo;
43
+ }
44
+ }
45
+ //# sourceMappingURL=ApprovalManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ApprovalManager.js","sourceRoot":"","sources":["../../src/agent/ApprovalManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,QAAQ,MAAM,UAAU,CAAC;AAErC,MAAM,OAAO,eAAe;IAClB,IAAI,CAAU;IACd,kBAAkB,GAAG,IAAI,GAAG,EAAU,CAAC;IAE/C,YAAY,IAAI,GAAG,KAAK;QACtB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,KAAK,CAAC,OAAO,CACX,QAAgB,EAChB,MAAc,EACd,WAAmB;QAEnB,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACd,OAAO,IAAI,CAAC;QACd,CAAC;QAED,IAAI,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;YACxC,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;QACvC,OAAO,CAAC,GAAG,CAAC,SAAS,QAAQ,EAAE,CAAC,CAAC;QACjC,OAAO,CAAC,GAAG,CAAC,WAAW,WAAW,EAAE,CAAC,CAAC;QACtC,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;QAC1B,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;QACjC,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;QAC7C,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QAE3B,MAAM,EAAE,GAAG,QAAQ,CAAC,eAAe,CAAC;YAClC,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,MAAM,EAAE,OAAO,CAAC,MAAM;SACvB,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,MAAM,IAAI,OAAO,CAAS,OAAO,CAAC,EAAE;YACjD,EAAE,CAAC,QAAQ,CAAC,uBAAuB,EAAE,OAAO,CAAC,CAAC;QAChD,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,KAAK,EAAE,CAAC;QAEX,QAAQ,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;YACtB,KAAK,GAAG;gBACN,OAAO,IAAI,CAAC;YACd,KAAK,GAAG;gBACN,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;gBACpC,OAAO,IAAI,CAAC;YACd,KAAK,GAAG,CAAC;YACT;gBACE,OAAO,KAAK,CAAC;QACjB,CAAC;IACH,CAAC;IAED,OAAO,CAAC,IAAa;QACnB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF"}
@@ -0,0 +1,9 @@
1
+ import type { LanguageModel, ModelMessage } from 'ai';
2
+ export declare class ContextCompressor {
3
+ private readonly model;
4
+ constructor(model: LanguageModel);
5
+ compress(history: ModelMessage[], _systemPrompt: string): Promise<string>;
6
+ private buildCompactionPrompt;
7
+ private formatContent;
8
+ }
9
+ //# sourceMappingURL=ContextCompressor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ContextCompressor.d.ts","sourceRoot":"","sources":["../../src/agent/ContextCompressor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAGtD,qBAAa,iBAAiB;IAChB,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,aAAa;IAE3C,QAAQ,CACZ,OAAO,EAAE,YAAY,EAAE,EACvB,aAAa,EAAE,MAAM,GACpB,OAAO,CAAC,MAAM,CAAC;IAUlB,OAAO,CAAC,qBAAqB;IAiB7B,OAAO,CAAC,aAAa;CA4BtB"}
@@ -0,0 +1,58 @@
1
+ import { generateText } from 'ai';
2
+ export class ContextCompressor {
3
+ model;
4
+ constructor(model) {
5
+ this.model = model;
6
+ }
7
+ async compress(history, _systemPrompt) {
8
+ const compactionPrompt = this.buildCompactionPrompt(history);
9
+ const response = await generateText({
10
+ model: this.model,
11
+ maxOutputTokens: 1024,
12
+ prompt: compactionPrompt,
13
+ });
14
+ return response.text.trim();
15
+ }
16
+ buildCompactionPrompt(history) {
17
+ const historyText = history
18
+ .map((msg, i) => `## Message ${i + 1}\nRole: ${msg.role}\nContent: ${this.formatContent(msg.content)}`)
19
+ .join('\n\n');
20
+ return `You are tasked with compacting a conversation context. Focus on:
21
+ 1. Current task state and goals
22
+ 2. Important errors and solutions
23
+ 3. Key decisions made
24
+ 4. Pending TODO items
25
+
26
+ Context to compress:
27
+ ${historyText}
28
+
29
+ Provide a concise summary that preserves essential information.`;
30
+ }
31
+ formatContent(content) {
32
+ if (typeof content === 'string') {
33
+ return content;
34
+ }
35
+ if (Array.isArray(content)) {
36
+ return content
37
+ .map(part => {
38
+ if (typeof part !== 'object' || !part) {
39
+ return undefined;
40
+ }
41
+ if ('text' in part && typeof part.text === 'string') {
42
+ return part.text;
43
+ }
44
+ if ('type' in part && part.type === 'tool-call') {
45
+ return `[tool:${part.toolName}] ${JSON.stringify(part.input)}`;
46
+ }
47
+ if ('type' in part && part.type === 'tool-result') {
48
+ return `[tool-result:${part.toolName}] ${JSON.stringify(part.output)}`;
49
+ }
50
+ return `[${part.type ?? 'unknown-part'}]`;
51
+ })
52
+ .filter((value) => typeof value === 'string')
53
+ .join('\n');
54
+ }
55
+ return JSON.stringify(content);
56
+ }
57
+ }
58
+ //# sourceMappingURL=ContextCompressor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ContextCompressor.js","sourceRoot":"","sources":["../../src/agent/ContextCompressor.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAElC,MAAM,OAAO,iBAAiB;IACC;IAA7B,YAA6B,KAAoB;QAApB,UAAK,GAAL,KAAK,CAAe;IAAG,CAAC;IAErD,KAAK,CAAC,QAAQ,CACZ,OAAuB,EACvB,aAAqB;QAErB,MAAM,gBAAgB,GAAG,IAAI,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC;QAC7D,MAAM,QAAQ,GAAG,MAAM,YAAY,CAAC;YAClC,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,eAAe,EAAE,IAAI;YACrB,MAAM,EAAE,gBAAgB;SACzB,CAAC,CAAC;QACH,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;IAC9B,CAAC;IAEO,qBAAqB,CAAC,OAAuB;QACnD,MAAM,WAAW,GAAG,OAAO;aACxB,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,cAAc,CAAC,GAAG,CAAC,WAAW,GAAG,CAAC,IAAI,cAAc,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;aACtG,IAAI,CAAC,MAAM,CAAC,CAAC;QAEhB,OAAO;;;;;;;EAOT,WAAW;;gEAEmD,CAAC;IAC/D,CAAC;IAEO,aAAa,CAAC,OAAgC;QACpD,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;YAChC,OAAO,OAAO,CAAC;QACjB,CAAC;QAED,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;YAC3B,OAAO,OAAO;iBACX,GAAG,CAAC,IAAI,CAAC,EAAE;gBACV,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC;oBACtC,OAAO,SAAS,CAAC;gBACnB,CAAC;gBACD,IAAI,MAAM,IAAI,IAAI,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;oBACpD,OAAO,IAAI,CAAC,IAAI,CAAC;gBACnB,CAAC;gBACD,IAAI,MAAM,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,WAAW,EAAE,CAAC;oBAChD,OAAO,SAAS,IAAI,CAAC,QAAQ,KAAK,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;gBACjE,CAAC;gBACD,IAAI,MAAM,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,aAAa,EAAE,CAAC;oBAClD,OAAO,gBAAgB,IAAI,CAAC,QAAQ,KAAK,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;gBACzE,CAAC;gBACD,OAAO,IAAK,IAA0B,CAAC,IAAI,IAAI,cAAc,GAAG,CAAC;YACnE,CAAC,CAAC;iBACD,MAAM,CAAC,CAAC,KAAK,EAAmB,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC;iBAC7D,IAAI,CAAC,IAAI,CAAC,CAAC;QAChB,CAAC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IACjC,CAAC;CACF"}
@@ -0,0 +1,19 @@
1
+ import type { ModelMessage } from 'ai';
2
+ export declare class ConversationContext {
3
+ private messages;
4
+ private _tokenCount;
5
+ private checkpointCounter;
6
+ private storageFile;
7
+ private isMemoryMode;
8
+ constructor(storageFile: string);
9
+ loadFromDisk(): Promise<boolean>;
10
+ createCheckpoint(): Promise<number>;
11
+ addMessage(message: ModelMessage | ModelMessage[]): Promise<void>;
12
+ updateTokenCount(count: number): Promise<void>;
13
+ revertToCheckpoint(checkpointId: number): Promise<void>;
14
+ getHistory(): ModelMessage[];
15
+ get tokenCount(): number;
16
+ get checkpointCount(): number;
17
+ private persistRecord;
18
+ }
19
+ //# sourceMappingURL=ConversationContext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ConversationContext.d.ts","sourceRoot":"","sources":["../../src/agent/ConversationContext.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAA+B,MAAM,IAAI,CAAC;AAoJpE,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,QAAQ,CAAsB;IACtC,OAAO,CAAC,WAAW,CAAK;IACxB,OAAO,CAAC,iBAAiB,CAAK;IAC9B,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,YAAY,CAAU;gBAElB,WAAW,EAAE,MAAM;IAKzB,YAAY,IAAI,OAAO,CAAC,OAAO,CAAC;IAiChC,gBAAgB,IAAI,OAAO,CAAC,MAAM,CAAC;IAMnC,UAAU,CACd,OAAO,EAAE,YAAY,GAAG,YAAY,EAAE,GACrC,OAAO,CAAC,IAAI,CAAC;IASV,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAK9C,kBAAkB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA8C7D,UAAU,IAAI,YAAY,EAAE;IAI5B,IAAI,UAAU,IAAI,MAAM,CAEvB;IAED,IAAI,eAAe,IAAI,MAAM,CAE5B;YAEa,aAAa;CAU5B"}