@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
package/README.en.md CHANGED
@@ -13,7 +13,7 @@ The server-side component of `ta serve`. It is functionally equivalent to Codex'
13
13
  | `TaAuthServerImpl` | `@Rpc(TaAuthServer)`: runs pi's `/login` flow on the server (OAuth login page, device code, or API key). It sends only the page to open and fields for the user to fill to the initiating connection (`TaClient.onAuthEvent`); the user's answer is sent back via `answer`. The `logout` method deletes stored credentials. Credentials are written to the server-side pi's `auth.json` and shared across all sessions; they are never sent back to the client. |
14
14
  | `RelayBridge` | `@Rpc(TaRelayServer)`: reads `relay.json` from the agent directory. When paired devices exist, it connects to Relay and opens a connection to `/api/ws` on this machine for each device (see [@celljs/ta-relay](../ta-relay/README.md)). The `pair` and `unpair` commands work the same as `ta pair`. If no Relay is provided, it uses `https://relay.cellbang.com`. |
15
15
  | `TaWorkingDirectory` | The working directory set by `setWorkingDirectory`, recorded in `ta.json` in the agent directory (`workingDirectory`), persists across restarts. Open sessions are unaffected. |
16
- | `TaSessionRegistry` | Manages open sessions. Rejects requests when exceeding `maxSessions`, closes sessions that are idle (no clients, not running, no pending dialogs) for longer than `idleTimeoutMs`. Session files are retained. |
16
+ | `TaSessionRegistry` | Manages open sessions. Rejects requests when exceeding `maxSessions`, closes sessions that are idle (no clients, not running, no pending dialogs) for longer than `idleTimeoutMs`. Session files are retained. A session closed while idle or by a restart of ta serve keeps its id (`TaSessionHandles`, `ta-sessions.json` in the agent directory, the latest 200): the next call with that id opens it again from its file, so clients never notice it closed; only `closeSession`, an extension ending the session, or a deleted session file give `CELL_TA_SESSION_NOT_FOUND`. |
17
17
  | `TaSessionFactory` | Assembles sessions the same way the pi command does: project trust, settings, extensions, themes. All sessions share one model runtime. Opened again from its file alone, a session keeps the role (`ta-role`) and group (`ta-group`) written in it. Can be replaced by `rebind`. |
18
18
  | `TaSession` | One open session: event log, acknowledgments, connected clients. After `newSession`/`fork`/`switchSession` the id remains unchanged and broadcasts `session_replaced`. The `navigateTree` command (pi's `/tree`) also broadcasts when switching branches within the same session. |
19
19
  | `RemoteUiContext` | The pi extension's `ctx.ui`: dialogs are broadcast to all clients. The first response takes effect; if timed out, the default value from the extension is used. |
package/README.md CHANGED
@@ -13,7 +13,7 @@
13
13
  | `TaAuthServerImpl` | `@Rpc(TaAuthServer)`:在服务端跑 pi 的 `/login` 流程(OAuth 的登录页或设备码,或 API Key),把要打开的页面、要用户填的内容只发给发起登录的连接(`TaClient.onAuthEvent`),用户的回答用 `answer` 送回;`logout` 删掉存下的凭据。凭据写进服务端 pi 的 `auth.json`,所有会话共用,不会发回客户端 |
14
14
  | `RelayBridge` | `@Rpc(TaRelayServer)`:读 agent 目录的 `relay.json`,有配对的设备时连上 Relay,并替每台设备开一条到本机 `/api/ws` 的连接(见 [@celljs/ta-relay](../ta-relay/README.md));`pair` / `unpair` 与 `ta pair` 相同,没给 Relay 时用 `https://relay.cellbang.com` |
15
15
  | `TaWorkingDirectory` | `setWorkingDirectory` 设的工作目录,记在 agent 目录的 `ta.json`(`workingDirectory`),跨重启保留;已经打开的会话不受影响 |
16
- | `TaSessionRegistry` | 打开的会话;超过 `maxSessions` 拒绝,空闲(无客户端、无运行、无待答对话框)超过 `idleTimeoutMs` 关闭,会话文件保留 |
16
+ | `TaSessionRegistry` | 打开的会话;超过 `maxSessions` 拒绝,空闲(无客户端、无运行、无待答对话框)超过 `idleTimeoutMs` 关闭,会话文件保留;空闲关闭或 ta serve 重启关掉的会话保留原 id(`TaSessionHandles`,存在 agent 目录的 `ta-sessions.json`,最近 200 个),下次有调用用这个 id 时从会话文件原样重新打开,客户端感觉不到它关过;只有 `closeSession`、扩展结束会话或会话文件已删时才回 `CELL_TA_SESSION_NOT_FOUND` |
17
17
  | `TaSessionFactory` | 像 pi 命令那样装配会话:项目信任、设置、扩展、主题;所有会话共用一个模型运行时。只按会话文件重新打开时,沿用文件里记下的角色(`ta-role`)和分组(`ta-group`)。可 `rebind` 替换 |
18
18
  | `TaSession` | 一个打开的会话:事件日志、回执、已连接的客户端;`newSession`/`fork`/`switchSession` 后 id 不变,并发 `session_replaced`;`navigateTree`(pi 的 `/tree`)在同一会话里换分支后也发 |
19
19
  | `RemoteUiContext` | pi 扩展的 `ctx.ui`:对话框广播给所有客户端,第一个回答生效,超时按扩展给的默认值 |
@@ -15,7 +15,8 @@ export declare class EventLog {
15
15
  protected head: number;
16
16
  protected bytes: number;
17
17
  protected seq: number;
18
- constructor(sessionId: string, maxBytes: number);
18
+ /** `firstSeq`: the seq before the first event; a session opened again under its id starts past those its clients saw. */
19
+ constructor(sessionId: string, maxBytes: number, firstSeq?: number);
19
20
  get lastSeq(): number;
20
21
  append(event: TaEvent): LoggedEvent;
21
22
  /** The events after `afterSeq`; `gap` when some of them are gone. */
@@ -3,13 +3,14 @@
3
3
  * what happened is in the session file, and a client that fell further behind reads it again.
4
4
  */
5
5
  export class EventLog {
6
- constructor(sessionId, maxBytes) {
6
+ /** `firstSeq`: the seq before the first event; a session opened again under its id starts past those its clients saw. */
7
+ constructor(sessionId, maxBytes, firstSeq = 0) {
7
8
  this.sessionId = sessionId;
8
9
  this.maxBytes = maxBytes;
9
10
  this.entries = [];
10
11
  this.head = 0;
11
12
  this.bytes = 0;
12
- this.seq = 0;
13
+ this.seq = firstSeq;
13
14
  }
14
15
  get lastSeq() {
15
16
  return this.seq;
@@ -1,4 +1,5 @@
1
1
  import { ExecClient, type ExecEnvironment, ExecEnvironmentFactory } from '@celljs/ta-exec';
2
+ import { TaLocation } from '@celljs/ta-protocol';
2
3
  import { type TaExecOptions } from './host-protocol.js';
3
4
  import { RemoteHosts } from './remote/remote-protocol.js';
4
5
  import { TaWorkingDirectory } from './working-directory.js';
@@ -15,7 +16,13 @@ export declare class DefaultExecEnvironmentFactory implements ExecEnvironmentFac
15
16
  protected client?: ExecClient;
16
17
  /** Its `cwd` is the path there: the one to resolve paths against, not the location. */
17
18
  create(location: string): ExecEnvironment;
19
+ /**
20
+ * A location as the user wrote it, whole: `~` is the home directory of its machine (where ssh starts
21
+ * there, and where the exec server started), and a relative path is under the default directory.
22
+ */
23
+ resolve(location: string): Promise<string>;
18
24
  /** The working directory the user chose, else that of this process, or of the exec server. */
19
25
  defaultCwd(): Promise<string>;
26
+ protected parse(location: string): TaLocation.Remote | undefined;
20
27
  protected remote(): ExecClient | undefined;
21
28
  }
@@ -7,6 +7,8 @@ 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 { homedir } from 'node:os';
11
+ import { posix, win32 } from 'node:path';
10
12
  import { Autowired, Component, Optional, Value } from '@celljs/core';
11
13
  import { ExecClient, ExecEnvironmentFactory, LocalExecEnvironment, RemoteExecEnvironment } from '@celljs/ta-exec';
12
14
  import { TaLocation } from '@celljs/ta-protocol';
@@ -23,13 +25,7 @@ import { TaWorkingDirectory } from './working-directory.js';
23
25
  let DefaultExecEnvironmentFactory = class DefaultExecEnvironmentFactory {
24
26
  /** Its `cwd` is the path there: the one to resolve paths against, not the location. */
25
27
  create(location) {
26
- let remote;
27
- try {
28
- remote = TaLocation.parse(location);
29
- }
30
- catch (error) {
31
- throw TaErrors.invalidArgument(error.message, 'Write ssh://<host>/<absolute path>.');
32
- }
28
+ const remote = this.parse(location);
33
29
  if (remote) {
34
30
  if (!remote.path) {
35
31
  throw TaErrors.invalidArgument(`${location} names no directory.`, 'Resolve it first (TaRemoteServer.resolveLocation), or write its path.');
@@ -39,6 +35,25 @@ let DefaultExecEnvironmentFactory = class DefaultExecEnvironmentFactory {
39
35
  const client = this.remote();
40
36
  return client ? new RemoteExecEnvironment(client, location) : new LocalExecEnvironment(location);
41
37
  }
38
+ /**
39
+ * A location as the user wrote it, whole: `~` is the home directory of its machine (where ssh starts
40
+ * there, and where the exec server started), and a relative path is under the default directory.
41
+ */
42
+ async resolve(location) {
43
+ var _a;
44
+ var _b;
45
+ const remote = this.parse(location);
46
+ const home = TaLocation.homeRelative(location);
47
+ if (remote) {
48
+ return home === undefined ? location : TaLocation.ssh(remote.host, posix.join((await this.remoteHosts.client(remote.host).info()).cwd, home));
49
+ }
50
+ const info = await ((_a = this.remote()) === null || _a === void 0 ? void 0 : _a.info());
51
+ const path = ((_b = info === null || info === void 0 ? void 0 : info.platform) !== null && _b !== void 0 ? _b : process.platform) === 'win32' ? win32 : posix;
52
+ if (home !== undefined) {
53
+ return path.join(info ? info.cwd : homedir(), home);
54
+ }
55
+ return path.isAbsolute(location) ? location : path.resolve(await this.defaultCwd(), location);
56
+ }
42
57
  /** The working directory the user chose, else that of this process, or of the exec server. */
43
58
  async defaultCwd() {
44
59
  var _a;
@@ -49,6 +64,14 @@ let DefaultExecEnvironmentFactory = class DefaultExecEnvironmentFactory {
49
64
  const client = this.remote();
50
65
  return client ? (await client.info()).cwd : process.cwd();
51
66
  }
67
+ parse(location) {
68
+ try {
69
+ return TaLocation.parse(location);
70
+ }
71
+ catch (error) {
72
+ throw TaErrors.invalidArgument(error.message, 'Write ssh://<host>/<absolute path>.');
73
+ }
74
+ }
52
75
  remote() {
53
76
  var _a, _b;
54
77
  const { url, token = '', epoch } = (_a = this.options) !== null && _a !== void 0 ? _a : {};
@@ -26,15 +26,24 @@ export interface TaExecOptions {
26
26
  epoch?: number;
27
27
  }
28
28
  export interface TaSessionFactory {
29
- create(options: TaOpenSessionOptions, requestClose: (session: TaSession) => void): Promise<TaSession>;
29
+ /** `id`: the id the session had, when it opens again under it. */
30
+ create(options: TaOpenSessionOptions, requestClose: (session: TaSession, idle?: boolean) => void, id?: string): Promise<TaSession>;
30
31
  }
31
32
  /** The open sessions. */
32
33
  export interface TaSessionRegistry {
33
34
  open(options: TaOpenSessionOptions): Promise<TaSession>;
34
- /** Throws CELL_TA_SESSION_NOT_FOUND. */
35
+ /** An open session; throws CELL_TA_SESSION_NOT_FOUND. */
35
36
  require(sessionId: string): TaSession;
37
+ /**
38
+ * A session by its id, opened again from its file under that id when the service closed it while idle or
39
+ * by a restart (TaSessionHandles); throws CELL_TA_SESSION_NOT_FOUND when it was closed for good or its
40
+ * file is gone.
41
+ */
42
+ resolve(sessionId: string): Promise<TaSession>;
36
43
  list(): TaSession[];
37
- close(sessionId: string): Promise<void>;
44
+ /** `idle`: closed to save its memory (idle, or the service stops), it keeps its id and opens again when called; otherwise for good. */
45
+ close(sessionId: string, idle?: boolean): Promise<void>;
46
+ /** As the service stops: each keeps its id, and opens again when called after the restart. */
38
47
  closeAll(): Promise<void>;
39
48
  channel(connection: RpcConnection): ClientChannel;
40
49
  }
@@ -16,6 +16,7 @@ export * from './remote/index.js';
16
16
  export * from './remote-ui-context.js';
17
17
  export * from './session-catalog.js';
18
18
  export * from './session-files.js';
19
+ export * from './session-handles.js';
19
20
  export * from './session-info-util.js';
20
21
  export * from './session-storage/index.js';
21
22
  export * from './settings-server-impl.js';
package/esm/node/index.js CHANGED
@@ -16,6 +16,7 @@ export * from './remote/index.js';
16
16
  export * from './remote-ui-context.js';
17
17
  export * from './session-catalog.js';
18
18
  export * from './session-files.js';
19
+ export * from './session-handles.js';
19
20
  export * from './session-info-util.js';
20
21
  export * from './session-storage/index.js';
21
22
  export * from './settings-server-impl.js';
@@ -2,7 +2,7 @@ import { type CodingAgentOptions } from '@celljs/ai-coding-agent';
2
2
  import { type Application, ApplicationLifecycle } from '@celljs/core';
3
3
  import type { RpcConnection } from '@celljs/rpc/lib/node';
4
4
  import { type ExecClient, SshHost, type SshQuestion } from '@celljs/ta-exec';
5
- import { TaLocation, type TaRemoteEvent, type TaRemoteHost, type TaRemotePrompt } from '@celljs/ta-protocol';
5
+ import { type TaRemoteEvent, type TaRemoteHost, type TaRemotePrompt } from '@celljs/ta-protocol';
6
6
  import { TaWorkingDirectory } from '../working-directory.js';
7
7
  import { RemoteHosts, type TaRemoteOptions } from './remote-protocol.js';
8
8
  interface Waiting {
@@ -25,7 +25,6 @@ export declare class DefaultRemoteHosts implements RemoteHosts, ApplicationLifec
25
25
  list(): TaRemoteHost[];
26
26
  add(host: string): void;
27
27
  remove(host: string): Promise<void>;
28
- resolve(location: string): Promise<string>;
29
28
  disconnect(host: string): Promise<void>;
30
29
  onDisconnect(listener: (host: string) => void): () => void;
31
30
  watch(connection: RpcConnection): TaRemotePrompt[];
@@ -35,6 +34,5 @@ export declare class DefaultRemoteHosts implements RemoteHosts, ApplicationLifec
35
34
  protected broadcast(event: TaRemoteEvent): void;
36
35
  protected check(host: string): string;
37
36
  protected connected(host: string): boolean;
38
- protected parse(location: string): TaLocation.Remote | undefined;
39
37
  }
40
38
  export {};
@@ -69,13 +69,6 @@ let DefaultRemoteHosts = class DefaultRemoteHosts {
69
69
  await this.disconnect(host);
70
70
  this.workingDirectory.removeRecentHost(host);
71
71
  }
72
- async resolve(location) {
73
- const remote = this.parse(location);
74
- if (!remote || remote.path) {
75
- return location;
76
- }
77
- return TaLocation.ssh(remote.host, (await this.client(remote.host).info()).cwd);
78
- }
79
72
  async disconnect(host) {
80
73
  const ssh = this.hosts.get(host);
81
74
  this.hosts.delete(host);
@@ -142,14 +135,6 @@ let DefaultRemoteHosts = class DefaultRemoteHosts {
142
135
  var _b;
143
136
  return (_b = (_a = this.hosts.get(host)) === null || _a === void 0 ? void 0 : _a.client.connected) !== null && _b !== void 0 ? _b : false;
144
137
  }
145
- parse(location) {
146
- try {
147
- return TaLocation.parse(location);
148
- }
149
- catch (error) {
150
- throw TaErrors.invalidArgument(error.message, 'Write ssh://<host>/<absolute path>.');
151
- }
152
- }
153
138
  };
154
139
  __decorate([
155
140
  Value(TA_REMOTE_OPTIONS),
@@ -23,8 +23,6 @@ export interface RemoteHosts {
23
23
  add(host: string): void;
24
24
  /** Disconnects and drops it from the list of those opened before. */
25
25
  remove(host: string): Promise<void>;
26
- /** The location with the home directory as its path when it has none. */
27
- resolve(location: string): Promise<string>;
28
26
  disconnect(host: string): Promise<void>;
29
27
  /** Runs once a host is disconnected on purpose. */
30
28
  onDisconnect(listener: (host: string) => void): () => void;
@@ -26,7 +26,7 @@ let TaRemoteServerImpl = class TaRemoteServerImpl {
26
26
  return TaErrors.guard(() => this.hosts.remove(host));
27
27
  }
28
28
  resolveLocation(location) {
29
- return TaErrors.guard(() => this.hosts.resolve(location));
29
+ return TaErrors.guard(() => this.environments.resolve(location));
30
30
  }
31
31
  forwardPort(port, cwd) {
32
32
  return TaErrors.guard(async () => this.ports.forward(cwd || (await this.environments.defaultCwd()), port));
@@ -36,12 +36,12 @@ export declare class RemoteUiContext implements ExtensionUIContext {
36
36
  setWidget(key: string, content: unknown, options?: {
37
37
  placement?: 'aboveEditor' | 'belowEditor';
38
38
  }): void;
39
+ setWorkingMessage(message?: string): void;
39
40
  setTitle(title: string): void;
40
41
  setEditorText(text: string): void;
41
42
  pasteToEditor(text: string): void;
42
43
  getEditorText(): string;
43
44
  onTerminalInput(): () => void;
44
- setWorkingMessage(): void;
45
45
  setWorkingVisible(): void;
46
46
  setWorkingIndicator(): void;
47
47
  setHiddenThinkingLabel(): void;
@@ -72,6 +72,9 @@ export class RemoteUiContext {
72
72
  this.keep(`widget:${key}`, (content === null || content === void 0 ? void 0 : content.length) ? request : undefined);
73
73
  }
74
74
  }
75
+ setWorkingMessage(message) {
76
+ this.publish({ type: 'working_message', message: message || undefined });
77
+ }
75
78
  setTitle(title) {
76
79
  this.tell({ method: 'setTitle', title });
77
80
  }
@@ -88,7 +91,6 @@ export class RemoteUiContext {
88
91
  onTerminalInput() {
89
92
  return () => undefined;
90
93
  }
91
- setWorkingMessage() { }
92
94
  setWorkingVisible() { }
93
95
  setWorkingIndicator() { }
94
96
  setHiddenThinkingLabel() { }
@@ -74,6 +74,7 @@ export var SessionCatalogUtil;
74
74
  let header;
75
75
  let sessionName;
76
76
  let firstMessage;
77
+ const messages = [];
77
78
  let messageCount = 0;
78
79
  let updatedAt;
79
80
  const marks = [];
@@ -99,6 +100,7 @@ export var SessionCatalogUtil;
99
100
  const message = entry.message;
100
101
  messageCount++;
101
102
  firstMessage !== null && firstMessage !== void 0 ? firstMessage : (firstMessage = SessionInfoUtil.firstMessage([message]));
103
+ messages.push(message);
102
104
  if (typeof message.timestamp === 'number') {
103
105
  updatedAt = Math.max(updatedAt !== null && updatedAt !== void 0 ? updatedAt : 0, message.timestamp);
104
106
  }
@@ -114,6 +116,7 @@ export var SessionCatalogUtil;
114
116
  piCwd: typeof header.cwd === 'string' ? header.cwd : '',
115
117
  sessionName,
116
118
  firstMessage,
119
+ lastMessage: SessionInfoUtil.lastMessage(messages),
117
120
  messageCount,
118
121
  createdAt,
119
122
  updatedAt: updatedAt !== null && updatedAt !== void 0 ? updatedAt : createdAt,
@@ -0,0 +1,32 @@
1
+ import type { TaClientToolDefinition } from '@celljs/ta-protocol';
2
+ export declare const TaSessionHandles: unique symbol;
3
+ /** What opens a session again under the id clients have: its file, where it works, the tools its clients run. */
4
+ export interface TaSessionHandle {
5
+ sessionFile: string;
6
+ cwd: string;
7
+ clientTools?: TaClientToolDefinition[];
8
+ }
9
+ /**
10
+ * The ids of the sessions ta serve gave, with what opens each again. A session closed while idle, or by a
11
+ * restart, keeps its id: the next call with it opens it again (TaSessionRegistry.resolve), so that a page
12
+ * that slept through it carries on rather than failing with CELL_TA_SESSION_NOT_FOUND. Only a session
13
+ * closed for good (closeSession, an extension that ends it) loses its id.
14
+ */
15
+ export interface TaSessionHandles {
16
+ get(sessionId: string): TaSessionHandle | undefined;
17
+ /** The id kept for a session file. */
18
+ idOf(sessionFile: string): string | undefined;
19
+ set(sessionId: string, handle: TaSessionHandle): void;
20
+ delete(sessionId: string): void;
21
+ }
22
+ /** In ta-sessions.json of the agent directory, the latest last; kept across restarts. */
23
+ export declare class TaSessionHandlesImpl implements TaSessionHandles {
24
+ protected readonly file: string;
25
+ protected cache?: Map<string, TaSessionHandle>;
26
+ get(sessionId: string): TaSessionHandle | undefined;
27
+ idOf(sessionFile: string): string | undefined;
28
+ set(sessionId: string, handle: TaSessionHandle): void;
29
+ delete(sessionId: string): void;
30
+ protected read(): Map<string, TaSessionHandle>;
31
+ protected write(handles: Map<string, TaSessionHandle>): void;
32
+ }
@@ -0,0 +1,86 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ 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;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { readFileSync, renameSync, writeFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { Component } from '@celljs/core';
10
+ import { TaBrand } from '@celljs/ta-harness/lib/node/ta-brand';
11
+ export const TaSessionHandles = Symbol('TaSessionHandles');
12
+ /** Handles kept: the latest ones, as a client that slept longer has the conversation in its list again. */
13
+ const MAX_HANDLES = 200;
14
+ /** In ta-sessions.json of the agent directory, the latest last; kept across restarts. */
15
+ let TaSessionHandlesImpl = class TaSessionHandlesImpl {
16
+ constructor() {
17
+ this.file = join(TaBrand.agentDir(), 'ta-sessions.json');
18
+ }
19
+ get(sessionId) {
20
+ return this.read().get(sessionId);
21
+ }
22
+ idOf(sessionFile) {
23
+ for (const [id, handle] of this.read()) {
24
+ if (handle.sessionFile === sessionFile) {
25
+ return id;
26
+ }
27
+ }
28
+ return undefined;
29
+ }
30
+ set(sessionId, handle) {
31
+ const handles = this.read();
32
+ // One id per file: the file opened under another is reached by that one.
33
+ for (const [id, other] of handles) {
34
+ if (id !== sessionId && other.sessionFile === handle.sessionFile) {
35
+ handles.delete(id);
36
+ }
37
+ }
38
+ handles.delete(sessionId);
39
+ handles.set(sessionId, handle);
40
+ for (const id of handles.keys()) {
41
+ if (handles.size <= MAX_HANDLES) {
42
+ break;
43
+ }
44
+ handles.delete(id);
45
+ }
46
+ this.write(handles);
47
+ }
48
+ delete(sessionId) {
49
+ const handles = this.read();
50
+ if (handles.delete(sessionId)) {
51
+ this.write(handles);
52
+ }
53
+ }
54
+ read() {
55
+ if (!this.cache) {
56
+ this.cache = new Map();
57
+ try {
58
+ const data = JSON.parse(readFileSync(this.file, 'utf8'));
59
+ for (const [id, handle] of Object.entries(data && typeof data === 'object' && !Array.isArray(data) ? data : {})) {
60
+ const { sessionFile, cwd } = (handle !== null && handle !== void 0 ? handle : {});
61
+ if (typeof sessionFile === 'string' && typeof cwd === 'string') {
62
+ this.cache.set(id, handle);
63
+ }
64
+ }
65
+ }
66
+ catch (_a) {
67
+ // None yet, or not readable: no handles.
68
+ }
69
+ }
70
+ return this.cache;
71
+ }
72
+ write(handles) {
73
+ try {
74
+ writeFileSync(`${this.file}.tmp`, `${JSON.stringify(Object.fromEntries(handles))}\n`, { mode: 0o600 });
75
+ renameSync(`${this.file}.tmp`, this.file);
76
+ }
77
+ catch (_a) {
78
+ // Kept in memory: only a restart forgets them.
79
+ }
80
+ }
81
+ };
82
+ TaSessionHandlesImpl = __decorate([
83
+ Component(TaSessionHandles)
84
+ ], TaSessionHandlesImpl);
85
+ export { TaSessionHandlesImpl };
86
+ //# 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. */
@@ -1,8 +1,10 @@
1
- import { TaMessageContext, TaSkillUse } from '@celljs/ta-protocol';
1
+ import { TaAgentSummary, TaImageNote, TaMessageContext, TaSkillUse } from '@celljs/ta-protocol';
2
2
  /** What a list of conversations shows of one: its first message, as pi's session list does, and when it last changed. */
3
3
  export var SessionInfoUtil;
4
4
  (function (SessionInfoUtil) {
5
5
  const LENGTH = 120;
6
+ /** Of the text of the last message, what lastMessage reads: its lines are joined, many of them empty or marks only. */
7
+ const PREVIEW_READ = 2000;
6
8
  /**
7
9
  * The first line of the first message of the user that has text, without its context, cut to a title's length;
8
10
  * a skill the user ran is `/skill:name` and what follows, not the skill's file.
@@ -12,7 +14,7 @@ export var SessionInfoUtil;
12
14
  if (message.role !== 'user') {
13
15
  continue;
14
16
  }
15
- const said = TaMessageContext.strip(text(message.content));
17
+ const said = TaImageNote.strip(TaMessageContext.strip(text(message.content)));
16
18
  const skill = TaSkillUse.parse(said);
17
19
  const line = (skill ? TaSkillUse.command(skill) : said)
18
20
  .split('\n')
@@ -25,6 +27,36 @@ export var SessionInfoUtil;
25
27
  return undefined;
26
28
  }
27
29
  SessionInfoUtil.firstMessage = firstMessage;
30
+ /**
31
+ * The text of the last message of the user or the agent that has some, on one line and cut to a preview's
32
+ * length, as a messaging app shows the last thing said under its name: without its context, the marks of
33
+ * markdown at the start of its lines, and the thinking and tool calls of the agent.
34
+ */
35
+ function lastMessage(messages) {
36
+ for (let i = messages.length - 1; i >= 0; i--) {
37
+ const message = messages[i];
38
+ if (message.role !== 'user' && message.role !== 'assistant') {
39
+ continue;
40
+ }
41
+ const said = message.role === 'user' ? TaImageNote.strip(TaMessageContext.strip(text(message.content))) : TaAgentSummary.strip(text(message.content));
42
+ // A list asks for it every few seconds: only the start of a long reply is read, enough for a preview.
43
+ const line = said
44
+ .slice(0, PREVIEW_READ)
45
+ .split('\n')
46
+ .map(part => part
47
+ .replace(/^\s*(?:#{1,6}\s+|>\s*|[-*+]\s+|\d+\.\s+)/, '')
48
+ .replace(/[*_`]{1,3}/g, '')
49
+ .trim())
50
+ .filter(Boolean)
51
+ .join(' ')
52
+ .replace(/\s+/g, ' ');
53
+ if (line) {
54
+ return line.length > LENGTH ? `${line.slice(0, LENGTH - 1)}…` : line;
55
+ }
56
+ }
57
+ return undefined;
58
+ }
59
+ SessionInfoUtil.lastMessage = lastMessage;
28
60
  /** The time of the last message that has one, else `fallback`. */
29
61
  function updatedAt(messages, fallback) {
30
62
  for (let i = messages.length - 1; i >= 0; i--) {
@@ -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;
@@ -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: process.env.TA_SERVE_TOKEN ? kept : this.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 (process.env.TA_SERVE_OPEN_WEB) {
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, process.env.TA_SERVE_TOKEN ? undefined : this.token)) {
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
  }
@@ -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
  }