@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.
Files changed (79) 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 +14 -5
  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.d.ts +1 -1
  17. package/esm/node/session-catalog.js +8 -3
  18. package/esm/node/session-handles.d.ts +32 -0
  19. package/esm/node/session-handles.js +86 -0
  20. package/esm/node/session-info-util.d.ts +6 -0
  21. package/esm/node/session-info-util.js +34 -2
  22. package/esm/node/sign-in/sign-in-pages.js +7 -1
  23. package/esm/node/ta-access.d.ts +11 -0
  24. package/esm/node/ta-access.js +29 -3
  25. package/esm/node/ta-errors.js +17 -2
  26. package/esm/node/ta-event-util.d.ts +12 -2
  27. package/esm/node/ta-event-util.js +71 -3
  28. package/esm/node/ta-server-impl.d.ts +0 -2
  29. package/esm/node/ta-server-impl.js +11 -10
  30. package/esm/node/ta-session-factory.d.ts +10 -1
  31. package/esm/node/ta-session-factory.js +22 -2
  32. package/esm/node/ta-session-registry.d.ts +12 -1
  33. package/esm/node/ta-session-registry.js +71 -20
  34. package/esm/node/ta-session.d.ts +9 -5
  35. package/esm/node/ta-session.js +18 -10
  36. package/esm/node/workspace-files.d.ts +15 -5
  37. package/esm/node/workspace-files.js +22 -15
  38. package/esm/node/workspace-protocol.d.ts +1 -1
  39. package/esm/node/workspace-util.d.ts +2 -0
  40. package/esm/node/workspace-util.js +8 -3
  41. package/lib/node/event-log.d.ts +2 -1
  42. package/lib/node/event-log.js +3 -2
  43. package/lib/node/exec-environment-factory.d.ts +7 -0
  44. package/lib/node/exec-environment-factory.js +30 -7
  45. package/lib/node/host-protocol.d.ts +14 -5
  46. package/lib/node/index.d.ts +1 -0
  47. package/lib/node/index.js +1 -0
  48. package/lib/node/remote/remote-hosts.d.ts +1 -3
  49. package/lib/node/remote/remote-hosts.js +0 -15
  50. package/lib/node/remote/remote-protocol.d.ts +0 -2
  51. package/lib/node/remote/remote-server-impl.js +1 -1
  52. package/lib/node/remote-ui-context.d.ts +1 -1
  53. package/lib/node/remote-ui-context.js +3 -1
  54. package/lib/node/session-catalog.d.ts +1 -1
  55. package/lib/node/session-catalog.js +8 -3
  56. package/lib/node/session-handles.d.ts +33 -0
  57. package/lib/node/session-handles.js +89 -0
  58. package/lib/node/session-info-util.d.ts +6 -0
  59. package/lib/node/session-info-util.js +33 -1
  60. package/lib/node/sign-in/sign-in-pages.js +7 -1
  61. package/lib/node/ta-access.d.ts +11 -0
  62. package/lib/node/ta-access.js +29 -3
  63. package/lib/node/ta-errors.js +17 -2
  64. package/lib/node/ta-event-util.d.ts +12 -2
  65. package/lib/node/ta-event-util.js +71 -3
  66. package/lib/node/ta-server-impl.d.ts +0 -2
  67. package/lib/node/ta-server-impl.js +11 -10
  68. package/lib/node/ta-session-factory.d.ts +10 -1
  69. package/lib/node/ta-session-factory.js +23 -3
  70. package/lib/node/ta-session-registry.d.ts +12 -1
  71. package/lib/node/ta-session-registry.js +71 -20
  72. package/lib/node/ta-session.d.ts +9 -5
  73. package/lib/node/ta-session.js +18 -10
  74. package/lib/node/workspace-files.d.ts +15 -5
  75. package/lib/node/workspace-files.js +22 -15
  76. package/lib/node/workspace-protocol.d.ts +1 -1
  77. package/lib/node/workspace-util.d.ts +2 -0
  78. package/lib/node/workspace-util.js +8 -3
  79. package/package.json +12 -12
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.TaSessionHandlesImpl = exports.TaSessionHandles = void 0;
10
+ const node_fs_1 = require("node:fs");
11
+ const node_path_1 = require("node:path");
12
+ const core_1 = require("@celljs/core");
13
+ const ta_brand_1 = require("@celljs/ta-harness/lib/node/ta-brand");
14
+ exports.TaSessionHandles = Symbol('TaSessionHandles');
15
+ /** Handles kept: the latest ones, as a client that slept longer has the conversation in its list again. */
16
+ const MAX_HANDLES = 200;
17
+ /** In ta-sessions.json of the agent directory, the latest last; kept across restarts. */
18
+ let TaSessionHandlesImpl = class TaSessionHandlesImpl {
19
+ constructor() {
20
+ this.file = (0, node_path_1.join)(ta_brand_1.TaBrand.agentDir(), 'ta-sessions.json');
21
+ }
22
+ get(sessionId) {
23
+ return this.read().get(sessionId);
24
+ }
25
+ idOf(sessionFile) {
26
+ for (const [id, handle] of this.read()) {
27
+ if (handle.sessionFile === sessionFile) {
28
+ return id;
29
+ }
30
+ }
31
+ return undefined;
32
+ }
33
+ set(sessionId, handle) {
34
+ const handles = this.read();
35
+ // One id per file: the file opened under another is reached by that one.
36
+ for (const [id, other] of handles) {
37
+ if (id !== sessionId && other.sessionFile === handle.sessionFile) {
38
+ handles.delete(id);
39
+ }
40
+ }
41
+ handles.delete(sessionId);
42
+ handles.set(sessionId, handle);
43
+ for (const id of handles.keys()) {
44
+ if (handles.size <= MAX_HANDLES) {
45
+ break;
46
+ }
47
+ handles.delete(id);
48
+ }
49
+ this.write(handles);
50
+ }
51
+ delete(sessionId) {
52
+ const handles = this.read();
53
+ if (handles.delete(sessionId)) {
54
+ this.write(handles);
55
+ }
56
+ }
57
+ read() {
58
+ if (!this.cache) {
59
+ this.cache = new Map();
60
+ try {
61
+ const data = JSON.parse((0, node_fs_1.readFileSync)(this.file, 'utf8'));
62
+ for (const [id, handle] of Object.entries(data && typeof data === 'object' && !Array.isArray(data) ? data : {})) {
63
+ const { sessionFile, cwd } = (handle !== null && handle !== void 0 ? handle : {});
64
+ if (typeof sessionFile === 'string' && typeof cwd === 'string') {
65
+ this.cache.set(id, handle);
66
+ }
67
+ }
68
+ }
69
+ catch (_a) {
70
+ // None yet, or not readable: no handles.
71
+ }
72
+ }
73
+ return this.cache;
74
+ }
75
+ write(handles) {
76
+ try {
77
+ (0, node_fs_1.writeFileSync)(`${this.file}.tmp`, `${JSON.stringify(Object.fromEntries(handles))}\n`, { mode: 0o600 });
78
+ (0, node_fs_1.renameSync)(`${this.file}.tmp`, this.file);
79
+ }
80
+ catch (_a) {
81
+ // Kept in memory: only a restart forgets them.
82
+ }
83
+ }
84
+ };
85
+ exports.TaSessionHandlesImpl = TaSessionHandlesImpl;
86
+ exports.TaSessionHandlesImpl = TaSessionHandlesImpl = __decorate([
87
+ (0, core_1.Component)(exports.TaSessionHandles)
88
+ ], TaSessionHandlesImpl);
89
+ //# sourceMappingURL=session-handles.js.map
@@ -11,6 +11,12 @@ export declare namespace SessionInfoUtil {
11
11
  * a skill the user ran is `/skill:name` and what follows, not the skill's file.
12
12
  */
13
13
  function firstMessage(messages: readonly MessageLike[]): string | undefined;
14
+ /**
15
+ * The text of the last message of the user or the agent that has some, on one line and cut to a preview's
16
+ * length, as a messaging app shows the last thing said under its name: without its context, the marks of
17
+ * markdown at the start of its lines, and the thinking and tool calls of the agent.
18
+ */
19
+ function lastMessage(messages: readonly MessageLike[]): string | undefined;
14
20
  /** The time of the last message that has one, else `fallback`. */
15
21
  function updatedAt(messages: readonly MessageLike[], fallback: number): number;
16
22
  /** The text of the content of a message. */
@@ -6,6 +6,8 @@ const ta_protocol_1 = require("@celljs/ta-protocol");
6
6
  var SessionInfoUtil;
7
7
  (function (SessionInfoUtil) {
8
8
  const LENGTH = 120;
9
+ /** Of the text of the last message, what lastMessage reads: its lines are joined, many of them empty or marks only. */
10
+ const PREVIEW_READ = 2000;
9
11
  /**
10
12
  * The first line of the first message of the user that has text, without its context, cut to a title's length;
11
13
  * a skill the user ran is `/skill:name` and what follows, not the skill's file.
@@ -15,7 +17,7 @@ var SessionInfoUtil;
15
17
  if (message.role !== 'user') {
16
18
  continue;
17
19
  }
18
- const said = ta_protocol_1.TaMessageContext.strip(text(message.content));
20
+ const said = ta_protocol_1.TaImageNote.strip(ta_protocol_1.TaMessageContext.strip(text(message.content)));
19
21
  const skill = ta_protocol_1.TaSkillUse.parse(said);
20
22
  const line = (skill ? ta_protocol_1.TaSkillUse.command(skill) : said)
21
23
  .split('\n')
@@ -28,6 +30,36 @@ var SessionInfoUtil;
28
30
  return undefined;
29
31
  }
30
32
  SessionInfoUtil.firstMessage = firstMessage;
33
+ /**
34
+ * The text of the last message of the user or the agent that has some, on one line and cut to a preview's
35
+ * length, as a messaging app shows the last thing said under its name: without its context, the marks of
36
+ * markdown at the start of its lines, and the thinking and tool calls of the agent.
37
+ */
38
+ function lastMessage(messages) {
39
+ for (let i = messages.length - 1; i >= 0; i--) {
40
+ const message = messages[i];
41
+ if (message.role !== 'user' && message.role !== 'assistant') {
42
+ continue;
43
+ }
44
+ const said = message.role === 'user' ? ta_protocol_1.TaImageNote.strip(ta_protocol_1.TaMessageContext.strip(text(message.content))) : ta_protocol_1.TaAgentSummary.strip(text(message.content));
45
+ // A list asks for it every few seconds: only the start of a long reply is read, enough for a preview.
46
+ const line = said
47
+ .slice(0, PREVIEW_READ)
48
+ .split('\n')
49
+ .map(part => part
50
+ .replace(/^\s*(?:#{1,6}\s+|>\s*|[-*+]\s+|\d+\.\s+)/, '')
51
+ .replace(/[*_`]{1,3}/g, '')
52
+ .trim())
53
+ .filter(Boolean)
54
+ .join(' ')
55
+ .replace(/\s+/g, ' ');
56
+ if (line) {
57
+ return line.length > LENGTH ? `${line.slice(0, LENGTH - 1)}…` : line;
58
+ }
59
+ }
60
+ return undefined;
61
+ }
62
+ SessionInfoUtil.lastMessage = lastMessage;
31
63
  /** The time of the last message that has one, else `fallback`. */
32
64
  function updatedAt(messages, fallback) {
33
65
  for (let i = messages.length - 1; i >= 0; i--) {
@@ -11,7 +11,13 @@ var SignInPageUtil;
11
11
  for (const part of (header !== null && header !== void 0 ? header : '').split(';')) {
12
12
  const [key, ...value] = part.trim().split('=');
13
13
  if (key === name) {
14
- return decodeURIComponent(value.join('='));
14
+ try {
15
+ return decodeURIComponent(value.join('='));
16
+ }
17
+ catch (_a) {
18
+ // Not one of ours: a browser or a page sent it broken.
19
+ return undefined;
20
+ }
15
21
  }
16
22
  }
17
23
  return undefined;
@@ -21,6 +21,14 @@ export declare namespace TaAccessUtil {
21
21
  * calls on its WebSocket only, where a call knows its connection (attach, terminals) and gets pushes.
22
22
  */
23
23
  function isHttpCall(request: IncomingMessage): boolean;
24
+ /**
25
+ * What starts this ta serve (`ta serve --host --port --exec`, the desktop app, the gateway) and is read
26
+ * once it listens. Left in its environment, every program of its sessions and terminals would take it: a
27
+ * `ta serve` or a Cell app run there would listen on this one's port, a Ta reached from there would take its token.
28
+ */
29
+ const SERVE_ENV: string[];
30
+ /** Removes {@link SERVE_ENV} from `env`, for what this process starts. */
31
+ function releaseServeEnv(env: NodeJS.ProcessEnv): void;
24
32
  /** The token goes in the fragment, which the browser does not send to the server or in `Referer`. */
25
33
  function webUrl(httpUrl: string, token: string): string;
26
34
  /**
@@ -40,6 +48,9 @@ export declare namespace TaAccessUtil {
40
48
  export declare class TaAccess implements RpcWebSocketGuard, Middleware, ServerAware, ApplicationLifecycle<Application> {
41
49
  readonly priority = 10000;
42
50
  readonly token: string;
51
+ /** Read before the environment lets them go (TaAccessUtil.releaseServeEnv). */
52
+ protected readonly chosenToken: boolean;
53
+ protected readonly openWeb: boolean;
43
54
  protected readonly host?: string;
44
55
  protected readonly sessions: TaSessionRegistry;
45
56
  protected readonly signIn: TaSignIn;
@@ -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.');
@@ -61,8 +60,8 @@ let TaServerImpl = class TaServerImpl {
61
60
  }
62
61
  listSavedSessions() {
63
62
  return this.guard(async () => {
64
- const open = new Set(this.sessions.list().map(session => session.pi.sessionFile));
65
- return (await this.catalog.list()).filter(session => !open.has(session.sessionFile));
63
+ const open = new Set(this.sessions.list().flatMap(session => { var _a; return (_a = session.pi.sessionFile) !== null && _a !== void 0 ? _a : []; }));
64
+ return this.catalog.list(open);
66
65
  });
67
66
  }
68
67
  attach(sessionId, afterSeq, options) {
@@ -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