@celljs/ta-host 4.9.1 → 4.11.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 (117) hide show
  1. package/README.en.md +5 -5
  2. package/README.md +5 -5
  3. package/esm/node/client-tool-broker.d.ts +6 -2
  4. package/esm/node/client-tool-broker.js +11 -4
  5. package/esm/node/event-log.d.ts +2 -1
  6. package/esm/node/event-log.js +3 -2
  7. package/esm/node/exec-environment-factory.d.ts +7 -0
  8. package/esm/node/exec-environment-factory.js +30 -7
  9. package/esm/node/host-protocol.d.ts +24 -10
  10. package/esm/node/index.d.ts +2 -0
  11. package/esm/node/index.js +2 -0
  12. package/esm/node/package-hosts.d.ts +6 -0
  13. package/esm/node/package-hosts.js +36 -1
  14. package/esm/node/package-server-impl.d.ts +0 -1
  15. package/esm/node/package-server-impl.js +0 -3
  16. package/esm/node/relay-bridge.d.ts +12 -2
  17. package/esm/node/relay-bridge.js +93 -3
  18. package/esm/node/remote/remote-hosts.d.ts +1 -3
  19. package/esm/node/remote/remote-hosts.js +0 -15
  20. package/esm/node/remote/remote-protocol.d.ts +0 -2
  21. package/esm/node/remote/remote-server-impl.js +1 -1
  22. package/esm/node/remote-ui-context.d.ts +1 -1
  23. package/esm/node/remote-ui-context.js +3 -1
  24. package/esm/node/rooms-bridge.d.ts +60 -0
  25. package/esm/node/rooms-bridge.js +155 -0
  26. package/esm/node/session-catalog.d.ts +7 -3
  27. package/esm/node/session-catalog.js +15 -4
  28. package/esm/node/session-handles.d.ts +32 -0
  29. package/esm/node/session-handles.js +86 -0
  30. package/esm/node/session-info-util.d.ts +7 -0
  31. package/esm/node/session-info-util.js +63 -4
  32. package/esm/node/session-list-feed.d.ts +28 -0
  33. package/esm/node/session-list-feed.js +62 -0
  34. package/esm/node/sign-in/sign-in-flow.d.ts +2 -0
  35. package/esm/node/sign-in/sign-in-flow.js +9 -0
  36. package/esm/node/sign-in/sign-in-provider.js +3 -2
  37. package/esm/node/slash-command-util.d.ts +43 -0
  38. package/esm/node/slash-command-util.js +105 -0
  39. package/esm/node/ta-access.d.ts +11 -0
  40. package/esm/node/ta-access.js +29 -3
  41. package/esm/node/ta-errors.js +17 -2
  42. package/esm/node/ta-event-util.d.ts +19 -2
  43. package/esm/node/ta-event-util.js +97 -3
  44. package/esm/node/ta-server-impl.d.ts +13 -7
  45. package/esm/node/ta-server-impl.js +43 -24
  46. package/esm/node/ta-session-factory.d.ts +26 -2
  47. package/esm/node/ta-session-factory.js +64 -16
  48. package/esm/node/ta-session-registry.d.ts +16 -2
  49. package/esm/node/ta-session-registry.js +79 -20
  50. package/esm/node/ta-session.d.ts +16 -6
  51. package/esm/node/ta-session.js +59 -14
  52. package/esm/node/web-extension-catalog.d.ts +5 -1
  53. package/esm/node/web-extension-catalog.js +15 -19
  54. package/esm/node/web-extension-util.js +7 -3
  55. package/esm/node/workspace-files.d.ts +19 -5
  56. package/esm/node/workspace-files.js +26 -15
  57. package/esm/node/workspace-protocol.d.ts +1 -1
  58. package/esm/node/workspace-util.d.ts +2 -0
  59. package/esm/node/workspace-util.js +8 -3
  60. package/lib/node/client-tool-broker.d.ts +6 -2
  61. package/lib/node/client-tool-broker.js +11 -4
  62. package/lib/node/event-log.d.ts +2 -1
  63. package/lib/node/event-log.js +3 -2
  64. package/lib/node/exec-environment-factory.d.ts +7 -0
  65. package/lib/node/exec-environment-factory.js +30 -7
  66. package/lib/node/host-protocol.d.ts +24 -10
  67. package/lib/node/index.d.ts +2 -0
  68. package/lib/node/index.js +2 -0
  69. package/lib/node/package-hosts.d.ts +6 -0
  70. package/lib/node/package-hosts.js +35 -0
  71. package/lib/node/package-server-impl.d.ts +0 -1
  72. package/lib/node/package-server-impl.js +0 -3
  73. package/lib/node/relay-bridge.d.ts +12 -2
  74. package/lib/node/relay-bridge.js +91 -1
  75. package/lib/node/remote/remote-hosts.d.ts +1 -3
  76. package/lib/node/remote/remote-hosts.js +0 -15
  77. package/lib/node/remote/remote-protocol.d.ts +0 -2
  78. package/lib/node/remote/remote-server-impl.js +1 -1
  79. package/lib/node/remote-ui-context.d.ts +1 -1
  80. package/lib/node/remote-ui-context.js +3 -1
  81. package/lib/node/rooms-bridge.d.ts +61 -0
  82. package/lib/node/rooms-bridge.js +158 -0
  83. package/lib/node/session-catalog.d.ts +7 -3
  84. package/lib/node/session-catalog.js +15 -4
  85. package/lib/node/session-handles.d.ts +33 -0
  86. package/lib/node/session-handles.js +89 -0
  87. package/lib/node/session-info-util.d.ts +7 -0
  88. package/lib/node/session-info-util.js +62 -3
  89. package/lib/node/session-list-feed.d.ts +29 -0
  90. package/lib/node/session-list-feed.js +66 -0
  91. package/lib/node/sign-in/sign-in-flow.d.ts +2 -0
  92. package/lib/node/sign-in/sign-in-flow.js +10 -1
  93. package/lib/node/sign-in/sign-in-provider.js +3 -2
  94. package/lib/node/slash-command-util.d.ts +44 -0
  95. package/lib/node/slash-command-util.js +108 -0
  96. package/lib/node/ta-access.d.ts +11 -0
  97. package/lib/node/ta-access.js +29 -3
  98. package/lib/node/ta-errors.js +17 -2
  99. package/lib/node/ta-event-util.d.ts +19 -2
  100. package/lib/node/ta-event-util.js +97 -3
  101. package/lib/node/ta-server-impl.d.ts +13 -7
  102. package/lib/node/ta-server-impl.js +41 -22
  103. package/lib/node/ta-session-factory.d.ts +26 -2
  104. package/lib/node/ta-session-factory.js +65 -17
  105. package/lib/node/ta-session-registry.d.ts +16 -2
  106. package/lib/node/ta-session-registry.js +79 -20
  107. package/lib/node/ta-session.d.ts +16 -6
  108. package/lib/node/ta-session.js +59 -14
  109. package/lib/node/web-extension-catalog.d.ts +5 -1
  110. package/lib/node/web-extension-catalog.js +15 -19
  111. package/lib/node/web-extension-util.js +7 -3
  112. package/lib/node/workspace-files.d.ts +19 -5
  113. package/lib/node/workspace-files.js +26 -15
  114. package/lib/node/workspace-protocol.d.ts +1 -1
  115. package/lib/node/workspace-util.d.ts +2 -0
  116. package/lib/node/workspace-util.js +8 -3
  117. package/package.json +12 -12
@@ -8,7 +8,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
10
  import { existsSync } from 'node:fs';
11
- import { hostname, userInfo } from 'node:os';
11
+ import { homedir, hostname, userInfo } from 'node:os';
12
12
  import { PiSdkUtil } from '@celljs/ai-coding-agent';
13
13
  import { Autowired } from '@celljs/core';
14
14
  import { Rpc } from '@celljs/rpc';
@@ -16,9 +16,9 @@ import { RpcContext } from '@celljs/rpc/lib/node';
16
16
  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
- import { TaSessionCatalog, TaSessionRegistry } from './host-protocol.js';
20
- import { RemoteHosts } from './remote/remote-protocol.js';
19
+ import { TaSessionCatalog, TaSessionFactory, TaSessionRegistry } from './host-protocol.js';
21
20
  import { SessionInfoUtil } from './session-info-util.js';
21
+ import { SlashCommandUtil } from './slash-command-util.js';
22
22
  import { TaErrors } from './ta-errors.js';
23
23
  import { TaWorkingDirectory } from './working-directory.js';
24
24
  /**
@@ -33,12 +33,13 @@ let TaServerImpl = class TaServerImpl {
33
33
  cwd: await this.environments.defaultCwd(),
34
34
  user: userInfo().username,
35
35
  host: hostname().replace(/\.local$/, ''),
36
+ home: homedir(),
36
37
  }));
37
38
  }
38
39
  async setWorkingDirectory(cwd) {
39
40
  return this.guard(async () => {
40
41
  var _a;
41
- const path = typeof cwd === 'string' && cwd.trim() ? await this.remoteHosts.resolve(cwd.trim()) : '';
42
+ const path = typeof cwd === 'string' && cwd.trim() ? await this.environments.resolve(cwd.trim()) : '';
42
43
  const env = path ? this.environments.create(path) : undefined;
43
44
  if (!env || !((_a = (await env.stat(env.cwd))) === null || _a === void 0 ? void 0 : _a.isDirectory)) {
44
45
  throw TaErrors.invalidArgument(`${cwd} is not a directory.`, 'Pass the absolute path of a directory that exists on the server, or an ssh:// location.');
@@ -47,8 +48,15 @@ let TaServerImpl = class TaServerImpl {
47
48
  return this.getServerInfo();
48
49
  });
49
50
  }
50
- async openSession(options) {
51
- return this.guard(async () => (await this.sessions.open(options)).info());
51
+ async openSession({ attach, ...options }) {
52
+ return this.guard(async () => {
53
+ const session = await this.sessions.open(options);
54
+ if (!attach) {
55
+ return session.info();
56
+ }
57
+ const attached = session.attach(this.sessions.channel(RpcContext.requireConnection()), undefined, attach);
58
+ return { ...attached.info, attachment: attached };
59
+ });
52
60
  }
53
61
  closeSession(sessionId) {
54
62
  return this.guard(() => this.sessions.close(sessionId));
@@ -56,10 +64,13 @@ let TaServerImpl = class TaServerImpl {
56
64
  async listSessions() {
57
65
  return this.sessions.list().map(session => session.info());
58
66
  }
59
- listSavedSessions() {
67
+ async watchSessions() {
68
+ return this.sessions.watch(RpcContext.requireConnection());
69
+ }
70
+ listSavedSessions(query) {
60
71
  return this.guard(async () => {
61
72
  const open = new Set(this.sessions.list().flatMap(session => { var _a; return (_a = session.pi.sessionFile) !== null && _a !== void 0 ? _a : []; }));
62
- return this.catalog.list(open);
73
+ return this.catalog.list(open, query !== null && query !== void 0 ? query : undefined);
63
74
  });
64
75
  }
65
76
  attach(sessionId, afterSeq, options) {
@@ -68,8 +79,17 @@ let TaServerImpl = class TaServerImpl {
68
79
  getEarlierMessages(sessionId, before, timestamp, budget) {
69
80
  return this.on(sessionId, session => session.earlierMessages(before !== null && before !== void 0 ? before : undefined, timestamp !== null && timestamp !== void 0 ? timestamp : undefined, budget));
70
81
  }
82
+ getMessageImage(sessionId, timestamp, index) {
83
+ return this.on(sessionId, session => session.messageImage(timestamp, index));
84
+ }
71
85
  detach(sessionId) {
72
- return this.on(sessionId, session => session.detach(this.sessions.channel(RpcContext.requireConnection())));
86
+ // Not opened again to be left: a session closed meanwhile has no client.
87
+ return this.guard(async () => {
88
+ var _a;
89
+ (_a = this.sessions
90
+ .list()
91
+ .find(session => session.id === sessionId)) === null || _a === void 0 ? void 0 : _a.detach(this.sessions.channel(RpcContext.requireConnection()));
92
+ });
73
93
  }
74
94
  respondUi(sessionId, response) {
75
95
  return this.on(sessionId, session => session.respondUi(response));
@@ -78,7 +98,7 @@ let TaServerImpl = class TaServerImpl {
78
98
  return this.on(sessionId, session => session.claimClientTool(this.sessions.channel(RpcContext.requireConnection()), id));
79
99
  }
80
100
  respondClientTool(sessionId, result) {
81
- return this.on(sessionId, session => session.respondClientTool(result));
101
+ return this.on(sessionId, session => session.respondClientTool(this.sessions.channel(RpcContext.requireConnection()), result));
82
102
  }
83
103
  prompt(sessionId, input) {
84
104
  return this.on(sessionId, session => session.prompt(input));
@@ -261,17 +281,16 @@ let TaServerImpl = class TaServerImpl {
261
281
  }
262
282
  getCommands(sessionId) {
263
283
  return this.on(sessionId, ({ pi }) => ({
264
- commands: [
265
- ...pi.extensionRunner
266
- .getRegisteredCommands()
267
- .map(c => ({ name: c.invocationName, description: c.description, source: 'extension', sourceInfo: c.sourceInfo })),
268
- ...pi.promptTemplates.map(t => ({ name: t.name, description: t.description, source: 'prompt', sourceInfo: t.sourceInfo })),
269
- ...pi.resourceLoader
270
- .getSkills()
271
- .skills.map(s => ({ name: `skill:${s.name}`, description: s.description, source: 'skill', sourceInfo: s.sourceInfo })),
272
- ],
284
+ commands: SlashCommandUtil.list({
285
+ commands: pi.extensionRunner.getRegisteredCommands(),
286
+ prompts: pi.promptTemplates,
287
+ skills: pi.resourceLoader.getSkills().skills,
288
+ }),
273
289
  }));
274
290
  }
291
+ getDirectoryCommands(cwd) {
292
+ return this.guard(async () => ({ commands: await this.factory.commands(cwd) }));
293
+ }
275
294
  reload(sessionId) {
276
295
  return this.on(sessionId, session => {
277
296
  if (session.pi.isStreaming) {
@@ -281,7 +300,7 @@ let TaServerImpl = class TaServerImpl {
281
300
  });
282
301
  }
283
302
  on(sessionId, command) {
284
- return this.guard(async () => command(this.sessions.require(sessionId)));
303
+ return this.guard(async () => command(await this.sessions.resolve(sessionId)));
285
304
  }
286
305
  guard(command) {
287
306
  return TaErrors.guard(command);
@@ -299,14 +318,14 @@ __decorate([
299
318
  Autowired(TaWorkingDirectory),
300
319
  __metadata("design:type", Object)
301
320
  ], TaServerImpl.prototype, "workingDirectory", void 0);
302
- __decorate([
303
- Autowired(RemoteHosts),
304
- __metadata("design:type", Object)
305
- ], TaServerImpl.prototype, "remoteHosts", void 0);
306
321
  __decorate([
307
322
  Autowired(TaSessionCatalog),
308
323
  __metadata("design:type", Object)
309
324
  ], TaServerImpl.prototype, "catalog", void 0);
325
+ __decorate([
326
+ Autowired(TaSessionFactory),
327
+ __metadata("design:type", Object)
328
+ ], TaServerImpl.prototype, "factory", void 0);
310
329
  TaServerImpl = __decorate([
311
330
  Rpc(TaServer)
312
331
  ], TaServerImpl);
@@ -1,7 +1,7 @@
1
1
  import { AgentExtension, AgentTool, type CodingAgentOptions, ModelRuntimeProvider, type PiSdk } from '@celljs/ai-coding-agent';
2
2
  import { type ExecEnvironment, ExecEnvironmentFactory } from '@celljs/ta-exec';
3
3
  import { type ContextFile, type InlineExtension, SessionLock } from '@celljs/ta-harness';
4
- import type { TaOpenSessionOptions } from '@celljs/ta-protocol';
4
+ import type { TaOpenSessionOptions, TaSlashCommand } from '@celljs/ta-protocol';
5
5
  import { ExtensionProviders } from './extension-providers.js';
6
6
  import { type TaHostOptions, TaSessionFactory } from './host-protocol.js';
7
7
  import { PackageHosts } from './package-hosts.js';
@@ -12,7 +12,25 @@ 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;
25
+ type AgentSessionServices = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).AgentSessionServices;
26
+ interface ServicesOptions {
27
+ cwd: string;
28
+ agentDir: string;
29
+ modelRuntime: ModelRuntime;
30
+ lock: SessionLock;
31
+ appendSystemPrompt?: string;
32
+ commandsOnly?: boolean;
33
+ }
16
34
  type SessionManager = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).SessionManager;
17
35
  type Model = NonNullable<import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).AgentSession['model']>;
18
36
  /** Sets up pi for each session the way its command does, with one model runtime for all of them. */
@@ -26,7 +44,13 @@ export declare class DefaultTaSessionFactory implements TaSessionFactory {
26
44
  protected readonly packageHosts: PackageHosts;
27
45
  protected readonly directories: PiDirectories;
28
46
  protected readonly extensionProviders: ExtensionProviders;
29
- create(requested: TaOpenSessionOptions, requestClose: (session: TaSession) => void): Promise<TaSession>;
47
+ create(requested: TaOpenSessionOptions, requestClose: (session: TaSession, idle?: boolean) => void, id?: string): Promise<TaSession>;
48
+ commands(cwd: string): Promise<TaSlashCommand[]>;
49
+ /**
50
+ * pi's services of a session in `cwd` (a directory of pi): its settings, its resources and extensions with
51
+ * those of Ta. `commandsOnly`: for what a session would have, the context files of another machine not read.
52
+ */
53
+ protected services(sdk: PiSdk, options: ServicesOptions): Promise<AgentSessionServices>;
30
54
  protected openSessionManager(sdk: PiSdk, options: TaOpenSessionOptions): SessionManager;
31
55
  /**
32
56
  * 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';
@@ -20,15 +21,34 @@ import { PackageHosts } from './package-hosts.js';
20
21
  import { PiDirectories } from './remote/remote-protocol.js';
21
22
  import { SessionCatalogUtil } from './session-catalog.js';
22
23
  import { ExecSessionFiles } from './session-files.js';
24
+ import { SlashCommandUtil } from './slash-command-util.js';
23
25
  import { TaErrors } from './ta-errors.js';
24
26
  import { TaSession } from './ta-session.js';
27
+ export var SessionFileUtil;
28
+ (function (SessionFileUtil) {
29
+ /**
30
+ * The directory pi is to work in for a session file it opens: none for a file that says (pi reads it from
31
+ * its header); `cwd`, where the caller asks, for one with no header yet. pi writes a file once the agent
32
+ * first answered, so the file of a session opened and never answered (an agent made but not yet asked) is
33
+ * not there, and pi would take the directory ta serve runs in, the home directory under the desktop app.
34
+ */
35
+ function cwdOverride(sessionFile, cwd) {
36
+ try {
37
+ return statSync(sessionFile).size > 0 ? undefined : cwd;
38
+ }
39
+ catch (_a) {
40
+ return cwd;
41
+ }
42
+ }
43
+ SessionFileUtil.cwdOverride = cwdOverride;
44
+ })(SessionFileUtil || (SessionFileUtil = {}));
25
45
  /** Sets up pi for each session the way its command does, with one model runtime for all of them. */
26
46
  let DefaultTaSessionFactory = class DefaultTaSessionFactory {
27
47
  constructor() {
28
48
  this.extensions = [];
29
49
  this.tools = [];
30
50
  }
31
- async create(requested, requestClose) {
51
+ async create(requested, requestClose, id) {
32
52
  var _a;
33
53
  var _b, _c, _d;
34
54
  const clientTools = new ClientToolBroker(requested.clientTools);
@@ -60,20 +80,7 @@ let DefaultTaSessionFactory = class DefaultTaSessionFactory {
60
80
  const model = options.model ? this.resolveModel(modelRuntime, options.model) : undefined;
61
81
  const runtime = await sdk.createAgentSessionRuntime(async ({ cwd, agentDir: dir, sessionManager: manager, sessionStartEvent }) => {
62
82
  var _a;
63
- const environment = this.environments.create(this.directories.fromPi(cwd));
64
- const settingsManager = sdk.SettingsManager.create(cwd, dir, { projectTrusted: this.isTrusted(sdk, cwd, dir) });
65
- const services = await sdk.createAgentSessionServices({
66
- cwd,
67
- agentDir: dir,
68
- settingsManager,
69
- modelRuntime,
70
- resourceLoaderOptions: {
71
- ...TaPackages.loaderOptions(dir),
72
- ...(await this.contextFiles(environment, dir)),
73
- extensionFactories: this.extensionFactories(sdk, environment, cwd, lock),
74
- appendSystemPrompt: options.appendSystemPrompt ? [options.appendSystemPrompt] : undefined,
75
- },
76
- });
83
+ const services = await this.services(sdk, { cwd, agentDir: dir, modelRuntime, lock, appendSystemPrompt: options.appendSystemPrompt });
77
84
  const created = await sdk.createAgentSessionFromServices({
78
85
  services,
79
86
  sessionManager: manager,
@@ -90,6 +97,7 @@ let DefaultTaSessionFactory = class DefaultTaSessionFactory {
90
97
  clientTools,
91
98
  options: this.options,
92
99
  requestClose,
100
+ id,
93
101
  group: options.group,
94
102
  role: options.appendSystemPrompt,
95
103
  locate: cwd => this.directories.fromPi(cwd),
@@ -102,12 +110,52 @@ let DefaultTaSessionFactory = class DefaultTaSessionFactory {
102
110
  throw error;
103
111
  }
104
112
  }
113
+ async commands(cwd) {
114
+ var _a;
115
+ var _b;
116
+ const sdk = await PiSdkUtil.load();
117
+ const agentDir = (_b = (_a = this.codingAgentOptions) === null || _a === void 0 ? void 0 : _a.agentDir) !== null && _b !== void 0 ? _b : sdk.getAgentDir();
118
+ const services = await this.services(sdk, {
119
+ cwd: this.directories.toPi(cwd),
120
+ agentDir,
121
+ modelRuntime: await this.modelRuntimeProvider.provide(),
122
+ lock: new SessionLock(),
123
+ commandsOnly: true,
124
+ });
125
+ const loader = services.resourceLoader;
126
+ return SlashCommandUtil.list({
127
+ commands: SlashCommandUtil.invocationNames(loader.getExtensions().extensions.flatMap(extension => [...extension.commands.values()])),
128
+ prompts: loader.getPrompts().prompts,
129
+ skills: loader.getSkills().skills,
130
+ });
131
+ }
132
+ /**
133
+ * pi's services of a session in `cwd` (a directory of pi): its settings, its resources and extensions with
134
+ * those of Ta. `commandsOnly`: for what a session would have, the context files of another machine not read.
135
+ */
136
+ async services(sdk, options) {
137
+ const { cwd, agentDir, modelRuntime, lock, appendSystemPrompt, commandsOnly } = options;
138
+ const environment = this.environments.create(this.directories.fromPi(cwd));
139
+ const settingsManager = sdk.SettingsManager.create(cwd, agentDir, { projectTrusted: this.isTrusted(sdk, cwd, agentDir) });
140
+ return sdk.createAgentSessionServices({
141
+ cwd,
142
+ agentDir,
143
+ settingsManager,
144
+ modelRuntime,
145
+ resourceLoaderOptions: {
146
+ ...TaPackages.loaderOptions(agentDir),
147
+ ...(commandsOnly ? {} : await this.contextFiles(environment, agentDir)),
148
+ extensionFactories: this.extensionFactories(sdk, environment, cwd, lock),
149
+ appendSystemPrompt: appendSystemPrompt ? [appendSystemPrompt] : undefined,
150
+ },
151
+ });
152
+ }
105
153
  openSessionManager(sdk, options) {
106
154
  if (!options.sessionFile) {
107
155
  return sdk.SessionManager.create(options.cwd);
108
156
  }
109
157
  try {
110
- return sdk.SessionManager.open(options.sessionFile);
158
+ return sdk.SessionManager.open(options.sessionFile, undefined, SessionFileUtil.cwdOverride(options.sessionFile, options.cwd));
111
159
  }
112
160
  catch (error) {
113
161
  throw TaErrors.invalidArgument(`Cannot open the session ${options.sessionFile}: ${error.message}`, 'Pass a session file that exists; listSessions shows the open ones.');
@@ -1,22 +1,36 @@
1
1
  import type { RpcConnection } from '@celljs/rpc/lib/node';
2
- import type { TaOpenSessionOptions } from '@celljs/ta-protocol';
2
+ import type { TaOpenSessionOptions, TaSessionInfo } 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';
6
+ import { SessionListFeed } from './session-list-feed.js';
5
7
  import type { TaSession } from './ta-session.js';
8
+ /**
9
+ * The open sessions. A session's id outlives its memory: closed while idle or by a restart, it opens again
10
+ * from its file under the same id at the next call (TaSessionHandles), so clients never see it go.
11
+ */
6
12
  export declare class DefaultTaSessionRegistry implements TaSessionRegistry {
7
13
  protected readonly options: TaHostOptions;
8
14
  protected readonly factory: TaSessionFactory;
15
+ protected readonly handles: TaSessionHandles;
9
16
  protected readonly sessions: Map<string, TaSession>;
10
17
  protected readonly channels: WeakMap<RpcConnection, ClientChannel>;
11
18
  /** Sessions being created count against the limit too. */
12
19
  protected opening: number;
13
20
  /** The closes under way, by session file: out of the list already, their files locked until they end. */
14
21
  protected readonly closing: Map<string, Promise<void>>;
22
+ /** Sessions opening again under their ids: the calls that come meanwhile wait for the same. */
23
+ protected readonly waking: Map<string, Promise<TaSession>>;
24
+ protected readonly feed: SessionListFeed;
15
25
  open(options: TaOpenSessionOptions): Promise<TaSession>;
16
26
  require(sessionId: string): TaSession;
27
+ resolve(sessionId: string): Promise<TaSession>;
17
28
  list(): TaSession[];
18
- close(sessionId: string): Promise<void>;
29
+ watch(connection: RpcConnection): TaSessionInfo[];
30
+ close(sessionId: string, idle?: boolean): Promise<void>;
19
31
  closeAll(): Promise<void>;
20
32
  /** The one channel of a connection; it leaves every session when the connection ends. */
21
33
  channel(connection: RpcConnection): ClientChannel;
34
+ /** `id`: the id it had, to open it again under. */
35
+ protected create(options: TaOpenSessionOptions, id: string | undefined): Promise<TaSession>;
22
36
  }
@@ -9,10 +9,17 @@ 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';
17
+ import { SessionListFeed } from './session-list-feed.js';
15
18
  import { TaErrors } from './ta-errors.js';
19
+ /**
20
+ * The open sessions. A session's id outlives its memory: closed while idle or by a restart, it opens again
21
+ * from its file under the same id at the next call (TaSessionHandles), so clients never see it go.
22
+ */
16
23
  let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
17
24
  constructor() {
18
25
  this.sessions = new Map();
@@ -21,25 +28,18 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
21
28
  this.opening = 0;
22
29
  /** The closes under way, by session file: out of the list already, their files locked until they end. */
23
30
  this.closing = new Map();
31
+ /** Sessions opening again under their ids: the calls that come meanwhile wait for the same. */
32
+ this.waking = new Map();
33
+ this.feed = new SessionListFeed(() => this.list().map(session => session.info()));
24
34
  }
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--;
35
+ open(options) {
36
+ // A file that had a session keeps its id, which pages may still have.
37
+ const known = options.sessionFile ? this.handles.idOf(options.sessionFile) : undefined;
38
+ const waking = known && this.waking.get(known);
39
+ if (waking) {
40
+ return waking;
42
41
  }
42
+ return this.create(options, known && !this.sessions.has(known) ? known : undefined);
43
43
  }
44
44
  require(sessionId) {
45
45
  const session = this.sessions.get(sessionId);
@@ -48,17 +48,46 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
48
48
  }
49
49
  return session;
50
50
  }
51
+ resolve(sessionId) {
52
+ const session = this.sessions.get(sessionId);
53
+ if (session) {
54
+ return Promise.resolve(session);
55
+ }
56
+ const waking = this.waking.get(sessionId);
57
+ if (waking) {
58
+ return waking;
59
+ }
60
+ const handle = this.handles.get(sessionId);
61
+ if (!handle || !existsSync(handle.sessionFile)) {
62
+ return Promise.reject(TaErrors.sessionNotFound(sessionId));
63
+ }
64
+ const options = { cwd: handle.cwd, sessionFile: handle.sessionFile, clientTools: handle.clientTools };
65
+ const opening = this.create(options, sessionId).finally(() => this.waking.delete(sessionId));
66
+ this.waking.set(sessionId, opening);
67
+ return opening;
68
+ }
51
69
  list() {
52
70
  return [...this.sessions.values()];
53
71
  }
54
- async close(sessionId) {
72
+ watch(connection) {
73
+ return this.feed.watch(connection);
74
+ }
75
+ async close(sessionId, idle = false) {
76
+ if (!idle) {
77
+ this.handles.delete(sessionId);
78
+ }
55
79
  const session = this.sessions.get(sessionId);
56
80
  if (!session) {
57
81
  return;
58
82
  }
59
83
  this.sessions.delete(sessionId);
84
+ this.feed.changed();
60
85
  const file = session.pi.sessionFile;
61
- const closing = session.close();
86
+ if (idle && file) {
87
+ // The conversation it has now: pi may have moved to another file since it opened.
88
+ this.handles.set(sessionId, { ...this.handles.get(sessionId), sessionFile: file, cwd: session.cwd });
89
+ }
90
+ const closing = session.close(!idle);
62
91
  if (file) {
63
92
  this.closing.set(file, closing);
64
93
  }
@@ -72,7 +101,7 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
72
101
  }
73
102
  }
74
103
  async closeAll() {
75
- await Promise.all([...this.sessions.keys()].map(id => this.close(id)));
104
+ await Promise.all([...this.sessions.keys()].map(id => this.close(id, true)));
76
105
  }
77
106
  /** The one channel of a connection; it leaves every session when the connection ends. */
78
107
  channel(connection) {
@@ -89,6 +118,32 @@ let DefaultTaSessionRegistry = class DefaultTaSessionRegistry {
89
118
  }
90
119
  return channel;
91
120
  }
121
+ /** `id`: the id it had, to open it again under. */
122
+ async create(options, id) {
123
+ // A conversation closed a moment ago (idle, or by another client) opens once it is closed, not refused.
124
+ const closing = options.sessionFile && this.closing.get(options.sessionFile);
125
+ if (closing) {
126
+ await closing.catch(() => undefined);
127
+ }
128
+ if (this.sessions.size + this.opening >= this.options.maxSessions) {
129
+ throw TaErrors.tooManySessions(this.options.maxSessions);
130
+ }
131
+ this.opening++;
132
+ try {
133
+ const session = await this.factory.create(options, (ended, idle) => void this.close(ended.id, idle), id);
134
+ this.sessions.set(session.id, session);
135
+ session.onInfoChange(() => this.sessions.get(session.id) === session && this.feed.changed());
136
+ this.feed.changed();
137
+ const sessionFile = session.pi.sessionFile;
138
+ if (sessionFile) {
139
+ this.handles.set(session.id, { sessionFile, cwd: session.cwd, clientTools: options.clientTools });
140
+ }
141
+ return session;
142
+ }
143
+ finally {
144
+ this.opening--;
145
+ }
146
+ }
92
147
  };
93
148
  __decorate([
94
149
  Value(TA_HOST_OPTIONS),
@@ -98,6 +153,10 @@ __decorate([
98
153
  Autowired(TaSessionFactory),
99
154
  __metadata("design:type", Object)
100
155
  ], DefaultTaSessionRegistry.prototype, "factory", void 0);
156
+ __decorate([
157
+ Autowired(TaSessionHandles),
158
+ __metadata("design:type", Object)
159
+ ], DefaultTaSessionRegistry.prototype, "handles", void 0);
101
160
  DefaultTaSessionRegistry = __decorate([
102
161
  Component(TaSessionRegistry)
103
162
  ], 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 { ImageContent, 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;
@@ -42,19 +44,27 @@ export declare class TaSession {
42
44
  protected unsubscribe?: () => void;
43
45
  protected idleTimer?: ReturnType<typeof setTimeout>;
44
46
  protected started: boolean;
47
+ protected readonly infoListeners: Set<() => void>;
45
48
  constructor(context: TaSessionContext);
46
49
  get pi(): AgentSession;
47
50
  /** Where the session works, as clients name it: a path, or an `ssh://` location. */
48
51
  get cwd(): string;
49
52
  start(): Promise<void>;
50
53
  info(): TaSessionInfo;
54
+ /** What `info` gives may have changed (TaServer.watchSessions). */
55
+ onInfoChange(listener: () => void): () => void;
51
56
  attach(channel: ClientChannel, afterSeq?: number, options?: TaAttachOptions): TaAttachResult;
52
57
  earlierMessages(before: number | undefined, timestamp: number | undefined, budget: number): TaMessagePage;
58
+ /** The image of a message of the user that the conversation gives without its bytes (TaShownImage). */
59
+ messageImage(timestamp: number, index: number): ImageContent | undefined;
60
+ /** The conversation of the events sent, as clients get it. */
61
+ protected conversation(): TaConversation;
53
62
  detach(channel: ClientChannel): void;
54
63
  respondUi(response: RpcExtensionUIResponse): boolean;
55
64
  /** Only a client attached runs a call: one that left would hold it for nobody. */
56
65
  claimClientTool(channel: ClientChannel, id: string): boolean;
57
- respondClientTool(result: TaClientToolResult): boolean;
66
+ /** Only a client attached answers, and only the one that claimed the call when one did. */
67
+ respondClientTool(channel: ClientChannel, result: TaClientToolResult): boolean;
58
68
  prompt(input: TaPromptInput): Promise<TaPromptReceipt>;
59
69
  steer(input: TaPromptInput): Promise<TaPromptReceipt>;
60
70
  followUp(input: TaPromptInput): Promise<TaPromptReceipt>;
@@ -73,7 +83,7 @@ export declare class TaSession {
73
83
  * (a tool that ignores the abort, a stream that hangs) or an extension slow to shut down is given
74
84
  * `closeTimeoutMs`; then pi is cut off from its agent, so that nothing more goes into the file.
75
85
  */
76
- close(): Promise<void>;
86
+ close(announce?: boolean): Promise<void>;
77
87
  /** False when `work` takes longer than closeTimeoutMs. */
78
88
  protected within(work: Promise<void>): Promise<boolean>;
79
89
  protected accept(input: TaPromptInput, run: () => Promise<PromptDisposition>): Promise<TaPromptReceipt>;