@di-code/coding-agent 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 (157) hide show
  1. package/dist/cli.d.ts +26 -0
  2. package/dist/cli.d.ts.map +1 -0
  3. package/dist/cli.js +117 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/config/models-loader.d.ts +4 -0
  6. package/dist/config/models-loader.d.ts.map +1 -0
  7. package/dist/config/models-loader.js +134 -0
  8. package/dist/config/models-loader.js.map +1 -0
  9. package/dist/config/models-types.d.ts +23 -0
  10. package/dist/config/models-types.d.ts.map +1 -0
  11. package/dist/config/models-types.js +2 -0
  12. package/dist/config/models-types.js.map +1 -0
  13. package/dist/config/settings-loader.d.ts +3 -0
  14. package/dist/config/settings-loader.d.ts.map +1 -0
  15. package/dist/config/settings-loader.js +130 -0
  16. package/dist/config/settings-loader.js.map +1 -0
  17. package/dist/config/settings-types.d.ts +21 -0
  18. package/dist/config/settings-types.d.ts.map +1 -0
  19. package/dist/config/settings-types.js +2 -0
  20. package/dist/config/settings-types.js.map +1 -0
  21. package/dist/core/context-builder.d.ts +8 -0
  22. package/dist/core/context-builder.d.ts.map +1 -0
  23. package/dist/core/context-builder.js +46 -0
  24. package/dist/core/context-builder.js.map +1 -0
  25. package/dist/core/model-catalog-store.d.ts +8 -0
  26. package/dist/core/model-catalog-store.d.ts.map +1 -0
  27. package/dist/core/model-catalog-store.js +68 -0
  28. package/dist/core/model-catalog-store.js.map +1 -0
  29. package/dist/core/model-composer.d.ts +4 -0
  30. package/dist/core/model-composer.d.ts.map +1 -0
  31. package/dist/core/model-composer.js +37 -0
  32. package/dist/core/model-composer.js.map +1 -0
  33. package/dist/core/session/session-manager.d.ts +44 -0
  34. package/dist/core/session/session-manager.d.ts.map +1 -0
  35. package/dist/core/session/session-manager.js +138 -0
  36. package/dist/core/session/session-manager.js.map +1 -0
  37. package/dist/core/session/session-storage.d.ts +11 -0
  38. package/dist/core/session/session-storage.d.ts.map +1 -0
  39. package/dist/core/session/session-storage.js +382 -0
  40. package/dist/core/session/session-storage.js.map +1 -0
  41. package/dist/core/session/types.d.ts +65 -0
  42. package/dist/core/session/types.d.ts.map +1 -0
  43. package/dist/core/session/types.js +28 -0
  44. package/dist/core/session/types.js.map +1 -0
  45. package/dist/core/session.d.ts +80 -0
  46. package/dist/core/session.d.ts.map +1 -0
  47. package/dist/core/session.js +262 -0
  48. package/dist/core/session.js.map +1 -0
  49. package/dist/core/tools/bash.d.ts +39 -0
  50. package/dist/core/tools/bash.d.ts.map +1 -0
  51. package/dist/core/tools/bash.js +208 -0
  52. package/dist/core/tools/bash.js.map +1 -0
  53. package/dist/core/tools/edit.d.ts +18 -0
  54. package/dist/core/tools/edit.d.ts.map +1 -0
  55. package/dist/core/tools/edit.js +107 -0
  56. package/dist/core/tools/edit.js.map +1 -0
  57. package/dist/core/tools/file-mutation-queue.d.ts +2 -0
  58. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -0
  59. package/dist/core/tools/file-mutation-queue.js +24 -0
  60. package/dist/core/tools/file-mutation-queue.js.map +1 -0
  61. package/dist/core/tools/path-boundary.d.ts +3 -0
  62. package/dist/core/tools/path-boundary.d.ts.map +1 -0
  63. package/dist/core/tools/path-boundary.js +62 -0
  64. package/dist/core/tools/path-boundary.js.map +1 -0
  65. package/dist/core/tools/read.d.ts +17 -0
  66. package/dist/core/tools/read.d.ts.map +1 -0
  67. package/dist/core/tools/read.js +132 -0
  68. package/dist/core/tools/read.js.map +1 -0
  69. package/dist/core/tools/write.d.ts +17 -0
  70. package/dist/core/tools/write.d.ts.map +1 -0
  71. package/dist/core/tools/write.js +45 -0
  72. package/dist/core/tools/write.js.map +1 -0
  73. package/dist/entry.d.ts +3 -0
  74. package/dist/entry.d.ts.map +1 -0
  75. package/dist/entry.js +27 -0
  76. package/dist/entry.js.map +1 -0
  77. package/dist/extensions/index.d.ts +5 -0
  78. package/dist/extensions/index.d.ts.map +1 -0
  79. package/dist/extensions/index.js +3 -0
  80. package/dist/extensions/index.js.map +1 -0
  81. package/dist/extensions/runtime.d.ts +46 -0
  82. package/dist/extensions/runtime.d.ts.map +1 -0
  83. package/dist/extensions/runtime.js +179 -0
  84. package/dist/extensions/runtime.js.map +1 -0
  85. package/dist/extensions/trust.d.ts +8 -0
  86. package/dist/extensions/trust.d.ts.map +1 -0
  87. package/dist/extensions/trust.js +59 -0
  88. package/dist/extensions/trust.js.map +1 -0
  89. package/dist/extensions/types.d.ts +46 -0
  90. package/dist/extensions/types.d.ts.map +1 -0
  91. package/dist/extensions/types.js +2 -0
  92. package/dist/extensions/types.js.map +1 -0
  93. package/dist/index.d.ts +8 -0
  94. package/dist/index.d.ts.map +1 -0
  95. package/dist/index.js +8 -0
  96. package/dist/index.js.map +1 -0
  97. package/dist/main.d.ts +19 -0
  98. package/dist/main.d.ts.map +1 -0
  99. package/dist/main.js +198 -0
  100. package/dist/main.js.map +1 -0
  101. package/dist/modes/interactive-components.d.ts +41 -0
  102. package/dist/modes/interactive-components.d.ts.map +1 -0
  103. package/dist/modes/interactive-components.js +195 -0
  104. package/dist/modes/interactive-components.js.map +1 -0
  105. package/dist/modes/interactive-layout.d.ts +20 -0
  106. package/dist/modes/interactive-layout.d.ts.map +1 -0
  107. package/dist/modes/interactive-layout.js +34 -0
  108. package/dist/modes/interactive-layout.js.map +1 -0
  109. package/dist/modes/interactive-state.d.ts +61 -0
  110. package/dist/modes/interactive-state.d.ts.map +1 -0
  111. package/dist/modes/interactive-state.js +201 -0
  112. package/dist/modes/interactive-state.js.map +1 -0
  113. package/dist/modes/interactive.d.ts +61 -0
  114. package/dist/modes/interactive.d.ts.map +1 -0
  115. package/dist/modes/interactive.js +436 -0
  116. package/dist/modes/interactive.js.map +1 -0
  117. package/dist/modes/json.d.ts +14 -0
  118. package/dist/modes/json.d.ts.map +1 -0
  119. package/dist/modes/json.js +26 -0
  120. package/dist/modes/json.js.map +1 -0
  121. package/dist/modes/print.d.ts +10 -0
  122. package/dist/modes/print.d.ts.map +1 -0
  123. package/dist/modes/print.js +28 -0
  124. package/dist/modes/print.js.map +1 -0
  125. package/dist/provider-onboarding.d.ts +13 -0
  126. package/dist/provider-onboarding.d.ts.map +1 -0
  127. package/dist/provider-onboarding.js +162 -0
  128. package/dist/provider-onboarding.js.map +1 -0
  129. package/dist/rpc/client.d.ts +38 -0
  130. package/dist/rpc/client.d.ts.map +1 -0
  131. package/dist/rpc/client.js +153 -0
  132. package/dist/rpc/client.js.map +1 -0
  133. package/dist/rpc/index.d.ts +5 -0
  134. package/dist/rpc/index.d.ts.map +1 -0
  135. package/dist/rpc/index.js +5 -0
  136. package/dist/rpc/index.js.map +1 -0
  137. package/dist/rpc/jsonl.d.ts +17 -0
  138. package/dist/rpc/jsonl.d.ts.map +1 -0
  139. package/dist/rpc/jsonl.js +52 -0
  140. package/dist/rpc/jsonl.js.map +1 -0
  141. package/dist/rpc/protocol.d.ts +80 -0
  142. package/dist/rpc/protocol.d.ts.map +1 -0
  143. package/dist/rpc/protocol.js +231 -0
  144. package/dist/rpc/protocol.js.map +1 -0
  145. package/dist/rpc/server.d.ts +41 -0
  146. package/dist/rpc/server.d.ts.map +1 -0
  147. package/dist/rpc/server.js +186 -0
  148. package/dist/rpc/server.js.map +1 -0
  149. package/dist/rpc-entry.d.ts +3 -0
  150. package/dist/rpc-entry.d.ts.map +1 -0
  151. package/dist/rpc-entry.js +28 -0
  152. package/dist/rpc-entry.js.map +1 -0
  153. package/dist/startup.d.ts +24 -0
  154. package/dist/startup.d.ts.map +1 -0
  155. package/dist/startup.js +227 -0
  156. package/dist/startup.js.map +1 -0
  157. package/package.json +43 -0
@@ -0,0 +1,262 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { Agent, estimateContextTokens, generateCompactionSummary, prepareCompaction, resolveContextBudget, shouldCompact, } from "@di-code/agent";
3
+ import { buildSessionContext } from "./context-builder.js";
4
+ import { createBashTool } from "./tools/bash.js";
5
+ import { createEditTool } from "./tools/edit.js";
6
+ import { createReadTool } from "./tools/read.js";
7
+ import { createWriteTool } from "./tools/write.js";
8
+ export class AgentSession {
9
+ agent;
10
+ allowedRootValue;
11
+ sessionManager;
12
+ provider;
13
+ model;
14
+ sessionIdValue;
15
+ now;
16
+ compactionEnabledValue;
17
+ contextBudget;
18
+ keepRecentTokens;
19
+ usageTotals;
20
+ persistenceError;
21
+ promptActive = false;
22
+ sessionListeners = new Set();
23
+ constructor(options) {
24
+ this.allowedRootValue = options.allowedRoot;
25
+ this.sessionManager = options.sessionManager;
26
+ this.provider = options.provider;
27
+ this.model = options.model;
28
+ this.sessionIdValue = options.sessionManager?.header.id ?? randomUUID();
29
+ this.now = options.now ?? Date.now;
30
+ this.contextBudget = resolveContextBudget(options.model);
31
+ if (options.compaction?.enabled !== undefined && typeof options.compaction.enabled !== "boolean") {
32
+ throw new TypeError("compaction.enabled must be a boolean");
33
+ }
34
+ this.compactionEnabledValue = options.sessionManager !== undefined && options.compaction?.enabled !== false;
35
+ const defaultKeepRecentTokens = Math.max(1, Math.min(20_000, Math.floor(this.contextBudget.triggerTokens / 2)));
36
+ this.keepRecentTokens = options.compaction?.keepRecentTokens ?? defaultKeepRecentTokens;
37
+ if (!Number.isInteger(this.keepRecentTokens) || this.keepRecentTokens <= 0) {
38
+ throw new RangeError("compaction.keepRecentTokens must be a positive integer");
39
+ }
40
+ this.usageTotals = {
41
+ requestCount: 0,
42
+ inputTokens: 0,
43
+ outputTokens: 0,
44
+ cacheReadTokens: 0,
45
+ cacheWriteTokens: 0,
46
+ totalTokens: 0,
47
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
48
+ };
49
+ for (const message of options.sessionManager?.messages ?? []) {
50
+ if (message.role === "assistant")
51
+ this.addUsage(message.usage);
52
+ }
53
+ const initialContext = options.sessionManager ? buildSessionContext(options.sessionManager.entries) : undefined;
54
+ this.agent = new Agent({
55
+ provider: options.provider,
56
+ model: options.model,
57
+ sessionId: this.sessionIdValue,
58
+ tools: [
59
+ createReadTool(options.allowedRoot),
60
+ createWriteTool(options.allowedRoot),
61
+ createEditTool(options.allowedRoot),
62
+ createBashTool(options.allowedRoot),
63
+ ],
64
+ now: this.now,
65
+ initialMessages: options.sessionManager?.messages,
66
+ initialContextMessages: initialContext?.messages,
67
+ });
68
+ this.agent.subscribe(async (event) => {
69
+ if (event.type !== "message_end" || this.sessionManager === undefined || this.persistenceError !== undefined) {
70
+ return;
71
+ }
72
+ try {
73
+ await this.sessionManager.appendMessage(event.message);
74
+ }
75
+ catch (cause) {
76
+ this.persistenceError = cause;
77
+ throw cause;
78
+ }
79
+ });
80
+ this.agent.subscribe(async (event) => {
81
+ if (event.type !== "message_end" || event.message.role !== "assistant")
82
+ return;
83
+ this.addUsage(event.message.usage);
84
+ await this.emitSession({ type: "usage_update", usage: this.usage });
85
+ });
86
+ this.agent.subscribe(async (event) => {
87
+ await this.emitSession(event);
88
+ });
89
+ }
90
+ get transcript() {
91
+ return this.agent.transcript;
92
+ }
93
+ get isStreaming() {
94
+ return this.promptActive;
95
+ }
96
+ get sessionId() {
97
+ return this.sessionIdValue;
98
+ }
99
+ get modelId() {
100
+ return this.model.id;
101
+ }
102
+ get allowedRoot() {
103
+ return this.allowedRootValue;
104
+ }
105
+ get availableModels() {
106
+ return structuredClone(this.provider.models);
107
+ }
108
+ setModel(modelId) {
109
+ if (this.promptActive)
110
+ throw new Error("Cannot change model while AgentSession is processing a prompt.");
111
+ const next = this.provider.models.find((model) => model.id === modelId);
112
+ if (!next)
113
+ throw new Error(`Unknown model "${modelId}" for provider "${this.provider.id}".`);
114
+ this.model = structuredClone(next);
115
+ this.agent.setModel(this.model);
116
+ this.contextBudget = resolveContextBudget(this.model);
117
+ this.keepRecentTokens = Math.min(this.keepRecentTokens, Math.max(1, Math.min(20_000, Math.floor(this.contextBudget.triggerTokens / 2))));
118
+ return structuredClone(this.model);
119
+ }
120
+ get compactionEnabled() {
121
+ return this.compactionEnabledValue;
122
+ }
123
+ setCompactionEnabled(enabled) {
124
+ if (this.promptActive)
125
+ throw new Error("Cannot change compaction while AgentSession is processing a prompt.");
126
+ this.compactionEnabledValue = enabled && this.sessionManager !== undefined;
127
+ return this.compactionEnabledValue;
128
+ }
129
+ get sessionFile() {
130
+ return this.sessionManager?.filePath;
131
+ }
132
+ get sessionDiagnostics() {
133
+ return this.sessionManager?.diagnostics ?? [];
134
+ }
135
+ get usage() {
136
+ return {
137
+ ...this.usageTotals,
138
+ cost: { ...this.usageTotals.cost },
139
+ estimatedContextTokens: estimateContextTokens(this.agent.contextMessages),
140
+ contextWindow: this.contextBudget.contextWindow,
141
+ reserveTokens: this.contextBudget.reserveTokens,
142
+ triggerTokens: this.contextBudget.triggerTokens,
143
+ };
144
+ }
145
+ async prompt(text, signal) {
146
+ if (this.persistenceError !== undefined) {
147
+ throw this.persistenceError;
148
+ }
149
+ if (this.promptActive) {
150
+ throw new Error("AgentSession is already processing a prompt.");
151
+ }
152
+ this.promptActive = true;
153
+ try {
154
+ await this.compactIfNeeded(text, signal);
155
+ return await this.agent.prompt(text, signal);
156
+ }
157
+ finally {
158
+ this.promptActive = false;
159
+ }
160
+ }
161
+ async compact(signal) {
162
+ if (this.promptActive)
163
+ throw new Error("AgentSession is already processing a prompt.");
164
+ if (!this.sessionManager)
165
+ throw new Error("Cannot compact without a persisted session.");
166
+ this.promptActive = true;
167
+ try {
168
+ await this.compactNow(signal, "manual");
169
+ }
170
+ finally {
171
+ this.promptActive = false;
172
+ }
173
+ }
174
+ subscribe(listener) {
175
+ return this.agent.subscribe(listener);
176
+ }
177
+ subscribeSession(listener) {
178
+ this.sessionListeners.add(listener);
179
+ return () => this.sessionListeners.delete(listener);
180
+ }
181
+ async emitSession(event) {
182
+ for (const listener of this.sessionListeners)
183
+ await listener(structuredClone(event));
184
+ }
185
+ addUsage(usage) {
186
+ this.usageTotals = {
187
+ requestCount: this.usageTotals.requestCount + 1,
188
+ inputTokens: this.usageTotals.inputTokens + usage.input,
189
+ outputTokens: this.usageTotals.outputTokens + usage.output,
190
+ cacheReadTokens: this.usageTotals.cacheReadTokens + usage.cacheRead,
191
+ cacheWriteTokens: this.usageTotals.cacheWriteTokens + usage.cacheWrite,
192
+ totalTokens: this.usageTotals.totalTokens + usage.totalTokens,
193
+ cost: {
194
+ input: this.usageTotals.cost.input + usage.cost.input,
195
+ output: this.usageTotals.cost.output + usage.cost.output,
196
+ cacheRead: this.usageTotals.cost.cacheRead + usage.cost.cacheRead,
197
+ cacheWrite: this.usageTotals.cost.cacheWrite + usage.cost.cacheWrite,
198
+ total: this.usageTotals.cost.total + usage.cost.total,
199
+ },
200
+ };
201
+ }
202
+ async compactIfNeeded(text, signal) {
203
+ if (!this.compactionEnabledValue || !this.sessionManager)
204
+ return;
205
+ const context = buildSessionContext(this.sessionManager.entries);
206
+ const pendingUser = {
207
+ role: "user",
208
+ content: [{ type: "text", text }],
209
+ timestamp: 0,
210
+ };
211
+ const estimatedTokens = estimateContextTokens([...context.messages, pendingUser]);
212
+ if (!shouldCompact(estimatedTokens, this.contextBudget))
213
+ return;
214
+ await this.compactNow(signal, "threshold");
215
+ }
216
+ async compactNow(signal, reason) {
217
+ if (!this.sessionManager)
218
+ throw new Error("Cannot compact without a persisted session.");
219
+ const context = buildSessionContext(this.sessionManager.entries);
220
+ await this.emitSession({ type: "compaction_start", reason });
221
+ const preparation = prepareCompaction(context.messages, this.keepRecentTokens);
222
+ const firstKeptEntryId = preparation ? context.sourceEntryIds[preparation.firstKeptMessageIndex] : undefined;
223
+ if (!preparation || typeof firstKeptEntryId !== "string") {
224
+ const errorMessage = reason === "manual"
225
+ ? "No valid compaction cut point was found for the current session."
226
+ : "Context limit reached but no valid compaction cut point was found.";
227
+ await this.emitSession({ type: "compaction_end", reason, success: false, errorMessage });
228
+ throw new Error(errorMessage);
229
+ }
230
+ let summary;
231
+ try {
232
+ summary = await generateCompactionSummary(preparation, this.provider, this.model, {
233
+ reserveTokens: this.contextBudget.reserveTokens,
234
+ signal,
235
+ now: this.now,
236
+ onUsage: (usage) => this.addUsage(usage),
237
+ });
238
+ await this.emitSession({ type: "usage_update", usage: this.usage });
239
+ }
240
+ catch (cause) {
241
+ const errorMessage = cause instanceof Error ? cause.message : String(cause);
242
+ await this.emitSession({ type: "compaction_end", reason, success: false, errorMessage });
243
+ throw cause;
244
+ }
245
+ try {
246
+ await this.sessionManager.appendSummary({
247
+ summary,
248
+ firstKeptEntryId,
249
+ tokensBefore: preparation.tokensBefore,
250
+ });
251
+ }
252
+ catch (cause) {
253
+ this.persistenceError = cause;
254
+ const errorMessage = cause instanceof Error ? cause.message : String(cause);
255
+ await this.emitSession({ type: "compaction_end", reason, success: false, errorMessage });
256
+ throw cause;
257
+ }
258
+ this.agent.replaceContext(buildSessionContext(this.sessionManager.entries).messages);
259
+ await this.emitSession({ type: "compaction_end", reason, success: true });
260
+ }
261
+ }
262
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../../src/core/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACN,KAAK,EAGL,qBAAqB,EACrB,yBAAyB,EACzB,iBAAiB,EACjB,oBAAoB,EACpB,aAAa,GACb,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAG3D,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAsCnD,MAAM,OAAO,YAAY;IACP,KAAK,CAAQ;IACb,gBAAgB,CAAS;IACzB,cAAc,CAAkB;IAChC,QAAQ,CAAW;IAC5B,KAAK,CAAQ;IACJ,cAAc,CAAS;IACvB,GAAG,CAAe;IAC3B,sBAAsB,CA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K,CAAC;QACb,CAAC;QAED,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,mBAAmB,CAAC,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC;QACrF,MAAM,IAAI,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,gBAAgB,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IAC3E,CAAC;CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n\tAgent,\n\ttype AgentListener,\n\ttype ContextBudget,\n\testimateContextTokens,\n\tgenerateCompactionSummary,\n\tprepareCompaction,\n\tresolveContextBudget,\n\tshouldCompact,\n} from \"@di-code/agent\";\nimport type { AssistantMessage, Message, Model, Provider, Usage } from \"@di-code/ai\";\nimport { buildSessionContext } from \"./context-builder.ts\";\nimport type { SessionManager } from \"./session/session-manager.ts\";\nimport type { SessionDiagnostic } from \"./session/types.ts\";\nimport { createBashTool } from \"./tools/bash.ts\";\nimport { createEditTool } from \"./tools/edit.ts\";\nimport { createReadTool } from \"./tools/read.ts\";\nimport { createWriteTool } from \"./tools/write.ts\";\n\nexport interface AgentSessionCompactionOptions {\n\treadonly enabled?: boolean;\n\treadonly keepRecentTokens?: number;\n}\n\nexport interface SessionUsage {\n\treadonly requestCount: number;\n\treadonly inputTokens: number;\n\treadonly outputTokens: number;\n\treadonly cacheReadTokens: number;\n\treadonly cacheWriteTokens: number;\n\treadonly totalTokens: number;\n\treadonly cost: Usage[\"cost\"];\n\treadonly estimatedContextTokens: number;\n\treadonly contextWindow: number;\n\treadonly reserveTokens: number;\n\treadonly triggerTokens: number;\n}\n\nexport interface AgentSessionOptions {\n\treadonly allowedRoot: string;\n\treadonly provider: Provider;\n\treadonly model: Model;\n\treadonly now?: () => number;\n\treadonly sessionManager?: SessionManager;\n\treadonly compaction?: AgentSessionCompactionOptions;\n}\n\nexport type AgentSessionEvent =\n\t| import(\"@di-code/agent\").AgentEvent\n\t| { type: \"compaction_start\"; reason: \"threshold\" | \"manual\" }\n\t| { type: \"compaction_end\"; reason: \"threshold\" | \"manual\"; success: boolean; errorMessage?: string }\n\t| { type: \"usage_update\"; usage: SessionUsage };\n\nexport type AgentSessionListener = (event: AgentSessionEvent) => void | Promise<void>;\n\nexport class AgentSession {\n\tprivate readonly agent: Agent;\n\tprivate readonly allowedRootValue: string;\n\tprivate readonly sessionManager?: SessionManager;\n\tprivate readonly provider: Provider;\n\tprivate model: Model;\n\tprivate readonly sessionIdValue: string;\n\tprivate readonly now: () => number;\n\tprivate compactionEnabledValue: boolean;\n\tprivate contextBudget: ContextBudget;\n\tprivate keepRecentTokens: number;\n\tprivate usageTotals: Omit<\n\t\tSessionUsage,\n\t\t\"estimatedContextTokens\" | \"contextWindow\" | \"reserveTokens\" | \"triggerTokens\"\n\t>;\n\tprivate persistenceError?: unknown;\n\tprivate promptActive = false;\n\tprivate readonly sessionListeners = new Set<AgentSessionListener>();\n\n\tconstructor(options: AgentSessionOptions) {\n\t\tthis.allowedRootValue = options.allowedRoot;\n\t\tthis.sessionManager = options.sessionManager;\n\t\tthis.provider = options.provider;\n\t\tthis.model = options.model;\n\t\tthis.sessionIdValue = options.sessionManager?.header.id ?? randomUUID();\n\t\tthis.now = options.now ?? Date.now;\n\t\tthis.contextBudget = resolveContextBudget(options.model);\n\t\tif (options.compaction?.enabled !== undefined && typeof options.compaction.enabled !== \"boolean\") {\n\t\t\tthrow new TypeError(\"compaction.enabled must be a boolean\");\n\t\t}\n\t\tthis.compactionEnabledValue = options.sessionManager !== undefined && options.compaction?.enabled !== false;\n\t\tconst defaultKeepRecentTokens = Math.max(1, Math.min(20_000, Math.floor(this.contextBudget.triggerTokens / 2)));\n\t\tthis.keepRecentTokens = options.compaction?.keepRecentTokens ?? defaultKeepRecentTokens;\n\t\tif (!Number.isInteger(this.keepRecentTokens) || this.keepRecentTokens <= 0) {\n\t\t\tthrow new RangeError(\"compaction.keepRecentTokens must be a positive integer\");\n\t\t}\n\t\tthis.usageTotals = {\n\t\t\trequestCount: 0,\n\t\t\tinputTokens: 0,\n\t\t\toutputTokens: 0,\n\t\t\tcacheReadTokens: 0,\n\t\t\tcacheWriteTokens: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t};\n\t\tfor (const message of options.sessionManager?.messages ?? []) {\n\t\t\tif (message.role === \"assistant\") this.addUsage(message.usage);\n\t\t}\n\t\tconst initialContext = options.sessionManager ? buildSessionContext(options.sessionManager.entries) : undefined;\n\t\tthis.agent = new Agent({\n\t\t\tprovider: options.provider,\n\t\t\tmodel: options.model,\n\t\t\tsessionId: this.sessionIdValue,\n\t\t\ttools: [\n\t\t\t\tcreateReadTool(options.allowedRoot),\n\t\t\t\tcreateWriteTool(options.allowedRoot),\n\t\t\t\tcreateEditTool(options.allowedRoot),\n\t\t\t\tcreateBashTool(options.allowedRoot),\n\t\t\t],\n\t\t\tnow: this.now,\n\t\t\tinitialMessages: options.sessionManager?.messages,\n\t\t\tinitialContextMessages: initialContext?.messages,\n\t\t});\n\t\tthis.agent.subscribe(async (event) => {\n\t\t\tif (event.type !== \"message_end\" || this.sessionManager === undefined || this.persistenceError !== undefined) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait this.sessionManager.appendMessage(event.message);\n\t\t\t} catch (cause) {\n\t\t\t\tthis.persistenceError = cause;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t});\n\t\tthis.agent.subscribe(async (event) => {\n\t\t\tif (event.type !== \"message_end\" || event.message.role !== \"assistant\") return;\n\t\t\tthis.addUsage(event.message.usage);\n\t\t\tawait this.emitSession({ type: \"usage_update\", usage: this.usage });\n\t\t});\n\t\tthis.agent.subscribe(async (event) => {\n\t\t\tawait this.emitSession(event);\n\t\t});\n\t}\n\n\tget transcript(): readonly Message[] {\n\t\treturn this.agent.transcript;\n\t}\n\n\tget isStreaming(): boolean {\n\t\treturn this.promptActive;\n\t}\n\n\tget sessionId(): string {\n\t\treturn this.sessionIdValue;\n\t}\n\n\tget modelId(): string {\n\t\treturn this.model.id;\n\t}\n\n\tget allowedRoot(): string {\n\t\treturn this.allowedRootValue;\n\t}\n\n\tget availableModels(): readonly Model[] {\n\t\treturn structuredClone(this.provider.models);\n\t}\n\n\tsetModel(modelId: string): Model {\n\t\tif (this.promptActive) throw new Error(\"Cannot change model while AgentSession is processing a prompt.\");\n\t\tconst next = this.provider.models.find((model) => model.id === modelId);\n\t\tif (!next) throw new Error(`Unknown model \"${modelId}\" for provider \"${this.provider.id}\".`);\n\t\tthis.model = structuredClone(next);\n\t\tthis.agent.setModel(this.model);\n\t\tthis.contextBudget = resolveContextBudget(this.model);\n\t\tthis.keepRecentTokens = Math.min(\n\t\t\tthis.keepRecentTokens,\n\t\t\tMath.max(1, Math.min(20_000, Math.floor(this.contextBudget.triggerTokens / 2))),\n\t\t);\n\t\treturn structuredClone(this.model);\n\t}\n\n\tget compactionEnabled(): boolean {\n\t\treturn this.compactionEnabledValue;\n\t}\n\n\tsetCompactionEnabled(enabled: boolean): boolean {\n\t\tif (this.promptActive) throw new Error(\"Cannot change compaction while AgentSession is processing a prompt.\");\n\t\tthis.compactionEnabledValue = enabled && this.sessionManager !== undefined;\n\t\treturn this.compactionEnabledValue;\n\t}\n\n\tget sessionFile(): string | undefined {\n\t\treturn this.sessionManager?.filePath;\n\t}\n\n\tget sessionDiagnostics(): readonly SessionDiagnostic[] {\n\t\treturn this.sessionManager?.diagnostics ?? [];\n\t}\n\n\tget usage(): SessionUsage {\n\t\treturn {\n\t\t\t...this.usageTotals,\n\t\t\tcost: { ...this.usageTotals.cost },\n\t\t\testimatedContextTokens: estimateContextTokens(this.agent.contextMessages),\n\t\t\tcontextWindow: this.contextBudget.contextWindow,\n\t\t\treserveTokens: this.contextBudget.reserveTokens,\n\t\t\ttriggerTokens: this.contextBudget.triggerTokens,\n\t\t};\n\t}\n\n\tasync prompt(text: string, signal?: AbortSignal): Promise<AssistantMessage> {\n\t\tif (this.persistenceError !== undefined) {\n\t\t\tthrow this.persistenceError;\n\t\t}\n\t\tif (this.promptActive) {\n\t\t\tthrow new Error(\"AgentSession is already processing a prompt.\");\n\t\t}\n\n\t\tthis.promptActive = true;\n\t\ttry {\n\t\t\tawait this.compactIfNeeded(text, signal);\n\t\t\treturn await this.agent.prompt(text, signal);\n\t\t} finally {\n\t\t\tthis.promptActive = false;\n\t\t}\n\t}\n\n\tasync compact(signal?: AbortSignal): Promise<void> {\n\t\tif (this.promptActive) throw new Error(\"AgentSession is already processing a prompt.\");\n\t\tif (!this.sessionManager) throw new Error(\"Cannot compact without a persisted session.\");\n\t\tthis.promptActive = true;\n\t\ttry {\n\t\t\tawait this.compactNow(signal, \"manual\");\n\t\t} finally {\n\t\t\tthis.promptActive = false;\n\t\t}\n\t}\n\n\tsubscribe(listener: AgentListener): () => void {\n\t\treturn this.agent.subscribe(listener);\n\t}\n\n\tsubscribeSession(listener: AgentSessionListener): () => void {\n\t\tthis.sessionListeners.add(listener);\n\t\treturn () => this.sessionListeners.delete(listener);\n\t}\n\n\tprivate async emitSession(event: AgentSessionEvent): Promise<void> {\n\t\tfor (const listener of this.sessionListeners) await listener(structuredClone(event));\n\t}\n\n\tprivate addUsage(usage: Usage): void {\n\t\tthis.usageTotals = {\n\t\t\trequestCount: this.usageTotals.requestCount + 1,\n\t\t\tinputTokens: this.usageTotals.inputTokens + usage.input,\n\t\t\toutputTokens: this.usageTotals.outputTokens + usage.output,\n\t\t\tcacheReadTokens: this.usageTotals.cacheReadTokens + usage.cacheRead,\n\t\t\tcacheWriteTokens: this.usageTotals.cacheWriteTokens + usage.cacheWrite,\n\t\t\ttotalTokens: this.usageTotals.totalTokens + usage.totalTokens,\n\t\t\tcost: {\n\t\t\t\tinput: this.usageTotals.cost.input + usage.cost.input,\n\t\t\t\toutput: this.usageTotals.cost.output + usage.cost.output,\n\t\t\t\tcacheRead: this.usageTotals.cost.cacheRead + usage.cost.cacheRead,\n\t\t\t\tcacheWrite: this.usageTotals.cost.cacheWrite + usage.cost.cacheWrite,\n\t\t\t\ttotal: this.usageTotals.cost.total + usage.cost.total,\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate async compactIfNeeded(text: string, signal?: AbortSignal): Promise<void> {\n\t\tif (!this.compactionEnabledValue || !this.sessionManager) return;\n\n\t\tconst context = buildSessionContext(this.sessionManager.entries);\n\t\tconst pendingUser: Message = {\n\t\t\trole: \"user\",\n\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\ttimestamp: 0,\n\t\t};\n\t\tconst estimatedTokens = estimateContextTokens([...context.messages, pendingUser]);\n\t\tif (!shouldCompact(estimatedTokens, this.contextBudget)) return;\n\n\t\tawait this.compactNow(signal, \"threshold\");\n\t}\n\n\tprivate async compactNow(signal: AbortSignal | undefined, reason: \"threshold\" | \"manual\"): Promise<void> {\n\t\tif (!this.sessionManager) throw new Error(\"Cannot compact without a persisted session.\");\n\t\tconst context = buildSessionContext(this.sessionManager.entries);\n\t\tawait this.emitSession({ type: \"compaction_start\", reason });\n\t\tconst preparation = prepareCompaction(context.messages, this.keepRecentTokens);\n\t\tconst firstKeptEntryId = preparation ? context.sourceEntryIds[preparation.firstKeptMessageIndex] : undefined;\n\t\tif (!preparation || typeof firstKeptEntryId !== \"string\") {\n\t\t\tconst errorMessage =\n\t\t\t\treason === \"manual\"\n\t\t\t\t\t? \"No valid compaction cut point was found for the current session.\"\n\t\t\t\t\t: \"Context limit reached but no valid compaction cut point was found.\";\n\t\t\tawait this.emitSession({ type: \"compaction_end\", reason, success: false, errorMessage });\n\t\t\tthrow new Error(errorMessage);\n\t\t}\n\n\t\tlet summary: string;\n\t\ttry {\n\t\t\tsummary = await generateCompactionSummary(preparation, this.provider, this.model, {\n\t\t\t\treserveTokens: this.contextBudget.reserveTokens,\n\t\t\t\tsignal,\n\t\t\t\tnow: this.now,\n\t\t\t\tonUsage: (usage) => this.addUsage(usage),\n\t\t\t});\n\t\t\tawait this.emitSession({ type: \"usage_update\", usage: this.usage });\n\t\t} catch (cause) {\n\t\t\tconst errorMessage = cause instanceof Error ? cause.message : String(cause);\n\t\t\tawait this.emitSession({ type: \"compaction_end\", reason, success: false, errorMessage });\n\t\t\tthrow cause;\n\t\t}\n\n\t\ttry {\n\t\t\tawait this.sessionManager.appendSummary({\n\t\t\t\tsummary,\n\t\t\t\tfirstKeptEntryId,\n\t\t\t\ttokensBefore: preparation.tokensBefore,\n\t\t\t});\n\t\t} catch (cause) {\n\t\t\tthis.persistenceError = cause;\n\t\t\tconst errorMessage = cause instanceof Error ? cause.message : String(cause);\n\t\t\tawait this.emitSession({ type: \"compaction_end\", reason, success: false, errorMessage });\n\t\t\tthrow cause;\n\t\t}\n\n\t\tthis.agent.replaceContext(buildSessionContext(this.sessionManager.entries).messages);\n\t\tawait this.emitSession({ type: \"compaction_end\", reason, success: true });\n\t}\n}\n"]}
@@ -0,0 +1,39 @@
1
+ import type { AgentTool } from "@di-code/agent";
2
+ import { type Static, Type } from "@di-code/ai";
3
+ export declare const DEFAULT_BASH_TIMEOUT_MS = 30000;
4
+ export declare const MAX_BASH_TIMEOUT_MS = 300000;
5
+ export declare const DEFAULT_BASH_MAX_OUTPUT_BYTES: number;
6
+ export declare const bashParameters: Type.TObject<{
7
+ command: Type.TString;
8
+ timeoutMs: Type.TOptional<Type.TInteger>;
9
+ }>;
10
+ export type BashParameters = Static<typeof bashParameters>;
11
+ export interface BashRunOptions {
12
+ readonly signal?: AbortSignal;
13
+ readonly timeoutMs: number;
14
+ readonly onStdout: (chunk: Buffer) => void;
15
+ readonly onStderr: (chunk: Buffer) => void;
16
+ }
17
+ export interface BashExecution {
18
+ readonly exitCode: number | null;
19
+ readonly timedOut: boolean;
20
+ readonly aborted: boolean;
21
+ }
22
+ export interface BashOperations {
23
+ run(command: string, cwd: string, options: BashRunOptions): Promise<BashExecution>;
24
+ }
25
+ export interface BashToolOptions {
26
+ readonly operations?: BashOperations;
27
+ readonly maxOutputBytes?: number;
28
+ }
29
+ export type BashTool = AgentTool<typeof bashParameters>;
30
+ export interface ShellRuntime {
31
+ readonly executable: string;
32
+ readonly detached: boolean;
33
+ readonly description: string;
34
+ args(command: string): readonly string[];
35
+ }
36
+ export declare function resolveShellRuntime(platform?: NodeJS.Platform): ShellRuntime;
37
+ export declare function createLocalBashOperations(): BashOperations;
38
+ export declare function createBashTool(allowedRoot: string, options?: BashToolOptions): BashTool;
39
+ //# sourceMappingURL=bash.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,KAAK,MAAM,EAA0B,IAAI,EAAE,MAAM,aAAa,CAAC;AAExE,eAAO,MAAM,uBAAuB,QAAS,CAAC;AAC9C,eAAO,MAAM,mBAAmB,SAAU,CAAC;AAC3C,eAAO,MAAM,6BAA6B,QAAY,CAAC;AAEvD,eAAO,MAAM,cAAc;;;EAGzB,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE3D,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;IAC9B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAC3C,QAAQ,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;CAC3C;AAED,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACjC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,cAAc;IAC9B,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;CACnF;AAED,MAAM,WAAW,eAAe;IAC/B,QAAQ,CAAC,UAAU,CAAC,EAAE,cAAc,CAAC;IACrC,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;CACjC;AAED,MAAM,MAAM,QAAQ,GAAG,SAAS,CAAC,OAAO,cAAc,CAAC,CAAC;AAExD,MAAM,WAAW,YAAY;IAC5B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC;CACzC;AAoED,wBAAgB,mBAAmB,CAAC,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAAG,YAAY,CAkB9F;AAyFD,wBAAgB,yBAAyB,IAAI,cAAc,CAE1D;AAaD,wBAAgB,cAAc,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,GAAE,eAAoB,GAAG,QAAQ,CAqC3F"}
@@ -0,0 +1,208 @@
1
+ import { spawn } from "node:child_process";
2
+ import { realpath } from "node:fs/promises";
3
+ import { StringDecoder } from "node:string_decoder";
4
+ import { Type } from "@di-code/ai";
5
+ export const DEFAULT_BASH_TIMEOUT_MS = 30_000;
6
+ export const MAX_BASH_TIMEOUT_MS = 300_000;
7
+ export const DEFAULT_BASH_MAX_OUTPUT_BYTES = 50 * 1024;
8
+ export const bashParameters = Type.Object({
9
+ command: Type.String({ minLength: 1 }),
10
+ timeoutMs: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_BASH_TIMEOUT_MS })),
11
+ });
12
+ function assertTimeout(timeoutMs) {
13
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_BASH_TIMEOUT_MS) {
14
+ throw new Error(`timeoutMs must be an integer between 1 and ${MAX_BASH_TIMEOUT_MS}`);
15
+ }
16
+ }
17
+ function assertMaxOutputBytes(maxOutputBytes) {
18
+ if (!Number.isInteger(maxOutputBytes) || maxOutputBytes < 1) {
19
+ throw new Error("maxOutputBytes must be a positive integer");
20
+ }
21
+ }
22
+ function createOutputCapture(maxBytes) {
23
+ const chunks = [];
24
+ let bytes = 0;
25
+ let truncated = false;
26
+ return {
27
+ append(chunk) {
28
+ const remaining = maxBytes - bytes;
29
+ if (remaining > 0) {
30
+ const kept = chunk.subarray(0, remaining);
31
+ chunks.push(Buffer.from(kept));
32
+ bytes += kept.length;
33
+ }
34
+ if (chunk.length > remaining)
35
+ truncated = true;
36
+ },
37
+ snapshot() {
38
+ const decoder = new StringDecoder("utf8");
39
+ return { text: decoder.write(Buffer.concat(chunks, bytes)), truncated };
40
+ },
41
+ };
42
+ }
43
+ function createPowerShellScript(command) {
44
+ return [
45
+ "$OutputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)",
46
+ "$script:diCodeSucceeded = $false",
47
+ "$script:diCodeExitCode = 0",
48
+ "& {",
49
+ command,
50
+ "$script:diCodeSucceeded = $?",
51
+ "$script:diCodeExitCode = $LASTEXITCODE",
52
+ "} | Out-Default",
53
+ "if ($script:diCodeSucceeded) { exit 0 }",
54
+ "if ($script:diCodeExitCode -is [int] -and $script:diCodeExitCode -ne 0) { exit $script:diCodeExitCode }",
55
+ "exit 1",
56
+ ].join("\n");
57
+ }
58
+ export function resolveShellRuntime(platform = process.platform) {
59
+ if (platform === "win32") {
60
+ return {
61
+ executable: "powershell.exe",
62
+ detached: false,
63
+ description: "Execute a Windows PowerShell command in the allowed root with timeout and bounded output. Use PowerShell syntax such as Get-ChildItem and Get-Content; do not use Bash syntax.",
64
+ args: (command) => ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", createPowerShellScript(command)],
65
+ };
66
+ }
67
+ return {
68
+ executable: "/bin/sh",
69
+ detached: true,
70
+ description: "Execute a POSIX shell command using /bin/sh in the allowed root with timeout and bounded output. Use portable POSIX syntax; Bash-only extensions may not be available.",
71
+ args: (command) => ["-c", command],
72
+ };
73
+ }
74
+ function waitForProcess(command, cwd, options) {
75
+ return new Promise((resolve, reject) => {
76
+ if (options.signal?.aborted) {
77
+ reject(new Error("Operation aborted"));
78
+ return;
79
+ }
80
+ const runtime = resolveShellRuntime();
81
+ const child = spawn(runtime.executable, [...runtime.args(command)], {
82
+ cwd,
83
+ detached: runtime.detached,
84
+ stdio: ["ignore", "pipe", "pipe"],
85
+ windowsHide: true,
86
+ });
87
+ let timedOut = false;
88
+ let aborted = false;
89
+ let settled = false;
90
+ let termination;
91
+ const requestTermination = () => {
92
+ if (child.pid !== undefined)
93
+ termination ??= killProcessTree(child.pid, child);
94
+ };
95
+ const onAbort = () => {
96
+ aborted = true;
97
+ requestTermination();
98
+ };
99
+ const timeout = setTimeout(() => {
100
+ timedOut = true;
101
+ requestTermination();
102
+ }, options.timeoutMs);
103
+ options.signal?.addEventListener("abort", onAbort, { once: true });
104
+ if (options.signal?.aborted)
105
+ onAbort();
106
+ child.stdout.on("data", options.onStdout);
107
+ child.stderr.on("data", options.onStderr);
108
+ const cleanup = () => {
109
+ clearTimeout(timeout);
110
+ options.signal?.removeEventListener("abort", onAbort);
111
+ };
112
+ child.once("error", (error) => {
113
+ if (settled)
114
+ return;
115
+ settled = true;
116
+ cleanup();
117
+ reject(error);
118
+ });
119
+ child.once("close", (exitCode) => {
120
+ if (settled)
121
+ return;
122
+ settled = true;
123
+ cleanup();
124
+ void (termination ?? Promise.resolve()).then(() => resolve({ exitCode, timedOut, aborted }), (error) => reject(error));
125
+ });
126
+ });
127
+ }
128
+ function waitForChild(child) {
129
+ return new Promise((resolve) => {
130
+ child.once("error", () => resolve());
131
+ child.once("close", () => resolve());
132
+ });
133
+ }
134
+ async function killProcessTree(pid, child) {
135
+ if (process.platform === "win32") {
136
+ const killer = spawn("taskkill", ["/F", "/T", "/PID", String(pid)], {
137
+ stdio: "ignore",
138
+ windowsHide: true,
139
+ });
140
+ await waitForChild(killer);
141
+ return;
142
+ }
143
+ try {
144
+ process.kill(-pid, "SIGKILL");
145
+ }
146
+ catch {
147
+ try {
148
+ child.kill("SIGKILL");
149
+ }
150
+ catch {
151
+ // The process already exited between the timeout and termination request.
152
+ }
153
+ }
154
+ }
155
+ export function createLocalBashOperations() {
156
+ return { run: waitForProcess };
157
+ }
158
+ function formatResult(stdout, stderr, execution) {
159
+ const status = {
160
+ exitCode: execution.exitCode,
161
+ timedOut: execution.timedOut,
162
+ aborted: execution.aborted,
163
+ stdoutTruncated: stdout.truncated,
164
+ stderrTruncated: stderr.truncated,
165
+ };
166
+ return `stdout:\n${stdout.text || "(empty)"}\n\nstderr:\n${stderr.text || "(empty)"}\n\nstatus: ${JSON.stringify(status)}`;
167
+ }
168
+ export function createBashTool(allowedRoot, options = {}) {
169
+ const operations = options.operations ?? createLocalBashOperations();
170
+ const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_BASH_MAX_OUTPUT_BYTES;
171
+ const runtime = resolveShellRuntime();
172
+ assertMaxOutputBytes(maxOutputBytes);
173
+ return {
174
+ name: "bash",
175
+ description: runtime.description,
176
+ parameters: bashParameters,
177
+ async execute(_toolCallId, parameters, signal) {
178
+ if (signal?.aborted)
179
+ throw new Error("Operation aborted");
180
+ if (parameters.command.length === 0)
181
+ throw new Error("command must not be empty");
182
+ const timeoutMs = parameters.timeoutMs ?? DEFAULT_BASH_TIMEOUT_MS;
183
+ assertTimeout(timeoutMs);
184
+ const cwd = await realpath(allowedRoot);
185
+ if (signal?.aborted)
186
+ throw new Error("Operation aborted");
187
+ const stdout = createOutputCapture(maxOutputBytes);
188
+ const stderr = createOutputCapture(maxOutputBytes);
189
+ const executionResult = await operations.run(parameters.command, cwd, {
190
+ signal,
191
+ timeoutMs,
192
+ onStdout: (chunk) => stdout.append(chunk),
193
+ onStderr: (chunk) => stderr.append(chunk),
194
+ });
195
+ const execution = signal?.aborted ? { ...executionResult, aborted: true } : executionResult;
196
+ const output = formatResult(stdout.snapshot(), stderr.snapshot(), execution);
197
+ if (execution.aborted)
198
+ throw new Error(`Command aborted\n\n${output}`);
199
+ if (execution.timedOut)
200
+ throw new Error(`Command timed out after ${timeoutMs} ms\n\n${output}`);
201
+ if (execution.exitCode !== 0) {
202
+ throw new Error(`Command exited with code ${execution.exitCode ?? "unknown"}\n\n${output}`);
203
+ }
204
+ return [{ type: "text", text: output }];
205
+ },
206
+ };
207
+ }
208
+ //# sourceMappingURL=bash.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAuC,IAAI,EAAE,MAAM,aAAa,CAAC;AAExE,MAAM,CAAC,MAAM,uBAAuB,GAAG,MAAM,CAAC;AAC9C,MAAM,CAAC,MAAM,mBAAmB,GAAG,OAAO,CAAC;AAC3C,MAAM,CAAC,MAAM,6BAA6B,GAAG,EAAE,GAAG,IAAI,CAAC;AAEvD,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,CAAC,MAAM,CAAC;IACzC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC;IACtC,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE,mBAAmB,EAAE,CAAC,CAAC;CACpF,CAAC,CAAC;AAgDH,SAAS,aAAa,CAAC,SAAiB;IACvC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,SAAS,CAAC,IAAI,SAAS,GAAG,CAAC,IAAI,SAAS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;YAChG,IAAI,SAAS,CAAC,QAAQ,KAAK,CAAC,EAAE,CAAC;gBAC9B,MAAM,IAAI,KAAK,CAAC,4BAA4B,SAAS,CAAC,QAAQ,IAAI,SAAS,OAAO,MAAM,EAAE,CAAC,CAAC;YAC7F,CAAC;YACD,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;QACzC,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { realpath } from \"node:fs/promises\";\nimport { StringDecoder } from \"node:string_decoder\";\nimport type { AgentTool } from \"@di-code/agent\";\nimport { type Static, type ToolResultContent, Type } from \"@di-code/ai\";\n\nexport const DEFAULT_BASH_TIMEOUT_MS = 30_000;\nexport const MAX_BASH_TIMEOUT_MS = 300_000;\nexport const DEFAULT_BASH_MAX_OUTPUT_BYTES = 50 * 1024;\n\nexport const bashParameters = Type.Object({\n\tcommand: Type.String({ minLength: 1 }),\n\ttimeoutMs: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_BASH_TIMEOUT_MS })),\n});\n\nexport type BashParameters = Static<typeof bashParameters>;\n\nexport interface BashRunOptions {\n\treadonly signal?: AbortSignal;\n\treadonly timeoutMs: number;\n\treadonly onStdout: (chunk: Buffer) => void;\n\treadonly onStderr: (chunk: Buffer) => void;\n}\n\nexport interface BashExecution {\n\treadonly exitCode: number | null;\n\treadonly timedOut: boolean;\n\treadonly aborted: boolean;\n}\n\nexport interface BashOperations {\n\trun(command: string, cwd: string, options: BashRunOptions): Promise<BashExecution>;\n}\n\nexport interface BashToolOptions {\n\treadonly operations?: BashOperations;\n\treadonly maxOutputBytes?: number;\n}\n\nexport type BashTool = AgentTool<typeof bashParameters>;\n\nexport interface ShellRuntime {\n\treadonly executable: string;\n\treadonly detached: boolean;\n\treadonly description: string;\n\targs(command: string): readonly string[];\n}\n\ninterface OutputSnapshot {\n\treadonly text: string;\n\treadonly truncated: boolean;\n}\n\ninterface BashStatus {\n\treadonly exitCode: number | null;\n\treadonly timedOut: boolean;\n\treadonly aborted: boolean;\n\treadonly stdoutTruncated: boolean;\n\treadonly stderrTruncated: boolean;\n}\n\nfunction assertTimeout(timeoutMs: number): void {\n\tif (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_BASH_TIMEOUT_MS) {\n\t\tthrow new Error(`timeoutMs must be an integer between 1 and ${MAX_BASH_TIMEOUT_MS}`);\n\t}\n}\n\nfunction assertMaxOutputBytes(maxOutputBytes: number): void {\n\tif (!Number.isInteger(maxOutputBytes) || maxOutputBytes < 1) {\n\t\tthrow new Error(\"maxOutputBytes must be a positive integer\");\n\t}\n}\n\nfunction createOutputCapture(maxBytes: number): {\n\tappend(chunk: Buffer): void;\n\tsnapshot(): OutputSnapshot;\n} {\n\tconst chunks: Buffer[] = [];\n\tlet bytes = 0;\n\tlet truncated = false;\n\n\treturn {\n\t\tappend(chunk) {\n\t\t\tconst remaining = maxBytes - bytes;\n\t\t\tif (remaining > 0) {\n\t\t\t\tconst kept = chunk.subarray(0, remaining);\n\t\t\t\tchunks.push(Buffer.from(kept));\n\t\t\t\tbytes += kept.length;\n\t\t\t}\n\t\t\tif (chunk.length > remaining) truncated = true;\n\t\t},\n\t\tsnapshot() {\n\t\t\tconst decoder = new StringDecoder(\"utf8\");\n\t\t\treturn { text: decoder.write(Buffer.concat(chunks, bytes)), truncated };\n\t\t},\n\t};\n}\n\nfunction createPowerShellScript(command: string): string {\n\treturn [\n\t\t\"$OutputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)\",\n\t\t\"$script:diCodeSucceeded = $false\",\n\t\t\"$script:diCodeExitCode = 0\",\n\t\t\"& {\",\n\t\tcommand,\n\t\t\"$script:diCodeSucceeded = $?\",\n\t\t\"$script:diCodeExitCode = $LASTEXITCODE\",\n\t\t\"} | Out-Default\",\n\t\t\"if ($script:diCodeSucceeded) { exit 0 }\",\n\t\t\"if ($script:diCodeExitCode -is [int] -and $script:diCodeExitCode -ne 0) { exit $script:diCodeExitCode }\",\n\t\t\"exit 1\",\n\t].join(\"\\n\");\n}\n\nexport function resolveShellRuntime(platform: NodeJS.Platform = process.platform): ShellRuntime {\n\tif (platform === \"win32\") {\n\t\treturn {\n\t\t\texecutable: \"powershell.exe\",\n\t\t\tdetached: false,\n\t\t\tdescription:\n\t\t\t\t\"Execute a Windows PowerShell command in the allowed root with timeout and bounded output. Use PowerShell syntax such as Get-ChildItem and Get-Content; do not use Bash syntax.\",\n\t\t\targs: (command) => [\"-NoLogo\", \"-NoProfile\", \"-NonInteractive\", \"-Command\", createPowerShellScript(command)],\n\t\t};\n\t}\n\n\treturn {\n\t\texecutable: \"/bin/sh\",\n\t\tdetached: true,\n\t\tdescription:\n\t\t\t\"Execute a POSIX shell command using /bin/sh in the allowed root with timeout and bounded output. Use portable POSIX syntax; Bash-only extensions may not be available.\",\n\t\targs: (command) => [\"-c\", command],\n\t};\n}\n\nfunction waitForProcess(command: string, cwd: string, options: BashRunOptions): Promise<BashExecution> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (options.signal?.aborted) {\n\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\treturn;\n\t\t}\n\n\t\tconst runtime = resolveShellRuntime();\n\t\tconst child = spawn(runtime.executable, [...runtime.args(command)], {\n\t\t\tcwd,\n\t\t\tdetached: runtime.detached,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\twindowsHide: true,\n\t\t});\n\n\t\tlet timedOut = false;\n\t\tlet aborted = false;\n\t\tlet settled = false;\n\t\tlet termination: Promise<void> | undefined;\n\n\t\tconst requestTermination = (): void => {\n\t\t\tif (child.pid !== undefined) termination ??= killProcessTree(child.pid, child);\n\t\t};\n\t\tconst onAbort = (): void => {\n\t\t\taborted = true;\n\t\t\trequestTermination();\n\t\t};\n\t\tconst timeout = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\trequestTermination();\n\t\t}, options.timeoutMs);\n\n\t\toptions.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tif (options.signal?.aborted) onAbort();\n\t\tchild.stdout.on(\"data\", options.onStdout);\n\t\tchild.stderr.on(\"data\", options.onStderr);\n\n\t\tconst cleanup = (): void => {\n\t\t\tclearTimeout(timeout);\n\t\t\toptions.signal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tchild.once(\"error\", (error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(error);\n\t\t});\n\t\tchild.once(\"close\", (exitCode) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tvoid (termination ?? Promise.resolve()).then(\n\t\t\t\t() => resolve({ exitCode, timedOut, aborted }),\n\t\t\t\t(error: unknown) => reject(error),\n\t\t\t);\n\t\t});\n\t});\n}\n\nfunction waitForChild(child: ReturnType<typeof spawn>): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tchild.once(\"error\", () => resolve());\n\t\tchild.once(\"close\", () => resolve());\n\t});\n}\n\nasync function killProcessTree(pid: number, child: ReturnType<typeof spawn>): Promise<void> {\n\tif (process.platform === \"win32\") {\n\t\tconst killer = spawn(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], {\n\t\t\tstdio: \"ignore\",\n\t\t\twindowsHide: true,\n\t\t});\n\t\tawait waitForChild(killer);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tprocess.kill(-pid, \"SIGKILL\");\n\t} catch {\n\t\ttry {\n\t\t\tchild.kill(\"SIGKILL\");\n\t\t} catch {\n\t\t\t// The process already exited between the timeout and termination request.\n\t\t}\n\t}\n}\n\nexport function createLocalBashOperations(): BashOperations {\n\treturn { run: waitForProcess };\n}\n\nfunction formatResult(stdout: OutputSnapshot, stderr: OutputSnapshot, execution: BashExecution): string {\n\tconst status: BashStatus = {\n\t\texitCode: execution.exitCode,\n\t\ttimedOut: execution.timedOut,\n\t\taborted: execution.aborted,\n\t\tstdoutTruncated: stdout.truncated,\n\t\tstderrTruncated: stderr.truncated,\n\t};\n\treturn `stdout:\\n${stdout.text || \"(empty)\"}\\n\\nstderr:\\n${stderr.text || \"(empty)\"}\\n\\nstatus: ${JSON.stringify(status)}`;\n}\n\nexport function createBashTool(allowedRoot: string, options: BashToolOptions = {}): BashTool {\n\tconst operations = options.operations ?? createLocalBashOperations();\n\tconst maxOutputBytes = options.maxOutputBytes ?? DEFAULT_BASH_MAX_OUTPUT_BYTES;\n\tconst runtime = resolveShellRuntime();\n\tassertMaxOutputBytes(maxOutputBytes);\n\n\treturn {\n\t\tname: \"bash\",\n\t\tdescription: runtime.description,\n\t\tparameters: bashParameters,\n\t\tasync execute(_toolCallId, parameters, signal): Promise<ToolResultContent[]> {\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\tif (parameters.command.length === 0) throw new Error(\"command must not be empty\");\n\t\t\tconst timeoutMs = parameters.timeoutMs ?? DEFAULT_BASH_TIMEOUT_MS;\n\t\t\tassertTimeout(timeoutMs);\n\t\t\tconst cwd = await realpath(allowedRoot);\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\tconst stdout = createOutputCapture(maxOutputBytes);\n\t\t\tconst stderr = createOutputCapture(maxOutputBytes);\n\t\t\tconst executionResult = await operations.run(parameters.command, cwd, {\n\t\t\t\tsignal,\n\t\t\t\ttimeoutMs,\n\t\t\t\tonStdout: (chunk) => stdout.append(chunk),\n\t\t\t\tonStderr: (chunk) => stderr.append(chunk),\n\t\t\t});\n\t\t\tconst execution = signal?.aborted ? { ...executionResult, aborted: true } : executionResult;\n\t\t\tconst output = formatResult(stdout.snapshot(), stderr.snapshot(), execution);\n\n\t\t\tif (execution.aborted) throw new Error(`Command aborted\\n\\n${output}`);\n\t\t\tif (execution.timedOut) throw new Error(`Command timed out after ${timeoutMs} ms\\n\\n${output}`);\n\t\t\tif (execution.exitCode !== 0) {\n\t\t\t\tthrow new Error(`Command exited with code ${execution.exitCode ?? \"unknown\"}\\n\\n${output}`);\n\t\t\t}\n\t\t\treturn [{ type: \"text\", text: output }];\n\t\t},\n\t};\n}\n"]}
@@ -0,0 +1,18 @@
1
+ import type { AgentTool } from "@di-code/agent";
2
+ import { type Static, Type } from "@di-code/ai";
3
+ export declare const editParameters: Type.TObject<{
4
+ path: Type.TString;
5
+ oldText: Type.TString;
6
+ newText: Type.TString;
7
+ }>;
8
+ export type EditParameters = Static<typeof editParameters>;
9
+ export interface EditOperations {
10
+ readFile(filePath: string): Promise<Buffer>;
11
+ writeFile(filePath: string, content: string): Promise<void>;
12
+ }
13
+ export interface EditToolOptions {
14
+ readonly operations?: EditOperations;
15
+ }
16
+ export type EditTool = AgentTool<typeof editParameters>;
17
+ export declare function createEditTool(allowedRoot: string, options?: EditToolOptions): EditTool;
18
+ //# sourceMappingURL=edit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,KAAK,MAAM,EAA0B,IAAI,EAAE,MAAM,aAAa,CAAC;AAIxE,eAAO,MAAM,cAAc;;;;EAIzB,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE3D,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC5C,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5D;AAED,MAAM,WAAW,eAAe;IAC/B,QAAQ,CAAC,UAAU,CAAC,EAAE,cAAc,CAAC;CACrC;AAED,MAAM,MAAM,QAAQ,GAAG,SAAS,CAAC,OAAO,cAAc,CAAC,CAAC;AA6DxD,wBAAgB,cAAc,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,GAAE,eAAoB,GAAG,QAAQ,CAyC3F"}