@trans-ai/trans-code 0.0.0-stage → 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.
@@ -0,0 +1,334 @@
1
+ import {
2
+ AIMessage,
3
+ SystemMessage,
4
+ ToolMessage,
5
+ type BaseMessage,
6
+ } from '@langchain/core/messages';
7
+ import type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';
8
+ import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
9
+ import type { AIMessageChunk } from '@langchain/core/messages';
10
+ import {
11
+ AGENT_TOOLS,
12
+ bindableTools,
13
+ findAgentTool,
14
+ invokeTool,
15
+ type AgentTool,
16
+ type ToolKind,
17
+ } from './tools.js';
18
+
19
+ export type AgentEvent =
20
+ | { type: 'text'; text: string }
21
+ | { type: 'thought'; text: string }
22
+ | {
23
+ type: 'tool_call';
24
+ toolCallId: string;
25
+ name: string;
26
+ title: string;
27
+ kind: ToolKind;
28
+ input: Record<string, unknown>;
29
+ }
30
+ | {
31
+ type: 'tool_result';
32
+ toolCallId: string;
33
+ name: string;
34
+ output: string;
35
+ ok: boolean;
36
+ };
37
+
38
+ export interface PermissionRequest {
39
+ toolCallId: string;
40
+ name: string;
41
+ title: string;
42
+ kind: ToolKind;
43
+ input: Record<string, unknown>;
44
+ }
45
+
46
+ export type RequestPermission = (request: PermissionRequest) => Promise<boolean>;
47
+
48
+ export type StopReason =
49
+ | 'end_turn'
50
+ | 'cancelled'
51
+ | 'max_turn_requests'
52
+ | 'refusal';
53
+
54
+ export interface AgentLoopOptions {
55
+ model?: BaseChatModel;
56
+ cwd: string;
57
+ messages: BaseMessage[];
58
+ systemPrompt: string;
59
+ tools?: AgentTool[];
60
+ maxTurns?: number;
61
+ signal?: AbortSignal;
62
+ onEvent: (event: AgentEvent) => void | Promise<void>;
63
+ requestPermission?: RequestPermission;
64
+ }
65
+
66
+ export interface AgentLoopResult {
67
+ stopReason: StopReason;
68
+ messages: BaseMessage[];
69
+ }
70
+
71
+ interface PartialToolCall {
72
+ id?: string;
73
+ name?: string;
74
+ args: string;
75
+ }
76
+
77
+ function textFromContent(content: unknown): string {
78
+ if (typeof content === 'string') return content;
79
+ if (!Array.isArray(content)) return '';
80
+
81
+ return content
82
+ .map((block) => {
83
+ if (typeof block === 'string') return block;
84
+ if (block && typeof block === 'object') {
85
+ const value = block as Record<string, unknown>;
86
+ if (typeof value.text === 'string') return value.text;
87
+ }
88
+ return '';
89
+ })
90
+ .join('');
91
+ }
92
+
93
+ function mergeToolCallChunk(map: Map<number, PartialToolCall>, chunk: ToolCallChunk): void {
94
+ const index = typeof chunk.index === 'number' ? chunk.index : 0;
95
+ const current = map.get(index) ?? { args: '' };
96
+ if (chunk.id) current.id = chunk.id;
97
+ if (chunk.name) current.name = chunk.name;
98
+ if (typeof chunk.args === 'string') current.args += chunk.args;
99
+ map.set(index, current);
100
+ }
101
+
102
+ function parseToolCalls(
103
+ partials: Map<number, PartialToolCall>,
104
+ finalChunk: AIMessageChunk | undefined,
105
+ turn: number,
106
+ ): ToolCall[] {
107
+ const calls: ToolCall[] = [];
108
+
109
+ if (partials.size === 0 && finalChunk?.tool_calls?.length) {
110
+ return finalChunk.tool_calls;
111
+ }
112
+
113
+ for (const [index, partial] of [...partials.entries()].sort((a, b) => a[0] - b[0])) {
114
+ if (!partial.name) continue;
115
+ let args: Record<string, unknown> = {};
116
+ if (partial.args.trim()) {
117
+ try {
118
+ const parsed = JSON.parse(partial.args);
119
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
120
+ args = parsed as Record<string, unknown>;
121
+ } else {
122
+ args = { value: parsed };
123
+ }
124
+ } catch {
125
+ args = { _raw: partial.args };
126
+ }
127
+ }
128
+ calls.push({
129
+ id: partial.id ?? `call_${turn}_${index}`,
130
+ name: partial.name,
131
+ args,
132
+ });
133
+ }
134
+
135
+ return calls;
136
+ }
137
+
138
+ function lastHumanText(messages: BaseMessage[]): string {
139
+ for (let index = messages.length - 1; index >= 0; index--) {
140
+ if (messages[index].getType() === 'human') {
141
+ return textFromContent(messages[index].content);
142
+ }
143
+ }
144
+ return '';
145
+ }
146
+
147
+ async function runMockTurn(
148
+ options: AgentLoopOptions,
149
+ prompt: string,
150
+ ): Promise<StopReason> {
151
+ if (prompt.includes('MOCK_TOOL_BASH')) {
152
+ const tool = findAgentTool('bash');
153
+ const input = { command: 'echo mock-tool-ok' };
154
+ const toolCallId = 'mock_call_1';
155
+
156
+ if (!tool) {
157
+ await options.onEvent({ type: 'text', text: '[mock] bash tool is unavailable' });
158
+ return 'end_turn';
159
+ }
160
+
161
+ await options.onEvent({
162
+ type: 'tool_call',
163
+ toolCallId,
164
+ name: tool.name,
165
+ title: tool.title(input),
166
+ kind: tool.kind,
167
+ input,
168
+ });
169
+
170
+ const allowed = options.requestPermission
171
+ ? await options.requestPermission({
172
+ toolCallId,
173
+ name: tool.name,
174
+ title: tool.title(input),
175
+ kind: tool.kind,
176
+ input,
177
+ })
178
+ : true;
179
+
180
+ const result = allowed
181
+ ? await invokeTool(tool, input, { cwd: options.cwd, signal: options.signal })
182
+ : { ok: false, output: 'Permission denied.' };
183
+
184
+ await options.onEvent({
185
+ type: 'tool_result',
186
+ toolCallId,
187
+ name: tool.name,
188
+ output: result.output,
189
+ ok: result.ok,
190
+ });
191
+
192
+ options.messages.push(
193
+ new AIMessage({
194
+ content: '',
195
+ tool_calls: [{ id: toolCallId, name: 'bash', args: input }],
196
+ }),
197
+ new ToolMessage({
198
+ content: result.output,
199
+ tool_call_id: toolCallId,
200
+ name: 'bash',
201
+ }),
202
+ );
203
+
204
+ await options.onEvent({
205
+ type: 'text',
206
+ text: `[mock] tool completed: ${result.output.split('\n')[0] ?? ''}`,
207
+ });
208
+ return 'end_turn';
209
+ }
210
+
211
+ await options.onEvent({ type: 'text', text: `[mock] ${prompt}` });
212
+ return 'end_turn';
213
+ }
214
+
215
+ export async function runAgentLoop(
216
+ options: AgentLoopOptions,
217
+ ): Promise<AgentLoopResult> {
218
+ const messages = options.messages;
219
+ if (!messages.some((message) => message.getType() === 'system')) {
220
+ messages.unshift(new SystemMessage(options.systemPrompt));
221
+ }
222
+
223
+ if (process.env.TRANSCODE_MOCK === '1') {
224
+ return {
225
+ stopReason: await runMockTurn(options, lastHumanText(messages)),
226
+ messages,
227
+ };
228
+ }
229
+
230
+ const tools = options.tools ?? AGENT_TOOLS;
231
+ const maxTurns = options.maxTurns ?? 50;
232
+ if (!options.model) throw new Error('No model configured for the agent loop');
233
+
234
+ const runnable =
235
+ tools.length > 0 && options.model.bindTools
236
+ ? options.model.bindTools(bindableTools(tools))
237
+ : options.model;
238
+
239
+ for (let turn = 0; turn < maxTurns; turn++) {
240
+ if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
241
+
242
+ const partials = new Map<number, PartialToolCall>();
243
+ let text = '';
244
+ let finalChunk: AIMessageChunk | undefined;
245
+
246
+ const stream = await runnable.stream(messages, {
247
+ signal: options.signal,
248
+ });
249
+
250
+ for await (const chunk of stream) {
251
+ if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
252
+ finalChunk = chunk;
253
+
254
+ const delta = textFromContent(chunk.content);
255
+ if (delta) {
256
+ text += delta;
257
+ await options.onEvent({ type: 'text', text: delta });
258
+ }
259
+
260
+ for (const toolCallChunk of chunk.tool_call_chunks ?? []) {
261
+ mergeToolCallChunk(partials, toolCallChunk);
262
+ }
263
+ }
264
+
265
+ if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
266
+
267
+ const toolCalls = parseToolCalls(partials, finalChunk, turn);
268
+ messages.push(new AIMessage({ content: text, tool_calls: toolCalls }));
269
+
270
+ if (toolCalls.length === 0) {
271
+ return { stopReason: 'end_turn', messages };
272
+ }
273
+
274
+ for (const call of toolCalls) {
275
+ if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
276
+
277
+ const input = (call.args ?? {}) as Record<string, unknown>;
278
+ const tool = findAgentTool(call.name);
279
+ const toolCallId = call.id ?? `call_${turn}_${call.name}`;
280
+ const title = tool ? tool.title(input) : call.name;
281
+
282
+ await options.onEvent({
283
+ type: 'tool_call',
284
+ toolCallId,
285
+ name: call.name,
286
+ title,
287
+ kind: tool?.kind ?? 'other',
288
+ input,
289
+ });
290
+
291
+ let result: { ok: boolean; output: string };
292
+ if (!tool) {
293
+ result = { ok: false, output: `Unknown tool: ${call.name}` };
294
+ } else {
295
+ const needsPermission = tool.isMutating;
296
+ const allowed =
297
+ !needsPermission || !options.requestPermission
298
+ ? true
299
+ : await options.requestPermission({
300
+ toolCallId,
301
+ name: tool.name,
302
+ title,
303
+ kind: tool.kind,
304
+ input,
305
+ });
306
+
307
+ result = allowed
308
+ ? await invokeTool(tool, input, {
309
+ cwd: options.cwd,
310
+ signal: options.signal,
311
+ })
312
+ : { ok: false, output: 'Permission denied by the client.' };
313
+ }
314
+
315
+ await options.onEvent({
316
+ type: 'tool_result',
317
+ toolCallId,
318
+ name: call.name,
319
+ output: result.output,
320
+ ok: result.ok,
321
+ });
322
+
323
+ messages.push(
324
+ new ToolMessage({
325
+ content: result.output,
326
+ tool_call_id: toolCallId,
327
+ name: call.name,
328
+ }),
329
+ );
330
+ }
331
+ }
332
+
333
+ return { stopReason: 'max_turn_requests', messages };
334
+ }
@@ -0,0 +1,86 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ const CONTEXT_FILES = ['AGENTS.md', 'CLAUDE.md', 'TRANSCODE.md', '.transcode/AGENTS.md'];
5
+ const MAX_CONTEXT_CHARS = 40_000;
6
+
7
+ export interface ProjectContext {
8
+ cwd: string;
9
+ gitBranch?: string;
10
+ projectFiles: { path: string; content: string }[];
11
+ }
12
+
13
+ async function readOptional(file: string): Promise<string | null> {
14
+ try {
15
+ const content = await fs.readFile(file, 'utf8');
16
+ return content.trim() || null;
17
+ } catch {
18
+ return null;
19
+ }
20
+ }
21
+
22
+ async function gitBranch(cwd: string): Promise<string | undefined> {
23
+ try {
24
+ const { execFile } = await import('node:child_process');
25
+ return await new Promise<string | undefined>((resolve) => {
26
+ execFile('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd }, (error, stdout) => {
27
+ resolve(error ? undefined : stdout.trim() || undefined);
28
+ });
29
+ });
30
+ } catch {
31
+ return undefined;
32
+ }
33
+ }
34
+
35
+ export async function loadProjectContext(cwd: string): Promise<ProjectContext> {
36
+ const projectFiles: ProjectContext['projectFiles'] = [];
37
+ let budget = MAX_CONTEXT_CHARS;
38
+
39
+ for (const relative of CONTEXT_FILES) {
40
+ if (budget <= 0) break;
41
+ const absolute = path.join(cwd, relative);
42
+ const content = await readOptional(absolute);
43
+ if (!content) continue;
44
+
45
+ const clipped =
46
+ content.length > budget
47
+ ? `${content.slice(0, budget)}\n... (project instructions truncated)`
48
+ : content;
49
+ projectFiles.push({ path: relative, content: clipped });
50
+ budget -= clipped.length;
51
+ }
52
+
53
+ return { cwd, gitBranch: await gitBranch(cwd), projectFiles };
54
+ }
55
+
56
+ export function buildSystemPrompt(context: ProjectContext): string {
57
+ const sections: string[] = [
58
+ 'You are transcode, a coding agent running as a local CLI agent in a terminal.',
59
+ 'You work directly in the user-provided workspace and can read, search, edit and execute code.',
60
+ '',
61
+ '## Environment',
62
+ `- Workspace: ${context.cwd}`,
63
+ `- Platform: ${process.platform}`,
64
+ `- Date: ${new Date().toISOString().slice(0, 10)}`,
65
+ ...(context.gitBranch ? [`- Git branch: ${context.gitBranch}`] : []),
66
+ '',
67
+ '## How to work',
68
+ '- Inspect the repository before changing it. Read the relevant files first.',
69
+ '- Prefer read_file, glob and grep for exploration; use bash for builds, tests and git.',
70
+ '- Use edit_file for targeted changes and write_file for new files.',
71
+ '- Keep changes focused on the task. Do not undo unrelated user work.',
72
+ '- After changing code, run the cheapest relevant check (typecheck, targeted test) when available.',
73
+ '- Never claim a command succeeded unless you actually ran it and saw the result.',
74
+ '- When the task is complete, reply with a short summary of what changed and any verification performed.',
75
+ '- If a tool fails, read the error and adapt instead of repeating the same call.',
76
+ ];
77
+
78
+ if (context.projectFiles.length > 0) {
79
+ sections.push('', '## Project instructions');
80
+ for (const file of context.projectFiles) {
81
+ sections.push('', `### ${file.path}`, file.content);
82
+ }
83
+ }
84
+
85
+ return sections.join('\n');
86
+ }