@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
@@ -7,21 +7,35 @@ import { RemoteUiContext } from './remote-ui-context.js';
7
7
  import { SessionCatalogUtil } from './session-catalog.js';
8
8
  import { SessionInfoUtil } from './session-info-util.js';
9
9
  import { TaEventUtil } from './ta-event-util.js';
10
+ /** The events after which what a list shows of a session (its info) may differ. */
11
+ const INFO_EVENTS = new Set([
12
+ 'agent_start',
13
+ 'agent_settled',
14
+ 'message_end',
15
+ 'session_info_changed',
16
+ 'session_replaced',
17
+ 'extension_ui_request',
18
+ 'ui_request_resolved',
19
+ ]);
10
20
  /**
11
21
  * One open session of `ta serve`: pi's runtime, its event log, and the clients attached to it. Its id
12
22
  * stays the same while the runtime moves between conversations.
13
23
  */
14
24
  export class TaSession {
15
25
  constructor(context) {
26
+ var _a;
16
27
  this.context = context;
17
- this.id = randomUUID();
18
28
  this.createdAt = Date.now();
19
29
  this.receipts = new ReceiptBook();
20
30
  this.channels = new Set();
21
31
  this.live = new LiveRun();
22
32
  this.started = false;
33
+ this.infoListeners = new Set();
23
34
  this.runtime = context.runtime;
24
- this.log = new EventLog(this.id, context.options.eventBufferBytes);
35
+ this.id = (_a = context.id) !== null && _a !== void 0 ? _a : randomUUID();
36
+ // Opened again: its seqs start past any the session gave before (fewer than one per millisecond), so a
37
+ // client that attaches with one of those gets the conversation again rather than events of another log.
38
+ this.log = new EventLog(this.id, context.options.eventBufferBytes, context.id ? Date.now() : 0);
25
39
  this.ui = new RemoteUiContext(event => this.publish(event));
26
40
  context.clientTools.connect(event => this.publish(event));
27
41
  }
@@ -49,8 +63,10 @@ export class TaSession {
49
63
  sessionFile: pi.sessionFile,
50
64
  sessionName: pi.sessionName,
51
65
  firstMessage: SessionInfoUtil.firstMessage(pi.messages),
66
+ lastMessage: SessionInfoUtil.lastMessage(pi.messages),
52
67
  model: model ? `${model.provider}/${model.id}` : undefined,
53
68
  isStreaming: pi.isStreaming,
69
+ waiting: this.ui.pendingRequests.length > 0,
54
70
  messageCount: pi.messages.length,
55
71
  attached: this.channels.size,
56
72
  createdAt: this.createdAt,
@@ -58,6 +74,11 @@ export class TaSession {
58
74
  group: this.context.group,
59
75
  };
60
76
  }
77
+ /** What `info` gives may have changed (TaServer.watchSessions). */
78
+ onInfoChange(listener) {
79
+ this.infoListeners.add(listener);
80
+ return () => this.infoListeners.delete(listener);
81
+ }
61
82
  attach(channel, afterSeq, options = {}) {
62
83
  this.channels.add(channel);
63
84
  this.watchIdle();
@@ -65,9 +86,7 @@ export class TaSession {
65
86
  return {
66
87
  info: this.info(),
67
88
  events,
68
- conversation: afterSeq === undefined || gap
69
- ? MessagePage.recent(this.live.conversation(this.pi.messages, this.pi.isStreaming), options.recentBytes)
70
- : undefined,
89
+ conversation: afterSeq === undefined || gap ? MessagePage.recent(this.conversation(), options.recentBytes) : undefined,
71
90
  pendingUi: this.ui.pendingRequests,
72
91
  shownUi: this.ui.shownRequests,
73
92
  pendingClientTools: this.context.clientTools.pendingRequests,
@@ -76,7 +95,18 @@ export class TaSession {
76
95
  };
77
96
  }
78
97
  earlierMessages(before, timestamp, budget) {
79
- return MessagePage.before(this.live.conversation(this.pi.messages, this.pi.isStreaming).messages, before, timestamp, budget);
98
+ return MessagePage.before(this.conversation().messages, before, timestamp, budget);
99
+ }
100
+ /** The image of a message of the user that the conversation gives without its bytes (TaShownImage). */
101
+ messageImage(timestamp, index) {
102
+ var _a;
103
+ const message = [...this.pi.messages].reverse().find(candidate => candidate.role === 'user' && candidate.timestamp === timestamp);
104
+ const block = Array.isArray(message === null || message === void 0 ? void 0 : message.content) ? message.content[index] : undefined;
105
+ return (block === null || block === void 0 ? void 0 : block.type) === 'image' && block.data ? { type: 'image', data: block.data, mimeType: (_a = block.mimeType) !== null && _a !== void 0 ? _a : '' } : undefined;
106
+ }
107
+ /** The conversation of the events sent, as clients get it. */
108
+ conversation() {
109
+ return TaEventUtil.leanConversation(this.live.conversation(this.pi.messages, this.pi.isStreaming));
80
110
  }
81
111
  detach(channel) {
82
112
  if (this.channels.delete(channel)) {
@@ -91,8 +121,9 @@ export class TaSession {
91
121
  claimClientTool(channel, id) {
92
122
  return this.channels.has(channel) && this.context.clientTools.claim(id, channel);
93
123
  }
94
- respondClientTool(result) {
95
- return this.context.clientTools.respond(result);
124
+ /** Only a client attached answers, and only the one that claimed the call when one did. */
125
+ respondClientTool(channel, result) {
126
+ return this.channels.has(channel) && this.context.clientTools.respond(result, channel);
96
127
  }
97
128
  prompt(input) {
98
129
  return this.accept(input, () => new Promise((resolve, reject) => {
@@ -156,12 +187,14 @@ export class TaSession {
156
187
  * (a tool that ignores the abort, a stream that hangs) or an extension slow to shut down is given
157
188
  * `closeTimeoutMs`; then pi is cut off from its agent, so that nothing more goes into the file.
158
189
  */
159
- async close() {
190
+ async close(announce = true) {
160
191
  var _a;
161
192
  clearTimeout(this.idleTimer);
162
193
  this.ui.cancelAll();
163
194
  this.context.clientTools.cancelAll();
164
- this.publish({ type: 'session_closed' });
195
+ if (announce) {
196
+ this.publish({ type: 'session_closed' });
197
+ }
165
198
  this.channels.clear();
166
199
  (_a = this.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
167
200
  try {
@@ -169,8 +202,15 @@ export class TaSession {
169
202
  // Its failure is no reason to keep the session: dispose below aborts the run as well.
170
203
  await this.within(this.pi.abort().catch(() => undefined));
171
204
  }
172
- if (!(await this.within(this.runtime.dispose()))) {
173
- this.pi.dispose();
205
+ let disposed = false;
206
+ try {
207
+ disposed = await this.within(this.runtime.dispose());
208
+ }
209
+ finally {
210
+ // Late or failed: either way nothing more of pi goes into the file once it is unlocked.
211
+ if (!disposed) {
212
+ this.pi.dispose();
213
+ }
174
214
  }
175
215
  }
176
216
  finally {
@@ -197,7 +237,7 @@ export class TaSession {
197
237
  }
198
238
  try {
199
239
  const disposition = await run();
200
- return { clientMessageId: input.clientMessageId, status: disposition === 'queued' ? 'queued' : 'accepted' };
240
+ return { clientMessageId: input.clientMessageId, status: disposition === 'started' ? 'accepted' : disposition };
201
241
  }
202
242
  catch (error) {
203
243
  this.receipts.forget(input.clientMessageId);
@@ -246,6 +286,11 @@ export class TaSession {
246
286
  for (const channel of this.channels) {
247
287
  channel.send(logged);
248
288
  }
289
+ if (INFO_EVENTS.has(event.type)) {
290
+ for (const listener of this.infoListeners) {
291
+ listener();
292
+ }
293
+ }
249
294
  }
250
295
  isIdle() {
251
296
  return this.channels.size === 0 && !this.pi.isStreaming && this.ui.pendingRequests.length === 0;
@@ -255,7 +300,7 @@ export class TaSession {
255
300
  clearTimeout(this.idleTimer);
256
301
  this.idleTimer = undefined;
257
302
  if (this.isIdle()) {
258
- this.idleTimer = setTimeout(() => this.isIdle() && this.context.requestClose(this), this.context.options.idleTimeoutMs);
303
+ this.idleTimer = setTimeout(() => this.isIdle() && this.context.requestClose(this, true), this.context.options.idleTimeoutMs);
259
304
  this.idleTimer.unref();
260
305
  }
261
306
  }
@@ -37,6 +37,11 @@ export declare class WebExtensionCatalogImpl implements WebExtensionCatalog {
37
37
  setTemporaryRetention(days: number): void;
38
38
  protected temporary(): TemporaryStore;
39
39
  packageOf(cwd: string, id: string): Promise<TaPackageInfo>;
40
+ /**
41
+ * The package an id names: its id of listPackages, or the id of one of its web extensions. Every method of a
42
+ * package takes either, so that a client holding a web extension never looks for its package first.
43
+ */
44
+ protected findPackage(packages: WebExtensionPackage[], id: string, kind?: string): WebExtensionPackage;
40
45
  /** A package another computer shared by a link, put in Ta's own temporary directory (RelayShareUtil). */
41
46
  protected fetchShare(link: string): Promise<string>;
42
47
  protected fetch(manager: PackageManager, source: string): Promise<string>;
@@ -46,7 +51,6 @@ export declare class WebExtensionCatalogImpl implements WebExtensionCatalog {
46
51
  removePackage(cwd: string, id: string): Promise<void>;
47
52
  list(cwd: string): Promise<TaWebExtensionInfo[]>;
48
53
  read(cwd: string, id: string): Promise<TaWebExtensionSource>;
49
- remove(cwd: string, id: string): Promise<void>;
50
54
  setEnabled(cwd: string, nameOrId: string, enabled: boolean): Promise<void>;
51
55
  protected removeRoot(pkg: WebExtensionPackage, manager: PackageManager): Promise<void>;
52
56
  protected agentDir(): string;
@@ -127,11 +127,18 @@ let WebExtensionCatalogImpl = class WebExtensionCatalogImpl {
127
127
  }
128
128
  async packageOf(cwd, id) {
129
129
  const { packages } = await this.load(cwd);
130
+ return WebExtensionUtil.describePackage(this.findPackage(packages, id));
131
+ }
132
+ /**
133
+ * The package an id names: its id of listPackages, or the id of one of its web extensions. Every method of a
134
+ * package takes either, so that a client holding a web extension never looks for its package first.
135
+ */
136
+ findPackage(packages, id, kind = 'package') {
130
137
  const pkg = packages.find(candidate => WebExtensionUtil.describePackage(candidate).id === id || WebExtensionUtil.describe(candidate).some(info => info.id === id));
131
138
  if (!pkg) {
132
- throw TaErrors.invalidArgument(`No package has the id ${id}.`, 'listPackages lists the ones there are; the package may have moved or gone.');
139
+ throw TaErrors.invalidArgument(`No ${kind} has the id ${id}.`, 'listPackages lists the ones there are; the package may have moved or gone.');
133
140
  }
134
- return WebExtensionUtil.describePackage(pkg);
141
+ return pkg;
135
142
  }
136
143
  /** A package another computer shared by a link, put in Ta's own temporary directory (RelayShareUtil). */
137
144
  async fetchShare(link) {
@@ -156,12 +163,7 @@ let WebExtensionCatalogImpl = class WebExtensionCatalogImpl {
156
163
  }
157
164
  async findTemporary(cwd, id) {
158
165
  const { packages } = await this.load(cwd);
159
- const pkg = packages.find(candidate => candidate.origin === 'temporary' &&
160
- (WebExtensionUtil.describePackage(candidate).id === id || WebExtensionUtil.describe(candidate).some(info => info.id === id)));
161
- if (!pkg) {
162
- throw TaErrors.invalidArgument(`No temporary package has the id ${id}.`, 'listPackages lists the ones there are; it may have been installed, removed or cleared.');
163
- }
164
- return pkg;
166
+ return this.findPackage(packages.filter(candidate => candidate.origin === 'temporary'), id, 'temporary package');
165
167
  }
166
168
  /** Ta's own directory is deleted, what pi fetched removed, a path of the user's only forgotten. */
167
169
  async dropTemporary(record, manager) {
@@ -176,11 +178,7 @@ let WebExtensionCatalogImpl = class WebExtensionCatalogImpl {
176
178
  }
177
179
  async removePackage(cwd, id) {
178
180
  const { packages, manager } = await this.load(cwd);
179
- const pkg = packages.find(candidate => WebExtensionUtil.describePackage(candidate).id === id);
180
- if (!pkg) {
181
- throw TaErrors.invalidArgument(`No package has the id ${id}.`, 'listPackages lists the ones there are; the package may have moved or gone.');
182
- }
183
- await this.removeRoot(pkg, manager);
181
+ await this.removeRoot(this.findPackage(packages, id), manager);
184
182
  }
185
183
  async list(cwd) {
186
184
  const { packages } = await this.load(cwd);
@@ -191,19 +189,17 @@ let WebExtensionCatalogImpl = class WebExtensionCatalogImpl {
191
189
  const code = WebExtensionUtil.read(pkg, info.entry);
192
190
  return { id, hash: WebExtensionUtil.hash(code), code };
193
191
  }
194
- async remove(cwd, id) {
195
- const { pkg } = await this.find(cwd, id);
196
- await this.removeRoot(pkg, (await this.load(cwd)).manager);
197
- }
198
192
  async setEnabled(cwd, nameOrId, enabled) {
199
193
  if (TaPackages.builtins().some(pkg => pkg.name === nameOrId)) {
200
194
  TaPackages.setEnabled(this.agentDir(), nameOrId, enabled);
201
195
  return;
202
196
  }
203
197
  const loaded = await this.load(cwd);
204
- const pkg = loaded.packages.find(candidate => candidate.origin !== 'builtin' && candidate.origin !== 'temporary' && WebExtensionUtil.describePackage(candidate).id === nameOrId);
198
+ const pkg = loaded.packages.find(candidate => candidate.origin !== 'builtin' &&
199
+ candidate.origin !== 'temporary' &&
200
+ (WebExtensionUtil.describePackage(candidate).id === nameOrId || WebExtensionUtil.describe(candidate).some(info => info.id === nameOrId)));
205
201
  if (!pkg) {
206
- throw TaErrors.invalidArgument(`${nameOrId} is neither a package that comes with Ta nor the id of a package.`, 'Pass the name of a built-in package, or an id of listPackages.');
202
+ throw TaErrors.invalidArgument(`${nameOrId} is neither a package that comes with Ta nor the id of a package.`, 'Pass the name of a built-in package, or an id of listPackages or of one of its web extensions.');
207
203
  }
208
204
  const resources = PackageSwitch.resourcesOf(await this.resolve(loaded.manager), pkg.root);
209
205
  if (resources.length === 0) {
@@ -10,21 +10,25 @@ const PI_RESOURCES = ['extensions', 'skills', 'prompts', 'themes'];
10
10
  export var WebExtensionUtil;
11
11
  (function (WebExtensionUtil) {
12
12
  function describe(pkg) {
13
+ var _a;
13
14
  const manifest = readManifest(pkg.root);
14
- return entries(pkg.root, manifest).map(entry => { var _a, _b; var _c, _d; return ({
15
+ const lists = Array.isArray((_a = manifest === null || manifest === void 0 ? void 0 : manifest.pi) === null || _a === void 0 ? void 0 : _a.lists) ? manifest.pi.lists.filter((kind) => typeof kind === 'string' && kind !== '') : [];
16
+ return entries(pkg.root, manifest).map(entry => { var _a, _b, _c; var _d, _e; return ({
15
17
  id: id(pkg, entry),
16
- name: (_c = manifest === null || manifest === void 0 ? void 0 : manifest.name) !== null && _c !== void 0 ? _c : basename(pkg.root),
18
+ name: (_d = manifest === null || manifest === void 0 ? void 0 : manifest.name) !== null && _d !== void 0 ? _d : basename(pkg.root),
17
19
  description: manifest === null || manifest === void 0 ? void 0 : manifest.description,
18
20
  version: manifest === null || manifest === void 0 ? void 0 : manifest.version,
19
21
  scope: pkg.scope,
20
22
  origin: pkg.origin,
21
- enabled: (_d = pkg.enabled) !== null && _d !== void 0 ? _d : true,
23
+ enabled: (_e = pkg.enabled) !== null && _e !== void 0 ? _e : true,
22
24
  source: pkg.source,
23
25
  entry,
24
26
  hash: hash(readFileSync(join(pkg.root, entry), 'utf8')),
25
27
  title: text((_a = manifest === null || manifest === void 0 ? void 0 : manifest.pi) === null || _a === void 0 ? void 0 : _a.title),
26
28
  icon: icon(manifest),
27
29
  activation: pkg.temporary || ((_b = manifest === null || manifest === void 0 ? void 0 : manifest.pi) === null || _b === void 0 ? void 0 : _b.webActivation) === 'open' ? 'open' : 'startup',
30
+ ...(typeof ((_c = manifest === null || manifest === void 0 ? void 0 : manifest.pi) === null || _c === void 0 ? void 0 : _c.category) === 'string' && manifest.pi.category ? { category: manifest.pi.category } : {}),
31
+ ...(lists.length > 0 ? { lists } : {}),
28
32
  ...(pkg.temporary ? { temporary: pkg.temporary } : {}),
29
33
  }); });
30
34
  }
@@ -2,6 +2,12 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import { type ExecEnvironment, ExecEnvironmentFactory, type FileStat } from '@celljs/ta-exec';
3
3
  import { type Context, Middleware } from '@celljs/web/lib/node';
4
4
  import { WorkspaceFiles } from './workspace-protocol.js';
5
+ interface ServedDirectory {
6
+ root: string;
7
+ cwd: string;
8
+ /** The name of the one file of `root` served: a file outside the directory of the conversation. */
9
+ only?: string;
10
+ }
5
11
  export declare namespace WorkspaceFilesUtil {
6
12
  function contentType(path: string): string;
7
13
  /** `/api/files/<id>/<path>`; undefined for other URLs or a path that does not decode. */
@@ -23,20 +29,27 @@ export declare namespace WorkspaceFilesUtil {
23
29
  /**
24
30
  * Answers `GET /api/files/<id>/<path>` with the bytes of a file, without the token of ta serve: `<id>`
25
31
  * 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.
32
+ * that directory; a directory answers its `index.html`. One range is served, so that videos seek. A file
33
+ * outside the directory of the conversation (a picture an agent left in `/tmp`) has an id of its own that
34
+ * stands for that file alone: the URL needs no token, so it must not open the directory the file is in
35
+ * (the home directory for `~/a.png`, with its keys) nor the pages of the workspace reach it.
27
36
  */
28
37
  export declare class DefaultWorkspaceFiles implements WorkspaceFiles, Middleware {
29
38
  /** Before TaAccess, which turns away `/api` requests without the token. */
30
39
  readonly priority: number;
31
40
  protected readonly environments: ExecEnvironmentFactory;
32
41
  protected readonly host?: string;
33
- protected readonly directories: Map<string, string>;
42
+ /**
43
+ * By id, the directory paths stay in, the one whose execution environment reads them, and for a file
44
+ * outside the conversation's directory, the one path of `root` served.
45
+ */
46
+ protected readonly directories: Map<string, ServedDirectory>;
34
47
  protected readonly ids: Map<string, string>;
35
48
  url(cwd: string, path: string): string;
36
49
  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<{
50
+ protected send(request: IncomingMessage, response: ServerResponse, directory: ServedDirectory, path: string): Promise<void>;
51
+ /** The file at `path` of `root`, or the `index.html` of the directory there. */
52
+ protected find(env: ExecEnvironment, root: string, path: string): Promise<{
40
53
  absolute: string;
41
54
  stat: FileStat;
42
55
  } | undefined>;
@@ -45,3 +58,4 @@ export declare class DefaultWorkspaceFiles implements WorkspaceFiles, Middleware
45
58
  protected acceptsHost(request: IncomingMessage): boolean;
46
59
  protected fail(response: ServerResponse, status: number): void;
47
60
  }
61
+ export {};
@@ -9,6 +9,7 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  };
10
10
  import { randomBytes } from 'node:crypto';
11
11
  import { createReadStream } from 'node:fs';
12
+ import { basename, dirname, resolve } from 'node:path';
12
13
  import { Autowired, Component, Value } from '@celljs/core';
13
14
  import { ExecEnvironmentFactory } from '@celljs/ta-exec';
14
15
  import { TA_FILES_PATH } from '@celljs/ta-protocol';
@@ -117,24 +118,34 @@ export var WorkspaceFilesUtil;
117
118
  /**
118
119
  * Answers `GET /api/files/<id>/<path>` with the bytes of a file, without the token of ta serve: `<id>`
119
120
  * stands for one directory, and only who has the token learns it (TaWorkspaceServer.fileUrl). Paths stay inside
120
- * that directory; a directory answers its `index.html`. One range is served, so that videos seek.
121
+ * that directory; a directory answers its `index.html`. One range is served, so that videos seek. A file
122
+ * outside the directory of the conversation (a picture an agent left in `/tmp`) has an id of its own that
123
+ * stands for that file alone: the URL needs no token, so it must not open the directory the file is in
124
+ * (the home directory for `~/a.png`, with its keys) nor the pages of the workspace reach it.
121
125
  */
122
126
  let DefaultWorkspaceFiles = class DefaultWorkspaceFiles {
123
127
  constructor() {
124
128
  /** Before TaAccess, which turns away `/api` requests without the token. */
125
129
  this.priority = ACCESS_MIDDLEWARE_PRIORITY + 1;
130
+ /**
131
+ * By id, the directory paths stay in, the one whose execution environment reads them, and for a file
132
+ * outside the conversation's directory, the one path of `root` served.
133
+ */
126
134
  this.directories = new Map();
127
135
  this.ids = new Map();
128
136
  }
129
137
  url(cwd, path) {
130
- const { relative } = WorkspaceUtil.inside(cwd, path);
131
- let id = this.ids.get(cwd);
138
+ const absolute = resolve(cwd, path || '.');
139
+ const inside = WorkspaceUtil.contains(cwd, absolute);
140
+ const served = inside ? { root: cwd, cwd } : { root: dirname(absolute), cwd, only: basename(absolute) };
141
+ const key = `${cwd}\0${inside ? '' : absolute}`;
142
+ let id = this.ids.get(key);
132
143
  if (!id) {
133
144
  id = randomBytes(ID_BYTES).toString('base64url');
134
- this.ids.set(cwd, id);
135
- this.directories.set(id, cwd);
145
+ this.ids.set(key, id);
146
+ this.directories.set(id, served);
136
147
  }
137
- return WorkspaceFilesUtil.url(id, relative);
148
+ return WorkspaceFilesUtil.url(id, WorkspaceUtil.inside(served.root, absolute).relative);
138
149
  }
139
150
  async handle(ctx, next) {
140
151
  const request = ctx.request;
@@ -144,8 +155,8 @@ let DefaultWorkspaceFiles = class DefaultWorkspaceFiles {
144
155
  return;
145
156
  }
146
157
  const response = ctx.response;
147
- const cwd = this.directories.get(target.id);
148
- if (!cwd || !this.acceptsHost(request)) {
158
+ const directory = this.directories.get(target.id);
159
+ if (!directory || !this.acceptsHost(request)) {
149
160
  this.fail(response, 404);
150
161
  return;
151
162
  }
@@ -154,11 +165,11 @@ let DefaultWorkspaceFiles = class DefaultWorkspaceFiles {
154
165
  this.fail(response, 405);
155
166
  return;
156
167
  }
157
- await this.send(request, response, cwd, target.path);
168
+ await this.send(request, response, directory, target.path);
158
169
  }
159
- async send(request, response, cwd, path) {
160
- const env = this.environments.create(cwd);
161
- const file = await this.find(env, path);
170
+ async send(request, response, directory, path) {
171
+ const env = this.environments.create(directory.cwd);
172
+ const file = directory.only === undefined || path === directory.only ? await this.find(env, directory.root, path) : undefined;
162
173
  if (!file) {
163
174
  this.fail(response, 404);
164
175
  return;
@@ -205,11 +216,11 @@ let DefaultWorkspaceFiles = class DefaultWorkspaceFiles {
205
216
  response.end(await this.read(env, absolute, stat.size, start, end));
206
217
  }
207
218
  }
208
- /** The file at `path`, or the `index.html` of the directory there. */
209
- async find(env, path) {
219
+ /** The file at `path` of `root`, or the `index.html` of the directory there. */
220
+ async find(env, root, path) {
210
221
  let absolute;
211
222
  try {
212
- absolute = WorkspaceUtil.inside(env.cwd, path).absolute;
223
+ absolute = WorkspaceUtil.inside(root, path).absolute;
213
224
  }
214
225
  catch (_a) {
215
226
  return undefined;
@@ -17,6 +17,6 @@ export interface TaWorkspace {
17
17
  }
18
18
  /** The bytes of workspace files over plain HTTP, for the page to show them as they are (TaWorkspaceServer.fileUrl). */
19
19
  export interface WorkspaceFiles {
20
- /** The URL of `path` of `cwd`; throws when it leaves `cwd`. */
20
+ /** The URL of `path` of `cwd`; a file outside `cwd` has a URL that serves it alone. */
21
21
  url(cwd: string, path: string): string;
22
22
  }
@@ -8,6 +8,8 @@ export declare namespace WorkspaceUtil {
8
8
  absolute: string;
9
9
  relative: string;
10
10
  };
11
+ /** Whether `absolute` is `cwd` or inside it. */
12
+ function contains(cwd: string, absolute: string): boolean;
11
13
  /** Joins a relative path of a directory with a name, with `/`. */
12
14
  function join(dir: string, name: string): string;
13
15
  /** Directories first, then by name as people sort (`file2` before `file10`). */
@@ -9,13 +9,18 @@ export var WorkspaceUtil;
9
9
  /** `path` inside `cwd`, absolute, and relative with `/`; throws when it leaves `cwd`. */
10
10
  function inside(cwd, path) {
11
11
  const absolute = resolve(cwd, path || '.');
12
- const rel = relative(cwd, absolute);
13
- if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
12
+ if (!contains(cwd, absolute)) {
14
13
  throw TaErrors.invalidArgument(`The path ${path} is outside of ${cwd}.`, 'Pass a path inside the directory of the workspace.');
15
14
  }
16
- return { absolute, relative: rel.split(sep).join('/') };
15
+ return { absolute, relative: relative(cwd, absolute).split(sep).join('/') };
17
16
  }
18
17
  WorkspaceUtil.inside = inside;
18
+ /** Whether `absolute` is `cwd` or inside it. */
19
+ function contains(cwd, absolute) {
20
+ const rel = relative(cwd, absolute);
21
+ return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
22
+ }
23
+ WorkspaceUtil.contains = contains;
19
24
  /** Joins a relative path of a directory with a name, with `/`. */
20
25
  function join(dir, name) {
21
26
  return dir && dir !== '.' ? posix.join(dir, name) : name;
@@ -29,8 +29,12 @@ export declare class ClientToolBroker {
29
29
  claim(id: string, runner: object): boolean;
30
30
  /** `runner` left the session: the calls it took and did not answer go to the others again. */
31
31
  release(runner: object): void;
32
- /** False when nobody waits for this call. */
33
- respond(result: TaClientToolResult): boolean;
32
+ /**
33
+ * False when nobody waits for this call, or another client took it: only the runner that claimed a call
34
+ * answers it, so that a page that did not run it cannot put an answer of its own in its place. A call nobody
35
+ * claimed (a client from before claims, or a result sent again after a reconnect) takes the first answer.
36
+ */
37
+ respond(result: TaClientToolResult, runner?: object): boolean;
34
38
  cancelAll(): void;
35
39
  protected call(toolName: string, id: string, input: unknown, signal?: AbortSignal): Promise<{
36
40
  content: {
@@ -63,11 +63,18 @@ class ClientToolBroker {
63
63
  }
64
64
  }
65
65
  }
66
- /** False when nobody waits for this call. */
67
- respond(result) {
66
+ /**
67
+ * False when nobody waits for this call, or another client took it: only the runner that claimed a call
68
+ * answers it, so that a page that did not run it cannot put an answer of its own in its place. A call nobody
69
+ * claimed (a client from before claims, or a result sent again after a reconnect) takes the first answer.
70
+ */
71
+ respond(result, runner) {
68
72
  const call = this.pending.get(result.id);
69
- call === null || call === void 0 ? void 0 : call.settle(result);
70
- return call !== undefined;
73
+ if (!call || (call.runner && call.runner !== runner)) {
74
+ return false;
75
+ }
76
+ call.settle(result);
77
+ return true;
71
78
  }
72
79
  cancelAll() {
73
80
  for (const call of [...this.pending.values()]) {
@@ -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. */
@@ -6,13 +6,14 @@ exports.EventLog = void 0;
6
6
  * what happened is in the session file, and a client that fell further behind reads it again.
7
7
  */
8
8
  class EventLog {
9
- constructor(sessionId, maxBytes) {
9
+ /** `firstSeq`: the seq before the first event; a session opened again under its id starts past those its clients saw. */
10
+ constructor(sessionId, maxBytes, firstSeq = 0) {
10
11
  this.sessionId = sessionId;
11
12
  this.maxBytes = maxBytes;
12
13
  this.entries = [];
13
14
  this.head = 0;
14
15
  this.bytes = 0;
15
- this.seq = 0;
16
+ this.seq = firstSeq;
16
17
  }
17
18
  get lastSeq() {
18
19
  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';
3
4
  import { RemoteHosts } from './remote/remote-protocol';
4
5
  import { TaWorkingDirectory } from './working-directory';
@@ -15,8 +16,14 @@ 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
  }
22
29
  //# sourceMappingURL=exec-environment-factory.d.ts.map
@@ -10,6 +10,8 @@ var __metadata = (this && this.__metadata) || function (k, v) {
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.DefaultExecEnvironmentFactory = void 0;
13
+ const node_os_1 = require("node:os");
14
+ const node_path_1 = require("node:path");
13
15
  const core_1 = require("@celljs/core");
14
16
  const ta_exec_1 = require("@celljs/ta-exec");
15
17
  const ta_protocol_1 = require("@celljs/ta-protocol");
@@ -26,13 +28,7 @@ const working_directory_1 = require("./working-directory");
26
28
  let DefaultExecEnvironmentFactory = class DefaultExecEnvironmentFactory {
27
29
  /** Its `cwd` is the path there: the one to resolve paths against, not the location. */
28
30
  create(location) {
29
- let remote;
30
- try {
31
- remote = ta_protocol_1.TaLocation.parse(location);
32
- }
33
- catch (error) {
34
- throw ta_errors_1.TaErrors.invalidArgument(error.message, 'Write ssh://<host>/<absolute path>.');
35
- }
31
+ const remote = this.parse(location);
36
32
  if (remote) {
37
33
  if (!remote.path) {
38
34
  throw ta_errors_1.TaErrors.invalidArgument(`${location} names no directory.`, 'Resolve it first (TaRemoteServer.resolveLocation), or write its path.');
@@ -42,6 +38,25 @@ let DefaultExecEnvironmentFactory = class DefaultExecEnvironmentFactory {
42
38
  const client = this.remote();
43
39
  return client ? new ta_exec_1.RemoteExecEnvironment(client, location) : new ta_exec_1.LocalExecEnvironment(location);
44
40
  }
41
+ /**
42
+ * A location as the user wrote it, whole: `~` is the home directory of its machine (where ssh starts
43
+ * there, and where the exec server started), and a relative path is under the default directory.
44
+ */
45
+ async resolve(location) {
46
+ var _a;
47
+ var _b;
48
+ const remote = this.parse(location);
49
+ const home = ta_protocol_1.TaLocation.homeRelative(location);
50
+ if (remote) {
51
+ return home === undefined ? location : ta_protocol_1.TaLocation.ssh(remote.host, node_path_1.posix.join((await this.remoteHosts.client(remote.host).info()).cwd, home));
52
+ }
53
+ const info = await ((_a = this.remote()) === null || _a === void 0 ? void 0 : _a.info());
54
+ const path = ((_b = info === null || info === void 0 ? void 0 : info.platform) !== null && _b !== void 0 ? _b : process.platform) === 'win32' ? node_path_1.win32 : node_path_1.posix;
55
+ if (home !== undefined) {
56
+ return path.join(info ? info.cwd : (0, node_os_1.homedir)(), home);
57
+ }
58
+ return path.isAbsolute(location) ? location : path.resolve(await this.defaultCwd(), location);
59
+ }
45
60
  /** The working directory the user chose, else that of this process, or of the exec server. */
46
61
  async defaultCwd() {
47
62
  var _a;
@@ -52,6 +67,14 @@ let DefaultExecEnvironmentFactory = class DefaultExecEnvironmentFactory {
52
67
  const client = this.remote();
53
68
  return client ? (await client.info()).cwd : process.cwd();
54
69
  }
70
+ parse(location) {
71
+ try {
72
+ return ta_protocol_1.TaLocation.parse(location);
73
+ }
74
+ catch (error) {
75
+ throw ta_errors_1.TaErrors.invalidArgument(error.message, 'Write ssh://<host>/<absolute path>.');
76
+ }
77
+ }
55
78
  remote() {
56
79
  var _a, _b;
57
80
  const { url, token = '', epoch } = (_a = this.options) !== null && _a !== void 0 ? _a : {};