@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
@@ -1,11 +1,21 @@
1
- import type { TaEvent } from '@celljs/ta-protocol';
1
+ import type { TaConversation, TaEvent, TaMessage } from '@celljs/ta-protocol';
2
2
  type AgentSessionEvent = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).AgentSessionEvent;
3
3
  export declare namespace TaEventUtil {
4
4
  /**
5
5
  * An event of pi as it goes on the wire, the JSON form of pi's RPC and JSON modes (pi does not export
6
6
  * its function). pi's `message_update` holds the whole message so far: sent as is, a reply would cost
7
- * the square of its length.
7
+ * the square of its length. The images of tool results go without their bytes (`leanMessage`).
8
8
  */
9
9
  function toWire(event: AgentSessionEvent): TaEvent;
10
+ /**
11
+ * A message as clients get it: a tool's result keeps its images' kind but not their bytes (`data` is
12
+ * empty). Clients do not show them (the model reads them), and screenshots are most of the bytes of a
13
+ * conversation that has them: on a slow network a page of it would be one picture nobody sees.
14
+ */
15
+ function leanMessage(message: TaMessage): TaMessage;
16
+ /** The result of a tool, or a message of one, without the bytes of its images. */
17
+ function leanResult<T>(result: T): T;
18
+ /** A conversation as clients get it: its messages and the results of its calls lean. */
19
+ function leanConversation(conversation: TaConversation): TaConversation;
10
20
  }
11
21
  export {};
@@ -1,14 +1,33 @@
1
+ /** The lean form of each message and result met, made once: the pages of a conversation measure it by its object. */
2
+ const leaned = new WeakMap();
1
3
  export var TaEventUtil;
2
4
  (function (TaEventUtil) {
3
5
  /**
4
6
  * An event of pi as it goes on the wire, the JSON form of pi's RPC and JSON modes (pi does not export
5
7
  * its function). pi's `message_update` holds the whole message so far: sent as is, a reply would cost
6
- * the square of its length.
8
+ * the square of its length. The images of tool results go without their bytes (`leanMessage`).
7
9
  */
8
10
  function toWire(event) {
9
11
  var _a;
10
- if (event.type !== 'message_update') {
11
- return event;
12
+ switch (event.type) {
13
+ case 'message_update':
14
+ break;
15
+ case 'message_start':
16
+ case 'message_end':
17
+ return withLean(event, 'message', leanMessage(event.message));
18
+ case 'tool_execution_update':
19
+ return withLean(event, 'partialResult', leanResult(event.partialResult));
20
+ case 'tool_execution_end':
21
+ return withLean(event, 'result', leanResult(event.result));
22
+ case 'turn_end': {
23
+ const message = leanMessage(event.message);
24
+ const toolResults = leanAll(event.toolResults);
25
+ return (message === event.message && toolResults === event.toolResults ? event : { ...event, message, toolResults });
26
+ }
27
+ case 'agent_end':
28
+ return withLean(event, 'messages', leanAll(event.messages));
29
+ default:
30
+ return event;
12
31
  }
13
32
  const { partial, ...delta } = event.assistantMessageEvent;
14
33
  const block = delta.type === 'toolcall_start' ? partial === null || partial === void 0 ? void 0 : partial.content[(_a = delta.contentIndex) !== null && _a !== void 0 ? _a : -1] : undefined;
@@ -16,5 +35,54 @@ export var TaEventUtil;
16
35
  return { type: 'message_update', usage: event.message.usage, assistantMessageEvent };
17
36
  }
18
37
  TaEventUtil.toWire = toWire;
38
+ /**
39
+ * A message as clients get it: a tool's result keeps its images' kind but not their bytes (`data` is
40
+ * empty). Clients do not show them (the model reads them), and screenshots are most of the bytes of a
41
+ * conversation that has them: on a slow network a page of it would be one picture nobody sees.
42
+ */
43
+ function leanMessage(message) {
44
+ return (message === null || message === void 0 ? void 0 : message.role) === 'toolResult' ? leanResult(message) : message;
45
+ }
46
+ TaEventUtil.leanMessage = leanMessage;
47
+ /** The result of a tool, or a message of one, without the bytes of its images. */
48
+ function leanResult(result) {
49
+ const content = result === null || result === void 0 ? void 0 : result.content;
50
+ if (!result || typeof result !== 'object' || !Array.isArray(content)) {
51
+ return result;
52
+ }
53
+ const known = leaned.get(result);
54
+ if (known) {
55
+ return known;
56
+ }
57
+ const heavy = content.some(block => (block === null || block === void 0 ? void 0 : block.type) === 'image' && block.data);
58
+ const lean = heavy
59
+ ? {
60
+ ...result,
61
+ content: content.map(block => (block === null || block === void 0 ? void 0 : block.type) === 'image' ? { type: 'image', mimeType: block.mimeType, data: '' } : block),
62
+ }
63
+ : result;
64
+ leaned.set(result, lean);
65
+ return lean;
66
+ }
67
+ TaEventUtil.leanResult = leanResult;
68
+ /** A conversation as clients get it: its messages and the results of its calls lean. */
69
+ function leanConversation(conversation) {
70
+ const tools = {};
71
+ for (const [id, run] of Object.entries(conversation.tools)) {
72
+ tools[id] = run.result === undefined ? run : { ...run, result: leanResult(run.result) };
73
+ }
74
+ return { ...conversation, messages: leanAll(conversation.messages), tools };
75
+ }
76
+ TaEventUtil.leanConversation = leanConversation;
77
+ function leanAll(messages) {
78
+ if (!Array.isArray(messages)) {
79
+ return messages;
80
+ }
81
+ const lean = messages.map(leanMessage);
82
+ return lean.every((message, index) => message === messages[index]) ? messages : lean;
83
+ }
84
+ function withLean(event, key, value) {
85
+ return (value === event[key] ? event : { ...event, [key]: value });
86
+ }
19
87
  })(TaEventUtil || (TaEventUtil = {}));
20
88
  //# sourceMappingURL=ta-event-util.js.map
@@ -1,7 +1,6 @@
1
1
  import { ExecEnvironmentFactory } from '@celljs/ta-exec';
2
2
  import { type RpcExtensionUIResponse, type TaAttachOptions, type TaAttachResult, type TaClientToolResult, type TaCommandResult, type TaForkFileResult, type TaMessagePage, type TaNavigateResult, type TaOpenSessionOptions, type TaPromptInput, type TaPromptReceipt, type TaSavedSessionInfo, TaServer, type TaServerInfo, type TaSessionInfo, type ThinkingLevel } from '@celljs/ta-protocol';
3
3
  import { TaSessionCatalog, TaSessionRegistry } from './host-protocol.js';
4
- import { RemoteHosts } from './remote/remote-protocol.js';
5
4
  import type { TaSession } from './ta-session.js';
6
5
  import { TaWorkingDirectory } from './working-directory.js';
7
6
  /**
@@ -13,7 +12,6 @@ export declare class TaServerImpl implements TaServer {
13
12
  protected readonly sessions: TaSessionRegistry;
14
13
  protected readonly environments: ExecEnvironmentFactory;
15
14
  protected readonly workingDirectory: TaWorkingDirectory;
16
- protected readonly remoteHosts: RemoteHosts;
17
15
  protected readonly catalog: TaSessionCatalog;
18
16
  getServerInfo(): Promise<TaServerInfo>;
19
17
  setWorkingDirectory(cwd: string): Promise<TaServerInfo>;
@@ -17,7 +17,6 @@ import { ExecEnvironmentFactory } from '@celljs/ta-exec';
17
17
  import { TaBrand } from '@celljs/ta-harness/lib/node/ta-brand';
18
18
  import { TaServer, } from '@celljs/ta-protocol';
19
19
  import { TaSessionCatalog, TaSessionRegistry } from './host-protocol.js';
20
- import { RemoteHosts } from './remote/remote-protocol.js';
21
20
  import { SessionInfoUtil } from './session-info-util.js';
22
21
  import { TaErrors } from './ta-errors.js';
23
22
  import { TaWorkingDirectory } from './working-directory.js';
@@ -38,7 +37,7 @@ let TaServerImpl = class TaServerImpl {
38
37
  async setWorkingDirectory(cwd) {
39
38
  return this.guard(async () => {
40
39
  var _a;
41
- const path = typeof cwd === 'string' && cwd.trim() ? await this.remoteHosts.resolve(cwd.trim()) : '';
40
+ const path = typeof cwd === 'string' && cwd.trim() ? await this.environments.resolve(cwd.trim()) : '';
42
41
  const env = path ? this.environments.create(path) : undefined;
43
42
  if (!env || !((_a = (await env.stat(env.cwd))) === null || _a === void 0 ? void 0 : _a.isDirectory)) {
44
43
  throw TaErrors.invalidArgument(`${cwd} is not a directory.`, 'Pass the absolute path of a directory that exists on the server, or an ssh:// location.');
@@ -69,7 +68,13 @@ let TaServerImpl = class TaServerImpl {
69
68
  return this.on(sessionId, session => session.earlierMessages(before !== null && before !== void 0 ? before : undefined, timestamp !== null && timestamp !== void 0 ? timestamp : undefined, budget));
70
69
  }
71
70
  detach(sessionId) {
72
- return this.on(sessionId, session => session.detach(this.sessions.channel(RpcContext.requireConnection())));
71
+ // Not opened again to be left: a session closed meanwhile has no client.
72
+ return this.guard(async () => {
73
+ var _a;
74
+ (_a = this.sessions
75
+ .list()
76
+ .find(session => session.id === sessionId)) === null || _a === void 0 ? void 0 : _a.detach(this.sessions.channel(RpcContext.requireConnection()));
77
+ });
73
78
  }
74
79
  respondUi(sessionId, response) {
75
80
  return this.on(sessionId, session => session.respondUi(response));
@@ -281,7 +286,7 @@ let TaServerImpl = class TaServerImpl {
281
286
  });
282
287
  }
283
288
  on(sessionId, command) {
284
- return this.guard(async () => command(this.sessions.require(sessionId)));
289
+ return this.guard(async () => command(await this.sessions.resolve(sessionId)));
285
290
  }
286
291
  guard(command) {
287
292
  return TaErrors.guard(command);
@@ -299,10 +304,6 @@ __decorate([
299
304
  Autowired(TaWorkingDirectory),
300
305
  __metadata("design:type", Object)
301
306
  ], TaServerImpl.prototype, "workingDirectory", void 0);
302
- __decorate([
303
- Autowired(RemoteHosts),
304
- __metadata("design:type", Object)
305
- ], TaServerImpl.prototype, "remoteHosts", void 0);
306
307
  __decorate([
307
308
  Autowired(TaSessionCatalog),
308
309
  __metadata("design:type", Object)
@@ -12,6 +12,15 @@ type AgentsFilesOverride = (base: {
12
12
  }) => {
13
13
  agentsFiles: ContextFile[];
14
14
  };
15
+ export declare namespace SessionFileUtil {
16
+ /**
17
+ * The directory pi is to work in for a session file it opens: none for a file that says (pi reads it from
18
+ * its header); `cwd`, where the caller asks, for one with no header yet. pi writes a file once the agent
19
+ * first answered, so the file of a session opened and never answered (an agent made but not yet asked) is
20
+ * not there, and pi would take the directory ta serve runs in, the home directory under the desktop app.
21
+ */
22
+ function cwdOverride(sessionFile: string, cwd: string): string | undefined;
23
+ }
15
24
  type ModelRuntime = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).ModelRuntime;
16
25
  type SessionManager = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).SessionManager;
17
26
  type Model = NonNullable<import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).AgentSession['model']>;
@@ -26,7 +35,7 @@ export declare class DefaultTaSessionFactory implements TaSessionFactory {
26
35
  protected readonly packageHosts: PackageHosts;
27
36
  protected readonly directories: PiDirectories;
28
37
  protected readonly extensionProviders: ExtensionProviders;
29
- create(requested: TaOpenSessionOptions, requestClose: (session: TaSession) => void): Promise<TaSession>;
38
+ create(requested: TaOpenSessionOptions, requestClose: (session: TaSession, idle?: boolean) => void, id?: string): Promise<TaSession>;
30
39
  protected openSessionManager(sdk: PiSdk, options: TaOpenSessionOptions): SessionManager;
31
40
  /**
32
41
  * For another machine, its context files (AGENTS.md...) instead of those pi finds above the directory
@@ -7,6 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __metadata = (this && this.__metadata) || function (k, v) {
8
8
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
9
  };
10
+ import { statSync } from 'node:fs';
10
11
  import { resolve, sep } from 'node:path';
11
12
  import { AgentExtension, AgentTool, AgentToolUtil, CODING_AGENT_OPTIONS, ModelRuntimeProvider, PiSdkUtil, } from '@celljs/ai-coding-agent';
12
13
  import { Autowired, Component, Optional, Value } from '@celljs/core';
@@ -22,13 +23,31 @@ import { SessionCatalogUtil } from './session-catalog.js';
22
23
  import { ExecSessionFiles } from './session-files.js';
23
24
  import { TaErrors } from './ta-errors.js';
24
25
  import { TaSession } from './ta-session.js';
26
+ export var SessionFileUtil;
27
+ (function (SessionFileUtil) {
28
+ /**
29
+ * The directory pi is to work in for a session file it opens: none for a file that says (pi reads it from
30
+ * its header); `cwd`, where the caller asks, for one with no header yet. pi writes a file once the agent
31
+ * first answered, so the file of a session opened and never answered (an agent made but not yet asked) is
32
+ * not there, and pi would take the directory ta serve runs in, the home directory under the desktop app.
33
+ */
34
+ function cwdOverride(sessionFile, cwd) {
35
+ try {
36
+ return statSync(sessionFile).size > 0 ? undefined : cwd;
37
+ }
38
+ catch (_a) {
39
+ return cwd;
40
+ }
41
+ }
42
+ SessionFileUtil.cwdOverride = cwdOverride;
43
+ })(SessionFileUtil || (SessionFileUtil = {}));
25
44
  /** Sets up pi for each session the way its command does, with one model runtime for all of them. */
26
45
  let DefaultTaSessionFactory = class DefaultTaSessionFactory {
27
46
  constructor() {
28
47
  this.extensions = [];
29
48
  this.tools = [];
30
49
  }
31
- async create(requested, requestClose) {
50
+ async create(requested, requestClose, id) {
32
51
  var _a;
33
52
  var _b, _c, _d;
34
53
  const clientTools = new ClientToolBroker(requested.clientTools);
@@ -90,6 +109,7 @@ let DefaultTaSessionFactory = class DefaultTaSessionFactory {
90
109
  clientTools,
91
110
  options: this.options,
92
111
  requestClose,
112
+ id,
93
113
  group: options.group,
94
114
  role: options.appendSystemPrompt,
95
115
  locate: cwd => this.directories.fromPi(cwd),
@@ -107,7 +127,7 @@ let DefaultTaSessionFactory = class DefaultTaSessionFactory {
107
127
  return sdk.SessionManager.create(options.cwd);
108
128
  }
109
129
  try {
110
- return sdk.SessionManager.open(options.sessionFile);
130
+ return sdk.SessionManager.open(options.sessionFile, undefined, SessionFileUtil.cwdOverride(options.sessionFile, options.cwd));
111
131
  }
112
132
  catch (error) {
113
133
  throw TaErrors.invalidArgument(`Cannot open the session ${options.sessionFile}: ${error.message}`, 'Pass a session file that exists; listSessions shows the open ones.');
@@ -2,21 +2,32 @@ import type { RpcConnection } from '@celljs/rpc/lib/node';
2
2
  import type { TaOpenSessionOptions } from '@celljs/ta-protocol';
3
3
  import { ClientChannel } from './client-channel.js';
4
4
  import { type TaHostOptions, TaSessionFactory, TaSessionRegistry } from './host-protocol.js';
5
+ import { TaSessionHandles } from './session-handles.js';
5
6
  import type { TaSession } from './ta-session.js';
7
+ /**
8
+ * The open sessions. A session's id outlives its memory: closed while idle or by a restart, it opens again
9
+ * from its file under the same id at the next call (TaSessionHandles), so clients never see it go.
10
+ */
6
11
  export declare class DefaultTaSessionRegistry implements TaSessionRegistry {
7
12
  protected readonly options: TaHostOptions;
8
13
  protected readonly factory: TaSessionFactory;
14
+ protected readonly handles: TaSessionHandles;
9
15
  protected readonly sessions: Map<string, TaSession>;
10
16
  protected readonly channels: WeakMap<RpcConnection, ClientChannel>;
11
17
  /** Sessions being created count against the limit too. */
12
18
  protected opening: number;
13
19
  /** The closes under way, by session file: out of the list already, their files locked until they end. */
14
20
  protected readonly closing: Map<string, Promise<void>>;
21
+ /** Sessions opening again under their ids: the calls that come meanwhile wait for the same. */
22
+ protected readonly waking: Map<string, Promise<TaSession>>;
15
23
  open(options: TaOpenSessionOptions): Promise<TaSession>;
16
24
  require(sessionId: string): TaSession;
25
+ resolve(sessionId: string): Promise<TaSession>;
17
26
  list(): TaSession[];
18
- close(sessionId: string): Promise<void>;
27
+ close(sessionId: string, idle?: boolean): Promise<void>;
19
28
  closeAll(): Promise<void>;
20
29
  /** The one channel of a connection; it leaves every session when the connection ends. */
21
30
  channel(connection: RpcConnection): ClientChannel;
31
+ /** `id`: the id it had, to open it again under. */
32
+ protected create(options: TaOpenSessionOptions, id: string | undefined): Promise<TaSession>;
22
33
  }
@@ -9,10 +9,16 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
9
9
  var __metadata = (this && this.__metadata) || function (k, v) {
10
10
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
11
11
  };
12
+ import { existsSync } from 'node:fs';
12
13
  import { Autowired, Component, Value } from '@celljs/core';
13
14
  import { ClientChannel } from './client-channel.js';
14
15
  import { TA_HOST_OPTIONS, TaSessionFactory, TaSessionRegistry } from './host-protocol.js';
16
+ import { TaSessionHandles } from './session-handles.js';
15
17
  import { TaErrors } from './ta-errors.js';
18
+ /**
19
+ * The open sessions. A session's id outlives its memory: closed while idle or by a restart, it opens again
20
+ * from its file under the same id at the next call (TaSessionHandles), so clients never see it go.
21
+ */
16
22
  let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
17
23
  constructor() {
18
24
  this.sessions = new Map();
@@ -21,25 +27,17 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
21
27
  this.opening = 0;
22
28
  /** The closes under way, by session file: out of the list already, their files locked until they end. */
23
29
  this.closing = new Map();
30
+ /** Sessions opening again under their ids: the calls that come meanwhile wait for the same. */
31
+ this.waking = new Map();
24
32
  }
25
- async open(options) {
26
- // A conversation closed a moment ago (idle, or by another client) opens once it is closed, not refused.
27
- const closing = options.sessionFile && this.closing.get(options.sessionFile);
28
- if (closing) {
29
- await closing.catch(() => undefined);
30
- }
31
- if (this.sessions.size + this.opening >= this.options.maxSessions) {
32
- throw TaErrors.tooManySessions(this.options.maxSessions);
33
- }
34
- this.opening++;
35
- try {
36
- const session = await this.factory.create(options, ended => void this.close(ended.id));
37
- this.sessions.set(session.id, session);
38
- return session;
39
- }
40
- finally {
41
- this.opening--;
33
+ open(options) {
34
+ // A file that had a session keeps its id, which pages may still have.
35
+ const known = options.sessionFile ? this.handles.idOf(options.sessionFile) : undefined;
36
+ const waking = known && this.waking.get(known);
37
+ if (waking) {
38
+ return waking;
42
39
  }
40
+ return this.create(options, known && !this.sessions.has(known) ? known : undefined);
43
41
  }
44
42
  require(sessionId) {
45
43
  const session = this.sessions.get(sessionId);
@@ -48,17 +46,42 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
48
46
  }
49
47
  return session;
50
48
  }
49
+ resolve(sessionId) {
50
+ const session = this.sessions.get(sessionId);
51
+ if (session) {
52
+ return Promise.resolve(session);
53
+ }
54
+ const waking = this.waking.get(sessionId);
55
+ if (waking) {
56
+ return waking;
57
+ }
58
+ const handle = this.handles.get(sessionId);
59
+ if (!handle || !existsSync(handle.sessionFile)) {
60
+ return Promise.reject(TaErrors.sessionNotFound(sessionId));
61
+ }
62
+ const options = { cwd: handle.cwd, sessionFile: handle.sessionFile, clientTools: handle.clientTools };
63
+ const opening = this.create(options, sessionId).finally(() => this.waking.delete(sessionId));
64
+ this.waking.set(sessionId, opening);
65
+ return opening;
66
+ }
51
67
  list() {
52
68
  return [...this.sessions.values()];
53
69
  }
54
- async close(sessionId) {
70
+ async close(sessionId, idle = false) {
71
+ if (!idle) {
72
+ this.handles.delete(sessionId);
73
+ }
55
74
  const session = this.sessions.get(sessionId);
56
75
  if (!session) {
57
76
  return;
58
77
  }
59
78
  this.sessions.delete(sessionId);
60
79
  const file = session.pi.sessionFile;
61
- const closing = session.close();
80
+ if (idle && file) {
81
+ // The conversation it has now: pi may have moved to another file since it opened.
82
+ this.handles.set(sessionId, { ...this.handles.get(sessionId), sessionFile: file, cwd: session.cwd });
83
+ }
84
+ const closing = session.close(!idle);
62
85
  if (file) {
63
86
  this.closing.set(file, closing);
64
87
  }
@@ -72,7 +95,7 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
72
95
  }
73
96
  }
74
97
  async closeAll() {
75
- await Promise.all([...this.sessions.keys()].map(id => this.close(id)));
98
+ await Promise.all([...this.sessions.keys()].map(id => this.close(id, true)));
76
99
  }
77
100
  /** The one channel of a connection; it leaves every session when the connection ends. */
78
101
  channel(connection) {
@@ -89,6 +112,30 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
89
112
  }
90
113
  return channel;
91
114
  }
115
+ /** `id`: the id it had, to open it again under. */
116
+ async create(options, id) {
117
+ // A conversation closed a moment ago (idle, or by another client) opens once it is closed, not refused.
118
+ const closing = options.sessionFile && this.closing.get(options.sessionFile);
119
+ if (closing) {
120
+ await closing.catch(() => undefined);
121
+ }
122
+ if (this.sessions.size + this.opening >= this.options.maxSessions) {
123
+ throw TaErrors.tooManySessions(this.options.maxSessions);
124
+ }
125
+ this.opening++;
126
+ try {
127
+ const session = await this.factory.create(options, (ended, idle) => void this.close(ended.id, idle), id);
128
+ this.sessions.set(session.id, session);
129
+ const sessionFile = session.pi.sessionFile;
130
+ if (sessionFile) {
131
+ this.handles.set(session.id, { sessionFile, cwd: session.cwd, clientTools: options.clientTools });
132
+ }
133
+ return session;
134
+ }
135
+ finally {
136
+ this.opening--;
137
+ }
138
+ }
92
139
  };
93
140
  __decorate([
94
141
  Value(TA_HOST_OPTIONS),
@@ -98,6 +145,10 @@ __decorate([
98
145
  Autowired(TaSessionFactory),
99
146
  __metadata("design:type", Object)
100
147
  ], DefaultTaSessionRegistry.prototype, "factory", void 0);
148
+ __decorate([
149
+ Autowired(TaSessionHandles),
150
+ __metadata("design:type", Object)
151
+ ], DefaultTaSessionRegistry.prototype, "handles", void 0);
101
152
  DefaultTaSessionRegistry = __decorate([
102
153
  Component(TaSessionRegistry)
103
154
  ], DefaultTaSessionRegistry);
@@ -1,5 +1,5 @@
1
1
  import type { SessionLock } from '@celljs/ta-harness';
2
- import type { RpcExtensionUIResponse, TaAttachOptions, TaAttachResult, TaClientToolResult, TaEvent, TaMessagePage, TaNavigateResult, TaPromptInput, TaPromptReceipt, TaSessionInfo } from '@celljs/ta-protocol';
2
+ import type { RpcExtensionUIResponse, TaAttachOptions, TaAttachResult, TaClientToolResult, TaConversation, TaEvent, TaMessagePage, TaNavigateResult, TaPromptInput, TaPromptReceipt, TaSessionInfo } from '@celljs/ta-protocol';
3
3
  import type { ClientChannel } from './client-channel.js';
4
4
  import type { ClientToolBroker } from './client-tool-broker.js';
5
5
  import { EventLog } from './event-log.js';
@@ -16,8 +16,10 @@ export interface TaSessionContext {
16
16
  /** The tools of the session that its clients run. */
17
17
  clientTools: ClientToolBroker;
18
18
  options: TaHostOptions;
19
- /** The session should end: it has been idle, or an extension asked. */
20
- requestClose(session: TaSession): void;
19
+ /** The session should end: it has been idle (`idle`: it opens again under its id when called), or an extension asked. */
20
+ requestClose(session: TaSession, idle?: boolean): void;
21
+ /** The id it had, when it opens again (TaSessionHandles); default: a new one. */
22
+ id?: string;
21
23
  /** TaOpenSessionOptions.group. */
22
24
  group?: string;
23
25
  /** TaOpenSessionOptions.appendSystemPrompt: kept in the session file, for when it opens again from it. */
@@ -31,7 +33,7 @@ export interface TaSessionContext {
31
33
  */
32
34
  export declare class TaSession {
33
35
  protected readonly context: TaSessionContext;
34
- readonly id: `${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>;
@@ -13,15 +13,18 @@ import { TaEventUtil } from './ta-event-util.js';
13
13
  */
14
14
  export class TaSession {
15
15
  constructor(context) {
16
+ var _a;
16
17
  this.context = context;
17
- this.id = randomUUID();
18
18
  this.createdAt = Date.now();
19
19
  this.receipts = new ReceiptBook();
20
20
  this.channels = new Set();
21
21
  this.live = new LiveRun();
22
22
  this.started = false;
23
23
  this.runtime = context.runtime;
24
- this.log = new EventLog(this.id, context.options.eventBufferBytes);
24
+ this.id = (_a = context.id) !== null && _a !== void 0 ? _a : randomUUID();
25
+ // Opened again: its seqs start past any the session gave before (fewer than one per millisecond), so a
26
+ // client that attaches with one of those gets the conversation again rather than events of another log.
27
+ this.log = new EventLog(this.id, context.options.eventBufferBytes, context.id ? Date.now() : 0);
25
28
  this.ui = new RemoteUiContext(event => this.publish(event));
26
29
  context.clientTools.connect(event => this.publish(event));
27
30
  }
@@ -49,6 +52,7 @@ export class TaSession {
49
52
  sessionFile: pi.sessionFile,
50
53
  sessionName: pi.sessionName,
51
54
  firstMessage: SessionInfoUtil.firstMessage(pi.messages),
55
+ lastMessage: SessionInfoUtil.lastMessage(pi.messages),
52
56
  model: model ? `${model.provider}/${model.id}` : undefined,
53
57
  isStreaming: pi.isStreaming,
54
58
  messageCount: pi.messages.length,
@@ -65,9 +69,7 @@ export class TaSession {
65
69
  return {
66
70
  info: this.info(),
67
71
  events,
68
- conversation: afterSeq === undefined || gap
69
- ? MessagePage.recent(this.live.conversation(this.pi.messages, this.pi.isStreaming), options.recentBytes)
70
- : undefined,
72
+ conversation: afterSeq === undefined || gap ? MessagePage.recent(this.conversation(), options.recentBytes) : undefined,
71
73
  pendingUi: this.ui.pendingRequests,
72
74
  shownUi: this.ui.shownRequests,
73
75
  pendingClientTools: this.context.clientTools.pendingRequests,
@@ -76,7 +78,11 @@ export class TaSession {
76
78
  };
77
79
  }
78
80
  earlierMessages(before, timestamp, budget) {
79
- return MessagePage.before(this.live.conversation(this.pi.messages, this.pi.isStreaming).messages, before, timestamp, budget);
81
+ return MessagePage.before(this.conversation().messages, before, timestamp, budget);
82
+ }
83
+ /** The conversation of the events sent, as clients get it. */
84
+ conversation() {
85
+ return TaEventUtil.leanConversation(this.live.conversation(this.pi.messages, this.pi.isStreaming));
80
86
  }
81
87
  detach(channel) {
82
88
  if (this.channels.delete(channel)) {
@@ -156,12 +162,14 @@ export class TaSession {
156
162
  * (a tool that ignores the abort, a stream that hangs) or an extension slow to shut down is given
157
163
  * `closeTimeoutMs`; then pi is cut off from its agent, so that nothing more goes into the file.
158
164
  */
159
- async close() {
165
+ async close(announce = true) {
160
166
  var _a;
161
167
  clearTimeout(this.idleTimer);
162
168
  this.ui.cancelAll();
163
169
  this.context.clientTools.cancelAll();
164
- this.publish({ type: 'session_closed' });
170
+ if (announce) {
171
+ this.publish({ type: 'session_closed' });
172
+ }
165
173
  this.channels.clear();
166
174
  (_a = this.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
167
175
  try {
@@ -197,7 +205,7 @@ export class TaSession {
197
205
  }
198
206
  try {
199
207
  const disposition = await run();
200
- return { clientMessageId: input.clientMessageId, status: disposition === 'queued' ? 'queued' : 'accepted' };
208
+ return { clientMessageId: input.clientMessageId, status: disposition === 'started' ? 'accepted' : disposition };
201
209
  }
202
210
  catch (error) {
203
211
  this.receipts.forget(input.clientMessageId);
@@ -255,7 +263,7 @@ export class TaSession {
255
263
  clearTimeout(this.idleTimer);
256
264
  this.idleTimer = undefined;
257
265
  if (this.isIdle()) {
258
- this.idleTimer = setTimeout(() => this.isIdle() && this.context.requestClose(this), this.context.options.idleTimeoutMs);
266
+ this.idleTimer = setTimeout(() => this.isIdle() && this.context.requestClose(this, true), this.context.options.idleTimeoutMs);
259
267
  this.idleTimer.unref();
260
268
  }
261
269
  }
@@ -23,20 +23,30 @@ export declare namespace WorkspaceFilesUtil {
23
23
  /**
24
24
  * Answers `GET /api/files/<id>/<path>` with the bytes of a file, without the token of ta serve: `<id>`
25
25
  * stands for one directory, and only who has the token learns it (TaWorkspaceServer.fileUrl). Paths stay inside
26
- * that directory; a directory answers its `index.html`. One range is served, so that videos seek.
26
+ * that directory; a directory answers its `index.html`. One range is served, so that videos seek. A file
27
+ * outside the directory of the conversation (a picture an agent left in `/tmp`) has the directory it is in
28
+ * as its own: who has the token runs programs there anyway, and the pages of the workspace still cannot
29
+ * reach it.
27
30
  */
28
31
  export declare class DefaultWorkspaceFiles implements WorkspaceFiles, Middleware {
29
32
  /** Before TaAccess, which turns away `/api` requests without the token. */
30
33
  readonly priority: number;
31
34
  protected readonly environments: ExecEnvironmentFactory;
32
35
  protected readonly host?: string;
33
- protected readonly directories: Map<string, string>;
36
+ /** By id, the directory paths stay in, and the one whose execution environment reads them. */
37
+ protected readonly directories: Map<string, {
38
+ root: string;
39
+ cwd: string;
40
+ }>;
34
41
  protected readonly ids: Map<string, string>;
35
42
  url(cwd: string, path: string): string;
36
43
  handle(ctx: Context, next: () => Promise<void>): Promise<void>;
37
- protected send(request: IncomingMessage, response: ServerResponse, cwd: string, path: string): Promise<void>;
38
- /** The file at `path`, or the `index.html` of the directory there. */
39
- protected find(env: ExecEnvironment, path: string): Promise<{
44
+ protected send(request: IncomingMessage, response: ServerResponse, directory: {
45
+ root: string;
46
+ cwd: string;
47
+ }, path: string): Promise<void>;
48
+ /** The file at `path` of `root`, or the `index.html` of the directory there. */
49
+ protected find(env: ExecEnvironment, root: string, path: string): Promise<{
40
50
  absolute: string;
41
51
  stat: FileStat;
42
52
  } | undefined>;