@celljs/ta-agents 0.0.0-stage → 4.8.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,166 @@
1
+ import type { Readable, Writable } from 'node:stream';
2
+
3
+ /** An error answer of the other side, with its JSON-RPC code. */
4
+ export class JsonRpcError extends Error {
5
+ constructor(
6
+ readonly code: number,
7
+ message: string,
8
+ readonly data?: unknown,
9
+ ) {
10
+ super(message);
11
+ this.name = 'JsonRpcError';
12
+ }
13
+ }
14
+
15
+ interface Pending {
16
+ resolve(value: unknown): void;
17
+ reject(error: Error): void;
18
+ }
19
+
20
+ interface Envelope {
21
+ id?: number | string | null;
22
+ method?: string;
23
+ params?: unknown;
24
+ result?: unknown;
25
+ error?: { code: number; message: string; data?: unknown };
26
+ }
27
+
28
+ /**
29
+ * JSON-RPC 2.0 over newline-delimited JSON, as ACP agents speak it on their standard input and output.
30
+ * Both sides send requests: the agent asks the client, for example, for a permission. Lines that are not
31
+ * JSON (a program that logs on its standard output) are skipped.
32
+ */
33
+ export class JsonRpcConnection {
34
+ /** Answers the requests of the other side; unknown methods get `-32601`. */
35
+ onRequest: (method: string, params: unknown) => Promise<unknown> = async method => {
36
+ throw new JsonRpcError(-32601, `Method not found: ${method}`);
37
+ };
38
+ onNotification: (method: string, params: unknown) => void = () => undefined;
39
+ onClose: (error: Error) => void = () => undefined;
40
+
41
+ protected nextId = 0;
42
+ protected readonly pending = new Map<number, Pending>();
43
+ protected buffer = '';
44
+ protected closed?: Error;
45
+
46
+ constructor(
47
+ protected readonly output: Writable,
48
+ input: Readable,
49
+ ) {
50
+ input.setEncoding('utf8');
51
+ input.on('data', (chunk: string) => this.receive(chunk));
52
+ input.on('end', () => this.close(new Error('The agent closed its output')));
53
+ output.on('error', error => this.close(error));
54
+ }
55
+
56
+ /** Requests sent and not answered yet. */
57
+ get pendingCount(): number {
58
+ return this.pending.size;
59
+ }
60
+
61
+ get isClosed(): boolean {
62
+ return this.closed !== undefined;
63
+ }
64
+
65
+ request<T>(method: string, params: unknown, signal?: AbortSignal): Promise<T> {
66
+ if (this.closed) {
67
+ return Promise.reject(this.closed);
68
+ }
69
+ const id = ++this.nextId;
70
+ return new Promise<T>((resolve, reject) => {
71
+ const abort = () => {
72
+ this.pending.delete(id);
73
+ reject(signal?.reason instanceof Error ? signal.reason : new Error('Aborted'));
74
+ };
75
+ if (signal?.aborted) {
76
+ abort();
77
+ return;
78
+ }
79
+ signal?.addEventListener('abort', abort, { once: true });
80
+ this.pending.set(id, {
81
+ resolve: value => {
82
+ signal?.removeEventListener('abort', abort);
83
+ resolve(value as T);
84
+ },
85
+ reject: error => {
86
+ signal?.removeEventListener('abort', abort);
87
+ reject(error);
88
+ },
89
+ });
90
+ this.send({ jsonrpc: '2.0', id, method, params });
91
+ });
92
+ }
93
+
94
+ notify(method: string, params: unknown): void {
95
+ if (!this.closed) {
96
+ this.send({ jsonrpc: '2.0', method, params });
97
+ }
98
+ }
99
+
100
+ /** Fails what is pending; later calls fail with `error`. */
101
+ close(error: Error): void {
102
+ if (this.closed) {
103
+ return;
104
+ }
105
+ this.closed = error;
106
+ for (const pending of this.pending.values()) {
107
+ pending.reject(error);
108
+ }
109
+ this.pending.clear();
110
+ this.onClose(error);
111
+ }
112
+
113
+ protected send(message: object): void {
114
+ this.output.write(`${JSON.stringify(message)}\n`);
115
+ }
116
+
117
+ protected receive(chunk: string): void {
118
+ this.buffer += chunk;
119
+ let end = this.buffer.indexOf('\n');
120
+ while (end >= 0) {
121
+ const line = this.buffer.slice(0, end).trim();
122
+ this.buffer = this.buffer.slice(end + 1);
123
+ if (line) {
124
+ this.dispatch(line);
125
+ }
126
+ end = this.buffer.indexOf('\n');
127
+ }
128
+ }
129
+
130
+ protected dispatch(line: string): void {
131
+ let message: Envelope;
132
+ try {
133
+ message = JSON.parse(line);
134
+ } catch {
135
+ return;
136
+ }
137
+ if (!message || typeof message !== 'object') {
138
+ return;
139
+ }
140
+ if (message.method === undefined) {
141
+ const pending = typeof message.id === 'number' ? this.pending.get(message.id) : undefined;
142
+ if (pending) {
143
+ this.pending.delete(message.id as number);
144
+ if (message.error) {
145
+ pending.reject(new JsonRpcError(message.error.code, message.error.message, message.error.data));
146
+ } else {
147
+ pending.resolve(message.result);
148
+ }
149
+ }
150
+ } else if (message.id === undefined || message.id === null) {
151
+ this.onNotification(message.method, message.params);
152
+ } else {
153
+ void this.answer(message.id, message.method, message.params);
154
+ }
155
+ }
156
+
157
+ protected async answer(id: number | string, method: string, params: unknown): Promise<void> {
158
+ try {
159
+ const result = await this.onRequest(method, params);
160
+ this.send({ jsonrpc: '2.0', id, result: result ?? null });
161
+ } catch (error) {
162
+ const code = error instanceof JsonRpcError ? error.code : -32603;
163
+ this.send({ jsonrpc: '2.0', id, error: { code, message: error instanceof Error ? error.message : String(error) } });
164
+ }
165
+ }
166
+ }
@@ -0,0 +1,139 @@
1
+ import type { AssistantMessage, AssistantMessageEvent, Model, ToolCall, Usage } from './pi-types';
2
+
3
+ /** pi's event stream of an assistant message, without importing pi: what its agent loop reads of it. */
4
+ export class MessageStream implements AsyncIterable<AssistantMessageEvent> {
5
+ protected readonly queue: AssistantMessageEvent[] = [];
6
+ protected waiting?: () => void;
7
+ protected done = false;
8
+ protected resolveResult!: (message: AssistantMessage) => void;
9
+ protected readonly final = new Promise<AssistantMessage>(resolve => (this.resolveResult = resolve));
10
+
11
+ push(event: AssistantMessageEvent): void {
12
+ if (this.done) {
13
+ return;
14
+ }
15
+ if (event.type === 'done' || event.type === 'error') {
16
+ this.done = true;
17
+ this.resolveResult(event.type === 'done' ? event.message : event.error);
18
+ }
19
+ this.queue.push(event);
20
+ this.waiting?.();
21
+ }
22
+
23
+ result(): Promise<AssistantMessage> {
24
+ return this.final;
25
+ }
26
+
27
+ async *[Symbol.asyncIterator](): AsyncIterator<AssistantMessageEvent> {
28
+ for (;;) {
29
+ const event = this.queue.shift();
30
+ if (event) {
31
+ yield event;
32
+ if (event.type === 'done' || event.type === 'error') {
33
+ return;
34
+ }
35
+ } else {
36
+ await new Promise<void>(resolve => (this.waiting = resolve));
37
+ this.waiting = undefined;
38
+ }
39
+ }
40
+ }
41
+ }
42
+
43
+ export function emptyUsage(): Usage {
44
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
45
+ }
46
+
47
+ /** Builds one assistant message on a stream: balanced block events, then exactly one `done` or `error`. */
48
+ export class MessageBuilder {
49
+ readonly message: AssistantMessage;
50
+ protected open?: { type: 'text' | 'thinking'; index: number };
51
+ protected ended = false;
52
+ protected readonly started = Date.now();
53
+
54
+ constructor(
55
+ protected readonly stream: MessageStream,
56
+ model: Model,
57
+ ) {
58
+ this.message = {
59
+ role: 'assistant',
60
+ content: [],
61
+ api: model.api,
62
+ provider: model.provider,
63
+ model: model.id,
64
+ usage: emptyUsage(),
65
+ stopReason: 'stop',
66
+ timestamp: this.started,
67
+ };
68
+ this.stream.push({ type: 'start', partial: this.message });
69
+ }
70
+
71
+ append(type: 'text' | 'thinking', delta: string): void {
72
+ if (!delta) {
73
+ return;
74
+ }
75
+ if (this.open?.type !== type) {
76
+ this.close();
77
+ const index = this.message.content.length;
78
+ this.message.content.push(type === 'text' ? { type: 'text', text: '' } : { type: 'thinking', thinking: '' });
79
+ this.open = { type, index };
80
+ this.stream.push({ type: type === 'text' ? 'text_start' : 'thinking_start', contentIndex: index, partial: this.message });
81
+ }
82
+ const index = this.open.index;
83
+ const block = this.message.content[index];
84
+ if (block.type === 'text') {
85
+ block.text += delta;
86
+ this.stream.push({ type: 'text_delta', contentIndex: index, delta, partial: this.message });
87
+ } else if (block.type === 'thinking') {
88
+ block.thinking += delta;
89
+ this.stream.push({ type: 'thinking_delta', contentIndex: index, delta, partial: this.message });
90
+ }
91
+ }
92
+
93
+ toolCall(call: ToolCall): void {
94
+ this.close();
95
+ const index = this.message.content.length;
96
+ this.message.content.push(call);
97
+ this.stream.push({ type: 'toolcall_start', contentIndex: index, partial: this.message });
98
+ this.stream.push({ type: 'toolcall_delta', contentIndex: index, delta: JSON.stringify(call.arguments), partial: this.message });
99
+ this.stream.push({ type: 'toolcall_end', contentIndex: index, toolCall: call, partial: this.message });
100
+ }
101
+
102
+ done(reason: 'stop' | 'length' | 'toolUse', usage?: Usage): void {
103
+ if (this.ended) {
104
+ return;
105
+ }
106
+ this.close();
107
+ this.ended = true;
108
+ this.message.stopReason = reason;
109
+ this.message.usage = usage ?? this.message.usage;
110
+ this.message.durationMs = Date.now() - this.started;
111
+ this.stream.push({ type: 'done', reason, message: this.message });
112
+ }
113
+
114
+ error(reason: 'error' | 'aborted', message: string): void {
115
+ if (this.ended) {
116
+ return;
117
+ }
118
+ this.close();
119
+ this.ended = true;
120
+ this.message.stopReason = reason;
121
+ this.message.errorMessage = message;
122
+ this.message.durationMs = Date.now() - this.started;
123
+ this.stream.push({ type: 'error', reason, error: this.message });
124
+ }
125
+
126
+ protected close(): void {
127
+ if (!this.open) {
128
+ return;
129
+ }
130
+ const { type, index } = this.open;
131
+ const block = this.message.content[index];
132
+ this.open = undefined;
133
+ if (type === 'text' && block.type === 'text') {
134
+ this.stream.push({ type: 'text_end', contentIndex: index, content: block.text, partial: this.message });
135
+ } else if (block.type === 'thinking') {
136
+ this.stream.push({ type: 'thinking_end', contentIndex: index, content: block.thinking, partial: this.message });
137
+ }
138
+ }
139
+ }
@@ -0,0 +1,22 @@
1
+ /** pi's types, which are ES modules, for this package's CommonJS build; only types, so the bundle imports nothing of pi. */
2
+ export type ExtensionAPI = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ExtensionAPI;
3
+ export type ExtensionContext = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ExtensionContext;
4
+ export type ProviderModelConfig = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ProviderModelConfig;
5
+ export type ToolDefinition = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ToolDefinition;
6
+ export type AgentToolResult = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).AgentToolResult<unknown>;
7
+
8
+ export type AssistantMessage = import('@earendil-works/pi-ai', { with: { 'resolution-mode': 'import' }}).AssistantMessage;
9
+ export type AssistantMessageEvent = import('@earendil-works/pi-ai', { with: { 'resolution-mode': 'import' }}).AssistantMessageEvent;
10
+ export type AssistantMessageEventStream = import('@earendil-works/pi-ai', { with: { 'resolution-mode': 'import' }}).AssistantMessageEventStream;
11
+ export type Message = import('@earendil-works/pi-ai', { with: { 'resolution-mode': 'import' }}).Message;
12
+ export type ImageContent = import('@earendil-works/pi-ai', { with: { 'resolution-mode': 'import' }}).ImageContent;
13
+ export type TextContent = import('@earendil-works/pi-ai', { with: { 'resolution-mode': 'import' }}).TextContent;
14
+ export type ToolCall = import('@earendil-works/pi-ai', { with: { 'resolution-mode': 'import' }}).ToolCall;
15
+ export type Usage = import('@earendil-works/pi-ai', { with: { 'resolution-mode': 'import' }}).Usage;
16
+ export type StopReason = import('@earendil-works/pi-ai', { with: { 'resolution-mode': 'import' }}).StopReason;
17
+ export type ThinkingLevel = import('@earendil-works/pi-ai', { with: { 'resolution-mode': 'import' }}).ThinkingLevel;
18
+ export type SimpleStreamOptions = import('@earendil-works/pi-ai', { with: { 'resolution-mode': 'import' }}).SimpleStreamOptions;
19
+ export type TranscriptContext = import('@earendil-works/pi-ai', { with: { 'resolution-mode': 'import' }}).TranscriptContext;
20
+ export type Model = import('@earendil-works/pi-ai', { with: { 'resolution-mode': 'import' }}).Model<
21
+ import('@earendil-works/pi-ai', { with: { 'resolution-mode': 'import' }}).Api
22
+ >;
@@ -0,0 +1,11 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { language } from './texts';
3
+
4
+ describe('texts', () => {
5
+ it("speaks the computer's language", () => {
6
+ expect(language({ LANG: 'zh_CN.UTF-8' })).toBe('zh');
7
+ expect(language({ LC_ALL: 'en_US.UTF-8', LANG: 'zh_CN.UTF-8' })).toBe('en');
8
+ expect(language({ LANG: 'C' })).toBe('en');
9
+ expect(language({ TA_LANGUAGE: 'zh-CN', LANG: 'en_US.UTF-8' })).toBe('zh');
10
+ });
11
+ });
package/src/texts.ts ADDED
@@ -0,0 +1,42 @@
1
+ /** What the package says to the user, in English and Chinese. */
2
+ const TEXTS = {
3
+ remote: {
4
+ en: (agent: string) => `${agent} works in directories of this computer; it cannot work in a remote directory yet.`,
5
+ zh: (agent: string) => `${agent} 只能在这台电脑上的目录里工作,暂不支持远程目录。`,
6
+ },
7
+ signIn: {
8
+ en: (agent: string, command: string) => `${agent} is not signed in. Run \`${command}\` in a terminal to sign in, then try again.`,
9
+ zh: (agent: string, command: string) => `${agent} 还没有登录。请在终端里运行 \`${command}\` 登录后再试。`,
10
+ },
11
+ notFound: {
12
+ en: (agent: string, command: string) => `${agent}: \`${command}\` was not found. Install it, or set its command in \`agents\` of settings.json.`,
13
+ zh: (agent: string, command: string) => `${agent}:找不到命令 \`${command}\`。请先安装,或在 settings.json 的 \`agents\` 里指定它的命令。`,
14
+ },
15
+ exited: {
16
+ en: (agent: string, code: string, last: string) => `${agent} exited (${code})${last ? `: ${last}` : ''}`,
17
+ zh: (agent: string, code: string, last: string) => `${agent} 已退出(${code})${last ? `:${last}` : ''}`,
18
+ },
19
+ commandDone: {
20
+ en: (agent: string, command: string) => `${agent} ran \`${command}\` and said nothing back; it may only show in ${agent}'s own interface.`,
21
+ zh: (agent: string, command: string) => `${agent} 已执行 \`${command}\`,没有返回内容(这个命令可能只在 ${agent} 自己的界面里有显示)。`,
22
+ },
23
+ unfinished: {
24
+ en: (agent: string) => `${agent} ended its turn before this call finished.`,
25
+ zh: (agent: string) => `${agent} 在这次调用完成前结束了这一轮。`,
26
+ },
27
+ } as const;
28
+
29
+ type Texts = typeof TEXTS;
30
+
31
+ /**
32
+ * The language of the messages: the one of Ta's pages (`TA_LANGUAGE`, which they give ta serve), else the
33
+ * computer's (`LC_ALL`, `LC_MESSAGES`, `LANG`, else the locale of Node), as a terminal's.
34
+ */
35
+ export function language(env: NodeJS.ProcessEnv = process.env): 'en' | 'zh' {
36
+ const locale = env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG || Intl.DateTimeFormat().resolvedOptions().locale;
37
+ return /^zh/i.test(locale) ? 'zh' : 'en';
38
+ }
39
+
40
+ export function text<K extends keyof Texts>(key: K, ...args: Parameters<Texts[K]['en']>): string {
41
+ return (TEXTS[key][language()] as (...values: typeof args) => string)(...args);
42
+ }