@celljs/ta-host 4.9.0 → 4.10.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.en.md +1 -1
- package/README.md +1 -1
- package/esm/node/event-log.d.ts +2 -1
- package/esm/node/event-log.js +3 -2
- package/esm/node/exec-environment-factory.d.ts +7 -0
- package/esm/node/exec-environment-factory.js +30 -7
- package/esm/node/host-protocol.d.ts +14 -5
- package/esm/node/index.d.ts +1 -0
- package/esm/node/index.js +1 -0
- package/esm/node/remote/remote-hosts.d.ts +1 -3
- package/esm/node/remote/remote-hosts.js +0 -15
- package/esm/node/remote/remote-protocol.d.ts +0 -2
- package/esm/node/remote/remote-server-impl.js +1 -1
- package/esm/node/remote-ui-context.d.ts +1 -1
- package/esm/node/remote-ui-context.js +3 -1
- package/esm/node/session-catalog.d.ts +1 -1
- package/esm/node/session-catalog.js +8 -3
- package/esm/node/session-handles.d.ts +32 -0
- package/esm/node/session-handles.js +86 -0
- package/esm/node/session-info-util.d.ts +6 -0
- package/esm/node/session-info-util.js +34 -2
- package/esm/node/sign-in/sign-in-pages.js +7 -1
- package/esm/node/ta-access.d.ts +11 -0
- package/esm/node/ta-access.js +29 -3
- package/esm/node/ta-errors.js +17 -2
- package/esm/node/ta-event-util.d.ts +12 -2
- package/esm/node/ta-event-util.js +71 -3
- package/esm/node/ta-server-impl.d.ts +0 -2
- package/esm/node/ta-server-impl.js +11 -10
- package/esm/node/ta-session-factory.d.ts +10 -1
- package/esm/node/ta-session-factory.js +22 -2
- package/esm/node/ta-session-registry.d.ts +12 -1
- package/esm/node/ta-session-registry.js +71 -20
- package/esm/node/ta-session.d.ts +9 -5
- package/esm/node/ta-session.js +18 -10
- package/esm/node/workspace-files.d.ts +15 -5
- package/esm/node/workspace-files.js +22 -15
- package/esm/node/workspace-protocol.d.ts +1 -1
- package/esm/node/workspace-util.d.ts +2 -0
- package/esm/node/workspace-util.js +8 -3
- package/lib/node/event-log.d.ts +2 -1
- package/lib/node/event-log.js +3 -2
- package/lib/node/exec-environment-factory.d.ts +7 -0
- package/lib/node/exec-environment-factory.js +30 -7
- package/lib/node/host-protocol.d.ts +14 -5
- package/lib/node/index.d.ts +1 -0
- package/lib/node/index.js +1 -0
- package/lib/node/remote/remote-hosts.d.ts +1 -3
- package/lib/node/remote/remote-hosts.js +0 -15
- package/lib/node/remote/remote-protocol.d.ts +0 -2
- package/lib/node/remote/remote-server-impl.js +1 -1
- package/lib/node/remote-ui-context.d.ts +1 -1
- package/lib/node/remote-ui-context.js +3 -1
- package/lib/node/session-catalog.d.ts +1 -1
- package/lib/node/session-catalog.js +8 -3
- package/lib/node/session-handles.d.ts +33 -0
- package/lib/node/session-handles.js +89 -0
- package/lib/node/session-info-util.d.ts +6 -0
- package/lib/node/session-info-util.js +33 -1
- package/lib/node/sign-in/sign-in-pages.js +7 -1
- package/lib/node/ta-access.d.ts +11 -0
- package/lib/node/ta-access.js +29 -3
- package/lib/node/ta-errors.js +17 -2
- package/lib/node/ta-event-util.d.ts +12 -2
- package/lib/node/ta-event-util.js +71 -3
- package/lib/node/ta-server-impl.d.ts +0 -2
- package/lib/node/ta-server-impl.js +11 -10
- package/lib/node/ta-session-factory.d.ts +10 -1
- package/lib/node/ta-session-factory.js +23 -3
- package/lib/node/ta-session-registry.d.ts +12 -1
- package/lib/node/ta-session-registry.js +71 -20
- package/lib/node/ta-session.d.ts +9 -5
- package/lib/node/ta-session.js +18 -10
- package/lib/node/workspace-files.d.ts +15 -5
- package/lib/node/workspace-files.js +22 -15
- package/lib/node/workspace-protocol.d.ts +1 -1
- package/lib/node/workspace-util.d.ts +2 -0
- package/lib/node/workspace-util.js +8 -3
- package/package.json +12 -12
package/esm/node/ta-access.js
CHANGED
|
@@ -65,6 +65,27 @@ export var TaAccessUtil;
|
|
|
65
65
|
return request.method === 'POST' && path.startsWith(`${API_PATH}/`);
|
|
66
66
|
}
|
|
67
67
|
TaAccessUtil.isHttpCall = isHttpCall;
|
|
68
|
+
/**
|
|
69
|
+
* What starts this ta serve (`ta serve --host --port --exec`, the desktop app, the gateway) and is read
|
|
70
|
+
* once it listens. Left in its environment, every program of its sessions and terminals would take it: a
|
|
71
|
+
* `ta serve` or a Cell app run there would listen on this one's port, a Ta reached from there would take its token.
|
|
72
|
+
*/
|
|
73
|
+
TaAccessUtil.SERVE_ENV = [
|
|
74
|
+
'CELL_SERVER__HOST',
|
|
75
|
+
'CELL_SERVER__PORT',
|
|
76
|
+
'CELL_TA__EXEC__URL',
|
|
77
|
+
'CELL_TA__EXEC__TOKEN',
|
|
78
|
+
'TA_EXEC_TOKEN',
|
|
79
|
+
'TA_SERVE_TOKEN',
|
|
80
|
+
'TA_SERVE_OPEN_WEB',
|
|
81
|
+
];
|
|
82
|
+
/** Removes {@link SERVE_ENV} from `env`, for what this process starts. */
|
|
83
|
+
function releaseServeEnv(env) {
|
|
84
|
+
for (const key of TaAccessUtil.SERVE_ENV) {
|
|
85
|
+
delete env[key];
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
TaAccessUtil.releaseServeEnv = releaseServeEnv;
|
|
68
89
|
/** The token goes in the fragment, which the browser does not send to the server or in `Referer`. */
|
|
69
90
|
function webUrl(httpUrl, token) {
|
|
70
91
|
return `${httpUrl}/#token=${token}`;
|
|
@@ -106,6 +127,9 @@ let TaAccess = class TaAccess {
|
|
|
106
127
|
constructor() {
|
|
107
128
|
this.priority = ACCESS_MIDDLEWARE_PRIORITY;
|
|
108
129
|
this.token = process.env.TA_SERVE_TOKEN || TaServeStateUtil.read().token || randomBytes(32).toString('base64url');
|
|
130
|
+
/** Read before the environment lets them go (TaAccessUtil.releaseServeEnv). */
|
|
131
|
+
this.chosenToken = !!process.env.TA_SERVE_TOKEN;
|
|
132
|
+
this.openWeb = !!process.env.TA_SERVE_OPEN_WEB;
|
|
109
133
|
this.infoFile = join(TaBrand.agentDir(), TA_SERVE_FILE);
|
|
110
134
|
}
|
|
111
135
|
allows(request) {
|
|
@@ -159,16 +183,18 @@ let TaAccess = class TaAccess {
|
|
|
159
183
|
chmodSync(this.infoFile, 0o600);
|
|
160
184
|
// A token that a parent process chose is its to keep.
|
|
161
185
|
const kept = TaServeStateUtil.read().token;
|
|
162
|
-
TaServeStateUtil.write({ port, token:
|
|
186
|
+
TaServeStateUtil.write({ port, token: this.chosenToken ? kept : this.token });
|
|
187
|
+
// Read: what the sessions and terminals start does not take it.
|
|
188
|
+
TaAccessUtil.releaseServeEnv(process.env);
|
|
163
189
|
console.log(`ta serve: ${info.url} (token in ${this.infoFile})`);
|
|
164
|
-
if (
|
|
190
|
+
if (this.openWeb) {
|
|
165
191
|
const url = TaAccessUtil.webUrl(`http://${origin}`, this.token);
|
|
166
192
|
console.log(`ta serve: web client at ${url}`);
|
|
167
193
|
TaAccessUtil.openBrowser(url);
|
|
168
194
|
}
|
|
169
195
|
else if (!TaAccessUtil.isLoopbackHost(this.host)) {
|
|
170
196
|
// Reached from elsewhere (a container, a server): whoever started it opens the link to sign in.
|
|
171
|
-
for (const line of TaAccessUtil.signInLines(this.signIn, port,
|
|
197
|
+
for (const line of TaAccessUtil.signInLines(this.signIn, port, this.chosenToken ? undefined : this.token)) {
|
|
172
198
|
console.log(`ta serve: ${line}`);
|
|
173
199
|
}
|
|
174
200
|
}
|
package/esm/node/ta-errors.js
CHANGED
|
@@ -5,7 +5,18 @@ const TaError = ApplicationError.declare(TA_RPC_ERROR_CODE, (code, message, hint
|
|
|
5
5
|
data: { code, hint },
|
|
6
6
|
}));
|
|
7
7
|
/** What pi says when no provider is signed in for the model, or no model can be used. */
|
|
8
|
-
const NOT_SIGNED_IN = /^No (API key found for|model selected|models available)\b/;
|
|
8
|
+
const NOT_SIGNED_IN = /^(No (API key found for|model selected|models available)|Authentication failed for)\b/;
|
|
9
|
+
/** What else pi says that a client words for the user by its code, as pi's messages are English. */
|
|
10
|
+
const KNOWN = [
|
|
11
|
+
{ pattern: /^Nothing to compact\b/, code: TaErrorCode.NOTHING_TO_COMPACT, hint: 'Compact once the conversation is longer.' },
|
|
12
|
+
{ pattern: /^Already compacted$/, code: TaErrorCode.ALREADY_COMPACTED, hint: 'Compact again once more has been said.' },
|
|
13
|
+
{
|
|
14
|
+
pattern: /^(Cannot submit a prompt while compaction is in progress|Wait for the current (response|compaction))\b/,
|
|
15
|
+
code: TaErrorCode.SESSION_BUSY,
|
|
16
|
+
hint: 'Try again once the session is idle.',
|
|
17
|
+
},
|
|
18
|
+
{ pattern: /^Compaction cancelled$/, code: TaErrorCode.CANCELLED, hint: 'It was stopped; nothing to do.' },
|
|
19
|
+
];
|
|
9
20
|
/** The failures of calls of the services of ta serve ({@link TaServer} and the others), which reach the client with their message and code. */
|
|
10
21
|
export var TaErrors;
|
|
11
22
|
(function (TaErrors) {
|
|
@@ -51,7 +62,11 @@ export var TaErrors;
|
|
|
51
62
|
const message = cause instanceof Error ? cause.message : String(cause);
|
|
52
63
|
if (NOT_SIGNED_IN.test(message)) {
|
|
53
64
|
// pi's own words go on about its /login and the paths of its documents, which a client does not have.
|
|
54
|
-
return TaError(TaErrorCode.NOT_SIGNED_IN, message.split(/\n| Use \/login/)[0].trim(), 'Sign in to a provider of models (TaAuthServer.login), then send it again.');
|
|
65
|
+
return TaError(TaErrorCode.NOT_SIGNED_IN, message.split(/\n| (Use |Run ')\/login/)[0].trim(), 'Sign in to a provider of models (TaAuthServer.login), then send it again.');
|
|
66
|
+
}
|
|
67
|
+
const known = KNOWN.find(({ pattern }) => pattern.test(message));
|
|
68
|
+
if (known) {
|
|
69
|
+
return TaError(known.code, message, known.hint);
|
|
55
70
|
}
|
|
56
71
|
return TaError(TaErrorCode.COMMAND_FAILED, message, 'The message comes from the agent; fix what it says and send the command again.');
|
|
57
72
|
}
|
|
@@ -1,11 +1,21 @@
|
|
|
1
|
-
import type { TaEvent } from '@celljs/ta-protocol';
|
|
1
|
+
import type { TaConversation, TaEvent, TaMessage } from '@celljs/ta-protocol';
|
|
2
2
|
type AgentSessionEvent = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).AgentSessionEvent;
|
|
3
3
|
export declare namespace TaEventUtil {
|
|
4
4
|
/**
|
|
5
5
|
* An event of pi as it goes on the wire, the JSON form of pi's RPC and JSON modes (pi does not export
|
|
6
6
|
* its function). pi's `message_update` holds the whole message so far: sent as is, a reply would cost
|
|
7
|
-
* the square of its length.
|
|
7
|
+
* the square of its length. The images of tool results go without their bytes (`leanMessage`).
|
|
8
8
|
*/
|
|
9
9
|
function toWire(event: AgentSessionEvent): TaEvent;
|
|
10
|
+
/**
|
|
11
|
+
* A message as clients get it: a tool's result keeps its images' kind but not their bytes (`data` is
|
|
12
|
+
* empty). Clients do not show them (the model reads them), and screenshots are most of the bytes of a
|
|
13
|
+
* conversation that has them: on a slow network a page of it would be one picture nobody sees.
|
|
14
|
+
*/
|
|
15
|
+
function leanMessage(message: TaMessage): TaMessage;
|
|
16
|
+
/** The result of a tool, or a message of one, without the bytes of its images. */
|
|
17
|
+
function leanResult<T>(result: T): T;
|
|
18
|
+
/** A conversation as clients get it: its messages and the results of its calls lean. */
|
|
19
|
+
function leanConversation(conversation: TaConversation): TaConversation;
|
|
10
20
|
}
|
|
11
21
|
export {};
|
|
@@ -1,14 +1,33 @@
|
|
|
1
|
+
/** The lean form of each message and result met, made once: the pages of a conversation measure it by its object. */
|
|
2
|
+
const leaned = new WeakMap();
|
|
1
3
|
export var TaEventUtil;
|
|
2
4
|
(function (TaEventUtil) {
|
|
3
5
|
/**
|
|
4
6
|
* An event of pi as it goes on the wire, the JSON form of pi's RPC and JSON modes (pi does not export
|
|
5
7
|
* its function). pi's `message_update` holds the whole message so far: sent as is, a reply would cost
|
|
6
|
-
* the square of its length.
|
|
8
|
+
* the square of its length. The images of tool results go without their bytes (`leanMessage`).
|
|
7
9
|
*/
|
|
8
10
|
function toWire(event) {
|
|
9
11
|
var _a;
|
|
10
|
-
|
|
11
|
-
|
|
12
|
+
switch (event.type) {
|
|
13
|
+
case 'message_update':
|
|
14
|
+
break;
|
|
15
|
+
case 'message_start':
|
|
16
|
+
case 'message_end':
|
|
17
|
+
return withLean(event, 'message', leanMessage(event.message));
|
|
18
|
+
case 'tool_execution_update':
|
|
19
|
+
return withLean(event, 'partialResult', leanResult(event.partialResult));
|
|
20
|
+
case 'tool_execution_end':
|
|
21
|
+
return withLean(event, 'result', leanResult(event.result));
|
|
22
|
+
case 'turn_end': {
|
|
23
|
+
const message = leanMessage(event.message);
|
|
24
|
+
const toolResults = leanAll(event.toolResults);
|
|
25
|
+
return (message === event.message && toolResults === event.toolResults ? event : { ...event, message, toolResults });
|
|
26
|
+
}
|
|
27
|
+
case 'agent_end':
|
|
28
|
+
return withLean(event, 'messages', leanAll(event.messages));
|
|
29
|
+
default:
|
|
30
|
+
return event;
|
|
12
31
|
}
|
|
13
32
|
const { partial, ...delta } = event.assistantMessageEvent;
|
|
14
33
|
const block = delta.type === 'toolcall_start' ? partial === null || partial === void 0 ? void 0 : partial.content[(_a = delta.contentIndex) !== null && _a !== void 0 ? _a : -1] : undefined;
|
|
@@ -16,5 +35,54 @@ export var TaEventUtil;
|
|
|
16
35
|
return { type: 'message_update', usage: event.message.usage, assistantMessageEvent };
|
|
17
36
|
}
|
|
18
37
|
TaEventUtil.toWire = toWire;
|
|
38
|
+
/**
|
|
39
|
+
* A message as clients get it: a tool's result keeps its images' kind but not their bytes (`data` is
|
|
40
|
+
* empty). Clients do not show them (the model reads them), and screenshots are most of the bytes of a
|
|
41
|
+
* conversation that has them: on a slow network a page of it would be one picture nobody sees.
|
|
42
|
+
*/
|
|
43
|
+
function leanMessage(message) {
|
|
44
|
+
return (message === null || message === void 0 ? void 0 : message.role) === 'toolResult' ? leanResult(message) : message;
|
|
45
|
+
}
|
|
46
|
+
TaEventUtil.leanMessage = leanMessage;
|
|
47
|
+
/** The result of a tool, or a message of one, without the bytes of its images. */
|
|
48
|
+
function leanResult(result) {
|
|
49
|
+
const content = result === null || result === void 0 ? void 0 : result.content;
|
|
50
|
+
if (!result || typeof result !== 'object' || !Array.isArray(content)) {
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
53
|
+
const known = leaned.get(result);
|
|
54
|
+
if (known) {
|
|
55
|
+
return known;
|
|
56
|
+
}
|
|
57
|
+
const heavy = content.some(block => (block === null || block === void 0 ? void 0 : block.type) === 'image' && block.data);
|
|
58
|
+
const lean = heavy
|
|
59
|
+
? {
|
|
60
|
+
...result,
|
|
61
|
+
content: content.map(block => (block === null || block === void 0 ? void 0 : block.type) === 'image' ? { type: 'image', mimeType: block.mimeType, data: '' } : block),
|
|
62
|
+
}
|
|
63
|
+
: result;
|
|
64
|
+
leaned.set(result, lean);
|
|
65
|
+
return lean;
|
|
66
|
+
}
|
|
67
|
+
TaEventUtil.leanResult = leanResult;
|
|
68
|
+
/** A conversation as clients get it: its messages and the results of its calls lean. */
|
|
69
|
+
function leanConversation(conversation) {
|
|
70
|
+
const tools = {};
|
|
71
|
+
for (const [id, run] of Object.entries(conversation.tools)) {
|
|
72
|
+
tools[id] = run.result === undefined ? run : { ...run, result: leanResult(run.result) };
|
|
73
|
+
}
|
|
74
|
+
return { ...conversation, messages: leanAll(conversation.messages), tools };
|
|
75
|
+
}
|
|
76
|
+
TaEventUtil.leanConversation = leanConversation;
|
|
77
|
+
function leanAll(messages) {
|
|
78
|
+
if (!Array.isArray(messages)) {
|
|
79
|
+
return messages;
|
|
80
|
+
}
|
|
81
|
+
const lean = messages.map(leanMessage);
|
|
82
|
+
return lean.every((message, index) => message === messages[index]) ? messages : lean;
|
|
83
|
+
}
|
|
84
|
+
function withLean(event, key, value) {
|
|
85
|
+
return (value === event[key] ? event : { ...event, [key]: value });
|
|
86
|
+
}
|
|
19
87
|
})(TaEventUtil || (TaEventUtil = {}));
|
|
20
88
|
//# sourceMappingURL=ta-event-util.js.map
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { ExecEnvironmentFactory } from '@celljs/ta-exec';
|
|
2
2
|
import { type RpcExtensionUIResponse, type TaAttachOptions, type TaAttachResult, type TaClientToolResult, type TaCommandResult, type TaForkFileResult, type TaMessagePage, type TaNavigateResult, type TaOpenSessionOptions, type TaPromptInput, type TaPromptReceipt, type TaSavedSessionInfo, TaServer, type TaServerInfo, type TaSessionInfo, type ThinkingLevel } from '@celljs/ta-protocol';
|
|
3
3
|
import { TaSessionCatalog, TaSessionRegistry } from './host-protocol.js';
|
|
4
|
-
import { RemoteHosts } from './remote/remote-protocol.js';
|
|
5
4
|
import type { TaSession } from './ta-session.js';
|
|
6
5
|
import { TaWorkingDirectory } from './working-directory.js';
|
|
7
6
|
/**
|
|
@@ -13,7 +12,6 @@ export declare class TaServerImpl implements TaServer {
|
|
|
13
12
|
protected readonly sessions: TaSessionRegistry;
|
|
14
13
|
protected readonly environments: ExecEnvironmentFactory;
|
|
15
14
|
protected readonly workingDirectory: TaWorkingDirectory;
|
|
16
|
-
protected readonly remoteHosts: RemoteHosts;
|
|
17
15
|
protected readonly catalog: TaSessionCatalog;
|
|
18
16
|
getServerInfo(): Promise<TaServerInfo>;
|
|
19
17
|
setWorkingDirectory(cwd: string): Promise<TaServerInfo>;
|
|
@@ -17,7 +17,6 @@ import { ExecEnvironmentFactory } from '@celljs/ta-exec';
|
|
|
17
17
|
import { TaBrand } from '@celljs/ta-harness/lib/node/ta-brand';
|
|
18
18
|
import { TaServer, } from '@celljs/ta-protocol';
|
|
19
19
|
import { TaSessionCatalog, TaSessionRegistry } from './host-protocol.js';
|
|
20
|
-
import { RemoteHosts } from './remote/remote-protocol.js';
|
|
21
20
|
import { SessionInfoUtil } from './session-info-util.js';
|
|
22
21
|
import { TaErrors } from './ta-errors.js';
|
|
23
22
|
import { TaWorkingDirectory } from './working-directory.js';
|
|
@@ -38,7 +37,7 @@ let TaServerImpl = class TaServerImpl {
|
|
|
38
37
|
async setWorkingDirectory(cwd) {
|
|
39
38
|
return this.guard(async () => {
|
|
40
39
|
var _a;
|
|
41
|
-
const path = typeof cwd === 'string' && cwd.trim() ? await this.
|
|
40
|
+
const path = typeof cwd === 'string' && cwd.trim() ? await this.environments.resolve(cwd.trim()) : '';
|
|
42
41
|
const env = path ? this.environments.create(path) : undefined;
|
|
43
42
|
if (!env || !((_a = (await env.stat(env.cwd))) === null || _a === void 0 ? void 0 : _a.isDirectory)) {
|
|
44
43
|
throw TaErrors.invalidArgument(`${cwd} is not a directory.`, 'Pass the absolute path of a directory that exists on the server, or an ssh:// location.');
|
|
@@ -58,8 +57,8 @@ let TaServerImpl = class TaServerImpl {
|
|
|
58
57
|
}
|
|
59
58
|
listSavedSessions() {
|
|
60
59
|
return this.guard(async () => {
|
|
61
|
-
const open = new Set(this.sessions.list().
|
|
62
|
-
return
|
|
60
|
+
const open = new Set(this.sessions.list().flatMap(session => { var _a; return (_a = session.pi.sessionFile) !== null && _a !== void 0 ? _a : []; }));
|
|
61
|
+
return this.catalog.list(open);
|
|
63
62
|
});
|
|
64
63
|
}
|
|
65
64
|
attach(sessionId, afterSeq, options) {
|
|
@@ -69,7 +68,13 @@ let TaServerImpl = class TaServerImpl {
|
|
|
69
68
|
return this.on(sessionId, session => session.earlierMessages(before !== null && before !== void 0 ? before : undefined, timestamp !== null && timestamp !== void 0 ? timestamp : undefined, budget));
|
|
70
69
|
}
|
|
71
70
|
detach(sessionId) {
|
|
72
|
-
|
|
71
|
+
// Not opened again to be left: a session closed meanwhile has no client.
|
|
72
|
+
return this.guard(async () => {
|
|
73
|
+
var _a;
|
|
74
|
+
(_a = this.sessions
|
|
75
|
+
.list()
|
|
76
|
+
.find(session => session.id === sessionId)) === null || _a === void 0 ? void 0 : _a.detach(this.sessions.channel(RpcContext.requireConnection()));
|
|
77
|
+
});
|
|
73
78
|
}
|
|
74
79
|
respondUi(sessionId, response) {
|
|
75
80
|
return this.on(sessionId, session => session.respondUi(response));
|
|
@@ -281,7 +286,7 @@ let TaServerImpl = class TaServerImpl {
|
|
|
281
286
|
});
|
|
282
287
|
}
|
|
283
288
|
on(sessionId, command) {
|
|
284
|
-
return this.guard(async () => command(this.sessions.
|
|
289
|
+
return this.guard(async () => command(await this.sessions.resolve(sessionId)));
|
|
285
290
|
}
|
|
286
291
|
guard(command) {
|
|
287
292
|
return TaErrors.guard(command);
|
|
@@ -299,10 +304,6 @@ __decorate([
|
|
|
299
304
|
Autowired(TaWorkingDirectory),
|
|
300
305
|
__metadata("design:type", Object)
|
|
301
306
|
], TaServerImpl.prototype, "workingDirectory", void 0);
|
|
302
|
-
__decorate([
|
|
303
|
-
Autowired(RemoteHosts),
|
|
304
|
-
__metadata("design:type", Object)
|
|
305
|
-
], TaServerImpl.prototype, "remoteHosts", void 0);
|
|
306
307
|
__decorate([
|
|
307
308
|
Autowired(TaSessionCatalog),
|
|
308
309
|
__metadata("design:type", Object)
|
|
@@ -12,6 +12,15 @@ type AgentsFilesOverride = (base: {
|
|
|
12
12
|
}) => {
|
|
13
13
|
agentsFiles: ContextFile[];
|
|
14
14
|
};
|
|
15
|
+
export declare namespace SessionFileUtil {
|
|
16
|
+
/**
|
|
17
|
+
* The directory pi is to work in for a session file it opens: none for a file that says (pi reads it from
|
|
18
|
+
* its header); `cwd`, where the caller asks, for one with no header yet. pi writes a file once the agent
|
|
19
|
+
* first answered, so the file of a session opened and never answered (an agent made but not yet asked) is
|
|
20
|
+
* not there, and pi would take the directory ta serve runs in, the home directory under the desktop app.
|
|
21
|
+
*/
|
|
22
|
+
function cwdOverride(sessionFile: string, cwd: string): string | undefined;
|
|
23
|
+
}
|
|
15
24
|
type ModelRuntime = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).ModelRuntime;
|
|
16
25
|
type SessionManager = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).SessionManager;
|
|
17
26
|
type Model = NonNullable<import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).AgentSession['model']>;
|
|
@@ -26,7 +35,7 @@ export declare class DefaultTaSessionFactory implements TaSessionFactory {
|
|
|
26
35
|
protected readonly packageHosts: PackageHosts;
|
|
27
36
|
protected readonly directories: PiDirectories;
|
|
28
37
|
protected readonly extensionProviders: ExtensionProviders;
|
|
29
|
-
create(requested: TaOpenSessionOptions, requestClose: (session: TaSession) => void): Promise<TaSession>;
|
|
38
|
+
create(requested: TaOpenSessionOptions, requestClose: (session: TaSession, idle?: boolean) => void, id?: string): Promise<TaSession>;
|
|
30
39
|
protected openSessionManager(sdk: PiSdk, options: TaOpenSessionOptions): SessionManager;
|
|
31
40
|
/**
|
|
32
41
|
* For another machine, its context files (AGENTS.md...) instead of those pi finds above the directory
|
|
@@ -7,6 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
7
7
|
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
8
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
9
|
};
|
|
10
|
+
import { statSync } from 'node:fs';
|
|
10
11
|
import { resolve, sep } from 'node:path';
|
|
11
12
|
import { AgentExtension, AgentTool, AgentToolUtil, CODING_AGENT_OPTIONS, ModelRuntimeProvider, PiSdkUtil, } from '@celljs/ai-coding-agent';
|
|
12
13
|
import { Autowired, Component, Optional, Value } from '@celljs/core';
|
|
@@ -22,13 +23,31 @@ import { SessionCatalogUtil } from './session-catalog.js';
|
|
|
22
23
|
import { ExecSessionFiles } from './session-files.js';
|
|
23
24
|
import { TaErrors } from './ta-errors.js';
|
|
24
25
|
import { TaSession } from './ta-session.js';
|
|
26
|
+
export var SessionFileUtil;
|
|
27
|
+
(function (SessionFileUtil) {
|
|
28
|
+
/**
|
|
29
|
+
* The directory pi is to work in for a session file it opens: none for a file that says (pi reads it from
|
|
30
|
+
* its header); `cwd`, where the caller asks, for one with no header yet. pi writes a file once the agent
|
|
31
|
+
* first answered, so the file of a session opened and never answered (an agent made but not yet asked) is
|
|
32
|
+
* not there, and pi would take the directory ta serve runs in, the home directory under the desktop app.
|
|
33
|
+
*/
|
|
34
|
+
function cwdOverride(sessionFile, cwd) {
|
|
35
|
+
try {
|
|
36
|
+
return statSync(sessionFile).size > 0 ? undefined : cwd;
|
|
37
|
+
}
|
|
38
|
+
catch (_a) {
|
|
39
|
+
return cwd;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
SessionFileUtil.cwdOverride = cwdOverride;
|
|
43
|
+
})(SessionFileUtil || (SessionFileUtil = {}));
|
|
25
44
|
/** Sets up pi for each session the way its command does, with one model runtime for all of them. */
|
|
26
45
|
let DefaultTaSessionFactory = class DefaultTaSessionFactory {
|
|
27
46
|
constructor() {
|
|
28
47
|
this.extensions = [];
|
|
29
48
|
this.tools = [];
|
|
30
49
|
}
|
|
31
|
-
async create(requested, requestClose) {
|
|
50
|
+
async create(requested, requestClose, id) {
|
|
32
51
|
var _a;
|
|
33
52
|
var _b, _c, _d;
|
|
34
53
|
const clientTools = new ClientToolBroker(requested.clientTools);
|
|
@@ -90,6 +109,7 @@ let DefaultTaSessionFactory = class DefaultTaSessionFactory {
|
|
|
90
109
|
clientTools,
|
|
91
110
|
options: this.options,
|
|
92
111
|
requestClose,
|
|
112
|
+
id,
|
|
93
113
|
group: options.group,
|
|
94
114
|
role: options.appendSystemPrompt,
|
|
95
115
|
locate: cwd => this.directories.fromPi(cwd),
|
|
@@ -107,7 +127,7 @@ let DefaultTaSessionFactory = class DefaultTaSessionFactory {
|
|
|
107
127
|
return sdk.SessionManager.create(options.cwd);
|
|
108
128
|
}
|
|
109
129
|
try {
|
|
110
|
-
return sdk.SessionManager.open(options.sessionFile);
|
|
130
|
+
return sdk.SessionManager.open(options.sessionFile, undefined, SessionFileUtil.cwdOverride(options.sessionFile, options.cwd));
|
|
111
131
|
}
|
|
112
132
|
catch (error) {
|
|
113
133
|
throw TaErrors.invalidArgument(`Cannot open the session ${options.sessionFile}: ${error.message}`, 'Pass a session file that exists; listSessions shows the open ones.');
|
|
@@ -2,21 +2,32 @@ import type { RpcConnection } from '@celljs/rpc/lib/node';
|
|
|
2
2
|
import type { TaOpenSessionOptions } from '@celljs/ta-protocol';
|
|
3
3
|
import { ClientChannel } from './client-channel.js';
|
|
4
4
|
import { type TaHostOptions, TaSessionFactory, TaSessionRegistry } from './host-protocol.js';
|
|
5
|
+
import { TaSessionHandles } from './session-handles.js';
|
|
5
6
|
import type { TaSession } from './ta-session.js';
|
|
7
|
+
/**
|
|
8
|
+
* The open sessions. A session's id outlives its memory: closed while idle or by a restart, it opens again
|
|
9
|
+
* from its file under the same id at the next call (TaSessionHandles), so clients never see it go.
|
|
10
|
+
*/
|
|
6
11
|
export declare class DefaultTaSessionRegistry implements TaSessionRegistry {
|
|
7
12
|
protected readonly options: TaHostOptions;
|
|
8
13
|
protected readonly factory: TaSessionFactory;
|
|
14
|
+
protected readonly handles: TaSessionHandles;
|
|
9
15
|
protected readonly sessions: Map<string, TaSession>;
|
|
10
16
|
protected readonly channels: WeakMap<RpcConnection, ClientChannel>;
|
|
11
17
|
/** Sessions being created count against the limit too. */
|
|
12
18
|
protected opening: number;
|
|
13
19
|
/** The closes under way, by session file: out of the list already, their files locked until they end. */
|
|
14
20
|
protected readonly closing: Map<string, Promise<void>>;
|
|
21
|
+
/** Sessions opening again under their ids: the calls that come meanwhile wait for the same. */
|
|
22
|
+
protected readonly waking: Map<string, Promise<TaSession>>;
|
|
15
23
|
open(options: TaOpenSessionOptions): Promise<TaSession>;
|
|
16
24
|
require(sessionId: string): TaSession;
|
|
25
|
+
resolve(sessionId: string): Promise<TaSession>;
|
|
17
26
|
list(): TaSession[];
|
|
18
|
-
close(sessionId: string): Promise<void>;
|
|
27
|
+
close(sessionId: string, idle?: boolean): Promise<void>;
|
|
19
28
|
closeAll(): Promise<void>;
|
|
20
29
|
/** The one channel of a connection; it leaves every session when the connection ends. */
|
|
21
30
|
channel(connection: RpcConnection): ClientChannel;
|
|
31
|
+
/** `id`: the id it had, to open it again under. */
|
|
32
|
+
protected create(options: TaOpenSessionOptions, id: string | undefined): Promise<TaSession>;
|
|
22
33
|
}
|
|
@@ -9,10 +9,16 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
9
9
|
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
10
10
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
11
11
|
};
|
|
12
|
+
import { existsSync } from 'node:fs';
|
|
12
13
|
import { Autowired, Component, Value } from '@celljs/core';
|
|
13
14
|
import { ClientChannel } from './client-channel.js';
|
|
14
15
|
import { TA_HOST_OPTIONS, TaSessionFactory, TaSessionRegistry } from './host-protocol.js';
|
|
16
|
+
import { TaSessionHandles } from './session-handles.js';
|
|
15
17
|
import { TaErrors } from './ta-errors.js';
|
|
18
|
+
/**
|
|
19
|
+
* The open sessions. A session's id outlives its memory: closed while idle or by a restart, it opens again
|
|
20
|
+
* from its file under the same id at the next call (TaSessionHandles), so clients never see it go.
|
|
21
|
+
*/
|
|
16
22
|
let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
|
|
17
23
|
constructor() {
|
|
18
24
|
this.sessions = new Map();
|
|
@@ -21,25 +27,17 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
|
|
|
21
27
|
this.opening = 0;
|
|
22
28
|
/** The closes under way, by session file: out of the list already, their files locked until they end. */
|
|
23
29
|
this.closing = new Map();
|
|
30
|
+
/** Sessions opening again under their ids: the calls that come meanwhile wait for the same. */
|
|
31
|
+
this.waking = new Map();
|
|
24
32
|
}
|
|
25
|
-
|
|
26
|
-
// A
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
if (this.sessions.size + this.opening >= this.options.maxSessions) {
|
|
32
|
-
throw TaErrors.tooManySessions(this.options.maxSessions);
|
|
33
|
-
}
|
|
34
|
-
this.opening++;
|
|
35
|
-
try {
|
|
36
|
-
const session = await this.factory.create(options, ended => void this.close(ended.id));
|
|
37
|
-
this.sessions.set(session.id, session);
|
|
38
|
-
return session;
|
|
39
|
-
}
|
|
40
|
-
finally {
|
|
41
|
-
this.opening--;
|
|
33
|
+
open(options) {
|
|
34
|
+
// A file that had a session keeps its id, which pages may still have.
|
|
35
|
+
const known = options.sessionFile ? this.handles.idOf(options.sessionFile) : undefined;
|
|
36
|
+
const waking = known && this.waking.get(known);
|
|
37
|
+
if (waking) {
|
|
38
|
+
return waking;
|
|
42
39
|
}
|
|
40
|
+
return this.create(options, known && !this.sessions.has(known) ? known : undefined);
|
|
43
41
|
}
|
|
44
42
|
require(sessionId) {
|
|
45
43
|
const session = this.sessions.get(sessionId);
|
|
@@ -48,17 +46,42 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
|
|
|
48
46
|
}
|
|
49
47
|
return session;
|
|
50
48
|
}
|
|
49
|
+
resolve(sessionId) {
|
|
50
|
+
const session = this.sessions.get(sessionId);
|
|
51
|
+
if (session) {
|
|
52
|
+
return Promise.resolve(session);
|
|
53
|
+
}
|
|
54
|
+
const waking = this.waking.get(sessionId);
|
|
55
|
+
if (waking) {
|
|
56
|
+
return waking;
|
|
57
|
+
}
|
|
58
|
+
const handle = this.handles.get(sessionId);
|
|
59
|
+
if (!handle || !existsSync(handle.sessionFile)) {
|
|
60
|
+
return Promise.reject(TaErrors.sessionNotFound(sessionId));
|
|
61
|
+
}
|
|
62
|
+
const options = { cwd: handle.cwd, sessionFile: handle.sessionFile, clientTools: handle.clientTools };
|
|
63
|
+
const opening = this.create(options, sessionId).finally(() => this.waking.delete(sessionId));
|
|
64
|
+
this.waking.set(sessionId, opening);
|
|
65
|
+
return opening;
|
|
66
|
+
}
|
|
51
67
|
list() {
|
|
52
68
|
return [...this.sessions.values()];
|
|
53
69
|
}
|
|
54
|
-
async close(sessionId) {
|
|
70
|
+
async close(sessionId, idle = false) {
|
|
71
|
+
if (!idle) {
|
|
72
|
+
this.handles.delete(sessionId);
|
|
73
|
+
}
|
|
55
74
|
const session = this.sessions.get(sessionId);
|
|
56
75
|
if (!session) {
|
|
57
76
|
return;
|
|
58
77
|
}
|
|
59
78
|
this.sessions.delete(sessionId);
|
|
60
79
|
const file = session.pi.sessionFile;
|
|
61
|
-
|
|
80
|
+
if (idle && file) {
|
|
81
|
+
// The conversation it has now: pi may have moved to another file since it opened.
|
|
82
|
+
this.handles.set(sessionId, { ...this.handles.get(sessionId), sessionFile: file, cwd: session.cwd });
|
|
83
|
+
}
|
|
84
|
+
const closing = session.close(!idle);
|
|
62
85
|
if (file) {
|
|
63
86
|
this.closing.set(file, closing);
|
|
64
87
|
}
|
|
@@ -72,7 +95,7 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
|
|
|
72
95
|
}
|
|
73
96
|
}
|
|
74
97
|
async closeAll() {
|
|
75
|
-
await Promise.all([...this.sessions.keys()].map(id => this.close(id)));
|
|
98
|
+
await Promise.all([...this.sessions.keys()].map(id => this.close(id, true)));
|
|
76
99
|
}
|
|
77
100
|
/** The one channel of a connection; it leaves every session when the connection ends. */
|
|
78
101
|
channel(connection) {
|
|
@@ -89,6 +112,30 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
|
|
|
89
112
|
}
|
|
90
113
|
return channel;
|
|
91
114
|
}
|
|
115
|
+
/** `id`: the id it had, to open it again under. */
|
|
116
|
+
async create(options, id) {
|
|
117
|
+
// A conversation closed a moment ago (idle, or by another client) opens once it is closed, not refused.
|
|
118
|
+
const closing = options.sessionFile && this.closing.get(options.sessionFile);
|
|
119
|
+
if (closing) {
|
|
120
|
+
await closing.catch(() => undefined);
|
|
121
|
+
}
|
|
122
|
+
if (this.sessions.size + this.opening >= this.options.maxSessions) {
|
|
123
|
+
throw TaErrors.tooManySessions(this.options.maxSessions);
|
|
124
|
+
}
|
|
125
|
+
this.opening++;
|
|
126
|
+
try {
|
|
127
|
+
const session = await this.factory.create(options, (ended, idle) => void this.close(ended.id, idle), id);
|
|
128
|
+
this.sessions.set(session.id, session);
|
|
129
|
+
const sessionFile = session.pi.sessionFile;
|
|
130
|
+
if (sessionFile) {
|
|
131
|
+
this.handles.set(session.id, { sessionFile, cwd: session.cwd, clientTools: options.clientTools });
|
|
132
|
+
}
|
|
133
|
+
return session;
|
|
134
|
+
}
|
|
135
|
+
finally {
|
|
136
|
+
this.opening--;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
92
139
|
};
|
|
93
140
|
__decorate([
|
|
94
141
|
Value(TA_HOST_OPTIONS),
|
|
@@ -98,6 +145,10 @@ __decorate([
|
|
|
98
145
|
Autowired(TaSessionFactory),
|
|
99
146
|
__metadata("design:type", Object)
|
|
100
147
|
], DefaultTaSessionRegistry.prototype, "factory", void 0);
|
|
148
|
+
__decorate([
|
|
149
|
+
Autowired(TaSessionHandles),
|
|
150
|
+
__metadata("design:type", Object)
|
|
151
|
+
], DefaultTaSessionRegistry.prototype, "handles", void 0);
|
|
101
152
|
DefaultTaSessionRegistry = __decorate([
|
|
102
153
|
Component(TaSessionRegistry)
|
|
103
154
|
], DefaultTaSessionRegistry);
|
package/esm/node/ta-session.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SessionLock } from '@celljs/ta-harness';
|
|
2
|
-
import type { RpcExtensionUIResponse, TaAttachOptions, TaAttachResult, TaClientToolResult, TaEvent, TaMessagePage, TaNavigateResult, TaPromptInput, TaPromptReceipt, TaSessionInfo } from '@celljs/ta-protocol';
|
|
2
|
+
import type { RpcExtensionUIResponse, TaAttachOptions, TaAttachResult, TaClientToolResult, TaConversation, TaEvent, TaMessagePage, TaNavigateResult, TaPromptInput, TaPromptReceipt, TaSessionInfo } from '@celljs/ta-protocol';
|
|
3
3
|
import type { ClientChannel } from './client-channel.js';
|
|
4
4
|
import type { ClientToolBroker } from './client-tool-broker.js';
|
|
5
5
|
import { EventLog } from './event-log.js';
|
|
@@ -16,8 +16,10 @@ export interface TaSessionContext {
|
|
|
16
16
|
/** The tools of the session that its clients run. */
|
|
17
17
|
clientTools: ClientToolBroker;
|
|
18
18
|
options: TaHostOptions;
|
|
19
|
-
/** The session should end: it has been idle, or an extension asked. */
|
|
20
|
-
requestClose(session: TaSession): void;
|
|
19
|
+
/** The session should end: it has been idle (`idle`: it opens again under its id when called), or an extension asked. */
|
|
20
|
+
requestClose(session: TaSession, idle?: boolean): void;
|
|
21
|
+
/** The id it had, when it opens again (TaSessionHandles); default: a new one. */
|
|
22
|
+
id?: string;
|
|
21
23
|
/** TaOpenSessionOptions.group. */
|
|
22
24
|
group?: string;
|
|
23
25
|
/** TaOpenSessionOptions.appendSystemPrompt: kept in the session file, for when it opens again from it. */
|
|
@@ -31,7 +33,7 @@ export interface TaSessionContext {
|
|
|
31
33
|
*/
|
|
32
34
|
export declare class TaSession {
|
|
33
35
|
protected readonly context: TaSessionContext;
|
|
34
|
-
readonly id:
|
|
36
|
+
readonly id: string;
|
|
35
37
|
readonly createdAt: number;
|
|
36
38
|
readonly ui: RemoteUiContext;
|
|
37
39
|
readonly runtime: AgentSessionRuntime;
|
|
@@ -50,6 +52,8 @@ export declare class TaSession {
|
|
|
50
52
|
info(): TaSessionInfo;
|
|
51
53
|
attach(channel: ClientChannel, afterSeq?: number, options?: TaAttachOptions): TaAttachResult;
|
|
52
54
|
earlierMessages(before: number | undefined, timestamp: number | undefined, budget: number): TaMessagePage;
|
|
55
|
+
/** The conversation of the events sent, as clients get it. */
|
|
56
|
+
protected conversation(): TaConversation;
|
|
53
57
|
detach(channel: ClientChannel): void;
|
|
54
58
|
respondUi(response: RpcExtensionUIResponse): boolean;
|
|
55
59
|
/** Only a client attached runs a call: one that left would hold it for nobody. */
|
|
@@ -73,7 +77,7 @@ export declare class TaSession {
|
|
|
73
77
|
* (a tool that ignores the abort, a stream that hangs) or an extension slow to shut down is given
|
|
74
78
|
* `closeTimeoutMs`; then pi is cut off from its agent, so that nothing more goes into the file.
|
|
75
79
|
*/
|
|
76
|
-
close(): Promise<void>;
|
|
80
|
+
close(announce?: boolean): Promise<void>;
|
|
77
81
|
/** False when `work` takes longer than closeTimeoutMs. */
|
|
78
82
|
protected within(work: Promise<void>): Promise<boolean>;
|
|
79
83
|
protected accept(input: TaPromptInput, run: () => Promise<PromptDisposition>): Promise<TaPromptReceipt>;
|