@celljs/ta-host 4.9.1 → 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.
Files changed (75) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/esm/node/event-log.d.ts +2 -1
  4. package/esm/node/event-log.js +3 -2
  5. package/esm/node/exec-environment-factory.d.ts +7 -0
  6. package/esm/node/exec-environment-factory.js +30 -7
  7. package/esm/node/host-protocol.d.ts +12 -3
  8. package/esm/node/index.d.ts +1 -0
  9. package/esm/node/index.js +1 -0
  10. package/esm/node/remote/remote-hosts.d.ts +1 -3
  11. package/esm/node/remote/remote-hosts.js +0 -15
  12. package/esm/node/remote/remote-protocol.d.ts +0 -2
  13. package/esm/node/remote/remote-server-impl.js +1 -1
  14. package/esm/node/remote-ui-context.d.ts +1 -1
  15. package/esm/node/remote-ui-context.js +3 -1
  16. package/esm/node/session-catalog.js +3 -0
  17. package/esm/node/session-handles.d.ts +32 -0
  18. package/esm/node/session-handles.js +86 -0
  19. package/esm/node/session-info-util.d.ts +6 -0
  20. package/esm/node/session-info-util.js +34 -2
  21. package/esm/node/ta-access.d.ts +11 -0
  22. package/esm/node/ta-access.js +29 -3
  23. package/esm/node/ta-errors.js +17 -2
  24. package/esm/node/ta-event-util.d.ts +12 -2
  25. package/esm/node/ta-event-util.js +71 -3
  26. package/esm/node/ta-server-impl.d.ts +0 -2
  27. package/esm/node/ta-server-impl.js +9 -8
  28. package/esm/node/ta-session-factory.d.ts +10 -1
  29. package/esm/node/ta-session-factory.js +22 -2
  30. package/esm/node/ta-session-registry.d.ts +12 -1
  31. package/esm/node/ta-session-registry.js +71 -20
  32. package/esm/node/ta-session.d.ts +9 -5
  33. package/esm/node/ta-session.js +18 -10
  34. package/esm/node/workspace-files.d.ts +15 -5
  35. package/esm/node/workspace-files.js +22 -15
  36. package/esm/node/workspace-protocol.d.ts +1 -1
  37. package/esm/node/workspace-util.d.ts +2 -0
  38. package/esm/node/workspace-util.js +8 -3
  39. package/lib/node/event-log.d.ts +2 -1
  40. package/lib/node/event-log.js +3 -2
  41. package/lib/node/exec-environment-factory.d.ts +7 -0
  42. package/lib/node/exec-environment-factory.js +30 -7
  43. package/lib/node/host-protocol.d.ts +12 -3
  44. package/lib/node/index.d.ts +1 -0
  45. package/lib/node/index.js +1 -0
  46. package/lib/node/remote/remote-hosts.d.ts +1 -3
  47. package/lib/node/remote/remote-hosts.js +0 -15
  48. package/lib/node/remote/remote-protocol.d.ts +0 -2
  49. package/lib/node/remote/remote-server-impl.js +1 -1
  50. package/lib/node/remote-ui-context.d.ts +1 -1
  51. package/lib/node/remote-ui-context.js +3 -1
  52. package/lib/node/session-catalog.js +3 -0
  53. package/lib/node/session-handles.d.ts +33 -0
  54. package/lib/node/session-handles.js +89 -0
  55. package/lib/node/session-info-util.d.ts +6 -0
  56. package/lib/node/session-info-util.js +33 -1
  57. package/lib/node/ta-access.d.ts +11 -0
  58. package/lib/node/ta-access.js +29 -3
  59. package/lib/node/ta-errors.js +17 -2
  60. package/lib/node/ta-event-util.d.ts +12 -2
  61. package/lib/node/ta-event-util.js +71 -3
  62. package/lib/node/ta-server-impl.d.ts +0 -2
  63. package/lib/node/ta-server-impl.js +9 -8
  64. package/lib/node/ta-session-factory.d.ts +10 -1
  65. package/lib/node/ta-session-factory.js +23 -3
  66. package/lib/node/ta-session-registry.d.ts +12 -1
  67. package/lib/node/ta-session-registry.js +71 -20
  68. package/lib/node/ta-session.d.ts +9 -5
  69. package/lib/node/ta-session.js +18 -10
  70. package/lib/node/workspace-files.d.ts +15 -5
  71. package/lib/node/workspace-files.js +22 -15
  72. package/lib/node/workspace-protocol.d.ts +1 -1
  73. package/lib/node/workspace-util.d.ts +2 -0
  74. package/lib/node/workspace-util.js +8 -3
  75. package/package.json +12 -12
@@ -68,6 +68,27 @@ var TaAccessUtil;
68
68
  return request.method === 'POST' && path.startsWith(`${API_PATH}/`);
69
69
  }
70
70
  TaAccessUtil.isHttpCall = isHttpCall;
71
+ /**
72
+ * What starts this ta serve (`ta serve --host --port --exec`, the desktop app, the gateway) and is read
73
+ * once it listens. Left in its environment, every program of its sessions and terminals would take it: a
74
+ * `ta serve` or a Cell app run there would listen on this one's port, a Ta reached from there would take its token.
75
+ */
76
+ TaAccessUtil.SERVE_ENV = [
77
+ 'CELL_SERVER__HOST',
78
+ 'CELL_SERVER__PORT',
79
+ 'CELL_TA__EXEC__URL',
80
+ 'CELL_TA__EXEC__TOKEN',
81
+ 'TA_EXEC_TOKEN',
82
+ 'TA_SERVE_TOKEN',
83
+ 'TA_SERVE_OPEN_WEB',
84
+ ];
85
+ /** Removes {@link SERVE_ENV} from `env`, for what this process starts. */
86
+ function releaseServeEnv(env) {
87
+ for (const key of TaAccessUtil.SERVE_ENV) {
88
+ delete env[key];
89
+ }
90
+ }
91
+ TaAccessUtil.releaseServeEnv = releaseServeEnv;
71
92
  /** The token goes in the fragment, which the browser does not send to the server or in `Referer`. */
72
93
  function webUrl(httpUrl, token) {
73
94
  return `${httpUrl}/#token=${token}`;
@@ -109,6 +130,9 @@ let TaAccess = class TaAccess {
109
130
  constructor() {
110
131
  this.priority = exports.ACCESS_MIDDLEWARE_PRIORITY;
111
132
  this.token = process.env.TA_SERVE_TOKEN || serve_state_1.TaServeStateUtil.read().token || (0, node_crypto_1.randomBytes)(32).toString('base64url');
133
+ /** Read before the environment lets them go (TaAccessUtil.releaseServeEnv). */
134
+ this.chosenToken = !!process.env.TA_SERVE_TOKEN;
135
+ this.openWeb = !!process.env.TA_SERVE_OPEN_WEB;
112
136
  this.infoFile = (0, node_path_1.join)(ta_brand_1.TaBrand.agentDir(), ta_protocol_1.TA_SERVE_FILE);
113
137
  }
114
138
  allows(request) {
@@ -162,16 +186,18 @@ let TaAccess = class TaAccess {
162
186
  (0, node_fs_1.chmodSync)(this.infoFile, 0o600);
163
187
  // A token that a parent process chose is its to keep.
164
188
  const kept = serve_state_1.TaServeStateUtil.read().token;
165
- serve_state_1.TaServeStateUtil.write({ port, token: process.env.TA_SERVE_TOKEN ? kept : this.token });
189
+ serve_state_1.TaServeStateUtil.write({ port, token: this.chosenToken ? kept : this.token });
190
+ // Read: what the sessions and terminals start does not take it.
191
+ TaAccessUtil.releaseServeEnv(process.env);
166
192
  console.log(`ta serve: ${info.url} (token in ${this.infoFile})`);
167
- if (process.env.TA_SERVE_OPEN_WEB) {
193
+ if (this.openWeb) {
168
194
  const url = TaAccessUtil.webUrl(`http://${origin}`, this.token);
169
195
  console.log(`ta serve: web client at ${url}`);
170
196
  TaAccessUtil.openBrowser(url);
171
197
  }
172
198
  else if (!TaAccessUtil.isLoopbackHost(this.host)) {
173
199
  // Reached from elsewhere (a container, a server): whoever started it opens the link to sign in.
174
- for (const line of TaAccessUtil.signInLines(this.signIn, port, process.env.TA_SERVE_TOKEN ? undefined : this.token)) {
200
+ for (const line of TaAccessUtil.signInLines(this.signIn, port, this.chosenToken ? undefined : this.token)) {
175
201
  console.log(`ta serve: ${line}`);
176
202
  }
177
203
  }
@@ -8,7 +8,18 @@ const TaError = core_1.ApplicationError.declare(ta_protocol_1.TA_RPC_ERROR_CODE,
8
8
  data: { code, hint },
9
9
  }));
10
10
  /** What pi says when no provider is signed in for the model, or no model can be used. */
11
- const NOT_SIGNED_IN = /^No (API key found for|model selected|models available)\b/;
11
+ const NOT_SIGNED_IN = /^(No (API key found for|model selected|models available)|Authentication failed for)\b/;
12
+ /** What else pi says that a client words for the user by its code, as pi's messages are English. */
13
+ const KNOWN = [
14
+ { pattern: /^Nothing to compact\b/, code: ta_protocol_1.TaErrorCode.NOTHING_TO_COMPACT, hint: 'Compact once the conversation is longer.' },
15
+ { pattern: /^Already compacted$/, code: ta_protocol_1.TaErrorCode.ALREADY_COMPACTED, hint: 'Compact again once more has been said.' },
16
+ {
17
+ pattern: /^(Cannot submit a prompt while compaction is in progress|Wait for the current (response|compaction))\b/,
18
+ code: ta_protocol_1.TaErrorCode.SESSION_BUSY,
19
+ hint: 'Try again once the session is idle.',
20
+ },
21
+ { pattern: /^Compaction cancelled$/, code: ta_protocol_1.TaErrorCode.CANCELLED, hint: 'It was stopped; nothing to do.' },
22
+ ];
12
23
  /** The failures of calls of the services of ta serve ({@link TaServer} and the others), which reach the client with their message and code. */
13
24
  var TaErrors;
14
25
  (function (TaErrors) {
@@ -54,7 +65,11 @@ var TaErrors;
54
65
  const message = cause instanceof Error ? cause.message : String(cause);
55
66
  if (NOT_SIGNED_IN.test(message)) {
56
67
  // pi's own words go on about its /login and the paths of its documents, which a client does not have.
57
- return TaError(ta_protocol_1.TaErrorCode.NOT_SIGNED_IN, message.split(/\n| Use \/login/)[0].trim(), 'Sign in to a provider of models (TaAuthServer.login), then send it again.');
68
+ return TaError(ta_protocol_1.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.');
69
+ }
70
+ const known = KNOWN.find(({ pattern }) => pattern.test(message));
71
+ if (known) {
72
+ return TaError(known.code, message, known.hint);
58
73
  }
59
74
  return TaError(ta_protocol_1.TaErrorCode.COMMAND_FAILED, message, 'The message comes from the agent; fix what it says and send the command again.');
60
75
  }
@@ -1,12 +1,22 @@
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 {};
12
22
  //# sourceMappingURL=ta-event-util.d.ts.map
@@ -1,17 +1,36 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.TaEventUtil = void 0;
4
+ /** The lean form of each message and result met, made once: the pages of a conversation measure it by its object. */
5
+ const leaned = new WeakMap();
4
6
  var TaEventUtil;
5
7
  (function (TaEventUtil) {
6
8
  /**
7
9
  * 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
10
  * 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.
11
+ * the square of its length. The images of tool results go without their bytes (`leanMessage`).
10
12
  */
11
13
  function toWire(event) {
12
14
  var _a;
13
- if (event.type !== 'message_update') {
14
- return event;
15
+ switch (event.type) {
16
+ case 'message_update':
17
+ break;
18
+ case 'message_start':
19
+ case 'message_end':
20
+ return withLean(event, 'message', leanMessage(event.message));
21
+ case 'tool_execution_update':
22
+ return withLean(event, 'partialResult', leanResult(event.partialResult));
23
+ case 'tool_execution_end':
24
+ return withLean(event, 'result', leanResult(event.result));
25
+ case 'turn_end': {
26
+ const message = leanMessage(event.message);
27
+ const toolResults = leanAll(event.toolResults);
28
+ return (message === event.message && toolResults === event.toolResults ? event : { ...event, message, toolResults });
29
+ }
30
+ case 'agent_end':
31
+ return withLean(event, 'messages', leanAll(event.messages));
32
+ default:
33
+ return event;
15
34
  }
16
35
  const { partial, ...delta } = event.assistantMessageEvent;
17
36
  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;
@@ -19,5 +38,54 @@ var TaEventUtil;
19
38
  return { type: 'message_update', usage: event.message.usage, assistantMessageEvent };
20
39
  }
21
40
  TaEventUtil.toWire = toWire;
41
+ /**
42
+ * A message as clients get it: a tool's result keeps its images' kind but not their bytes (`data` is
43
+ * empty). Clients do not show them (the model reads them), and screenshots are most of the bytes of a
44
+ * conversation that has them: on a slow network a page of it would be one picture nobody sees.
45
+ */
46
+ function leanMessage(message) {
47
+ return (message === null || message === void 0 ? void 0 : message.role) === 'toolResult' ? leanResult(message) : message;
48
+ }
49
+ TaEventUtil.leanMessage = leanMessage;
50
+ /** The result of a tool, or a message of one, without the bytes of its images. */
51
+ function leanResult(result) {
52
+ const content = result === null || result === void 0 ? void 0 : result.content;
53
+ if (!result || typeof result !== 'object' || !Array.isArray(content)) {
54
+ return result;
55
+ }
56
+ const known = leaned.get(result);
57
+ if (known) {
58
+ return known;
59
+ }
60
+ const heavy = content.some(block => (block === null || block === void 0 ? void 0 : block.type) === 'image' && block.data);
61
+ const lean = heavy
62
+ ? {
63
+ ...result,
64
+ content: content.map(block => (block === null || block === void 0 ? void 0 : block.type) === 'image' ? { type: 'image', mimeType: block.mimeType, data: '' } : block),
65
+ }
66
+ : result;
67
+ leaned.set(result, lean);
68
+ return lean;
69
+ }
70
+ TaEventUtil.leanResult = leanResult;
71
+ /** A conversation as clients get it: its messages and the results of its calls lean. */
72
+ function leanConversation(conversation) {
73
+ const tools = {};
74
+ for (const [id, run] of Object.entries(conversation.tools)) {
75
+ tools[id] = run.result === undefined ? run : { ...run, result: leanResult(run.result) };
76
+ }
77
+ return { ...conversation, messages: leanAll(conversation.messages), tools };
78
+ }
79
+ TaEventUtil.leanConversation = leanConversation;
80
+ function leanAll(messages) {
81
+ if (!Array.isArray(messages)) {
82
+ return messages;
83
+ }
84
+ const lean = messages.map(leanMessage);
85
+ return lean.every((message, index) => message === messages[index]) ? messages : lean;
86
+ }
87
+ function withLean(event, key, value) {
88
+ return (value === event[key] ? event : { ...event, [key]: value });
89
+ }
22
90
  })(TaEventUtil || (exports.TaEventUtil = TaEventUtil = {}));
23
91
  //# 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';
4
- import { RemoteHosts } from './remote/remote-protocol';
5
4
  import type { TaSession } from './ta-session';
6
5
  import { TaWorkingDirectory } from './working-directory';
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>;
@@ -20,7 +20,6 @@ const ta_exec_1 = require("@celljs/ta-exec");
20
20
  const ta_brand_1 = require("@celljs/ta-harness/lib/node/ta-brand");
21
21
  const ta_protocol_1 = require("@celljs/ta-protocol");
22
22
  const host_protocol_1 = require("./host-protocol");
23
- const remote_protocol_1 = require("./remote/remote-protocol");
24
23
  const session_info_util_1 = require("./session-info-util");
25
24
  const ta_errors_1 = require("./ta-errors");
26
25
  const working_directory_1 = require("./working-directory");
@@ -41,7 +40,7 @@ let TaServerImpl = class TaServerImpl {
41
40
  async setWorkingDirectory(cwd) {
42
41
  return this.guard(async () => {
43
42
  var _a;
44
- const path = typeof cwd === 'string' && cwd.trim() ? await this.remoteHosts.resolve(cwd.trim()) : '';
43
+ const path = typeof cwd === 'string' && cwd.trim() ? await this.environments.resolve(cwd.trim()) : '';
45
44
  const env = path ? this.environments.create(path) : undefined;
46
45
  if (!env || !((_a = (await env.stat(env.cwd))) === null || _a === void 0 ? void 0 : _a.isDirectory)) {
47
46
  throw ta_errors_1.TaErrors.invalidArgument(`${cwd} is not a directory.`, 'Pass the absolute path of a directory that exists on the server, or an ssh:// location.');
@@ -72,7 +71,13 @@ let TaServerImpl = class TaServerImpl {
72
71
  return this.on(sessionId, session => session.earlierMessages(before !== null && before !== void 0 ? before : undefined, timestamp !== null && timestamp !== void 0 ? timestamp : undefined, budget));
73
72
  }
74
73
  detach(sessionId) {
75
- return this.on(sessionId, session => session.detach(this.sessions.channel(node_1.RpcContext.requireConnection())));
74
+ // Not opened again to be left: a session closed meanwhile has no client.
75
+ return this.guard(async () => {
76
+ var _a;
77
+ (_a = this.sessions
78
+ .list()
79
+ .find(session => session.id === sessionId)) === null || _a === void 0 ? void 0 : _a.detach(this.sessions.channel(node_1.RpcContext.requireConnection()));
80
+ });
76
81
  }
77
82
  respondUi(sessionId, response) {
78
83
  return this.on(sessionId, session => session.respondUi(response));
@@ -284,7 +289,7 @@ let TaServerImpl = class TaServerImpl {
284
289
  });
285
290
  }
286
291
  on(sessionId, command) {
287
- return this.guard(async () => command(this.sessions.require(sessionId)));
292
+ return this.guard(async () => command(await this.sessions.resolve(sessionId)));
288
293
  }
289
294
  guard(command) {
290
295
  return ta_errors_1.TaErrors.guard(command);
@@ -303,10 +308,6 @@ __decorate([
303
308
  (0, core_1.Autowired)(working_directory_1.TaWorkingDirectory),
304
309
  __metadata("design:type", Object)
305
310
  ], TaServerImpl.prototype, "workingDirectory", void 0);
306
- __decorate([
307
- (0, core_1.Autowired)(remote_protocol_1.RemoteHosts),
308
- __metadata("design:type", Object)
309
- ], TaServerImpl.prototype, "remoteHosts", void 0);
310
311
  __decorate([
311
312
  (0, core_1.Autowired)(host_protocol_1.TaSessionCatalog),
312
313
  __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
@@ -9,7 +9,8 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.DefaultTaSessionFactory = void 0;
12
+ exports.DefaultTaSessionFactory = exports.SessionFileUtil = void 0;
13
+ const node_fs_1 = require("node:fs");
13
14
  const node_path_1 = require("node:path");
14
15
  const ai_coding_agent_1 = require("@celljs/ai-coding-agent");
15
16
  const core_1 = require("@celljs/core");
@@ -25,13 +26,31 @@ const session_catalog_1 = require("./session-catalog");
25
26
  const session_files_1 = require("./session-files");
26
27
  const ta_errors_1 = require("./ta-errors");
27
28
  const ta_session_1 = require("./ta-session");
29
+ var SessionFileUtil;
30
+ (function (SessionFileUtil) {
31
+ /**
32
+ * The directory pi is to work in for a session file it opens: none for a file that says (pi reads it from
33
+ * its header); `cwd`, where the caller asks, for one with no header yet. pi writes a file once the agent
34
+ * first answered, so the file of a session opened and never answered (an agent made but not yet asked) is
35
+ * not there, and pi would take the directory ta serve runs in, the home directory under the desktop app.
36
+ */
37
+ function cwdOverride(sessionFile, cwd) {
38
+ try {
39
+ return (0, node_fs_1.statSync)(sessionFile).size > 0 ? undefined : cwd;
40
+ }
41
+ catch (_a) {
42
+ return cwd;
43
+ }
44
+ }
45
+ SessionFileUtil.cwdOverride = cwdOverride;
46
+ })(SessionFileUtil || (exports.SessionFileUtil = SessionFileUtil = {}));
28
47
  /** Sets up pi for each session the way its command does, with one model runtime for all of them. */
29
48
  let DefaultTaSessionFactory = class DefaultTaSessionFactory {
30
49
  constructor() {
31
50
  this.extensions = [];
32
51
  this.tools = [];
33
52
  }
34
- async create(requested, requestClose) {
53
+ async create(requested, requestClose, id) {
35
54
  var _a;
36
55
  var _b, _c, _d;
37
56
  const clientTools = new client_tool_broker_1.ClientToolBroker(requested.clientTools);
@@ -93,6 +112,7 @@ let DefaultTaSessionFactory = class DefaultTaSessionFactory {
93
112
  clientTools,
94
113
  options: this.options,
95
114
  requestClose,
115
+ id,
96
116
  group: options.group,
97
117
  role: options.appendSystemPrompt,
98
118
  locate: cwd => this.directories.fromPi(cwd),
@@ -110,7 +130,7 @@ let DefaultTaSessionFactory = class DefaultTaSessionFactory {
110
130
  return sdk.SessionManager.create(options.cwd);
111
131
  }
112
132
  try {
113
- return sdk.SessionManager.open(options.sessionFile);
133
+ return sdk.SessionManager.open(options.sessionFile, undefined, SessionFileUtil.cwdOverride(options.sessionFile, options.cwd));
114
134
  }
115
135
  catch (error) {
116
136
  throw ta_errors_1.TaErrors.invalidArgument(`Cannot open the session ${options.sessionFile}: ${error.message}`, 'Pass a session file that exists; listSessions shows the open ones.');
@@ -2,22 +2,33 @@ import type { RpcConnection } from '@celljs/rpc/lib/node';
2
2
  import type { TaOpenSessionOptions } from '@celljs/ta-protocol';
3
3
  import { ClientChannel } from './client-channel';
4
4
  import { type TaHostOptions, TaSessionFactory, TaSessionRegistry } from './host-protocol';
5
+ import { TaSessionHandles } from './session-handles';
5
6
  import type { TaSession } from './ta-session';
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
  }
23
34
  //# sourceMappingURL=ta-session-registry.d.ts.map
@@ -10,10 +10,16 @@ var __metadata = (this && this.__metadata) || function (k, v) {
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.DefaultTaSessionRegistry = void 0;
13
+ const node_fs_1 = require("node:fs");
13
14
  const core_1 = require("@celljs/core");
14
15
  const client_channel_1 = require("./client-channel");
15
16
  const host_protocol_1 = require("./host-protocol");
17
+ const session_handles_1 = require("./session-handles");
16
18
  const ta_errors_1 = require("./ta-errors");
19
+ /**
20
+ * The open sessions. A session's id outlives its memory: closed while idle or by a restart, it opens again
21
+ * from its file under the same id at the next call (TaSessionHandles), so clients never see it go.
22
+ */
17
23
  let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
18
24
  constructor() {
19
25
  this.sessions = new Map();
@@ -22,25 +28,17 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
22
28
  this.opening = 0;
23
29
  /** The closes under way, by session file: out of the list already, their files locked until they end. */
24
30
  this.closing = new Map();
31
+ /** Sessions opening again under their ids: the calls that come meanwhile wait for the same. */
32
+ this.waking = new Map();
25
33
  }
26
- async open(options) {
27
- // A conversation closed a moment ago (idle, or by another client) opens once it is closed, not refused.
28
- const closing = options.sessionFile && this.closing.get(options.sessionFile);
29
- if (closing) {
30
- await closing.catch(() => undefined);
31
- }
32
- if (this.sessions.size + this.opening >= this.options.maxSessions) {
33
- throw ta_errors_1.TaErrors.tooManySessions(this.options.maxSessions);
34
- }
35
- this.opening++;
36
- try {
37
- const session = await this.factory.create(options, ended => void this.close(ended.id));
38
- this.sessions.set(session.id, session);
39
- return session;
40
- }
41
- finally {
42
- this.opening--;
34
+ open(options) {
35
+ // A file that had a session keeps its id, which pages may still have.
36
+ const known = options.sessionFile ? this.handles.idOf(options.sessionFile) : undefined;
37
+ const waking = known && this.waking.get(known);
38
+ if (waking) {
39
+ return waking;
43
40
  }
41
+ return this.create(options, known && !this.sessions.has(known) ? known : undefined);
44
42
  }
45
43
  require(sessionId) {
46
44
  const session = this.sessions.get(sessionId);
@@ -49,17 +47,42 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
49
47
  }
50
48
  return session;
51
49
  }
50
+ resolve(sessionId) {
51
+ const session = this.sessions.get(sessionId);
52
+ if (session) {
53
+ return Promise.resolve(session);
54
+ }
55
+ const waking = this.waking.get(sessionId);
56
+ if (waking) {
57
+ return waking;
58
+ }
59
+ const handle = this.handles.get(sessionId);
60
+ if (!handle || !(0, node_fs_1.existsSync)(handle.sessionFile)) {
61
+ return Promise.reject(ta_errors_1.TaErrors.sessionNotFound(sessionId));
62
+ }
63
+ const options = { cwd: handle.cwd, sessionFile: handle.sessionFile, clientTools: handle.clientTools };
64
+ const opening = this.create(options, sessionId).finally(() => this.waking.delete(sessionId));
65
+ this.waking.set(sessionId, opening);
66
+ return opening;
67
+ }
52
68
  list() {
53
69
  return [...this.sessions.values()];
54
70
  }
55
- async close(sessionId) {
71
+ async close(sessionId, idle = false) {
72
+ if (!idle) {
73
+ this.handles.delete(sessionId);
74
+ }
56
75
  const session = this.sessions.get(sessionId);
57
76
  if (!session) {
58
77
  return;
59
78
  }
60
79
  this.sessions.delete(sessionId);
61
80
  const file = session.pi.sessionFile;
62
- const closing = session.close();
81
+ if (idle && file) {
82
+ // The conversation it has now: pi may have moved to another file since it opened.
83
+ this.handles.set(sessionId, { ...this.handles.get(sessionId), sessionFile: file, cwd: session.cwd });
84
+ }
85
+ const closing = session.close(!idle);
63
86
  if (file) {
64
87
  this.closing.set(file, closing);
65
88
  }
@@ -73,7 +96,7 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
73
96
  }
74
97
  }
75
98
  async closeAll() {
76
- await Promise.all([...this.sessions.keys()].map(id => this.close(id)));
99
+ await Promise.all([...this.sessions.keys()].map(id => this.close(id, true)));
77
100
  }
78
101
  /** The one channel of a connection; it leaves every session when the connection ends. */
79
102
  channel(connection) {
@@ -90,6 +113,30 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
90
113
  }
91
114
  return channel;
92
115
  }
116
+ /** `id`: the id it had, to open it again under. */
117
+ async create(options, id) {
118
+ // A conversation closed a moment ago (idle, or by another client) opens once it is closed, not refused.
119
+ const closing = options.sessionFile && this.closing.get(options.sessionFile);
120
+ if (closing) {
121
+ await closing.catch(() => undefined);
122
+ }
123
+ if (this.sessions.size + this.opening >= this.options.maxSessions) {
124
+ throw ta_errors_1.TaErrors.tooManySessions(this.options.maxSessions);
125
+ }
126
+ this.opening++;
127
+ try {
128
+ const session = await this.factory.create(options, (ended, idle) => void this.close(ended.id, idle), id);
129
+ this.sessions.set(session.id, session);
130
+ const sessionFile = session.pi.sessionFile;
131
+ if (sessionFile) {
132
+ this.handles.set(session.id, { sessionFile, cwd: session.cwd, clientTools: options.clientTools });
133
+ }
134
+ return session;
135
+ }
136
+ finally {
137
+ this.opening--;
138
+ }
139
+ }
93
140
  };
94
141
  exports.DefaultTaSessionRegistry = DefaultTaSessionRegistry;
95
142
  __decorate([
@@ -100,6 +147,10 @@ __decorate([
100
147
  (0, core_1.Autowired)(host_protocol_1.TaSessionFactory),
101
148
  __metadata("design:type", Object)
102
149
  ], DefaultTaSessionRegistry.prototype, "factory", void 0);
150
+ __decorate([
151
+ (0, core_1.Autowired)(session_handles_1.TaSessionHandles),
152
+ __metadata("design:type", Object)
153
+ ], DefaultTaSessionRegistry.prototype, "handles", void 0);
103
154
  exports.DefaultTaSessionRegistry = DefaultTaSessionRegistry = __decorate([
104
155
  (0, core_1.Component)(host_protocol_1.TaSessionRegistry)
105
156
  ], DefaultTaSessionRegistry);
@@ -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';
4
4
  import type { ClientToolBroker } from './client-tool-broker';
5
5
  import { EventLog } from './event-log';
@@ -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: `${string}-${string}-${string}-${string}-${string}`;
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>;