@celljs/ta-host 0.0.0-stage → 4.5.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.
- package/README.md +33 -2
- package/cell.schema.json +33 -0
- package/cell.yml +14 -0
- package/esm/node/client-channel.d.ts +31 -0
- package/esm/node/client-channel.js +84 -0
- package/esm/node/client-channel.js.map +1 -0
- package/esm/node/event-log.d.ts +28 -0
- package/esm/node/event-log.js +48 -0
- package/esm/node/event-log.js.map +1 -0
- package/esm/node/host-protocol.d.ts +27 -0
- package/esm/node/host-protocol.js +4 -0
- package/esm/node/host-protocol.js.map +1 -0
- package/esm/node/index.d.ts +13 -0
- package/esm/node/index.js +14 -0
- package/esm/node/index.js.map +1 -0
- package/esm/node/local-exec-environment-factory.d.ts +4 -0
- package/esm/node/local-exec-environment-factory.js +18 -0
- package/esm/node/local-exec-environment-factory.js.map +1 -0
- package/esm/node/module.d.ts +3 -0
- package/esm/node/module.js +4 -0
- package/esm/node/module.js.map +1 -0
- package/esm/node/receipt-book.d.ts +12 -0
- package/esm/node/receipt-book.js +38 -0
- package/esm/node/receipt-book.js.map +1 -0
- package/esm/node/remote-ui-context.d.ts +63 -0
- package/esm/node/remote-ui-context.js +130 -0
- package/esm/node/remote-ui-context.js.map +1 -0
- package/esm/node/ta-access.d.ts +30 -0
- package/esm/node/ta-access.js +107 -0
- package/esm/node/ta-access.js.map +1 -0
- package/esm/node/ta-errors.d.ts +11 -0
- package/esm/node/ta-errors.js +44 -0
- package/esm/node/ta-errors.js.map +1 -0
- package/esm/node/ta-event-util.d.ts +11 -0
- package/esm/node/ta-event-util.js +20 -0
- package/esm/node/ta-event-util.js.map +1 -0
- package/esm/node/ta-server-impl.d.ts +50 -0
- package/esm/node/ta-server-impl.js +226 -0
- package/esm/node/ta-server-impl.js.map +1 -0
- package/esm/node/ta-session-factory.d.ts +32 -0
- package/esm/node/ta-session-factory.js +151 -0
- package/esm/node/ta-session-factory.js.map +1 -0
- package/esm/node/ta-session-registry.d.ts +20 -0
- package/esm/node/ta-session-registry.js +85 -0
- package/esm/node/ta-session-registry.js.map +1 -0
- package/esm/node/ta-session.d.ts +53 -0
- package/esm/node/ta-session.js +157 -0
- package/esm/node/ta-session.js.map +1 -0
- package/esm/package.json +3 -0
- package/lib/node/client-channel.d.ts +32 -0
- package/lib/node/client-channel.d.ts.map +1 -0
- package/lib/node/client-channel.js +88 -0
- package/lib/node/client-channel.js.map +1 -0
- package/lib/node/client-channel.spec.d.ts +2 -0
- package/lib/node/client-channel.spec.d.ts.map +1 -0
- package/lib/node/client-channel.spec.js +106 -0
- package/lib/node/client-channel.spec.js.map +1 -0
- package/lib/node/event-log.d.ts +29 -0
- package/lib/node/event-log.d.ts.map +1 -0
- package/lib/node/event-log.js +52 -0
- package/lib/node/event-log.js.map +1 -0
- package/lib/node/event-log.spec.d.ts +2 -0
- package/lib/node/event-log.spec.d.ts.map +1 -0
- package/lib/node/event-log.spec.js +48 -0
- package/lib/node/event-log.spec.js.map +1 -0
- package/lib/node/host-protocol.d.ts +28 -0
- package/lib/node/host-protocol.d.ts.map +1 -0
- package/lib/node/host-protocol.js +7 -0
- package/lib/node/host-protocol.js.map +1 -0
- package/lib/node/index.d.ts +14 -0
- package/lib/node/index.d.ts.map +1 -0
- package/lib/node/index.js +30 -0
- package/lib/node/index.js.map +1 -0
- package/lib/node/local-exec-environment-factory.d.ts +5 -0
- package/lib/node/local-exec-environment-factory.d.ts.map +1 -0
- package/lib/node/local-exec-environment-factory.js +21 -0
- package/lib/node/local-exec-environment-factory.js.map +1 -0
- package/lib/node/module.d.ts +4 -0
- package/lib/node/module.d.ts.map +1 -0
- package/lib/node/module.js +6 -0
- package/lib/node/module.js.map +1 -0
- package/lib/node/receipt-book.d.ts +13 -0
- package/lib/node/receipt-book.d.ts.map +1 -0
- package/lib/node/receipt-book.js +42 -0
- package/lib/node/receipt-book.js.map +1 -0
- package/lib/node/receipt-book.spec.d.ts +2 -0
- package/lib/node/receipt-book.spec.d.ts.map +1 -0
- package/lib/node/receipt-book.spec.js +39 -0
- package/lib/node/receipt-book.spec.js.map +1 -0
- package/lib/node/remote-ui-context.d.ts +64 -0
- package/lib/node/remote-ui-context.d.ts.map +1 -0
- package/lib/node/remote-ui-context.js +134 -0
- package/lib/node/remote-ui-context.js.map +1 -0
- package/lib/node/remote-ui-context.spec.d.ts +2 -0
- package/lib/node/remote-ui-context.spec.d.ts.map +1 -0
- package/lib/node/remote-ui-context.spec.js +62 -0
- package/lib/node/remote-ui-context.spec.js.map +1 -0
- package/lib/node/ta-access.d.ts +31 -0
- package/lib/node/ta-access.d.ts.map +1 -0
- package/lib/node/ta-access.js +110 -0
- package/lib/node/ta-access.js.map +1 -0
- package/lib/node/ta-access.spec.d.ts +2 -0
- package/lib/node/ta-access.spec.d.ts.map +1 -0
- package/lib/node/ta-access.spec.js +25 -0
- package/lib/node/ta-access.spec.js.map +1 -0
- package/lib/node/ta-errors.d.ts +12 -0
- package/lib/node/ta-errors.d.ts.map +1 -0
- package/lib/node/ta-errors.js +47 -0
- package/lib/node/ta-errors.js.map +1 -0
- package/lib/node/ta-event-util.d.ts +12 -0
- package/lib/node/ta-event-util.d.ts.map +1 -0
- package/lib/node/ta-event-util.js +23 -0
- package/lib/node/ta-event-util.js.map +1 -0
- package/lib/node/ta-event-util.spec.d.ts +2 -0
- package/lib/node/ta-event-util.spec.d.ts.map +1 -0
- package/lib/node/ta-event-util.spec.js +28 -0
- package/lib/node/ta-event-util.spec.js.map +1 -0
- package/lib/node/ta-server-impl.d.ts +51 -0
- package/lib/node/ta-server-impl.d.ts.map +1 -0
- package/lib/node/ta-server-impl.js +229 -0
- package/lib/node/ta-server-impl.js.map +1 -0
- package/lib/node/ta-session-factory.d.ts +33 -0
- package/lib/node/ta-session-factory.d.ts.map +1 -0
- package/lib/node/ta-session-factory.js +154 -0
- package/lib/node/ta-session-factory.js.map +1 -0
- package/lib/node/ta-session-registry.d.ts +21 -0
- package/lib/node/ta-session-registry.d.ts.map +1 -0
- package/lib/node/ta-session-registry.js +86 -0
- package/lib/node/ta-session-registry.js.map +1 -0
- package/lib/node/ta-session.d.ts +54 -0
- package/lib/node/ta-session.d.ts.map +1 -0
- package/lib/node/ta-session.js +161 -0
- package/lib/node/ta-session.js.map +1 -0
- package/package.json +80 -4
- package/src/node/client-channel.spec.ts +117 -0
- package/src/node/client-channel.ts +94 -0
- package/src/node/event-log.spec.ts +52 -0
- package/src/node/event-log.ts +59 -0
- package/src/node/host-protocol.ts +32 -0
- package/src/node/index.ts +13 -0
- package/src/node/local-exec-environment-factory.ts +9 -0
- package/src/node/module.ts +4 -0
- package/src/node/receipt-book.spec.ts +41 -0
- package/src/node/receipt-book.ts +40 -0
- package/src/node/remote-ui-context.spec.ts +68 -0
- package/src/node/remote-ui-context.ts +168 -0
- package/src/node/ta-access.spec.ts +27 -0
- package/src/node/ta-access.ts +98 -0
- package/src/node/ta-errors.ts +55 -0
- package/src/node/ta-event-util.spec.ts +29 -0
- package/src/node/ta-event-util.ts +23 -0
- package/src/node/ta-server-impl.ts +264 -0
- package/src/node/ta-session-factory.ts +156 -0
- package/src/node/ta-session-registry.ts +75 -0
- package/src/node/ta-session.ts +193 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import type { RpcExtensionUIRequest, RpcExtensionUIResponse, TaEvent } from '@celljs/ta-protocol';
|
|
3
|
+
|
|
4
|
+
type ExtensionUIContext = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ExtensionUIContext;
|
|
5
|
+
type DialogOptions = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ExtensionUIDialogOptions;
|
|
6
|
+
type Theme = ExtensionUIContext['theme'];
|
|
7
|
+
|
|
8
|
+
interface PendingDialog {
|
|
9
|
+
request: RpcExtensionUIRequest;
|
|
10
|
+
settle(response: RpcExtensionUIResponse | undefined): void;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
type DialogRequest = RpcExtensionUIRequest extends infer R ? (R extends { id: string } ? Omit<R, 'id' | 'type'> : never) : never;
|
|
14
|
+
|
|
15
|
+
const TEXT_STYLES = new Set(['fg', 'bg', 'bold', 'italic', 'underline', 'strikethrough', 'inverse']);
|
|
16
|
+
|
|
17
|
+
/** Clients draw their own UI: an extension's styled text reaches them without ANSI codes. */
|
|
18
|
+
const PLAIN_THEME = new Proxy(
|
|
19
|
+
{},
|
|
20
|
+
{
|
|
21
|
+
get: (_target, name) => (TEXT_STYLES.has(String(name)) ? (...args: string[]) => args[args.length - 1] : () => ''),
|
|
22
|
+
},
|
|
23
|
+
) as Theme;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* pi's extension UI for clients that are not this process. It has the shape of pi's RPC mode, with one
|
|
27
|
+
* difference: a dialog goes to every attached client, the first answer counts, and the others are told.
|
|
28
|
+
* A dialog nobody answers ends at its timeout, as the extension asked.
|
|
29
|
+
*/
|
|
30
|
+
export class RemoteUiContext implements ExtensionUIContext {
|
|
31
|
+
protected readonly pending = new Map<string, PendingDialog>();
|
|
32
|
+
|
|
33
|
+
readonly theme = PLAIN_THEME;
|
|
34
|
+
|
|
35
|
+
constructor(protected readonly publish: (event: TaEvent) => void) {}
|
|
36
|
+
|
|
37
|
+
get pendingRequests(): RpcExtensionUIRequest[] {
|
|
38
|
+
return [...this.pending.values()].map(dialog => dialog.request);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** False when the dialog was answered before or ended. */
|
|
42
|
+
respond(response: RpcExtensionUIResponse): boolean {
|
|
43
|
+
const dialog = this.pending.get(response.id);
|
|
44
|
+
dialog?.settle(response);
|
|
45
|
+
return dialog !== undefined;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Ends the open dialogs as if they timed out: the extensions go on, with their defaults. */
|
|
49
|
+
cancelAll(): void {
|
|
50
|
+
for (const dialog of [...this.pending.values()]) {
|
|
51
|
+
dialog.settle(undefined);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
select(title: string, options: string[], opts?: DialogOptions): Promise<string | undefined> {
|
|
56
|
+
return this.dialog({ method: 'select', title, options, timeout: opts?.timeout }, opts, undefined, r => ('value' in r ? r.value : undefined));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
confirm(title: string, message: string, opts?: DialogOptions): Promise<boolean> {
|
|
60
|
+
return this.dialog({ method: 'confirm', title, message, timeout: opts?.timeout }, opts, false, r => ('confirmed' in r ? r.confirmed : false));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
input(title: string, placeholder?: string, opts?: DialogOptions): Promise<string | undefined> {
|
|
64
|
+
return this.dialog({ method: 'input', title, placeholder, timeout: opts?.timeout }, opts, undefined, r => ('value' in r ? r.value : undefined));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
editor(title: string, prefill?: string): Promise<string | undefined> {
|
|
68
|
+
return this.dialog({ method: 'editor', title, prefill }, undefined, undefined, r => ('value' in r ? r.value : undefined));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
notify(message: string, type?: 'info' | 'warning' | 'error'): void {
|
|
72
|
+
this.tell({ method: 'notify', message, notifyType: type });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
setStatus(key: string, text: string | undefined): void {
|
|
76
|
+
this.tell({ method: 'setStatus', statusKey: key, statusText: text });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
setWidget(key: string, content: unknown, options?: { placement?: 'aboveEditor' | 'belowEditor' }): void {
|
|
80
|
+
// Clients cannot run a component factory; pi's RPC mode ignores those too.
|
|
81
|
+
if (content === undefined || Array.isArray(content)) {
|
|
82
|
+
this.tell({ method: 'setWidget', widgetKey: key, widgetLines: content, widgetPlacement: options?.placement });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
setTitle(title: string): void {
|
|
87
|
+
this.tell({ method: 'setTitle', title });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
setEditorText(text: string): void {
|
|
91
|
+
this.tell({ method: 'set_editor_text', text });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
pasteToEditor(text: string): void {
|
|
95
|
+
this.setEditorText(text);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
getEditorText(): string {
|
|
99
|
+
return '';
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// What needs a terminal in this process does nothing, as in pi's RPC mode.
|
|
103
|
+
onTerminalInput(): () => void {
|
|
104
|
+
return () => undefined;
|
|
105
|
+
}
|
|
106
|
+
setWorkingMessage(): void {}
|
|
107
|
+
setWorkingVisible(): void {}
|
|
108
|
+
setWorkingIndicator(): void {}
|
|
109
|
+
setHiddenThinkingLabel(): void {}
|
|
110
|
+
setFooter(): void {}
|
|
111
|
+
setHeader(): void {}
|
|
112
|
+
addAutocompleteProvider(): void {}
|
|
113
|
+
setEditorComponent(): void {}
|
|
114
|
+
getEditorComponent(): undefined {
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
async custom(): Promise<never> {
|
|
118
|
+
return undefined as never;
|
|
119
|
+
}
|
|
120
|
+
getAllThemes(): [] {
|
|
121
|
+
return [];
|
|
122
|
+
}
|
|
123
|
+
getTheme(): undefined {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
setTheme(): { success: boolean; error: string } {
|
|
127
|
+
return { success: false, error: 'Clients of ta serve choose their own theme.' };
|
|
128
|
+
}
|
|
129
|
+
getToolsExpanded(): boolean {
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
setToolsExpanded(): void {}
|
|
133
|
+
|
|
134
|
+
protected tell(request: DialogRequest): void {
|
|
135
|
+
this.publish({ type: 'extension_ui_request', id: randomUUID(), ...request } as RpcExtensionUIRequest);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
protected dialog<T>(
|
|
139
|
+
request: DialogRequest,
|
|
140
|
+
options: DialogOptions | undefined,
|
|
141
|
+
fallback: T,
|
|
142
|
+
parse: (response: Exclude<RpcExtensionUIResponse, { cancelled: true }>) => T,
|
|
143
|
+
): Promise<T> {
|
|
144
|
+
if (options?.signal?.aborted) {
|
|
145
|
+
return Promise.resolve(fallback);
|
|
146
|
+
}
|
|
147
|
+
const id = randomUUID();
|
|
148
|
+
return new Promise<T>(resolve => {
|
|
149
|
+
const settle = (response: RpcExtensionUIResponse | undefined) => {
|
|
150
|
+
clearTimeout(timer);
|
|
151
|
+
options?.signal?.removeEventListener('abort', onAbort);
|
|
152
|
+
this.pending.delete(id);
|
|
153
|
+
this.publish({ type: 'ui_request_resolved', id });
|
|
154
|
+
resolve(
|
|
155
|
+
!response || ('cancelled' in response && response.cancelled)
|
|
156
|
+
? fallback
|
|
157
|
+
: parse(response as Exclude<RpcExtensionUIResponse, { cancelled: true }>),
|
|
158
|
+
);
|
|
159
|
+
};
|
|
160
|
+
const onAbort = () => settle(undefined);
|
|
161
|
+
const timer = options?.timeout ? setTimeout(onAbort, options.timeout) : undefined;
|
|
162
|
+
options?.signal?.addEventListener('abort', onAbort, { once: true });
|
|
163
|
+
const full = { type: 'extension_ui_request', id, ...request } as RpcExtensionUIRequest;
|
|
164
|
+
this.pending.set(id, { request: full, settle });
|
|
165
|
+
this.publish(full);
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test';
|
|
2
|
+
import type { IncomingMessage } from 'node:http';
|
|
3
|
+
import { TaAccessUtil } from './ta-access';
|
|
4
|
+
|
|
5
|
+
const request = (url: string, headers: Record<string, string> = {}) => ({ url, headers }) as unknown as IncomingMessage;
|
|
6
|
+
|
|
7
|
+
describe('TaAccessUtil', () => {
|
|
8
|
+
it('reads the token from the header or the query', () => {
|
|
9
|
+
expect(TaAccessUtil.tokenOf(request('/api/ws', { authorization: 'Bearer abc' }))).toBe('abc');
|
|
10
|
+
expect(TaAccessUtil.tokenOf(request('/api/ws?token=abc'))).toBe('abc');
|
|
11
|
+
expect(TaAccessUtil.tokenOf(request('/api/ws'))).toBeUndefined();
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it('compares tokens of any length', () => {
|
|
15
|
+
expect(TaAccessUtil.equals('abc', 'abc')).toBe(true);
|
|
16
|
+
expect(TaAccessUtil.equals('abc', 'abd')).toBe(false);
|
|
17
|
+
expect(TaAccessUtil.equals('abc', 'abcd')).toBe(false);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it('knows the names of this machine', () => {
|
|
21
|
+
expect(TaAccessUtil.isLoopbackHost('127.0.0.1:3000')).toBe(true);
|
|
22
|
+
expect(TaAccessUtil.isLoopbackHost('localhost')).toBe(true);
|
|
23
|
+
expect(TaAccessUtil.isLoopbackHost('[::1]:3000')).toBe(true);
|
|
24
|
+
expect(TaAccessUtil.isLoopbackHost('evil.example:3000')).toBe(false);
|
|
25
|
+
expect(TaAccessUtil.isLoopbackHost(undefined)).toBe(false);
|
|
26
|
+
});
|
|
27
|
+
});
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { chmodSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import type { IncomingMessage, Server } from 'node:http';
|
|
4
|
+
import type { AddressInfo } from 'node:net';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { type Application, ApplicationLifecycle, Autowired, Component, Value } from '@celljs/core';
|
|
7
|
+
import { RpcContext, RpcWebSocketGuard } from '@celljs/rpc/lib/node';
|
|
8
|
+
import { TaBrand } from '@celljs/ta-harness/lib/node/ta-brand';
|
|
9
|
+
import { TA_SERVE_FILE, TA_WEBSOCKET_PATH, type TaServeInfo } from '@celljs/ta-protocol';
|
|
10
|
+
import { type Context, Middleware, ServerAware } from '@celljs/web/lib/node';
|
|
11
|
+
import { TaSessionRegistry } from './host-protocol';
|
|
12
|
+
|
|
13
|
+
const LOOPBACK_NAMES = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
14
|
+
|
|
15
|
+
/** Runs before everything else that handles a request. */
|
|
16
|
+
const ACCESS_MIDDLEWARE_PRIORITY = 10000;
|
|
17
|
+
|
|
18
|
+
export namespace TaAccessUtil {
|
|
19
|
+
/** From `Authorization: Bearer`, or `?token=` for browsers, whose WebSocket API cannot set headers. */
|
|
20
|
+
export function tokenOf(request: IncomingMessage): string | undefined {
|
|
21
|
+
const header = request.headers.authorization;
|
|
22
|
+
if (header?.startsWith('Bearer ')) {
|
|
23
|
+
return header.slice('Bearer '.length);
|
|
24
|
+
}
|
|
25
|
+
return new URL(request.url ?? '/', 'http://localhost').searchParams.get('token') ?? undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function equals(a: string, b: string): boolean {
|
|
29
|
+
const [left, right] = [Buffer.from(a), Buffer.from(b)];
|
|
30
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A page that rebinds its domain to 127.0.0.1 reaches the server with its own name in `Host`. */
|
|
34
|
+
export function isLoopbackHost(host: string | undefined): boolean {
|
|
35
|
+
return LOOPBACK_NAMES.has((host ?? '').replace(/:\d+$/, ''));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The token of this server: `TA_SERVE_TOKEN`, which a parent process (the desktop app) can choose, or a
|
|
41
|
+
* random one. It lets in connections and requests, and is published in a file only this user can read.
|
|
42
|
+
*/
|
|
43
|
+
@Component([RpcWebSocketGuard, Middleware, ServerAware, ApplicationLifecycle])
|
|
44
|
+
export class TaAccess implements RpcWebSocketGuard, Middleware, ServerAware, ApplicationLifecycle<Application> {
|
|
45
|
+
readonly priority = ACCESS_MIDDLEWARE_PRIORITY;
|
|
46
|
+
readonly token = process.env.TA_SERVE_TOKEN || randomBytes(32).toString('base64url');
|
|
47
|
+
|
|
48
|
+
@Value('server.host')
|
|
49
|
+
protected readonly host?: string;
|
|
50
|
+
|
|
51
|
+
@Autowired(TaSessionRegistry)
|
|
52
|
+
protected readonly sessions: TaSessionRegistry;
|
|
53
|
+
|
|
54
|
+
protected readonly infoFile = join(TaBrand.agentDir(), TA_SERVE_FILE);
|
|
55
|
+
|
|
56
|
+
allows(request: IncomingMessage): boolean {
|
|
57
|
+
const token = TaAccessUtil.tokenOf(request);
|
|
58
|
+
return token !== undefined && TaAccessUtil.equals(token, this.token) && this.acceptsHost(request);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Calls over a WebSocket were checked when it opened; this covers plain HTTP. */
|
|
62
|
+
async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
|
|
63
|
+
if (RpcContext.connection() || this.allows(ctx.request as unknown as IncomingMessage)) {
|
|
64
|
+
await next();
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
ctx.response.statusCode = 401;
|
|
68
|
+
ctx.response.end('Unauthorized');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async setServer(server: Server): Promise<void> {
|
|
72
|
+
const publish = () => this.publish(server);
|
|
73
|
+
if (server.listening) {
|
|
74
|
+
publish();
|
|
75
|
+
} else {
|
|
76
|
+
server.once('listening', publish);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async onStop(): Promise<void> {
|
|
81
|
+
rmSync(this.infoFile, { force: true });
|
|
82
|
+
await this.sessions.closeAll();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
protected acceptsHost(request: IncomingMessage): boolean {
|
|
86
|
+
return !TaAccessUtil.isLoopbackHost(this.host) || TaAccessUtil.isLoopbackHost(request.headers.host);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
protected publish(server: Server): void {
|
|
90
|
+
const { port } = server.address() as AddressInfo;
|
|
91
|
+
const info: TaServeInfo = { url: `ws://${this.host ?? '127.0.0.1'}:${port}${TA_WEBSOCKET_PATH}`, token: this.token, pid: process.pid };
|
|
92
|
+
mkdirSync(join(this.infoFile, '..'), { recursive: true });
|
|
93
|
+
writeFileSync(this.infoFile, JSON.stringify(info), { mode: 0o600 });
|
|
94
|
+
// The mode above only applies to a new file.
|
|
95
|
+
chmodSync(this.infoFile, 0o600);
|
|
96
|
+
console.log(`ta serve: ${info.url} (token in ${this.infoFile})`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { ApplicationError } from '@celljs/core';
|
|
2
|
+
import { TA_RPC_ERROR_CODE, TaErrorCode, type TaErrorData } from '@celljs/ta-protocol';
|
|
3
|
+
|
|
4
|
+
const TaError = ApplicationError.declare<number, TaErrorData>(TA_RPC_ERROR_CODE, (code: TaErrorCode, message: string, hint: string) => ({
|
|
5
|
+
message,
|
|
6
|
+
data: { code, hint },
|
|
7
|
+
}));
|
|
8
|
+
|
|
9
|
+
/** The failures of {@link TaServer} calls, which reach the client with their message and code. */
|
|
10
|
+
export namespace TaErrors {
|
|
11
|
+
export function sessionNotFound(sessionId: string): Error {
|
|
12
|
+
return TaError(
|
|
13
|
+
TaErrorCode.SESSION_NOT_FOUND,
|
|
14
|
+
`No open session has the id ${sessionId}.`,
|
|
15
|
+
'Open it again with openSession and its session file: idle sessions are closed, their files stay.',
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function sessionLocked(sessionFile: string): Error {
|
|
20
|
+
return TaError(TaErrorCode.SESSION_LOCKED, `The session ${sessionFile} is open elsewhere.`, 'Close it there first: a session has one writer.');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function tooManySessions(max: number): Error {
|
|
24
|
+
return TaError(TaErrorCode.TOO_MANY_SESSIONS, `${max} sessions are open, the limit of this server.`, 'Close a session, or raise ta.host.maxSessions.');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function messageConflict(clientMessageId: string): Error {
|
|
28
|
+
return TaError(
|
|
29
|
+
TaErrorCode.MESSAGE_CONFLICT,
|
|
30
|
+
`The message id ${clientMessageId} was used for a different message.`,
|
|
31
|
+
'Use a new clientMessageId for each message.',
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function modelNotFound(model: string): Error {
|
|
36
|
+
return TaError(
|
|
37
|
+
TaErrorCode.MODEL_NOT_FOUND,
|
|
38
|
+
`The model ${model} is not known or has no credentials.`,
|
|
39
|
+
'Use <provider>/<model id>; getAvailableModels lists the ones that work.',
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function invalidArgument(message: string, hint: string): Error {
|
|
44
|
+
return TaError(TaErrorCode.INVALID_ARGUMENT, message, hint);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A command that pi refused or that failed. Other errors would lose their message on the way out. */
|
|
48
|
+
export function commandFailed(cause: unknown): Error {
|
|
49
|
+
if (ApplicationError.is(cause as object)) {
|
|
50
|
+
return cause as Error;
|
|
51
|
+
}
|
|
52
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
53
|
+
return TaError(TaErrorCode.COMMAND_FAILED, message, 'The message comes from the agent; fix what it says and send the command again.');
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test';
|
|
2
|
+
import { TaEventUtil } from './ta-event-util';
|
|
3
|
+
|
|
4
|
+
const toWire = (event: unknown) => TaEventUtil.toWire(event as never) as any;
|
|
5
|
+
|
|
6
|
+
describe('TaEventUtil', () => {
|
|
7
|
+
it('leaves other events as they are', () => {
|
|
8
|
+
const event = { type: 'agent_start' };
|
|
9
|
+
expect(toWire(event)).toBe(event);
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it('sends a delta without the whole message', () => {
|
|
13
|
+
const wire = toWire({
|
|
14
|
+
type: 'message_update',
|
|
15
|
+
message: { role: 'assistant', usage: { input: 1 } },
|
|
16
|
+
assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta: 'x', partial: { content: ['a very long message'] } },
|
|
17
|
+
});
|
|
18
|
+
expect(wire).toEqual({ type: 'message_update', usage: { input: 1 }, assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta: 'x' } });
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('names the tool when a tool call starts', () => {
|
|
22
|
+
const wire = toWire({
|
|
23
|
+
type: 'message_update',
|
|
24
|
+
message: { role: 'assistant' },
|
|
25
|
+
assistantMessageEvent: { type: 'toolcall_start', contentIndex: 0, partial: { content: [{ type: 'toolCall', id: 'c1', name: 'bash' }] } },
|
|
26
|
+
});
|
|
27
|
+
expect(wire.assistantMessageEvent).toEqual({ type: 'toolcall_start', contentIndex: 0, id: 'c1', toolName: 'bash' });
|
|
28
|
+
});
|
|
29
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { TaEvent } from '@celljs/ta-protocol';
|
|
2
|
+
|
|
3
|
+
type AgentSessionEvent = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).AgentSessionEvent;
|
|
4
|
+
|
|
5
|
+
export namespace TaEventUtil {
|
|
6
|
+
/**
|
|
7
|
+
* An event of pi as it goes on the wire, the JSON form of pi's RPC and JSON modes (pi does not export
|
|
8
|
+
* its function). pi's `message_update` holds the whole message so far: sent as is, a reply would cost
|
|
9
|
+
* the square of its length.
|
|
10
|
+
*/
|
|
11
|
+
export function toWire(event: AgentSessionEvent): TaEvent {
|
|
12
|
+
if (event.type !== 'message_update') {
|
|
13
|
+
return event as TaEvent;
|
|
14
|
+
}
|
|
15
|
+
const { partial, ...delta } = event.assistantMessageEvent as typeof event.assistantMessageEvent & {
|
|
16
|
+
partial?: { content: { id?: string; name?: string }[] };
|
|
17
|
+
contentIndex?: number;
|
|
18
|
+
};
|
|
19
|
+
const block = delta.type === 'toolcall_start' ? partial?.content[delta.contentIndex ?? -1] : undefined;
|
|
20
|
+
const assistantMessageEvent = block ? { ...delta, id: block.id, toolName: block.name } : delta;
|
|
21
|
+
return { type: 'message_update', usage: (event.message as { usage?: unknown }).usage, assistantMessageEvent } as TaEvent;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { Autowired } from '@celljs/core';
|
|
2
|
+
import { Rpc } from '@celljs/rpc';
|
|
3
|
+
import { RpcContext } from '@celljs/rpc/lib/node';
|
|
4
|
+
import {
|
|
5
|
+
type RpcExtensionUIResponse,
|
|
6
|
+
type TaAttachResult,
|
|
7
|
+
type TaClientToolResult,
|
|
8
|
+
type TaCommandResult,
|
|
9
|
+
type TaOpenSessionOptions,
|
|
10
|
+
type TaPromptInput,
|
|
11
|
+
type TaPromptReceipt,
|
|
12
|
+
TaServer,
|
|
13
|
+
type TaSessionInfo,
|
|
14
|
+
type ThinkingLevel,
|
|
15
|
+
} from '@celljs/ta-protocol';
|
|
16
|
+
import { TaSessionRegistry } from './host-protocol';
|
|
17
|
+
import { TaErrors } from './ta-errors';
|
|
18
|
+
import type { TaSession } from './ta-session';
|
|
19
|
+
|
|
20
|
+
/** Each command does what the command of the same name does in pi's RPC mode. */
|
|
21
|
+
@Rpc(TaServer)
|
|
22
|
+
export class TaServerImpl implements TaServer {
|
|
23
|
+
@Autowired(TaSessionRegistry)
|
|
24
|
+
protected readonly sessions: TaSessionRegistry;
|
|
25
|
+
|
|
26
|
+
async openSession(options: TaOpenSessionOptions): Promise<TaSessionInfo> {
|
|
27
|
+
return this.guard(async () => (await this.sessions.open(options)).info());
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
closeSession(sessionId: string): Promise<void> {
|
|
31
|
+
return this.guard(() => this.sessions.close(sessionId));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async listSessions(): Promise<TaSessionInfo[]> {
|
|
35
|
+
return this.sessions.list().map(session => session.info());
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
attach(sessionId: string, afterSeq?: number): Promise<TaAttachResult> {
|
|
39
|
+
return this.on(sessionId, session => session.attach(this.sessions.channel(RpcContext.requireConnection()), afterSeq));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
detach(sessionId: string): Promise<void> {
|
|
43
|
+
return this.on(sessionId, session => session.detach(this.sessions.channel(RpcContext.requireConnection())));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
respondUi(sessionId: string, response: RpcExtensionUIResponse): Promise<boolean> {
|
|
47
|
+
return this.on(sessionId, session => session.respondUi(response));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Client tools are declared in the protocol and not run yet: nobody can be waiting. */
|
|
51
|
+
async respondClientTool(_sessionId: string, _result: TaClientToolResult): Promise<boolean> {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
prompt(sessionId: string, input: TaPromptInput): Promise<TaPromptReceipt> {
|
|
56
|
+
return this.on(sessionId, session => session.prompt(input));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
steer(sessionId: string, input: TaPromptInput): Promise<TaPromptReceipt> {
|
|
60
|
+
return this.on(sessionId, session => session.steer(input));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
followUp(sessionId: string, input: TaPromptInput): Promise<TaPromptReceipt> {
|
|
64
|
+
return this.on(sessionId, session => session.followUp(input));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
abort(sessionId: string): Promise<void> {
|
|
68
|
+
return this.on(sessionId, ({ pi }) => pi.abort());
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
clearQueue(sessionId: string): Promise<TaCommandResult<'clear_queue'>> {
|
|
72
|
+
return this.on(sessionId, ({ pi }) => pi.clearQueue());
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
newSession(sessionId: string, parentSession?: string): Promise<TaCommandResult<'new_session'>> {
|
|
76
|
+
return this.on(sessionId, ({ runtime }) => runtime.newSession(parentSession ? { parentSession } : undefined));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
getState(sessionId: string): Promise<TaCommandResult<'get_state'>> {
|
|
80
|
+
return this.on(sessionId, ({ pi }) => ({
|
|
81
|
+
model: pi.model,
|
|
82
|
+
thinkingLevel: pi.thinkingLevel,
|
|
83
|
+
isStreaming: pi.isStreaming,
|
|
84
|
+
isCompacting: pi.isCompacting,
|
|
85
|
+
steeringMode: pi.steeringMode,
|
|
86
|
+
followUpMode: pi.followUpMode,
|
|
87
|
+
sessionFile: pi.sessionFile,
|
|
88
|
+
sessionId: pi.sessionId,
|
|
89
|
+
sessionName: pi.sessionName,
|
|
90
|
+
autoCompactionEnabled: pi.autoCompactionEnabled,
|
|
91
|
+
messageCount: pi.messages.length,
|
|
92
|
+
pendingMessageCount: pi.pendingMessageCount,
|
|
93
|
+
}));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
setModel(sessionId: string, provider: string, modelId: string): Promise<TaCommandResult<'set_model'>> {
|
|
97
|
+
return this.on(sessionId, async ({ pi }) => {
|
|
98
|
+
const model = pi.modelRuntime.getAvailableSnapshot().find(m => m.provider === provider && m.id === modelId);
|
|
99
|
+
if (!model) {
|
|
100
|
+
throw TaErrors.modelNotFound(`${provider}/${modelId}`);
|
|
101
|
+
}
|
|
102
|
+
await pi.setModel(model);
|
|
103
|
+
return model;
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
cycleModel(sessionId: string): Promise<TaCommandResult<'cycle_model'>> {
|
|
108
|
+
return this.on(sessionId, async ({ pi }) => (await pi.cycleModel()) ?? null);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
getAvailableModels(sessionId: string): Promise<TaCommandResult<'get_available_models'>> {
|
|
112
|
+
return this.on(sessionId, ({ pi }) => ({ models: [...pi.modelRuntime.getAvailableSnapshot()] }));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
setThinkingLevel(sessionId: string, level: ThinkingLevel): Promise<void> {
|
|
116
|
+
return this.on(sessionId, ({ pi }) => pi.setThinkingLevel(level));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
cycleThinkingLevel(sessionId: string): Promise<TaCommandResult<'cycle_thinking_level'>> {
|
|
120
|
+
return this.on(sessionId, ({ pi }) => {
|
|
121
|
+
const level = pi.cycleThinkingLevel();
|
|
122
|
+
return level ? { level } : null;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
getAvailableThinkingLevels(sessionId: string): Promise<TaCommandResult<'get_available_thinking_levels'>> {
|
|
127
|
+
return this.on(sessionId, ({ pi }) => ({ levels: pi.getAvailableThinkingLevels() }));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
setSteeringMode(sessionId: string, mode: 'all' | 'one-at-a-time'): Promise<void> {
|
|
131
|
+
return this.on(sessionId, ({ pi }) => pi.setSteeringMode(mode));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
setFollowUpMode(sessionId: string, mode: 'all' | 'one-at-a-time'): Promise<void> {
|
|
135
|
+
return this.on(sessionId, ({ pi }) => pi.setFollowUpMode(mode));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
compact(sessionId: string, customInstructions?: string): Promise<TaCommandResult<'compact'>> {
|
|
139
|
+
return this.on(sessionId, ({ pi }) => pi.compact(customInstructions));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
setAutoCompaction(sessionId: string, enabled: boolean): Promise<void> {
|
|
143
|
+
return this.on(sessionId, ({ pi }) => pi.setAutoCompactionEnabled(enabled));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
setAutoRetry(sessionId: string, enabled: boolean): Promise<void> {
|
|
147
|
+
return this.on(sessionId, ({ pi }) => pi.setAutoRetryEnabled(enabled));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
abortRetry(sessionId: string): Promise<void> {
|
|
151
|
+
return this.on(sessionId, ({ pi }) => pi.abortRetry());
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
bash(sessionId: string, command: string, excludeFromContext?: boolean): Promise<TaCommandResult<'bash'>> {
|
|
155
|
+
return this.on(sessionId, async ({ pi }) => {
|
|
156
|
+
const handled = await pi.extensionRunner.emitUserBash({
|
|
157
|
+
type: 'user_bash',
|
|
158
|
+
command,
|
|
159
|
+
excludeFromContext: excludeFromContext ?? false,
|
|
160
|
+
cwd: pi.sessionManager.getCwd(),
|
|
161
|
+
});
|
|
162
|
+
if (handled?.result) {
|
|
163
|
+
pi.recordBashResult(command, handled.result, { excludeFromContext });
|
|
164
|
+
return handled.result;
|
|
165
|
+
}
|
|
166
|
+
return pi.executeBash(command, undefined, { excludeFromContext, operations: handled?.operations });
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
abortBash(sessionId: string): Promise<void> {
|
|
171
|
+
return this.on(sessionId, ({ pi }) => pi.abortBash());
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
getSessionStats(sessionId: string): Promise<TaCommandResult<'get_session_stats'>> {
|
|
175
|
+
return this.on(sessionId, ({ pi }) => pi.getSessionStats());
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
exportHtml(sessionId: string, outputPath?: string): Promise<TaCommandResult<'export_html'>> {
|
|
179
|
+
return this.on(sessionId, async ({ pi }) => ({ path: await pi.exportToHtml(outputPath) }));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
switchSession(sessionId: string, sessionPath: string): Promise<TaCommandResult<'switch_session'>> {
|
|
183
|
+
return this.on(sessionId, ({ runtime }) => runtime.switchSession(sessionPath));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
fork(sessionId: string, entryId: string): Promise<TaCommandResult<'fork'>> {
|
|
187
|
+
return this.on(sessionId, async ({ runtime }) => {
|
|
188
|
+
const result = await runtime.fork(entryId);
|
|
189
|
+
return { text: result.selectedText ?? '', cancelled: result.cancelled };
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
clone(sessionId: string): Promise<TaCommandResult<'clone'>> {
|
|
194
|
+
return this.on(sessionId, async ({ pi, runtime }) => {
|
|
195
|
+
const leafId = pi.sessionManager.getLeafId();
|
|
196
|
+
if (!leafId) {
|
|
197
|
+
throw TaErrors.invalidArgument('This session has nothing to clone yet.', 'Send a message first.');
|
|
198
|
+
}
|
|
199
|
+
return { cancelled: (await runtime.fork(leafId, { position: 'at' })).cancelled };
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
getForkMessages(sessionId: string): Promise<TaCommandResult<'get_fork_messages'>> {
|
|
204
|
+
return this.on(sessionId, ({ pi }) => ({ messages: pi.getUserMessagesForForking() }));
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
getEntries(sessionId: string, since?: string): Promise<TaCommandResult<'get_entries'>> {
|
|
208
|
+
return this.on(sessionId, ({ pi }) => {
|
|
209
|
+
const entries = pi.sessionManager.getEntries();
|
|
210
|
+
const index = since === undefined ? -1 : entries.findIndex(entry => entry.id === since);
|
|
211
|
+
if (since !== undefined && index === -1) {
|
|
212
|
+
throw TaErrors.invalidArgument(`No entry has the id ${since}.`, 'Pass the id of an entry of this session.');
|
|
213
|
+
}
|
|
214
|
+
return { entries: entries.slice(index + 1), leafId: pi.sessionManager.getLeafId() };
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
getTree(sessionId: string): Promise<TaCommandResult<'get_tree'>> {
|
|
219
|
+
return this.on(sessionId, ({ pi }) => ({ tree: pi.sessionManager.getTree(), leafId: pi.sessionManager.getLeafId() }));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
getLastAssistantText(sessionId: string): Promise<TaCommandResult<'get_last_assistant_text'>> {
|
|
223
|
+
return this.on(sessionId, ({ pi }) => ({ text: pi.getLastAssistantText() ?? null }));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
setSessionName(sessionId: string, name: string): Promise<void> {
|
|
227
|
+
return this.on(sessionId, ({ pi }) => {
|
|
228
|
+
if (!name.trim()) {
|
|
229
|
+
throw TaErrors.invalidArgument('A session name cannot be empty.', 'Pass a name with visible characters.');
|
|
230
|
+
}
|
|
231
|
+
pi.setSessionName(name.trim());
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
getMessages(sessionId: string): Promise<TaCommandResult<'get_messages'>> {
|
|
236
|
+
return this.on(sessionId, ({ pi }) => ({ messages: pi.messages }));
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
getCommands(sessionId: string): Promise<TaCommandResult<'get_commands'>> {
|
|
240
|
+
return this.on(sessionId, ({ pi }) => ({
|
|
241
|
+
commands: [
|
|
242
|
+
...pi.extensionRunner
|
|
243
|
+
.getRegisteredCommands()
|
|
244
|
+
.map(c => ({ name: c.invocationName, description: c.description, source: 'extension' as const, sourceInfo: c.sourceInfo })),
|
|
245
|
+
...pi.promptTemplates.map(t => ({ name: t.name, description: t.description, source: 'prompt' as const, sourceInfo: t.sourceInfo })),
|
|
246
|
+
...pi.resourceLoader
|
|
247
|
+
.getSkills()
|
|
248
|
+
.skills.map(s => ({ name: `skill:${s.name}`, description: s.description, source: 'skill' as const, sourceInfo: s.sourceInfo })),
|
|
249
|
+
],
|
|
250
|
+
}));
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
protected on<T>(sessionId: string, command: (session: TaSession) => T | Promise<T>): Promise<T> {
|
|
254
|
+
return this.guard(async () => command(this.sessions.require(sessionId)));
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
protected async guard<T>(command: () => Promise<T>): Promise<T> {
|
|
258
|
+
try {
|
|
259
|
+
return await command();
|
|
260
|
+
} catch (error) {
|
|
261
|
+
throw TaErrors.commandFailed(error);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|